PackageManagerService.java revision e980804df16c968c14a56b8853886bf5f049f46e
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.IActivityManager; 84import android.app.admin.IDevicePolicyManager; 85import android.app.backup.IBackupManager; 86import android.content.BroadcastReceiver; 87import android.content.ComponentName; 88import android.content.Context; 89import android.content.IIntentReceiver; 90import android.content.Intent; 91import android.content.IntentFilter; 92import android.content.IntentSender; 93import android.content.IntentSender.SendIntentException; 94import android.content.ServiceConnection; 95import android.content.pm.ActivityInfo; 96import android.content.pm.ApplicationInfo; 97import android.content.pm.FeatureInfo; 98import android.content.pm.IPackageDataObserver; 99import android.content.pm.IPackageDeleteObserver; 100import android.content.pm.IPackageDeleteObserver2; 101import android.content.pm.IPackageInstallObserver2; 102import android.content.pm.IPackageInstaller; 103import android.content.pm.IPackageManager; 104import android.content.pm.IPackageMoveObserver; 105import android.content.pm.IPackageStatsObserver; 106import android.content.pm.InstrumentationInfo; 107import android.content.pm.KeySet; 108import android.content.pm.ManifestDigest; 109import android.content.pm.PackageCleanItem; 110import android.content.pm.PackageInfo; 111import android.content.pm.PackageInfoLite; 112import android.content.pm.PackageInstaller; 113import android.content.pm.PackageManager; 114import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 115import android.content.pm.PackageParser.ActivityIntentInfo; 116import android.content.pm.PackageParser.PackageLite; 117import android.content.pm.PackageParser.PackageParserException; 118import android.content.pm.PackageParser; 119import android.content.pm.PackageStats; 120import android.content.pm.PackageUserState; 121import android.content.pm.ParceledListSlice; 122import android.content.pm.PermissionGroupInfo; 123import android.content.pm.PermissionInfo; 124import android.content.pm.ProviderInfo; 125import android.content.pm.ResolveInfo; 126import android.content.pm.ServiceInfo; 127import android.content.pm.Signature; 128import android.content.pm.UserInfo; 129import android.content.pm.VerificationParams; 130import android.content.pm.VerifierDeviceIdentity; 131import android.content.pm.VerifierInfo; 132import android.content.res.Resources; 133import android.hardware.display.DisplayManager; 134import android.net.Uri; 135import android.os.Binder; 136import android.os.Build; 137import android.os.Bundle; 138import android.os.Environment; 139import android.os.Environment.UserEnvironment; 140import android.os.storage.StorageManager; 141import android.os.Debug; 142import android.os.FileUtils; 143import android.os.Handler; 144import android.os.IBinder; 145import android.os.Looper; 146import android.os.Message; 147import android.os.Parcel; 148import android.os.ParcelFileDescriptor; 149import android.os.Process; 150import android.os.RemoteException; 151import android.os.SELinux; 152import android.os.ServiceManager; 153import android.os.SystemClock; 154import android.os.SystemProperties; 155import android.os.UserHandle; 156import android.os.UserManager; 157import android.security.KeyStore; 158import android.security.SystemKeyStore; 159import android.system.ErrnoException; 160import android.system.Os; 161import android.system.StructStat; 162import android.text.TextUtils; 163import android.util.ArraySet; 164import android.util.AtomicFile; 165import android.util.DisplayMetrics; 166import android.util.EventLog; 167import android.util.ExceptionUtils; 168import android.util.Log; 169import android.util.LogPrinter; 170import android.util.PrintStreamPrinter; 171import android.util.Slog; 172import android.util.SparseArray; 173import android.util.SparseBooleanArray; 174import android.view.Display; 175 176import java.io.BufferedInputStream; 177import java.io.BufferedOutputStream; 178import java.io.File; 179import java.io.FileDescriptor; 180import java.io.FileInputStream; 181import java.io.FileNotFoundException; 182import java.io.FileOutputStream; 183import java.io.FilenameFilter; 184import java.io.IOException; 185import java.io.InputStream; 186import java.io.PrintWriter; 187import java.nio.charset.StandardCharsets; 188import java.security.NoSuchAlgorithmException; 189import java.security.PublicKey; 190import java.security.cert.CertificateEncodingException; 191import java.security.cert.CertificateException; 192import java.text.SimpleDateFormat; 193import java.util.ArrayList; 194import java.util.Arrays; 195import java.util.Collection; 196import java.util.Collections; 197import java.util.Comparator; 198import java.util.Date; 199import java.util.HashMap; 200import java.util.HashSet; 201import java.util.Iterator; 202import java.util.List; 203import java.util.Map; 204import java.util.Set; 205import java.util.concurrent.atomic.AtomicBoolean; 206import java.util.concurrent.atomic.AtomicLong; 207 208import dalvik.system.DexFile; 209import dalvik.system.StaleDexCacheError; 210import dalvik.system.VMRuntime; 211 212import libcore.io.IoUtils; 213import libcore.util.EmptyArray; 214 215/** 216 * Keep track of all those .apks everywhere. 217 * 218 * This is very central to the platform's security; please run the unit 219 * tests whenever making modifications here: 220 * 221mmm frameworks/base/tests/AndroidTests 222adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 223adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 224 * 225 * {@hide} 226 */ 227public class PackageManagerService extends IPackageManager.Stub { 228 static final String TAG = "PackageManager"; 229 static final boolean DEBUG_SETTINGS = false; 230 static final boolean DEBUG_PREFERRED = false; 231 static final boolean DEBUG_UPGRADE = false; 232 private static final boolean DEBUG_INSTALL = false; 233 private static final boolean DEBUG_REMOVE = false; 234 private static final boolean DEBUG_BROADCASTS = false; 235 private static final boolean DEBUG_SHOW_INFO = false; 236 private static final boolean DEBUG_PACKAGE_INFO = false; 237 private static final boolean DEBUG_INTENT_MATCHING = false; 238 private static final boolean DEBUG_PACKAGE_SCANNING = false; 239 private static final boolean DEBUG_VERIFY = false; 240 private static final boolean DEBUG_DEXOPT = false; 241 private static final boolean DEBUG_ABI_SELECTION = false; 242 243 private static final int RADIO_UID = Process.PHONE_UID; 244 private static final int LOG_UID = Process.LOG_UID; 245 private static final int NFC_UID = Process.NFC_UID; 246 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 247 private static final int SHELL_UID = Process.SHELL_UID; 248 249 // Cap the size of permission trees that 3rd party apps can define 250 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 251 252 // Suffix used during package installation when copying/moving 253 // package apks to install directory. 254 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 255 256 static final int SCAN_NO_DEX = 1<<1; 257 static final int SCAN_FORCE_DEX = 1<<2; 258 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 259 static final int SCAN_NEW_INSTALL = 1<<4; 260 static final int SCAN_NO_PATHS = 1<<5; 261 static final int SCAN_UPDATE_TIME = 1<<6; 262 static final int SCAN_DEFER_DEX = 1<<7; 263 static final int SCAN_BOOTING = 1<<8; 264 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 265 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 266 static final int SCAN_REPLACING = 1<<11; 267 268 static final int REMOVE_CHATTY = 1<<16; 269 270 /** 271 * Timeout (in milliseconds) after which the watchdog should declare that 272 * our handler thread is wedged. The usual default for such things is one 273 * minute but we sometimes do very lengthy I/O operations on this thread, 274 * such as installing multi-gigabyte applications, so ours needs to be longer. 275 */ 276 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 277 278 /** 279 * Whether verification is enabled by default. 280 */ 281 private static final boolean DEFAULT_VERIFY_ENABLE = true; 282 283 /** 284 * The default maximum time to wait for the verification agent to return in 285 * milliseconds. 286 */ 287 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 288 289 /** 290 * The default response for package verification timeout. 291 * 292 * This can be either PackageManager.VERIFICATION_ALLOW or 293 * PackageManager.VERIFICATION_REJECT. 294 */ 295 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 296 297 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 298 299 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 300 DEFAULT_CONTAINER_PACKAGE, 301 "com.android.defcontainer.DefaultContainerService"); 302 303 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 304 305 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 306 307 private static String sPreferredInstructionSet; 308 309 final ServiceThread mHandlerThread; 310 311 private static final String IDMAP_PREFIX = "/data/resource-cache/"; 312 private static final String IDMAP_SUFFIX = "@idmap"; 313 314 final PackageHandler mHandler; 315 316 /** 317 * Messages for {@link #mHandler} that need to wait for system ready before 318 * being dispatched. 319 */ 320 private ArrayList<Message> mPostSystemReadyMessages; 321 322 final int mSdkVersion = Build.VERSION.SDK_INT; 323 324 final Context mContext; 325 final boolean mFactoryTest; 326 final boolean mOnlyCore; 327 final boolean mLazyDexOpt; 328 final DisplayMetrics mMetrics; 329 final int mDefParseFlags; 330 final String[] mSeparateProcesses; 331 332 // This is where all application persistent data goes. 333 final File mAppDataDir; 334 335 // This is where all application persistent data goes for secondary users. 336 final File mUserAppDataDir; 337 338 /** The location for ASEC container files on internal storage. */ 339 final String mAsecInternalPath; 340 341 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 342 // LOCK HELD. Can be called with mInstallLock held. 343 final Installer mInstaller; 344 345 /** Directory where installed third-party apps stored */ 346 final File mAppInstallDir; 347 348 /** 349 * Directory to which applications installed internally have their 350 * 32 bit native libraries copied. 351 */ 352 private File mAppLib32InstallDir; 353 354 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 355 // apps. 356 final File mDrmAppPrivateInstallDir; 357 358 // ---------------------------------------------------------------- 359 360 // Lock for state used when installing and doing other long running 361 // operations. Methods that must be called with this lock held have 362 // the suffix "LI". 363 final Object mInstallLock = new Object(); 364 365 // ---------------------------------------------------------------- 366 367 // Keys are String (package name), values are Package. This also serves 368 // as the lock for the global state. Methods that must be called with 369 // this lock held have the prefix "LP". 370 final HashMap<String, PackageParser.Package> mPackages = 371 new HashMap<String, PackageParser.Package>(); 372 373 // Tracks available target package names -> overlay package paths. 374 final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays = 375 new HashMap<String, HashMap<String, PackageParser.Package>>(); 376 377 final Settings mSettings; 378 boolean mRestoredSettings; 379 380 // System configuration read by SystemConfig. 381 final int[] mGlobalGids; 382 final SparseArray<HashSet<String>> mSystemPermissions; 383 final HashMap<String, FeatureInfo> mAvailableFeatures; 384 385 // If mac_permissions.xml was found for seinfo labeling. 386 boolean mFoundPolicyFile; 387 388 // If a recursive restorecon of /data/data/<pkg> is needed. 389 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 390 391 public static final class SharedLibraryEntry { 392 public final String path; 393 public final String apk; 394 395 SharedLibraryEntry(String _path, String _apk) { 396 path = _path; 397 apk = _apk; 398 } 399 } 400 401 // Currently known shared libraries. 402 final HashMap<String, SharedLibraryEntry> mSharedLibraries = 403 new HashMap<String, SharedLibraryEntry>(); 404 405 // All available activities, for your resolving pleasure. 406 final ActivityIntentResolver mActivities = 407 new ActivityIntentResolver(); 408 409 // All available receivers, for your resolving pleasure. 410 final ActivityIntentResolver mReceivers = 411 new ActivityIntentResolver(); 412 413 // All available services, for your resolving pleasure. 414 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 415 416 // All available providers, for your resolving pleasure. 417 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 418 419 // Mapping from provider base names (first directory in content URI codePath) 420 // to the provider information. 421 final HashMap<String, PackageParser.Provider> mProvidersByAuthority = 422 new HashMap<String, PackageParser.Provider>(); 423 424 // Mapping from instrumentation class names to info about them. 425 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 426 new HashMap<ComponentName, PackageParser.Instrumentation>(); 427 428 // Mapping from permission names to info about them. 429 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups = 430 new HashMap<String, PackageParser.PermissionGroup>(); 431 432 // Packages whose data we have transfered into another package, thus 433 // should no longer exist. 434 final HashSet<String> mTransferedPackages = new HashSet<String>(); 435 436 // Broadcast actions that are only available to the system. 437 final HashSet<String> mProtectedBroadcasts = new HashSet<String>(); 438 439 /** List of packages waiting for verification. */ 440 final SparseArray<PackageVerificationState> mPendingVerification 441 = new SparseArray<PackageVerificationState>(); 442 443 /** Set of packages associated with each app op permission. */ 444 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 445 446 final PackageInstallerService mInstallerService; 447 448 HashSet<PackageParser.Package> mDeferredDexOpt = null; 449 450 // Cache of users who need badging. 451 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 452 453 /** Token for keys in mPendingVerification. */ 454 private int mPendingVerificationToken = 0; 455 456 volatile boolean mSystemReady; 457 volatile boolean mSafeMode; 458 volatile boolean mHasSystemUidErrors; 459 460 ApplicationInfo mAndroidApplication; 461 final ActivityInfo mResolveActivity = new ActivityInfo(); 462 final ResolveInfo mResolveInfo = new ResolveInfo(); 463 ComponentName mResolveComponentName; 464 PackageParser.Package mPlatformPackage; 465 ComponentName mCustomResolverComponentName; 466 467 boolean mResolverReplaced = false; 468 469 // Set of pending broadcasts for aggregating enable/disable of components. 470 static class PendingPackageBroadcasts { 471 // for each user id, a map of <package name -> components within that package> 472 final SparseArray<HashMap<String, ArrayList<String>>> mUidMap; 473 474 public PendingPackageBroadcasts() { 475 mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2); 476 } 477 478 public ArrayList<String> get(int userId, String packageName) { 479 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 480 return packages.get(packageName); 481 } 482 483 public void put(int userId, String packageName, ArrayList<String> components) { 484 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 485 packages.put(packageName, components); 486 } 487 488 public void remove(int userId, String packageName) { 489 HashMap<String, ArrayList<String>> packages = mUidMap.get(userId); 490 if (packages != null) { 491 packages.remove(packageName); 492 } 493 } 494 495 public void remove(int userId) { 496 mUidMap.remove(userId); 497 } 498 499 public int userIdCount() { 500 return mUidMap.size(); 501 } 502 503 public int userIdAt(int n) { 504 return mUidMap.keyAt(n); 505 } 506 507 public HashMap<String, ArrayList<String>> packagesForUserId(int userId) { 508 return mUidMap.get(userId); 509 } 510 511 public int size() { 512 // total number of pending broadcast entries across all userIds 513 int num = 0; 514 for (int i = 0; i< mUidMap.size(); i++) { 515 num += mUidMap.valueAt(i).size(); 516 } 517 return num; 518 } 519 520 public void clear() { 521 mUidMap.clear(); 522 } 523 524 private HashMap<String, ArrayList<String>> getOrAllocate(int userId) { 525 HashMap<String, ArrayList<String>> map = mUidMap.get(userId); 526 if (map == null) { 527 map = new HashMap<String, ArrayList<String>>(); 528 mUidMap.put(userId, map); 529 } 530 return map; 531 } 532 } 533 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 534 535 // Service Connection to remote media container service to copy 536 // package uri's from external media onto secure containers 537 // or internal storage. 538 private IMediaContainerService mContainerService = null; 539 540 static final int SEND_PENDING_BROADCAST = 1; 541 static final int MCS_BOUND = 3; 542 static final int END_COPY = 4; 543 static final int INIT_COPY = 5; 544 static final int MCS_UNBIND = 6; 545 static final int START_CLEANING_PACKAGE = 7; 546 static final int FIND_INSTALL_LOC = 8; 547 static final int POST_INSTALL = 9; 548 static final int MCS_RECONNECT = 10; 549 static final int MCS_GIVE_UP = 11; 550 static final int UPDATED_MEDIA_STATUS = 12; 551 static final int WRITE_SETTINGS = 13; 552 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 553 static final int PACKAGE_VERIFIED = 15; 554 static final int CHECK_PENDING_VERIFICATION = 16; 555 556 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 557 558 // Delay time in millisecs 559 static final int BROADCAST_DELAY = 10 * 1000; 560 561 static UserManagerService sUserManager; 562 563 // Stores a list of users whose package restrictions file needs to be updated 564 private HashSet<Integer> mDirtyUsers = new HashSet<Integer>(); 565 566 final private DefaultContainerConnection mDefContainerConn = 567 new DefaultContainerConnection(); 568 class DefaultContainerConnection implements ServiceConnection { 569 public void onServiceConnected(ComponentName name, IBinder service) { 570 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 571 IMediaContainerService imcs = 572 IMediaContainerService.Stub.asInterface(service); 573 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 574 } 575 576 public void onServiceDisconnected(ComponentName name) { 577 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 578 } 579 }; 580 581 // Recordkeeping of restore-after-install operations that are currently in flight 582 // between the Package Manager and the Backup Manager 583 class PostInstallData { 584 public InstallArgs args; 585 public PackageInstalledInfo res; 586 587 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 588 args = _a; 589 res = _r; 590 } 591 }; 592 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 593 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 594 595 private final String mRequiredVerifierPackage; 596 597 private final PackageUsage mPackageUsage = new PackageUsage(); 598 599 private class PackageUsage { 600 private static final int WRITE_INTERVAL 601 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 602 603 private final Object mFileLock = new Object(); 604 private final AtomicLong mLastWritten = new AtomicLong(0); 605 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 606 607 private boolean mIsHistoricalPackageUsageAvailable = true; 608 609 boolean isHistoricalPackageUsageAvailable() { 610 return mIsHistoricalPackageUsageAvailable; 611 } 612 613 void write(boolean force) { 614 if (force) { 615 writeInternal(); 616 return; 617 } 618 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 619 && !DEBUG_DEXOPT) { 620 return; 621 } 622 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 623 new Thread("PackageUsage_DiskWriter") { 624 @Override 625 public void run() { 626 try { 627 writeInternal(); 628 } finally { 629 mBackgroundWriteRunning.set(false); 630 } 631 } 632 }.start(); 633 } 634 } 635 636 private void writeInternal() { 637 synchronized (mPackages) { 638 synchronized (mFileLock) { 639 AtomicFile file = getFile(); 640 FileOutputStream f = null; 641 try { 642 f = file.startWrite(); 643 BufferedOutputStream out = new BufferedOutputStream(f); 644 FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID); 645 StringBuilder sb = new StringBuilder(); 646 for (PackageParser.Package pkg : mPackages.values()) { 647 if (pkg.mLastPackageUsageTimeInMills == 0) { 648 continue; 649 } 650 sb.setLength(0); 651 sb.append(pkg.packageName); 652 sb.append(' '); 653 sb.append((long)pkg.mLastPackageUsageTimeInMills); 654 sb.append('\n'); 655 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 656 } 657 out.flush(); 658 file.finishWrite(f); 659 } catch (IOException e) { 660 if (f != null) { 661 file.failWrite(f); 662 } 663 Log.e(TAG, "Failed to write package usage times", e); 664 } 665 } 666 } 667 mLastWritten.set(SystemClock.elapsedRealtime()); 668 } 669 670 void readLP() { 671 synchronized (mFileLock) { 672 AtomicFile file = getFile(); 673 BufferedInputStream in = null; 674 try { 675 in = new BufferedInputStream(file.openRead()); 676 StringBuffer sb = new StringBuffer(); 677 while (true) { 678 String packageName = readToken(in, sb, ' '); 679 if (packageName == null) { 680 break; 681 } 682 String timeInMillisString = readToken(in, sb, '\n'); 683 if (timeInMillisString == null) { 684 throw new IOException("Failed to find last usage time for package " 685 + packageName); 686 } 687 PackageParser.Package pkg = mPackages.get(packageName); 688 if (pkg == null) { 689 continue; 690 } 691 long timeInMillis; 692 try { 693 timeInMillis = Long.parseLong(timeInMillisString.toString()); 694 } catch (NumberFormatException e) { 695 throw new IOException("Failed to parse " + timeInMillisString 696 + " as a long.", e); 697 } 698 pkg.mLastPackageUsageTimeInMills = timeInMillis; 699 } 700 } catch (FileNotFoundException expected) { 701 mIsHistoricalPackageUsageAvailable = false; 702 } catch (IOException e) { 703 Log.w(TAG, "Failed to read package usage times", e); 704 } finally { 705 IoUtils.closeQuietly(in); 706 } 707 } 708 mLastWritten.set(SystemClock.elapsedRealtime()); 709 } 710 711 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 712 throws IOException { 713 sb.setLength(0); 714 while (true) { 715 int ch = in.read(); 716 if (ch == -1) { 717 if (sb.length() == 0) { 718 return null; 719 } 720 throw new IOException("Unexpected EOF"); 721 } 722 if (ch == endOfToken) { 723 return sb.toString(); 724 } 725 sb.append((char)ch); 726 } 727 } 728 729 private AtomicFile getFile() { 730 File dataDir = Environment.getDataDirectory(); 731 File systemDir = new File(dataDir, "system"); 732 File fname = new File(systemDir, "package-usage.list"); 733 return new AtomicFile(fname); 734 } 735 } 736 737 class PackageHandler extends Handler { 738 private boolean mBound = false; 739 final ArrayList<HandlerParams> mPendingInstalls = 740 new ArrayList<HandlerParams>(); 741 742 private boolean connectToService() { 743 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 744 " DefaultContainerService"); 745 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 746 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 747 if (mContext.bindServiceAsUser(service, mDefContainerConn, 748 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 749 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 750 mBound = true; 751 return true; 752 } 753 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 754 return false; 755 } 756 757 private void disconnectService() { 758 mContainerService = null; 759 mBound = false; 760 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 761 mContext.unbindService(mDefContainerConn); 762 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 763 } 764 765 PackageHandler(Looper looper) { 766 super(looper); 767 } 768 769 public void handleMessage(Message msg) { 770 try { 771 doHandleMessage(msg); 772 } finally { 773 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 774 } 775 } 776 777 void doHandleMessage(Message msg) { 778 switch (msg.what) { 779 case INIT_COPY: { 780 HandlerParams params = (HandlerParams) msg.obj; 781 int idx = mPendingInstalls.size(); 782 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 783 // If a bind was already initiated we dont really 784 // need to do anything. The pending install 785 // will be processed later on. 786 if (!mBound) { 787 // If this is the only one pending we might 788 // have to bind to the service again. 789 if (!connectToService()) { 790 Slog.e(TAG, "Failed to bind to media container service"); 791 params.serviceError(); 792 return; 793 } else { 794 // Once we bind to the service, the first 795 // pending request will be processed. 796 mPendingInstalls.add(idx, params); 797 } 798 } else { 799 mPendingInstalls.add(idx, params); 800 // Already bound to the service. Just make 801 // sure we trigger off processing the first request. 802 if (idx == 0) { 803 mHandler.sendEmptyMessage(MCS_BOUND); 804 } 805 } 806 break; 807 } 808 case MCS_BOUND: { 809 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 810 if (msg.obj != null) { 811 mContainerService = (IMediaContainerService) msg.obj; 812 } 813 if (mContainerService == null) { 814 // Something seriously wrong. Bail out 815 Slog.e(TAG, "Cannot bind to media container service"); 816 for (HandlerParams params : mPendingInstalls) { 817 // Indicate service bind error 818 params.serviceError(); 819 } 820 mPendingInstalls.clear(); 821 } else if (mPendingInstalls.size() > 0) { 822 HandlerParams params = mPendingInstalls.get(0); 823 if (params != null) { 824 if (params.startCopy()) { 825 // We are done... look for more work or to 826 // go idle. 827 if (DEBUG_SD_INSTALL) Log.i(TAG, 828 "Checking for more work or unbind..."); 829 // Delete pending install 830 if (mPendingInstalls.size() > 0) { 831 mPendingInstalls.remove(0); 832 } 833 if (mPendingInstalls.size() == 0) { 834 if (mBound) { 835 if (DEBUG_SD_INSTALL) Log.i(TAG, 836 "Posting delayed MCS_UNBIND"); 837 removeMessages(MCS_UNBIND); 838 Message ubmsg = obtainMessage(MCS_UNBIND); 839 // Unbind after a little delay, to avoid 840 // continual thrashing. 841 sendMessageDelayed(ubmsg, 10000); 842 } 843 } else { 844 // There are more pending requests in queue. 845 // Just post MCS_BOUND message to trigger processing 846 // of next pending install. 847 if (DEBUG_SD_INSTALL) Log.i(TAG, 848 "Posting MCS_BOUND for next work"); 849 mHandler.sendEmptyMessage(MCS_BOUND); 850 } 851 } 852 } 853 } else { 854 // Should never happen ideally. 855 Slog.w(TAG, "Empty queue"); 856 } 857 break; 858 } 859 case MCS_RECONNECT: { 860 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 861 if (mPendingInstalls.size() > 0) { 862 if (mBound) { 863 disconnectService(); 864 } 865 if (!connectToService()) { 866 Slog.e(TAG, "Failed to bind to media container service"); 867 for (HandlerParams params : mPendingInstalls) { 868 // Indicate service bind error 869 params.serviceError(); 870 } 871 mPendingInstalls.clear(); 872 } 873 } 874 break; 875 } 876 case MCS_UNBIND: { 877 // If there is no actual work left, then time to unbind. 878 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 879 880 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 881 if (mBound) { 882 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 883 884 disconnectService(); 885 } 886 } else if (mPendingInstalls.size() > 0) { 887 // There are more pending requests in queue. 888 // Just post MCS_BOUND message to trigger processing 889 // of next pending install. 890 mHandler.sendEmptyMessage(MCS_BOUND); 891 } 892 893 break; 894 } 895 case MCS_GIVE_UP: { 896 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 897 mPendingInstalls.remove(0); 898 break; 899 } 900 case SEND_PENDING_BROADCAST: { 901 String packages[]; 902 ArrayList<String> components[]; 903 int size = 0; 904 int uids[]; 905 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 906 synchronized (mPackages) { 907 if (mPendingBroadcasts == null) { 908 return; 909 } 910 size = mPendingBroadcasts.size(); 911 if (size <= 0) { 912 // Nothing to be done. Just return 913 return; 914 } 915 packages = new String[size]; 916 components = new ArrayList[size]; 917 uids = new int[size]; 918 int i = 0; // filling out the above arrays 919 920 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 921 int packageUserId = mPendingBroadcasts.userIdAt(n); 922 Iterator<Map.Entry<String, ArrayList<String>>> it 923 = mPendingBroadcasts.packagesForUserId(packageUserId) 924 .entrySet().iterator(); 925 while (it.hasNext() && i < size) { 926 Map.Entry<String, ArrayList<String>> ent = it.next(); 927 packages[i] = ent.getKey(); 928 components[i] = ent.getValue(); 929 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 930 uids[i] = (ps != null) 931 ? UserHandle.getUid(packageUserId, ps.appId) 932 : -1; 933 i++; 934 } 935 } 936 size = i; 937 mPendingBroadcasts.clear(); 938 } 939 // Send broadcasts 940 for (int i = 0; i < size; i++) { 941 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 942 } 943 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 944 break; 945 } 946 case START_CLEANING_PACKAGE: { 947 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 948 final String packageName = (String)msg.obj; 949 final int userId = msg.arg1; 950 final boolean andCode = msg.arg2 != 0; 951 synchronized (mPackages) { 952 if (userId == UserHandle.USER_ALL) { 953 int[] users = sUserManager.getUserIds(); 954 for (int user : users) { 955 mSettings.addPackageToCleanLPw( 956 new PackageCleanItem(user, packageName, andCode)); 957 } 958 } else { 959 mSettings.addPackageToCleanLPw( 960 new PackageCleanItem(userId, packageName, andCode)); 961 } 962 } 963 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 964 startCleaningPackages(); 965 } break; 966 case POST_INSTALL: { 967 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 968 PostInstallData data = mRunningInstalls.get(msg.arg1); 969 mRunningInstalls.delete(msg.arg1); 970 boolean deleteOld = false; 971 972 if (data != null) { 973 InstallArgs args = data.args; 974 PackageInstalledInfo res = data.res; 975 976 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 977 res.removedInfo.sendBroadcast(false, true, false); 978 Bundle extras = new Bundle(1); 979 extras.putInt(Intent.EXTRA_UID, res.uid); 980 // Determine the set of users who are adding this 981 // package for the first time vs. those who are seeing 982 // an update. 983 int[] firstUsers; 984 int[] updateUsers = new int[0]; 985 if (res.origUsers == null || res.origUsers.length == 0) { 986 firstUsers = res.newUsers; 987 } else { 988 firstUsers = new int[0]; 989 for (int i=0; i<res.newUsers.length; i++) { 990 int user = res.newUsers[i]; 991 boolean isNew = true; 992 for (int j=0; j<res.origUsers.length; j++) { 993 if (res.origUsers[j] == user) { 994 isNew = false; 995 break; 996 } 997 } 998 if (isNew) { 999 int[] newFirst = new int[firstUsers.length+1]; 1000 System.arraycopy(firstUsers, 0, newFirst, 0, 1001 firstUsers.length); 1002 newFirst[firstUsers.length] = user; 1003 firstUsers = newFirst; 1004 } else { 1005 int[] newUpdate = new int[updateUsers.length+1]; 1006 System.arraycopy(updateUsers, 0, newUpdate, 0, 1007 updateUsers.length); 1008 newUpdate[updateUsers.length] = user; 1009 updateUsers = newUpdate; 1010 } 1011 } 1012 } 1013 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1014 res.pkg.applicationInfo.packageName, 1015 extras, null, null, firstUsers); 1016 final boolean update = res.removedInfo.removedPackage != null; 1017 if (update) { 1018 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1019 } 1020 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1021 res.pkg.applicationInfo.packageName, 1022 extras, null, null, updateUsers); 1023 if (update) { 1024 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1025 res.pkg.applicationInfo.packageName, 1026 extras, null, null, updateUsers); 1027 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1028 null, null, 1029 res.pkg.applicationInfo.packageName, null, updateUsers); 1030 1031 // treat asec-hosted packages like removable media on upgrade 1032 if (isForwardLocked(res.pkg) || isExternal(res.pkg)) { 1033 if (DEBUG_INSTALL) { 1034 Slog.i(TAG, "upgrading pkg " + res.pkg 1035 + " is ASEC-hosted -> AVAILABLE"); 1036 } 1037 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1038 ArrayList<String> pkgList = new ArrayList<String>(1); 1039 pkgList.add(res.pkg.applicationInfo.packageName); 1040 sendResourcesChangedBroadcast(true, true, 1041 pkgList,uidArray, null); 1042 } 1043 } 1044 if (res.removedInfo.args != null) { 1045 // Remove the replaced package's older resources safely now 1046 deleteOld = true; 1047 } 1048 1049 // Log current value of "unknown sources" setting 1050 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1051 getUnknownSourcesSettings()); 1052 } 1053 // Force a gc to clear up things 1054 Runtime.getRuntime().gc(); 1055 // We delete after a gc for applications on sdcard. 1056 if (deleteOld) { 1057 synchronized (mInstallLock) { 1058 res.removedInfo.args.doPostDeleteLI(true); 1059 } 1060 } 1061 if (args.observer != null) { 1062 try { 1063 Bundle extras = extrasForInstallResult(res); 1064 args.observer.onPackageInstalled(res.name, res.returnCode, 1065 res.returnMsg, extras); 1066 } catch (RemoteException e) { 1067 Slog.i(TAG, "Observer no longer exists."); 1068 } 1069 } 1070 } else { 1071 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1072 } 1073 } break; 1074 case UPDATED_MEDIA_STATUS: { 1075 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1076 boolean reportStatus = msg.arg1 == 1; 1077 boolean doGc = msg.arg2 == 1; 1078 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1079 if (doGc) { 1080 // Force a gc to clear up stale containers. 1081 Runtime.getRuntime().gc(); 1082 } 1083 if (msg.obj != null) { 1084 @SuppressWarnings("unchecked") 1085 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1086 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1087 // Unload containers 1088 unloadAllContainers(args); 1089 } 1090 if (reportStatus) { 1091 try { 1092 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1093 PackageHelper.getMountService().finishMediaUpdate(); 1094 } catch (RemoteException e) { 1095 Log.e(TAG, "MountService not running?"); 1096 } 1097 } 1098 } break; 1099 case WRITE_SETTINGS: { 1100 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1101 synchronized (mPackages) { 1102 removeMessages(WRITE_SETTINGS); 1103 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1104 mSettings.writeLPr(); 1105 mDirtyUsers.clear(); 1106 } 1107 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1108 } break; 1109 case WRITE_PACKAGE_RESTRICTIONS: { 1110 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1111 synchronized (mPackages) { 1112 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1113 for (int userId : mDirtyUsers) { 1114 mSettings.writePackageRestrictionsLPr(userId); 1115 } 1116 mDirtyUsers.clear(); 1117 } 1118 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1119 } break; 1120 case CHECK_PENDING_VERIFICATION: { 1121 final int verificationId = msg.arg1; 1122 final PackageVerificationState state = mPendingVerification.get(verificationId); 1123 1124 if ((state != null) && !state.timeoutExtended()) { 1125 final InstallArgs args = state.getInstallArgs(); 1126 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1127 1128 Slog.i(TAG, "Verification timed out for " + originUri); 1129 mPendingVerification.remove(verificationId); 1130 1131 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1132 1133 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1134 Slog.i(TAG, "Continuing with installation of " + originUri); 1135 state.setVerifierResponse(Binder.getCallingUid(), 1136 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1137 broadcastPackageVerified(verificationId, originUri, 1138 PackageManager.VERIFICATION_ALLOW, 1139 state.getInstallArgs().getUser()); 1140 try { 1141 ret = args.copyApk(mContainerService, true); 1142 } catch (RemoteException e) { 1143 Slog.e(TAG, "Could not contact the ContainerService"); 1144 } 1145 } else { 1146 broadcastPackageVerified(verificationId, originUri, 1147 PackageManager.VERIFICATION_REJECT, 1148 state.getInstallArgs().getUser()); 1149 } 1150 1151 processPendingInstall(args, ret); 1152 mHandler.sendEmptyMessage(MCS_UNBIND); 1153 } 1154 break; 1155 } 1156 case PACKAGE_VERIFIED: { 1157 final int verificationId = msg.arg1; 1158 1159 final PackageVerificationState state = mPendingVerification.get(verificationId); 1160 if (state == null) { 1161 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1162 break; 1163 } 1164 1165 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1166 1167 state.setVerifierResponse(response.callerUid, response.code); 1168 1169 if (state.isVerificationComplete()) { 1170 mPendingVerification.remove(verificationId); 1171 1172 final InstallArgs args = state.getInstallArgs(); 1173 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1174 1175 int ret; 1176 if (state.isInstallAllowed()) { 1177 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1178 broadcastPackageVerified(verificationId, originUri, 1179 response.code, state.getInstallArgs().getUser()); 1180 try { 1181 ret = args.copyApk(mContainerService, true); 1182 } catch (RemoteException e) { 1183 Slog.e(TAG, "Could not contact the ContainerService"); 1184 } 1185 } else { 1186 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1187 } 1188 1189 processPendingInstall(args, ret); 1190 1191 mHandler.sendEmptyMessage(MCS_UNBIND); 1192 } 1193 1194 break; 1195 } 1196 } 1197 } 1198 } 1199 1200 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1201 Bundle extras = null; 1202 switch (res.returnCode) { 1203 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1204 extras = new Bundle(); 1205 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1206 res.origPermission); 1207 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1208 res.origPackage); 1209 break; 1210 } 1211 } 1212 return extras; 1213 } 1214 1215 void scheduleWriteSettingsLocked() { 1216 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1217 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1218 } 1219 } 1220 1221 void scheduleWritePackageRestrictionsLocked(int userId) { 1222 if (!sUserManager.exists(userId)) return; 1223 mDirtyUsers.add(userId); 1224 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1225 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1226 } 1227 } 1228 1229 public static final PackageManagerService main(Context context, Installer installer, 1230 boolean factoryTest, boolean onlyCore) { 1231 PackageManagerService m = new PackageManagerService(context, installer, 1232 factoryTest, onlyCore); 1233 ServiceManager.addService("package", m); 1234 return m; 1235 } 1236 1237 static String[] splitString(String str, char sep) { 1238 int count = 1; 1239 int i = 0; 1240 while ((i=str.indexOf(sep, i)) >= 0) { 1241 count++; 1242 i++; 1243 } 1244 1245 String[] res = new String[count]; 1246 i=0; 1247 count = 0; 1248 int lastI=0; 1249 while ((i=str.indexOf(sep, i)) >= 0) { 1250 res[count] = str.substring(lastI, i); 1251 count++; 1252 i++; 1253 lastI = i; 1254 } 1255 res[count] = str.substring(lastI, str.length()); 1256 return res; 1257 } 1258 1259 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1260 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1261 Context.DISPLAY_SERVICE); 1262 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1263 } 1264 1265 public PackageManagerService(Context context, Installer installer, 1266 boolean factoryTest, boolean onlyCore) { 1267 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1268 SystemClock.uptimeMillis()); 1269 1270 if (mSdkVersion <= 0) { 1271 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1272 } 1273 1274 mContext = context; 1275 mFactoryTest = factoryTest; 1276 mOnlyCore = onlyCore; 1277 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1278 mMetrics = new DisplayMetrics(); 1279 mSettings = new Settings(context); 1280 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1281 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1282 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1283 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1284 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1285 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1286 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1287 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1288 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1289 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1290 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1291 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1292 1293 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1294 if (separateProcesses != null && separateProcesses.length() > 0) { 1295 if ("*".equals(separateProcesses)) { 1296 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1297 mSeparateProcesses = null; 1298 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1299 } else { 1300 mDefParseFlags = 0; 1301 mSeparateProcesses = separateProcesses.split(","); 1302 Slog.w(TAG, "Running with debug.separate_processes: " 1303 + separateProcesses); 1304 } 1305 } else { 1306 mDefParseFlags = 0; 1307 mSeparateProcesses = null; 1308 } 1309 1310 mInstaller = installer; 1311 1312 getDefaultDisplayMetrics(context, mMetrics); 1313 1314 SystemConfig systemConfig = SystemConfig.getInstance(); 1315 mGlobalGids = systemConfig.getGlobalGids(); 1316 mSystemPermissions = systemConfig.getSystemPermissions(); 1317 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1318 1319 synchronized (mInstallLock) { 1320 // writer 1321 synchronized (mPackages) { 1322 mHandlerThread = new ServiceThread(TAG, 1323 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1324 mHandlerThread.start(); 1325 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1326 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1327 1328 File dataDir = Environment.getDataDirectory(); 1329 mAppDataDir = new File(dataDir, "data"); 1330 mAppInstallDir = new File(dataDir, "app"); 1331 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1332 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1333 mUserAppDataDir = new File(dataDir, "user"); 1334 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1335 1336 sUserManager = new UserManagerService(context, this, 1337 mInstallLock, mPackages); 1338 1339 // Propagate permission configuration in to package manager. 1340 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1341 = systemConfig.getPermissions(); 1342 for (int i=0; i<permConfig.size(); i++) { 1343 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1344 BasePermission bp = mSettings.mPermissions.get(perm.name); 1345 if (bp == null) { 1346 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1347 mSettings.mPermissions.put(perm.name, bp); 1348 } 1349 if (perm.gids != null) { 1350 bp.gids = appendInts(bp.gids, perm.gids); 1351 } 1352 } 1353 1354 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1355 for (int i=0; i<libConfig.size(); i++) { 1356 mSharedLibraries.put(libConfig.keyAt(i), 1357 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1358 } 1359 1360 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1361 1362 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1363 mSdkVersion, mOnlyCore); 1364 1365 String customResolverActivity = Resources.getSystem().getString( 1366 R.string.config_customResolverActivity); 1367 if (TextUtils.isEmpty(customResolverActivity)) { 1368 customResolverActivity = null; 1369 } else { 1370 mCustomResolverComponentName = ComponentName.unflattenFromString( 1371 customResolverActivity); 1372 } 1373 1374 long startTime = SystemClock.uptimeMillis(); 1375 1376 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1377 startTime); 1378 1379 // Set flag to monitor and not change apk file paths when 1380 // scanning install directories. 1381 int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1382 1383 final HashSet<String> alreadyDexOpted = new HashSet<String>(); 1384 1385 /** 1386 * Add everything in the in the boot class path to the 1387 * list of process files because dexopt will have been run 1388 * if necessary during zygote startup. 1389 */ 1390 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1391 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1392 1393 if (bootClassPath != null) { 1394 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1395 for (String element : bootClassPathElements) { 1396 alreadyDexOpted.add(element); 1397 } 1398 } else { 1399 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1400 } 1401 1402 if (systemServerClassPath != null) { 1403 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1404 for (String element : systemServerClassPathElements) { 1405 alreadyDexOpted.add(element); 1406 } 1407 } else { 1408 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1409 } 1410 1411 boolean didDexOptLibraryOrTool = false; 1412 1413 final List<String> allInstructionSets = getAllInstructionSets(); 1414 final String[] dexCodeInstructionSets = 1415 getDexCodeInstructionSets(allInstructionSets.toArray(new String[allInstructionSets.size()])); 1416 1417 /** 1418 * Ensure all external libraries have had dexopt run on them. 1419 */ 1420 if (mSharedLibraries.size() > 0) { 1421 // NOTE: For now, we're compiling these system "shared libraries" 1422 // (and framework jars) into all available architectures. It's possible 1423 // to compile them only when we come across an app that uses them (there's 1424 // already logic for that in scanPackageLI) but that adds some complexity. 1425 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1426 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1427 final String lib = libEntry.path; 1428 if (lib == null) { 1429 continue; 1430 } 1431 1432 try { 1433 byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null, 1434 dexCodeInstructionSet, 1435 false); 1436 if (dexoptRequired != DexFile.UP_TO_DATE) { 1437 alreadyDexOpted.add(lib); 1438 1439 // The list of "shared libraries" we have at this point is 1440 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1441 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1442 } else { 1443 mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1444 } 1445 didDexOptLibraryOrTool = true; 1446 } 1447 } catch (FileNotFoundException e) { 1448 Slog.w(TAG, "Library not found: " + lib); 1449 } catch (IOException e) { 1450 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1451 + e.getMessage()); 1452 } 1453 } 1454 } 1455 } 1456 1457 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1458 1459 // Gross hack for now: we know this file doesn't contain any 1460 // code, so don't dexopt it to avoid the resulting log spew. 1461 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1462 1463 // Gross hack for now: we know this file is only part of 1464 // the boot class path for art, so don't dexopt it to 1465 // avoid the resulting log spew. 1466 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1467 1468 /** 1469 * And there are a number of commands implemented in Java, which 1470 * we currently need to do the dexopt on so that they can be 1471 * run from a non-root shell. 1472 */ 1473 String[] frameworkFiles = frameworkDir.list(); 1474 if (frameworkFiles != null) { 1475 // TODO: We could compile these only for the most preferred ABI. We should 1476 // first double check that the dex files for these commands are not referenced 1477 // by other system apps. 1478 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1479 for (int i=0; i<frameworkFiles.length; i++) { 1480 File libPath = new File(frameworkDir, frameworkFiles[i]); 1481 String path = libPath.getPath(); 1482 // Skip the file if we already did it. 1483 if (alreadyDexOpted.contains(path)) { 1484 continue; 1485 } 1486 // Skip the file if it is not a type we want to dexopt. 1487 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1488 continue; 1489 } 1490 try { 1491 byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null, 1492 dexCodeInstructionSet, 1493 false); 1494 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1495 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1496 didDexOptLibraryOrTool = true; 1497 } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) { 1498 mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1499 didDexOptLibraryOrTool = true; 1500 } 1501 } catch (FileNotFoundException e) { 1502 Slog.w(TAG, "Jar not found: " + path); 1503 } catch (IOException e) { 1504 Slog.w(TAG, "Exception reading jar: " + path, e); 1505 } 1506 } 1507 } 1508 } 1509 1510 // Collect vendor overlay packages. 1511 // (Do this before scanning any apps.) 1512 // For security and version matching reason, only consider 1513 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1514 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1515 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1516 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1517 1518 // Find base frameworks (resource packages without code). 1519 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1520 | PackageParser.PARSE_IS_SYSTEM_DIR 1521 | PackageParser.PARSE_IS_PRIVILEGED, 1522 scanFlags | SCAN_NO_DEX, 0); 1523 1524 // Collected privileged system packages. 1525 File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1526 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1527 | PackageParser.PARSE_IS_SYSTEM_DIR 1528 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1529 1530 // Collect ordinary system packages. 1531 File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1532 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1533 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1534 1535 // Collect all vendor packages. 1536 File vendorAppDir = new File("/vendor/app"); 1537 try { 1538 vendorAppDir = vendorAppDir.getCanonicalFile(); 1539 } catch (IOException e) { 1540 // failed to look up canonical path, continue with original one 1541 } 1542 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1543 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1544 1545 // Collect all OEM packages. 1546 File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1547 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1548 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1549 1550 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1551 mInstaller.moveFiles(); 1552 1553 // Prune any system packages that no longer exist. 1554 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1555 if (!mOnlyCore) { 1556 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1557 while (psit.hasNext()) { 1558 PackageSetting ps = psit.next(); 1559 1560 /* 1561 * If this is not a system app, it can't be a 1562 * disable system app. 1563 */ 1564 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1565 continue; 1566 } 1567 1568 /* 1569 * If the package is scanned, it's not erased. 1570 */ 1571 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1572 if (scannedPkg != null) { 1573 /* 1574 * If the system app is both scanned and in the 1575 * disabled packages list, then it must have been 1576 * added via OTA. Remove it from the currently 1577 * scanned package so the previously user-installed 1578 * application can be scanned. 1579 */ 1580 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1581 Slog.i(TAG, "Expecting better updatd system app for " + ps.name 1582 + "; removing system app"); 1583 removePackageLI(ps, true); 1584 } 1585 1586 continue; 1587 } 1588 1589 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1590 psit.remove(); 1591 String msg = "System package " + ps.name 1592 + " no longer exists; wiping its data"; 1593 reportSettingsProblem(Log.WARN, msg); 1594 removeDataDirsLI(ps.name); 1595 } else { 1596 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1597 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1598 possiblyDeletedUpdatedSystemApps.add(ps.name); 1599 } 1600 } 1601 } 1602 } 1603 1604 //look for any incomplete package installations 1605 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1606 //clean up list 1607 for(int i = 0; i < deletePkgsList.size(); i++) { 1608 //clean up here 1609 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1610 } 1611 //delete tmp files 1612 deleteTempPackageFiles(); 1613 1614 // Remove any shared userIDs that have no associated packages 1615 mSettings.pruneSharedUsersLPw(); 1616 1617 if (!mOnlyCore) { 1618 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 1619 SystemClock.uptimeMillis()); 1620 scanDirLI(mAppInstallDir, 0, scanFlags, 0); 1621 1622 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 1623 scanFlags, 0); 1624 1625 /** 1626 * Remove disable package settings for any updated system 1627 * apps that were removed via an OTA. If they're not a 1628 * previously-updated app, remove them completely. 1629 * Otherwise, just revoke their system-level permissions. 1630 */ 1631 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 1632 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 1633 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 1634 1635 String msg; 1636 if (deletedPkg == null) { 1637 msg = "Updated system package " + deletedAppName 1638 + " no longer exists; wiping its data"; 1639 removeDataDirsLI(deletedAppName); 1640 } else { 1641 msg = "Updated system app + " + deletedAppName 1642 + " no longer present; removing system privileges for " 1643 + deletedAppName; 1644 1645 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 1646 1647 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 1648 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 1649 } 1650 reportSettingsProblem(Log.WARN, msg); 1651 } 1652 } 1653 1654 // Now that we know all of the shared libraries, update all clients to have 1655 // the correct library paths. 1656 updateAllSharedLibrariesLPw(); 1657 1658 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 1659 // NOTE: We ignore potential failures here during a system scan (like 1660 // the rest of the commands above) because there's precious little we 1661 // can do about it. A settings error is reported, though. 1662 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 1663 false /* force dexopt */, false /* defer dexopt */); 1664 } 1665 1666 // Now that we know all the packages we are keeping, 1667 // read and update their last usage times. 1668 mPackageUsage.readLP(); 1669 1670 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 1671 SystemClock.uptimeMillis()); 1672 Slog.i(TAG, "Time to scan packages: " 1673 + ((SystemClock.uptimeMillis()-startTime)/1000f) 1674 + " seconds"); 1675 1676 // If the platform SDK has changed since the last time we booted, 1677 // we need to re-grant app permission to catch any new ones that 1678 // appear. This is really a hack, and means that apps can in some 1679 // cases get permissions that the user didn't initially explicitly 1680 // allow... it would be nice to have some better way to handle 1681 // this situation. 1682 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 1683 != mSdkVersion; 1684 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 1685 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 1686 + "; regranting permissions for internal storage"); 1687 mSettings.mInternalSdkPlatform = mSdkVersion; 1688 1689 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 1690 | (regrantPermissions 1691 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 1692 : 0)); 1693 1694 // If this is the first boot, and it is a normal boot, then 1695 // we need to initialize the default preferred apps. 1696 if (!mRestoredSettings && !onlyCore) { 1697 mSettings.readDefaultPreferredAppsLPw(this, 0); 1698 } 1699 1700 // If this is first boot after an OTA, and a normal boot, then 1701 // we need to clear code cache directories. 1702 if (!Build.FINGERPRINT.equals(mSettings.mFingerprint) && !onlyCore) { 1703 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 1704 for (String pkgName : mSettings.mPackages.keySet()) { 1705 deleteCodeCacheDirsLI(pkgName); 1706 } 1707 mSettings.mFingerprint = Build.FINGERPRINT; 1708 } 1709 1710 // All the changes are done during package scanning. 1711 mSettings.updateInternalDatabaseVersion(); 1712 1713 // can downgrade to reader 1714 mSettings.writeLPr(); 1715 1716 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 1717 SystemClock.uptimeMillis()); 1718 1719 1720 mRequiredVerifierPackage = getRequiredVerifierLPr(); 1721 } // synchronized (mPackages) 1722 } // synchronized (mInstallLock) 1723 1724 mInstallerService = new PackageInstallerService(context, this, mAppInstallDir); 1725 1726 // Now after opening every single application zip, make sure they 1727 // are all flushed. Not really needed, but keeps things nice and 1728 // tidy. 1729 Runtime.getRuntime().gc(); 1730 } 1731 1732 @Override 1733 public boolean isFirstBoot() { 1734 return !mRestoredSettings; 1735 } 1736 1737 @Override 1738 public boolean isOnlyCoreApps() { 1739 return mOnlyCore; 1740 } 1741 1742 private String getRequiredVerifierLPr() { 1743 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 1744 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 1745 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 1746 1747 String requiredVerifier = null; 1748 1749 final int N = receivers.size(); 1750 for (int i = 0; i < N; i++) { 1751 final ResolveInfo info = receivers.get(i); 1752 1753 if (info.activityInfo == null) { 1754 continue; 1755 } 1756 1757 final String packageName = info.activityInfo.packageName; 1758 1759 final PackageSetting ps = mSettings.mPackages.get(packageName); 1760 if (ps == null) { 1761 continue; 1762 } 1763 1764 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1765 if (!gp.grantedPermissions 1766 .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) { 1767 continue; 1768 } 1769 1770 if (requiredVerifier != null) { 1771 throw new RuntimeException("There can be only one required verifier"); 1772 } 1773 1774 requiredVerifier = packageName; 1775 } 1776 1777 return requiredVerifier; 1778 } 1779 1780 @Override 1781 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 1782 throws RemoteException { 1783 try { 1784 return super.onTransact(code, data, reply, flags); 1785 } catch (RuntimeException e) { 1786 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 1787 Slog.wtf(TAG, "Package Manager Crash", e); 1788 } 1789 throw e; 1790 } 1791 } 1792 1793 void cleanupInstallFailedPackage(PackageSetting ps) { 1794 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name); 1795 removeDataDirsLI(ps.name); 1796 1797 // TODO: try cleaning up codePath directory contents first, since it 1798 // might be a cluster 1799 1800 if (ps.codePath != null) { 1801 if (!ps.codePath.delete()) { 1802 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath); 1803 } 1804 } 1805 if (ps.resourcePath != null) { 1806 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) { 1807 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath); 1808 } 1809 } 1810 mSettings.removePackageLPw(ps.name); 1811 } 1812 1813 static int[] appendInts(int[] cur, int[] add) { 1814 if (add == null) return cur; 1815 if (cur == null) return add; 1816 final int N = add.length; 1817 for (int i=0; i<N; i++) { 1818 cur = appendInt(cur, add[i]); 1819 } 1820 return cur; 1821 } 1822 1823 static int[] removeInts(int[] cur, int[] rem) { 1824 if (rem == null) return cur; 1825 if (cur == null) return cur; 1826 final int N = rem.length; 1827 for (int i=0; i<N; i++) { 1828 cur = removeInt(cur, rem[i]); 1829 } 1830 return cur; 1831 } 1832 1833 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 1834 if (!sUserManager.exists(userId)) return null; 1835 final PackageSetting ps = (PackageSetting) p.mExtras; 1836 if (ps == null) { 1837 return null; 1838 } 1839 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1840 final PackageUserState state = ps.readUserState(userId); 1841 return PackageParser.generatePackageInfo(p, gp.gids, flags, 1842 ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions, 1843 state, userId); 1844 } 1845 1846 @Override 1847 public boolean isPackageAvailable(String packageName, int userId) { 1848 if (!sUserManager.exists(userId)) return false; 1849 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 1850 synchronized (mPackages) { 1851 PackageParser.Package p = mPackages.get(packageName); 1852 if (p != null) { 1853 final PackageSetting ps = (PackageSetting) p.mExtras; 1854 if (ps != null) { 1855 final PackageUserState state = ps.readUserState(userId); 1856 if (state != null) { 1857 return PackageParser.isAvailable(state); 1858 } 1859 } 1860 } 1861 } 1862 return false; 1863 } 1864 1865 @Override 1866 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 1867 if (!sUserManager.exists(userId)) return null; 1868 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 1869 // reader 1870 synchronized (mPackages) { 1871 PackageParser.Package p = mPackages.get(packageName); 1872 if (DEBUG_PACKAGE_INFO) 1873 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 1874 if (p != null) { 1875 return generatePackageInfo(p, flags, userId); 1876 } 1877 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 1878 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 1879 } 1880 } 1881 return null; 1882 } 1883 1884 @Override 1885 public String[] currentToCanonicalPackageNames(String[] names) { 1886 String[] out = new String[names.length]; 1887 // reader 1888 synchronized (mPackages) { 1889 for (int i=names.length-1; i>=0; i--) { 1890 PackageSetting ps = mSettings.mPackages.get(names[i]); 1891 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 1892 } 1893 } 1894 return out; 1895 } 1896 1897 @Override 1898 public String[] canonicalToCurrentPackageNames(String[] names) { 1899 String[] out = new String[names.length]; 1900 // reader 1901 synchronized (mPackages) { 1902 for (int i=names.length-1; i>=0; i--) { 1903 String cur = mSettings.mRenamedPackages.get(names[i]); 1904 out[i] = cur != null ? cur : names[i]; 1905 } 1906 } 1907 return out; 1908 } 1909 1910 @Override 1911 public int getPackageUid(String packageName, int userId) { 1912 if (!sUserManager.exists(userId)) return -1; 1913 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 1914 // reader 1915 synchronized (mPackages) { 1916 PackageParser.Package p = mPackages.get(packageName); 1917 if(p != null) { 1918 return UserHandle.getUid(userId, p.applicationInfo.uid); 1919 } 1920 PackageSetting ps = mSettings.mPackages.get(packageName); 1921 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 1922 return -1; 1923 } 1924 p = ps.pkg; 1925 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 1926 } 1927 } 1928 1929 @Override 1930 public int[] getPackageGids(String packageName) { 1931 // reader 1932 synchronized (mPackages) { 1933 PackageParser.Package p = mPackages.get(packageName); 1934 if (DEBUG_PACKAGE_INFO) 1935 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 1936 if (p != null) { 1937 final PackageSetting ps = (PackageSetting)p.mExtras; 1938 return ps.getGids(); 1939 } 1940 } 1941 // stupid thing to indicate an error. 1942 return new int[0]; 1943 } 1944 1945 static final PermissionInfo generatePermissionInfo( 1946 BasePermission bp, int flags) { 1947 if (bp.perm != null) { 1948 return PackageParser.generatePermissionInfo(bp.perm, flags); 1949 } 1950 PermissionInfo pi = new PermissionInfo(); 1951 pi.name = bp.name; 1952 pi.packageName = bp.sourcePackage; 1953 pi.nonLocalizedLabel = bp.name; 1954 pi.protectionLevel = bp.protectionLevel; 1955 return pi; 1956 } 1957 1958 @Override 1959 public PermissionInfo getPermissionInfo(String name, int flags) { 1960 // reader 1961 synchronized (mPackages) { 1962 final BasePermission p = mSettings.mPermissions.get(name); 1963 if (p != null) { 1964 return generatePermissionInfo(p, flags); 1965 } 1966 return null; 1967 } 1968 } 1969 1970 @Override 1971 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 1972 // reader 1973 synchronized (mPackages) { 1974 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 1975 for (BasePermission p : mSettings.mPermissions.values()) { 1976 if (group == null) { 1977 if (p.perm == null || p.perm.info.group == null) { 1978 out.add(generatePermissionInfo(p, flags)); 1979 } 1980 } else { 1981 if (p.perm != null && group.equals(p.perm.info.group)) { 1982 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 1983 } 1984 } 1985 } 1986 1987 if (out.size() > 0) { 1988 return out; 1989 } 1990 return mPermissionGroups.containsKey(group) ? out : null; 1991 } 1992 } 1993 1994 @Override 1995 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 1996 // reader 1997 synchronized (mPackages) { 1998 return PackageParser.generatePermissionGroupInfo( 1999 mPermissionGroups.get(name), flags); 2000 } 2001 } 2002 2003 @Override 2004 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2005 // reader 2006 synchronized (mPackages) { 2007 final int N = mPermissionGroups.size(); 2008 ArrayList<PermissionGroupInfo> out 2009 = new ArrayList<PermissionGroupInfo>(N); 2010 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2011 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2012 } 2013 return out; 2014 } 2015 } 2016 2017 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2018 int userId) { 2019 if (!sUserManager.exists(userId)) return null; 2020 PackageSetting ps = mSettings.mPackages.get(packageName); 2021 if (ps != null) { 2022 if (ps.pkg == null) { 2023 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2024 flags, userId); 2025 if (pInfo != null) { 2026 return pInfo.applicationInfo; 2027 } 2028 return null; 2029 } 2030 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2031 ps.readUserState(userId), userId); 2032 } 2033 return null; 2034 } 2035 2036 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2037 int userId) { 2038 if (!sUserManager.exists(userId)) return null; 2039 PackageSetting ps = mSettings.mPackages.get(packageName); 2040 if (ps != null) { 2041 PackageParser.Package pkg = ps.pkg; 2042 if (pkg == null) { 2043 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2044 return null; 2045 } 2046 // Only data remains, so we aren't worried about code paths 2047 pkg = new PackageParser.Package(packageName); 2048 pkg.applicationInfo.packageName = packageName; 2049 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2050 pkg.applicationInfo.dataDir = 2051 getDataPathForPackage(packageName, 0).getPath(); 2052 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2053 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2054 } 2055 return generatePackageInfo(pkg, flags, userId); 2056 } 2057 return null; 2058 } 2059 2060 @Override 2061 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2062 if (!sUserManager.exists(userId)) return null; 2063 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2064 // writer 2065 synchronized (mPackages) { 2066 PackageParser.Package p = mPackages.get(packageName); 2067 if (DEBUG_PACKAGE_INFO) Log.v( 2068 TAG, "getApplicationInfo " + packageName 2069 + ": " + p); 2070 if (p != null) { 2071 PackageSetting ps = mSettings.mPackages.get(packageName); 2072 if (ps == null) return null; 2073 // Note: isEnabledLP() does not apply here - always return info 2074 return PackageParser.generateApplicationInfo( 2075 p, flags, ps.readUserState(userId), userId); 2076 } 2077 if ("android".equals(packageName)||"system".equals(packageName)) { 2078 return mAndroidApplication; 2079 } 2080 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2081 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2082 } 2083 } 2084 return null; 2085 } 2086 2087 2088 @Override 2089 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2090 mContext.enforceCallingOrSelfPermission( 2091 android.Manifest.permission.CLEAR_APP_CACHE, null); 2092 // Queue up an async operation since clearing cache may take a little while. 2093 mHandler.post(new Runnable() { 2094 public void run() { 2095 mHandler.removeCallbacks(this); 2096 int retCode = -1; 2097 synchronized (mInstallLock) { 2098 retCode = mInstaller.freeCache(freeStorageSize); 2099 if (retCode < 0) { 2100 Slog.w(TAG, "Couldn't clear application caches"); 2101 } 2102 } 2103 if (observer != null) { 2104 try { 2105 observer.onRemoveCompleted(null, (retCode >= 0)); 2106 } catch (RemoteException e) { 2107 Slog.w(TAG, "RemoveException when invoking call back"); 2108 } 2109 } 2110 } 2111 }); 2112 } 2113 2114 @Override 2115 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2116 mContext.enforceCallingOrSelfPermission( 2117 android.Manifest.permission.CLEAR_APP_CACHE, null); 2118 // Queue up an async operation since clearing cache may take a little while. 2119 mHandler.post(new Runnable() { 2120 public void run() { 2121 mHandler.removeCallbacks(this); 2122 int retCode = -1; 2123 synchronized (mInstallLock) { 2124 retCode = mInstaller.freeCache(freeStorageSize); 2125 if (retCode < 0) { 2126 Slog.w(TAG, "Couldn't clear application caches"); 2127 } 2128 } 2129 if(pi != null) { 2130 try { 2131 // Callback via pending intent 2132 int code = (retCode >= 0) ? 1 : 0; 2133 pi.sendIntent(null, code, null, 2134 null, null); 2135 } catch (SendIntentException e1) { 2136 Slog.i(TAG, "Failed to send pending intent"); 2137 } 2138 } 2139 } 2140 }); 2141 } 2142 2143 void freeStorage(long freeStorageSize) throws IOException { 2144 synchronized (mInstallLock) { 2145 if (mInstaller.freeCache(freeStorageSize) < 0) { 2146 throw new IOException("Failed to free enough space"); 2147 } 2148 } 2149 } 2150 2151 @Override 2152 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2153 if (!sUserManager.exists(userId)) return null; 2154 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2155 synchronized (mPackages) { 2156 PackageParser.Activity a = mActivities.mActivities.get(component); 2157 2158 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2159 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2160 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2161 if (ps == null) return null; 2162 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2163 userId); 2164 } 2165 if (mResolveComponentName.equals(component)) { 2166 return mResolveActivity; 2167 } 2168 } 2169 return null; 2170 } 2171 2172 @Override 2173 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2174 String resolvedType) { 2175 synchronized (mPackages) { 2176 PackageParser.Activity a = mActivities.mActivities.get(component); 2177 if (a == null) { 2178 return false; 2179 } 2180 for (int i=0; i<a.intents.size(); i++) { 2181 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2182 intent.getData(), intent.getCategories(), TAG) >= 0) { 2183 return true; 2184 } 2185 } 2186 return false; 2187 } 2188 } 2189 2190 @Override 2191 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2192 if (!sUserManager.exists(userId)) return null; 2193 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2194 synchronized (mPackages) { 2195 PackageParser.Activity a = mReceivers.mActivities.get(component); 2196 if (DEBUG_PACKAGE_INFO) Log.v( 2197 TAG, "getReceiverInfo " + component + ": " + a); 2198 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2199 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2200 if (ps == null) return null; 2201 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2202 userId); 2203 } 2204 } 2205 return null; 2206 } 2207 2208 @Override 2209 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2210 if (!sUserManager.exists(userId)) return null; 2211 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2212 synchronized (mPackages) { 2213 PackageParser.Service s = mServices.mServices.get(component); 2214 if (DEBUG_PACKAGE_INFO) Log.v( 2215 TAG, "getServiceInfo " + component + ": " + s); 2216 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2217 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2218 if (ps == null) return null; 2219 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2220 userId); 2221 } 2222 } 2223 return null; 2224 } 2225 2226 @Override 2227 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2228 if (!sUserManager.exists(userId)) return null; 2229 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2230 synchronized (mPackages) { 2231 PackageParser.Provider p = mProviders.mProviders.get(component); 2232 if (DEBUG_PACKAGE_INFO) Log.v( 2233 TAG, "getProviderInfo " + component + ": " + p); 2234 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2235 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2236 if (ps == null) return null; 2237 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2238 userId); 2239 } 2240 } 2241 return null; 2242 } 2243 2244 @Override 2245 public String[] getSystemSharedLibraryNames() { 2246 Set<String> libSet; 2247 synchronized (mPackages) { 2248 libSet = mSharedLibraries.keySet(); 2249 int size = libSet.size(); 2250 if (size > 0) { 2251 String[] libs = new String[size]; 2252 libSet.toArray(libs); 2253 return libs; 2254 } 2255 } 2256 return null; 2257 } 2258 2259 @Override 2260 public FeatureInfo[] getSystemAvailableFeatures() { 2261 Collection<FeatureInfo> featSet; 2262 synchronized (mPackages) { 2263 featSet = mAvailableFeatures.values(); 2264 int size = featSet.size(); 2265 if (size > 0) { 2266 FeatureInfo[] features = new FeatureInfo[size+1]; 2267 featSet.toArray(features); 2268 FeatureInfo fi = new FeatureInfo(); 2269 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2270 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2271 features[size] = fi; 2272 return features; 2273 } 2274 } 2275 return null; 2276 } 2277 2278 @Override 2279 public boolean hasSystemFeature(String name) { 2280 synchronized (mPackages) { 2281 return mAvailableFeatures.containsKey(name); 2282 } 2283 } 2284 2285 private void checkValidCaller(int uid, int userId) { 2286 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2287 return; 2288 2289 throw new SecurityException("Caller uid=" + uid 2290 + " is not privileged to communicate with user=" + userId); 2291 } 2292 2293 @Override 2294 public int checkPermission(String permName, String pkgName) { 2295 synchronized (mPackages) { 2296 PackageParser.Package p = mPackages.get(pkgName); 2297 if (p != null && p.mExtras != null) { 2298 PackageSetting ps = (PackageSetting)p.mExtras; 2299 if (ps.sharedUser != null) { 2300 if (ps.sharedUser.grantedPermissions.contains(permName)) { 2301 return PackageManager.PERMISSION_GRANTED; 2302 } 2303 } else if (ps.grantedPermissions.contains(permName)) { 2304 return PackageManager.PERMISSION_GRANTED; 2305 } 2306 } 2307 } 2308 return PackageManager.PERMISSION_DENIED; 2309 } 2310 2311 @Override 2312 public int checkUidPermission(String permName, int uid) { 2313 synchronized (mPackages) { 2314 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2315 if (obj != null) { 2316 GrantedPermissions gp = (GrantedPermissions)obj; 2317 if (gp.grantedPermissions.contains(permName)) { 2318 return PackageManager.PERMISSION_GRANTED; 2319 } 2320 } else { 2321 HashSet<String> perms = mSystemPermissions.get(uid); 2322 if (perms != null && perms.contains(permName)) { 2323 return PackageManager.PERMISSION_GRANTED; 2324 } 2325 } 2326 } 2327 return PackageManager.PERMISSION_DENIED; 2328 } 2329 2330 /** 2331 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2332 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2333 * @param checkShell TODO(yamasani): 2334 * @param message the message to log on security exception 2335 */ 2336 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2337 boolean checkShell, String message) { 2338 if (userId < 0) { 2339 throw new IllegalArgumentException("Invalid userId " + userId); 2340 } 2341 if (checkShell) { 2342 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 2343 } 2344 if (userId == UserHandle.getUserId(callingUid)) return; 2345 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2346 if (requireFullPermission) { 2347 mContext.enforceCallingOrSelfPermission( 2348 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2349 } else { 2350 try { 2351 mContext.enforceCallingOrSelfPermission( 2352 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2353 } catch (SecurityException se) { 2354 mContext.enforceCallingOrSelfPermission( 2355 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2356 } 2357 } 2358 } 2359 } 2360 2361 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 2362 if (callingUid == Process.SHELL_UID) { 2363 if (userHandle >= 0 2364 && sUserManager.hasUserRestriction(restriction, userHandle)) { 2365 throw new SecurityException("Shell does not have permission to access user " 2366 + userHandle); 2367 } else if (userHandle < 0) { 2368 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 2369 + Debug.getCallers(3)); 2370 } 2371 } 2372 } 2373 2374 private BasePermission findPermissionTreeLP(String permName) { 2375 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2376 if (permName.startsWith(bp.name) && 2377 permName.length() > bp.name.length() && 2378 permName.charAt(bp.name.length()) == '.') { 2379 return bp; 2380 } 2381 } 2382 return null; 2383 } 2384 2385 private BasePermission checkPermissionTreeLP(String permName) { 2386 if (permName != null) { 2387 BasePermission bp = findPermissionTreeLP(permName); 2388 if (bp != null) { 2389 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2390 return bp; 2391 } 2392 throw new SecurityException("Calling uid " 2393 + Binder.getCallingUid() 2394 + " is not allowed to add to permission tree " 2395 + bp.name + " owned by uid " + bp.uid); 2396 } 2397 } 2398 throw new SecurityException("No permission tree found for " + permName); 2399 } 2400 2401 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2402 if (s1 == null) { 2403 return s2 == null; 2404 } 2405 if (s2 == null) { 2406 return false; 2407 } 2408 if (s1.getClass() != s2.getClass()) { 2409 return false; 2410 } 2411 return s1.equals(s2); 2412 } 2413 2414 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2415 if (pi1.icon != pi2.icon) return false; 2416 if (pi1.logo != pi2.logo) return false; 2417 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2418 if (!compareStrings(pi1.name, pi2.name)) return false; 2419 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2420 // We'll take care of setting this one. 2421 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2422 // These are not currently stored in settings. 2423 //if (!compareStrings(pi1.group, pi2.group)) return false; 2424 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2425 //if (pi1.labelRes != pi2.labelRes) return false; 2426 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2427 return true; 2428 } 2429 2430 int permissionInfoFootprint(PermissionInfo info) { 2431 int size = info.name.length(); 2432 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2433 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2434 return size; 2435 } 2436 2437 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2438 int size = 0; 2439 for (BasePermission perm : mSettings.mPermissions.values()) { 2440 if (perm.uid == tree.uid) { 2441 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2442 } 2443 } 2444 return size; 2445 } 2446 2447 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2448 // We calculate the max size of permissions defined by this uid and throw 2449 // if that plus the size of 'info' would exceed our stated maximum. 2450 if (tree.uid != Process.SYSTEM_UID) { 2451 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2452 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2453 throw new SecurityException("Permission tree size cap exceeded"); 2454 } 2455 } 2456 } 2457 2458 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2459 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2460 throw new SecurityException("Label must be specified in permission"); 2461 } 2462 BasePermission tree = checkPermissionTreeLP(info.name); 2463 BasePermission bp = mSettings.mPermissions.get(info.name); 2464 boolean added = bp == null; 2465 boolean changed = true; 2466 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2467 if (added) { 2468 enforcePermissionCapLocked(info, tree); 2469 bp = new BasePermission(info.name, tree.sourcePackage, 2470 BasePermission.TYPE_DYNAMIC); 2471 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2472 throw new SecurityException( 2473 "Not allowed to modify non-dynamic permission " 2474 + info.name); 2475 } else { 2476 if (bp.protectionLevel == fixedLevel 2477 && bp.perm.owner.equals(tree.perm.owner) 2478 && bp.uid == tree.uid 2479 && comparePermissionInfos(bp.perm.info, info)) { 2480 changed = false; 2481 } 2482 } 2483 bp.protectionLevel = fixedLevel; 2484 info = new PermissionInfo(info); 2485 info.protectionLevel = fixedLevel; 2486 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 2487 bp.perm.info.packageName = tree.perm.info.packageName; 2488 bp.uid = tree.uid; 2489 if (added) { 2490 mSettings.mPermissions.put(info.name, bp); 2491 } 2492 if (changed) { 2493 if (!async) { 2494 mSettings.writeLPr(); 2495 } else { 2496 scheduleWriteSettingsLocked(); 2497 } 2498 } 2499 return added; 2500 } 2501 2502 @Override 2503 public boolean addPermission(PermissionInfo info) { 2504 synchronized (mPackages) { 2505 return addPermissionLocked(info, false); 2506 } 2507 } 2508 2509 @Override 2510 public boolean addPermissionAsync(PermissionInfo info) { 2511 synchronized (mPackages) { 2512 return addPermissionLocked(info, true); 2513 } 2514 } 2515 2516 @Override 2517 public void removePermission(String name) { 2518 synchronized (mPackages) { 2519 checkPermissionTreeLP(name); 2520 BasePermission bp = mSettings.mPermissions.get(name); 2521 if (bp != null) { 2522 if (bp.type != BasePermission.TYPE_DYNAMIC) { 2523 throw new SecurityException( 2524 "Not allowed to modify non-dynamic permission " 2525 + name); 2526 } 2527 mSettings.mPermissions.remove(name); 2528 mSettings.writeLPr(); 2529 } 2530 } 2531 } 2532 2533 private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) { 2534 int index = pkg.requestedPermissions.indexOf(bp.name); 2535 if (index == -1) { 2536 throw new SecurityException("Package " + pkg.packageName 2537 + " has not requested permission " + bp.name); 2538 } 2539 boolean isNormal = 2540 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2541 == PermissionInfo.PROTECTION_NORMAL); 2542 boolean isDangerous = 2543 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2544 == PermissionInfo.PROTECTION_DANGEROUS); 2545 boolean isDevelopment = 2546 ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0); 2547 2548 if (!isNormal && !isDangerous && !isDevelopment) { 2549 throw new SecurityException("Permission " + bp.name 2550 + " is not a changeable permission type"); 2551 } 2552 2553 if (isNormal || isDangerous) { 2554 if (pkg.requestedPermissionsRequired.get(index)) { 2555 throw new SecurityException("Can't change " + bp.name 2556 + ". It is required by the application"); 2557 } 2558 } 2559 } 2560 2561 @Override 2562 public void grantPermission(String packageName, String permissionName) { 2563 mContext.enforceCallingOrSelfPermission( 2564 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2565 synchronized (mPackages) { 2566 final PackageParser.Package pkg = mPackages.get(packageName); 2567 if (pkg == null) { 2568 throw new IllegalArgumentException("Unknown package: " + packageName); 2569 } 2570 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2571 if (bp == null) { 2572 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2573 } 2574 2575 checkGrantRevokePermissions(pkg, bp); 2576 2577 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2578 if (ps == null) { 2579 return; 2580 } 2581 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2582 if (gp.grantedPermissions.add(permissionName)) { 2583 if (ps.haveGids) { 2584 gp.gids = appendInts(gp.gids, bp.gids); 2585 } 2586 mSettings.writeLPr(); 2587 } 2588 } 2589 } 2590 2591 @Override 2592 public void revokePermission(String packageName, String permissionName) { 2593 int changedAppId = -1; 2594 2595 synchronized (mPackages) { 2596 final PackageParser.Package pkg = mPackages.get(packageName); 2597 if (pkg == null) { 2598 throw new IllegalArgumentException("Unknown package: " + packageName); 2599 } 2600 if (pkg.applicationInfo.uid != Binder.getCallingUid()) { 2601 mContext.enforceCallingOrSelfPermission( 2602 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2603 } 2604 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2605 if (bp == null) { 2606 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2607 } 2608 2609 checkGrantRevokePermissions(pkg, bp); 2610 2611 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2612 if (ps == null) { 2613 return; 2614 } 2615 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2616 if (gp.grantedPermissions.remove(permissionName)) { 2617 gp.grantedPermissions.remove(permissionName); 2618 if (ps.haveGids) { 2619 gp.gids = removeInts(gp.gids, bp.gids); 2620 } 2621 mSettings.writeLPr(); 2622 changedAppId = ps.appId; 2623 } 2624 } 2625 2626 if (changedAppId >= 0) { 2627 // We changed the perm on someone, kill its processes. 2628 IActivityManager am = ActivityManagerNative.getDefault(); 2629 if (am != null) { 2630 final int callingUserId = UserHandle.getCallingUserId(); 2631 final long ident = Binder.clearCallingIdentity(); 2632 try { 2633 //XXX we should only revoke for the calling user's app permissions, 2634 // but for now we impact all users. 2635 //am.killUid(UserHandle.getUid(callingUserId, changedAppId), 2636 // "revoke " + permissionName); 2637 int[] users = sUserManager.getUserIds(); 2638 for (int user : users) { 2639 am.killUid(UserHandle.getUid(user, changedAppId), 2640 "revoke " + permissionName); 2641 } 2642 } catch (RemoteException e) { 2643 } finally { 2644 Binder.restoreCallingIdentity(ident); 2645 } 2646 } 2647 } 2648 } 2649 2650 @Override 2651 public boolean isProtectedBroadcast(String actionName) { 2652 synchronized (mPackages) { 2653 return mProtectedBroadcasts.contains(actionName); 2654 } 2655 } 2656 2657 @Override 2658 public int checkSignatures(String pkg1, String pkg2) { 2659 synchronized (mPackages) { 2660 final PackageParser.Package p1 = mPackages.get(pkg1); 2661 final PackageParser.Package p2 = mPackages.get(pkg2); 2662 if (p1 == null || p1.mExtras == null 2663 || p2 == null || p2.mExtras == null) { 2664 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2665 } 2666 return compareSignatures(p1.mSignatures, p2.mSignatures); 2667 } 2668 } 2669 2670 @Override 2671 public int checkUidSignatures(int uid1, int uid2) { 2672 // Map to base uids. 2673 uid1 = UserHandle.getAppId(uid1); 2674 uid2 = UserHandle.getAppId(uid2); 2675 // reader 2676 synchronized (mPackages) { 2677 Signature[] s1; 2678 Signature[] s2; 2679 Object obj = mSettings.getUserIdLPr(uid1); 2680 if (obj != null) { 2681 if (obj instanceof SharedUserSetting) { 2682 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 2683 } else if (obj instanceof PackageSetting) { 2684 s1 = ((PackageSetting)obj).signatures.mSignatures; 2685 } else { 2686 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2687 } 2688 } else { 2689 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2690 } 2691 obj = mSettings.getUserIdLPr(uid2); 2692 if (obj != null) { 2693 if (obj instanceof SharedUserSetting) { 2694 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 2695 } else if (obj instanceof PackageSetting) { 2696 s2 = ((PackageSetting)obj).signatures.mSignatures; 2697 } else { 2698 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2699 } 2700 } else { 2701 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2702 } 2703 return compareSignatures(s1, s2); 2704 } 2705 } 2706 2707 /** 2708 * Compares two sets of signatures. Returns: 2709 * <br /> 2710 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 2711 * <br /> 2712 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 2713 * <br /> 2714 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 2715 * <br /> 2716 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 2717 * <br /> 2718 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 2719 */ 2720 static int compareSignatures(Signature[] s1, Signature[] s2) { 2721 if (s1 == null) { 2722 return s2 == null 2723 ? PackageManager.SIGNATURE_NEITHER_SIGNED 2724 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 2725 } 2726 2727 if (s2 == null) { 2728 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 2729 } 2730 2731 if (s1.length != s2.length) { 2732 return PackageManager.SIGNATURE_NO_MATCH; 2733 } 2734 2735 // Since both signature sets are of size 1, we can compare without HashSets. 2736 if (s1.length == 1) { 2737 return s1[0].equals(s2[0]) ? 2738 PackageManager.SIGNATURE_MATCH : 2739 PackageManager.SIGNATURE_NO_MATCH; 2740 } 2741 2742 HashSet<Signature> set1 = new HashSet<Signature>(); 2743 for (Signature sig : s1) { 2744 set1.add(sig); 2745 } 2746 HashSet<Signature> set2 = new HashSet<Signature>(); 2747 for (Signature sig : s2) { 2748 set2.add(sig); 2749 } 2750 // Make sure s2 contains all signatures in s1. 2751 if (set1.equals(set2)) { 2752 return PackageManager.SIGNATURE_MATCH; 2753 } 2754 return PackageManager.SIGNATURE_NO_MATCH; 2755 } 2756 2757 /** 2758 * If the database version for this type of package (internal storage or 2759 * external storage) is less than the version where package signatures 2760 * were updated, return true. 2761 */ 2762 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2763 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 2764 DatabaseVersion.SIGNATURE_END_ENTITY)) 2765 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 2766 DatabaseVersion.SIGNATURE_END_ENTITY)); 2767 } 2768 2769 /** 2770 * Used for backward compatibility to make sure any packages with 2771 * certificate chains get upgraded to the new style. {@code existingSigs} 2772 * will be in the old format (since they were stored on disk from before the 2773 * system upgrade) and {@code scannedSigs} will be in the newer format. 2774 */ 2775 private int compareSignaturesCompat(PackageSignatures existingSigs, 2776 PackageParser.Package scannedPkg) { 2777 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 2778 return PackageManager.SIGNATURE_NO_MATCH; 2779 } 2780 2781 HashSet<Signature> existingSet = new HashSet<Signature>(); 2782 for (Signature sig : existingSigs.mSignatures) { 2783 existingSet.add(sig); 2784 } 2785 HashSet<Signature> scannedCompatSet = new HashSet<Signature>(); 2786 for (Signature sig : scannedPkg.mSignatures) { 2787 try { 2788 Signature[] chainSignatures = sig.getChainSignatures(); 2789 for (Signature chainSig : chainSignatures) { 2790 scannedCompatSet.add(chainSig); 2791 } 2792 } catch (CertificateEncodingException e) { 2793 scannedCompatSet.add(sig); 2794 } 2795 } 2796 /* 2797 * Make sure the expanded scanned set contains all signatures in the 2798 * existing one. 2799 */ 2800 if (scannedCompatSet.equals(existingSet)) { 2801 // Migrate the old signatures to the new scheme. 2802 existingSigs.assignSignatures(scannedPkg.mSignatures); 2803 // The new KeySets will be re-added later in the scanning process. 2804 synchronized (mPackages) { 2805 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 2806 } 2807 return PackageManager.SIGNATURE_MATCH; 2808 } 2809 return PackageManager.SIGNATURE_NO_MATCH; 2810 } 2811 2812 @Override 2813 public String[] getPackagesForUid(int uid) { 2814 uid = UserHandle.getAppId(uid); 2815 // reader 2816 synchronized (mPackages) { 2817 Object obj = mSettings.getUserIdLPr(uid); 2818 if (obj instanceof SharedUserSetting) { 2819 final SharedUserSetting sus = (SharedUserSetting) obj; 2820 final int N = sus.packages.size(); 2821 final String[] res = new String[N]; 2822 final Iterator<PackageSetting> it = sus.packages.iterator(); 2823 int i = 0; 2824 while (it.hasNext()) { 2825 res[i++] = it.next().name; 2826 } 2827 return res; 2828 } else if (obj instanceof PackageSetting) { 2829 final PackageSetting ps = (PackageSetting) obj; 2830 return new String[] { ps.name }; 2831 } 2832 } 2833 return null; 2834 } 2835 2836 @Override 2837 public String getNameForUid(int uid) { 2838 // reader 2839 synchronized (mPackages) { 2840 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2841 if (obj instanceof SharedUserSetting) { 2842 final SharedUserSetting sus = (SharedUserSetting) obj; 2843 return sus.name + ":" + sus.userId; 2844 } else if (obj instanceof PackageSetting) { 2845 final PackageSetting ps = (PackageSetting) obj; 2846 return ps.name; 2847 } 2848 } 2849 return null; 2850 } 2851 2852 @Override 2853 public int getUidForSharedUser(String sharedUserName) { 2854 if(sharedUserName == null) { 2855 return -1; 2856 } 2857 // reader 2858 synchronized (mPackages) { 2859 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false); 2860 if (suid == null) { 2861 return -1; 2862 } 2863 return suid.userId; 2864 } 2865 } 2866 2867 @Override 2868 public int getFlagsForUid(int uid) { 2869 synchronized (mPackages) { 2870 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2871 if (obj instanceof SharedUserSetting) { 2872 final SharedUserSetting sus = (SharedUserSetting) obj; 2873 return sus.pkgFlags; 2874 } else if (obj instanceof PackageSetting) { 2875 final PackageSetting ps = (PackageSetting) obj; 2876 return ps.pkgFlags; 2877 } 2878 } 2879 return 0; 2880 } 2881 2882 @Override 2883 public String[] getAppOpPermissionPackages(String permissionName) { 2884 synchronized (mPackages) { 2885 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 2886 if (pkgs == null) { 2887 return null; 2888 } 2889 return pkgs.toArray(new String[pkgs.size()]); 2890 } 2891 } 2892 2893 @Override 2894 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 2895 int flags, int userId) { 2896 if (!sUserManager.exists(userId)) return null; 2897 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 2898 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2899 return chooseBestActivity(intent, resolvedType, flags, query, userId); 2900 } 2901 2902 @Override 2903 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 2904 IntentFilter filter, int match, ComponentName activity) { 2905 final int userId = UserHandle.getCallingUserId(); 2906 if (DEBUG_PREFERRED) { 2907 Log.v(TAG, "setLastChosenActivity intent=" + intent 2908 + " resolvedType=" + resolvedType 2909 + " flags=" + flags 2910 + " filter=" + filter 2911 + " match=" + match 2912 + " activity=" + activity); 2913 filter.dump(new PrintStreamPrinter(System.out), " "); 2914 } 2915 intent.setComponent(null); 2916 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2917 // Find any earlier preferred or last chosen entries and nuke them 2918 findPreferredActivity(intent, resolvedType, 2919 flags, query, 0, false, true, false, userId); 2920 // Add the new activity as the last chosen for this filter 2921 addPreferredActivityInternal(filter, match, null, activity, false, userId, 2922 "Setting last chosen"); 2923 } 2924 2925 @Override 2926 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 2927 final int userId = UserHandle.getCallingUserId(); 2928 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 2929 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2930 return findPreferredActivity(intent, resolvedType, flags, query, 0, 2931 false, false, false, userId); 2932 } 2933 2934 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 2935 int flags, List<ResolveInfo> query, int userId) { 2936 if (query != null) { 2937 final int N = query.size(); 2938 if (N == 1) { 2939 return query.get(0); 2940 } else if (N > 1) { 2941 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 2942 // If there is more than one activity with the same priority, 2943 // then let the user decide between them. 2944 ResolveInfo r0 = query.get(0); 2945 ResolveInfo r1 = query.get(1); 2946 if (DEBUG_INTENT_MATCHING || debug) { 2947 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 2948 + r1.activityInfo.name + "=" + r1.priority); 2949 } 2950 // If the first activity has a higher priority, or a different 2951 // default, then it is always desireable to pick it. 2952 if (r0.priority != r1.priority 2953 || r0.preferredOrder != r1.preferredOrder 2954 || r0.isDefault != r1.isDefault) { 2955 return query.get(0); 2956 } 2957 // If we have saved a preference for a preferred activity for 2958 // this Intent, use that. 2959 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 2960 flags, query, r0.priority, true, false, debug, userId); 2961 if (ri != null) { 2962 return ri; 2963 } 2964 if (userId != 0) { 2965 ri = new ResolveInfo(mResolveInfo); 2966 ri.activityInfo = new ActivityInfo(ri.activityInfo); 2967 ri.activityInfo.applicationInfo = new ApplicationInfo( 2968 ri.activityInfo.applicationInfo); 2969 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 2970 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 2971 return ri; 2972 } 2973 return mResolveInfo; 2974 } 2975 } 2976 return null; 2977 } 2978 2979 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 2980 int flags, List<ResolveInfo> query, boolean debug, int userId) { 2981 final int N = query.size(); 2982 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 2983 .get(userId); 2984 // Get the list of persistent preferred activities that handle the intent 2985 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 2986 List<PersistentPreferredActivity> pprefs = ppir != null 2987 ? ppir.queryIntent(intent, resolvedType, 2988 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 2989 : null; 2990 if (pprefs != null && pprefs.size() > 0) { 2991 final int M = pprefs.size(); 2992 for (int i=0; i<M; i++) { 2993 final PersistentPreferredActivity ppa = pprefs.get(i); 2994 if (DEBUG_PREFERRED || debug) { 2995 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 2996 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 2997 + "\n component=" + ppa.mComponent); 2998 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 2999 } 3000 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3001 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3002 if (DEBUG_PREFERRED || debug) { 3003 Slog.v(TAG, "Found persistent preferred activity:"); 3004 if (ai != null) { 3005 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3006 } else { 3007 Slog.v(TAG, " null"); 3008 } 3009 } 3010 if (ai == null) { 3011 // This previously registered persistent preferred activity 3012 // component is no longer known. Ignore it and do NOT remove it. 3013 continue; 3014 } 3015 for (int j=0; j<N; j++) { 3016 final ResolveInfo ri = query.get(j); 3017 if (!ri.activityInfo.applicationInfo.packageName 3018 .equals(ai.applicationInfo.packageName)) { 3019 continue; 3020 } 3021 if (!ri.activityInfo.name.equals(ai.name)) { 3022 continue; 3023 } 3024 // Found a persistent preference that can handle the intent. 3025 if (DEBUG_PREFERRED || debug) { 3026 Slog.v(TAG, "Returning persistent preferred activity: " + 3027 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3028 } 3029 return ri; 3030 } 3031 } 3032 } 3033 return null; 3034 } 3035 3036 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3037 List<ResolveInfo> query, int priority, boolean always, 3038 boolean removeMatches, boolean debug, int userId) { 3039 if (!sUserManager.exists(userId)) return null; 3040 // writer 3041 synchronized (mPackages) { 3042 if (intent.getSelector() != null) { 3043 intent = intent.getSelector(); 3044 } 3045 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3046 3047 // Try to find a matching persistent preferred activity. 3048 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3049 debug, userId); 3050 3051 // If a persistent preferred activity matched, use it. 3052 if (pri != null) { 3053 return pri; 3054 } 3055 3056 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3057 // Get the list of preferred activities that handle the intent 3058 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3059 List<PreferredActivity> prefs = pir != null 3060 ? pir.queryIntent(intent, resolvedType, 3061 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3062 : null; 3063 if (prefs != null && prefs.size() > 0) { 3064 boolean changed = false; 3065 try { 3066 // First figure out how good the original match set is. 3067 // We will only allow preferred activities that came 3068 // from the same match quality. 3069 int match = 0; 3070 3071 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3072 3073 final int N = query.size(); 3074 for (int j=0; j<N; j++) { 3075 final ResolveInfo ri = query.get(j); 3076 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3077 + ": 0x" + Integer.toHexString(match)); 3078 if (ri.match > match) { 3079 match = ri.match; 3080 } 3081 } 3082 3083 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3084 + Integer.toHexString(match)); 3085 3086 match &= IntentFilter.MATCH_CATEGORY_MASK; 3087 final int M = prefs.size(); 3088 for (int i=0; i<M; i++) { 3089 final PreferredActivity pa = prefs.get(i); 3090 if (DEBUG_PREFERRED || debug) { 3091 Slog.v(TAG, "Checking PreferredActivity ds=" 3092 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3093 + "\n component=" + pa.mPref.mComponent); 3094 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3095 } 3096 if (pa.mPref.mMatch != match) { 3097 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3098 + Integer.toHexString(pa.mPref.mMatch)); 3099 continue; 3100 } 3101 // If it's not an "always" type preferred activity and that's what we're 3102 // looking for, skip it. 3103 if (always && !pa.mPref.mAlways) { 3104 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3105 continue; 3106 } 3107 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3108 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3109 if (DEBUG_PREFERRED || debug) { 3110 Slog.v(TAG, "Found preferred activity:"); 3111 if (ai != null) { 3112 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3113 } else { 3114 Slog.v(TAG, " null"); 3115 } 3116 } 3117 if (ai == null) { 3118 // This previously registered preferred activity 3119 // component is no longer known. Most likely an update 3120 // to the app was installed and in the new version this 3121 // component no longer exists. Clean it up by removing 3122 // it from the preferred activities list, and skip it. 3123 Slog.w(TAG, "Removing dangling preferred activity: " 3124 + pa.mPref.mComponent); 3125 pir.removeFilter(pa); 3126 changed = true; 3127 continue; 3128 } 3129 for (int j=0; j<N; j++) { 3130 final ResolveInfo ri = query.get(j); 3131 if (!ri.activityInfo.applicationInfo.packageName 3132 .equals(ai.applicationInfo.packageName)) { 3133 continue; 3134 } 3135 if (!ri.activityInfo.name.equals(ai.name)) { 3136 continue; 3137 } 3138 3139 if (removeMatches) { 3140 pir.removeFilter(pa); 3141 changed = true; 3142 if (DEBUG_PREFERRED) { 3143 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3144 } 3145 break; 3146 } 3147 3148 // Okay we found a previously set preferred or last chosen app. 3149 // If the result set is different from when this 3150 // was created, we need to clear it and re-ask the 3151 // user their preference, if we're looking for an "always" type entry. 3152 if (always && !pa.mPref.sameSet(query, priority)) { 3153 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3154 + intent + " type " + resolvedType); 3155 if (DEBUG_PREFERRED) { 3156 Slog.v(TAG, "Removing preferred activity since set changed " 3157 + pa.mPref.mComponent); 3158 } 3159 pir.removeFilter(pa); 3160 // Re-add the filter as a "last chosen" entry (!always) 3161 PreferredActivity lastChosen = new PreferredActivity( 3162 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3163 pir.addFilter(lastChosen); 3164 changed = true; 3165 return null; 3166 } 3167 3168 // Yay! Either the set matched or we're looking for the last chosen 3169 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3170 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3171 return ri; 3172 } 3173 } 3174 } finally { 3175 if (changed) { 3176 if (DEBUG_PREFERRED) { 3177 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 3178 } 3179 mSettings.writePackageRestrictionsLPr(userId); 3180 } 3181 } 3182 } 3183 } 3184 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3185 return null; 3186 } 3187 3188 /* 3189 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3190 */ 3191 @Override 3192 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3193 int targetUserId) { 3194 mContext.enforceCallingOrSelfPermission( 3195 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3196 List<CrossProfileIntentFilter> matches = 3197 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3198 if (matches != null) { 3199 int size = matches.size(); 3200 for (int i = 0; i < size; i++) { 3201 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3202 } 3203 } 3204 return false; 3205 } 3206 3207 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3208 String resolvedType, int userId) { 3209 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3210 if (resolver != null) { 3211 return resolver.queryIntent(intent, resolvedType, false, userId); 3212 } 3213 return null; 3214 } 3215 3216 @Override 3217 public List<ResolveInfo> queryIntentActivities(Intent intent, 3218 String resolvedType, int flags, int userId) { 3219 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3220 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 3221 ComponentName comp = intent.getComponent(); 3222 if (comp == null) { 3223 if (intent.getSelector() != null) { 3224 intent = intent.getSelector(); 3225 comp = intent.getComponent(); 3226 } 3227 } 3228 3229 if (comp != null) { 3230 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3231 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3232 if (ai != null) { 3233 final ResolveInfo ri = new ResolveInfo(); 3234 ri.activityInfo = ai; 3235 list.add(ri); 3236 } 3237 return list; 3238 } 3239 3240 // reader 3241 synchronized (mPackages) { 3242 final String pkgName = intent.getPackage(); 3243 if (pkgName == null) { 3244 List<CrossProfileIntentFilter> matchingFilters = 3245 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3246 // Check for results that need to skip the current profile. 3247 ResolveInfo resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3248 resolvedType, flags, userId); 3249 if (resolveInfo != null) { 3250 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3251 result.add(resolveInfo); 3252 return result; 3253 } 3254 // Check for cross profile results. 3255 resolveInfo = queryCrossProfileIntents( 3256 matchingFilters, intent, resolvedType, flags, userId); 3257 3258 // Check for results in the current profile. 3259 List<ResolveInfo> result = mActivities.queryIntent( 3260 intent, resolvedType, flags, userId); 3261 if (resolveInfo != null) { 3262 result.add(resolveInfo); 3263 Collections.sort(result, mResolvePrioritySorter); 3264 } 3265 return result; 3266 } 3267 final PackageParser.Package pkg = mPackages.get(pkgName); 3268 if (pkg != null) { 3269 return mActivities.queryIntentForPackage(intent, resolvedType, flags, 3270 pkg.activities, userId); 3271 } 3272 return new ArrayList<ResolveInfo>(); 3273 } 3274 } 3275 3276 private ResolveInfo querySkipCurrentProfileIntents( 3277 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3278 int flags, int sourceUserId) { 3279 if (matchingFilters != null) { 3280 int size = matchingFilters.size(); 3281 for (int i = 0; i < size; i ++) { 3282 CrossProfileIntentFilter filter = matchingFilters.get(i); 3283 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 3284 // Checking if there are activities in the target user that can handle the 3285 // intent. 3286 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3287 flags, sourceUserId); 3288 if (resolveInfo != null) { 3289 return resolveInfo; 3290 } 3291 } 3292 } 3293 } 3294 return null; 3295 } 3296 3297 // Return matching ResolveInfo if any for skip current profile intent filters. 3298 private ResolveInfo queryCrossProfileIntents( 3299 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3300 int flags, int sourceUserId) { 3301 if (matchingFilters != null) { 3302 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 3303 // match the same intent. For performance reasons, it is better not to 3304 // run queryIntent twice for the same userId 3305 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 3306 int size = matchingFilters.size(); 3307 for (int i = 0; i < size; i++) { 3308 CrossProfileIntentFilter filter = matchingFilters.get(i); 3309 int targetUserId = filter.getTargetUserId(); 3310 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 3311 && !alreadyTriedUserIds.get(targetUserId)) { 3312 // Checking if there are activities in the target user that can handle the 3313 // intent. 3314 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3315 flags, sourceUserId); 3316 if (resolveInfo != null) return resolveInfo; 3317 alreadyTriedUserIds.put(targetUserId, true); 3318 } 3319 } 3320 } 3321 return null; 3322 } 3323 3324 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 3325 String resolvedType, int flags, int sourceUserId) { 3326 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 3327 resolvedType, flags, filter.getTargetUserId()); 3328 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 3329 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 3330 } 3331 return null; 3332 } 3333 3334 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 3335 int sourceUserId, int targetUserId) { 3336 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 3337 String className; 3338 if (targetUserId == UserHandle.USER_OWNER) { 3339 className = FORWARD_INTENT_TO_USER_OWNER; 3340 } else { 3341 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 3342 } 3343 ComponentName forwardingActivityComponentName = new ComponentName( 3344 mAndroidApplication.packageName, className); 3345 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 3346 sourceUserId); 3347 if (targetUserId == UserHandle.USER_OWNER) { 3348 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 3349 forwardingResolveInfo.noResourceId = true; 3350 } 3351 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 3352 forwardingResolveInfo.priority = 0; 3353 forwardingResolveInfo.preferredOrder = 0; 3354 forwardingResolveInfo.match = 0; 3355 forwardingResolveInfo.isDefault = true; 3356 forwardingResolveInfo.filter = filter; 3357 forwardingResolveInfo.targetUserId = targetUserId; 3358 return forwardingResolveInfo; 3359 } 3360 3361 @Override 3362 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 3363 Intent[] specifics, String[] specificTypes, Intent intent, 3364 String resolvedType, int flags, int userId) { 3365 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3366 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 3367 false, "query intent activity options"); 3368 final String resultsAction = intent.getAction(); 3369 3370 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 3371 | PackageManager.GET_RESOLVED_FILTER, userId); 3372 3373 if (DEBUG_INTENT_MATCHING) { 3374 Log.v(TAG, "Query " + intent + ": " + results); 3375 } 3376 3377 int specificsPos = 0; 3378 int N; 3379 3380 // todo: note that the algorithm used here is O(N^2). This 3381 // isn't a problem in our current environment, but if we start running 3382 // into situations where we have more than 5 or 10 matches then this 3383 // should probably be changed to something smarter... 3384 3385 // First we go through and resolve each of the specific items 3386 // that were supplied, taking care of removing any corresponding 3387 // duplicate items in the generic resolve list. 3388 if (specifics != null) { 3389 for (int i=0; i<specifics.length; i++) { 3390 final Intent sintent = specifics[i]; 3391 if (sintent == null) { 3392 continue; 3393 } 3394 3395 if (DEBUG_INTENT_MATCHING) { 3396 Log.v(TAG, "Specific #" + i + ": " + sintent); 3397 } 3398 3399 String action = sintent.getAction(); 3400 if (resultsAction != null && resultsAction.equals(action)) { 3401 // If this action was explicitly requested, then don't 3402 // remove things that have it. 3403 action = null; 3404 } 3405 3406 ResolveInfo ri = null; 3407 ActivityInfo ai = null; 3408 3409 ComponentName comp = sintent.getComponent(); 3410 if (comp == null) { 3411 ri = resolveIntent( 3412 sintent, 3413 specificTypes != null ? specificTypes[i] : null, 3414 flags, userId); 3415 if (ri == null) { 3416 continue; 3417 } 3418 if (ri == mResolveInfo) { 3419 // ACK! Must do something better with this. 3420 } 3421 ai = ri.activityInfo; 3422 comp = new ComponentName(ai.applicationInfo.packageName, 3423 ai.name); 3424 } else { 3425 ai = getActivityInfo(comp, flags, userId); 3426 if (ai == null) { 3427 continue; 3428 } 3429 } 3430 3431 // Look for any generic query activities that are duplicates 3432 // of this specific one, and remove them from the results. 3433 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 3434 N = results.size(); 3435 int j; 3436 for (j=specificsPos; j<N; j++) { 3437 ResolveInfo sri = results.get(j); 3438 if ((sri.activityInfo.name.equals(comp.getClassName()) 3439 && sri.activityInfo.applicationInfo.packageName.equals( 3440 comp.getPackageName())) 3441 || (action != null && sri.filter.matchAction(action))) { 3442 results.remove(j); 3443 if (DEBUG_INTENT_MATCHING) Log.v( 3444 TAG, "Removing duplicate item from " + j 3445 + " due to specific " + specificsPos); 3446 if (ri == null) { 3447 ri = sri; 3448 } 3449 j--; 3450 N--; 3451 } 3452 } 3453 3454 // Add this specific item to its proper place. 3455 if (ri == null) { 3456 ri = new ResolveInfo(); 3457 ri.activityInfo = ai; 3458 } 3459 results.add(specificsPos, ri); 3460 ri.specificIndex = i; 3461 specificsPos++; 3462 } 3463 } 3464 3465 // Now we go through the remaining generic results and remove any 3466 // duplicate actions that are found here. 3467 N = results.size(); 3468 for (int i=specificsPos; i<N-1; i++) { 3469 final ResolveInfo rii = results.get(i); 3470 if (rii.filter == null) { 3471 continue; 3472 } 3473 3474 // Iterate over all of the actions of this result's intent 3475 // filter... typically this should be just one. 3476 final Iterator<String> it = rii.filter.actionsIterator(); 3477 if (it == null) { 3478 continue; 3479 } 3480 while (it.hasNext()) { 3481 final String action = it.next(); 3482 if (resultsAction != null && resultsAction.equals(action)) { 3483 // If this action was explicitly requested, then don't 3484 // remove things that have it. 3485 continue; 3486 } 3487 for (int j=i+1; j<N; j++) { 3488 final ResolveInfo rij = results.get(j); 3489 if (rij.filter != null && rij.filter.hasAction(action)) { 3490 results.remove(j); 3491 if (DEBUG_INTENT_MATCHING) Log.v( 3492 TAG, "Removing duplicate item from " + j 3493 + " due to action " + action + " at " + i); 3494 j--; 3495 N--; 3496 } 3497 } 3498 } 3499 3500 // If the caller didn't request filter information, drop it now 3501 // so we don't have to marshall/unmarshall it. 3502 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3503 rii.filter = null; 3504 } 3505 } 3506 3507 // Filter out the caller activity if so requested. 3508 if (caller != null) { 3509 N = results.size(); 3510 for (int i=0; i<N; i++) { 3511 ActivityInfo ainfo = results.get(i).activityInfo; 3512 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 3513 && caller.getClassName().equals(ainfo.name)) { 3514 results.remove(i); 3515 break; 3516 } 3517 } 3518 } 3519 3520 // If the caller didn't request filter information, 3521 // drop them now so we don't have to 3522 // marshall/unmarshall it. 3523 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3524 N = results.size(); 3525 for (int i=0; i<N; i++) { 3526 results.get(i).filter = null; 3527 } 3528 } 3529 3530 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 3531 return results; 3532 } 3533 3534 @Override 3535 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 3536 int userId) { 3537 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3538 ComponentName comp = intent.getComponent(); 3539 if (comp == null) { 3540 if (intent.getSelector() != null) { 3541 intent = intent.getSelector(); 3542 comp = intent.getComponent(); 3543 } 3544 } 3545 if (comp != null) { 3546 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3547 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 3548 if (ai != null) { 3549 ResolveInfo ri = new ResolveInfo(); 3550 ri.activityInfo = ai; 3551 list.add(ri); 3552 } 3553 return list; 3554 } 3555 3556 // reader 3557 synchronized (mPackages) { 3558 String pkgName = intent.getPackage(); 3559 if (pkgName == null) { 3560 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 3561 } 3562 final PackageParser.Package pkg = mPackages.get(pkgName); 3563 if (pkg != null) { 3564 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 3565 userId); 3566 } 3567 return null; 3568 } 3569 } 3570 3571 @Override 3572 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 3573 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 3574 if (!sUserManager.exists(userId)) return null; 3575 if (query != null) { 3576 if (query.size() >= 1) { 3577 // If there is more than one service with the same priority, 3578 // just arbitrarily pick the first one. 3579 return query.get(0); 3580 } 3581 } 3582 return null; 3583 } 3584 3585 @Override 3586 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 3587 int userId) { 3588 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3589 ComponentName comp = intent.getComponent(); 3590 if (comp == null) { 3591 if (intent.getSelector() != null) { 3592 intent = intent.getSelector(); 3593 comp = intent.getComponent(); 3594 } 3595 } 3596 if (comp != null) { 3597 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3598 final ServiceInfo si = getServiceInfo(comp, flags, userId); 3599 if (si != null) { 3600 final ResolveInfo ri = new ResolveInfo(); 3601 ri.serviceInfo = si; 3602 list.add(ri); 3603 } 3604 return list; 3605 } 3606 3607 // reader 3608 synchronized (mPackages) { 3609 String pkgName = intent.getPackage(); 3610 if (pkgName == null) { 3611 return mServices.queryIntent(intent, resolvedType, flags, userId); 3612 } 3613 final PackageParser.Package pkg = mPackages.get(pkgName); 3614 if (pkg != null) { 3615 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 3616 userId); 3617 } 3618 return null; 3619 } 3620 } 3621 3622 @Override 3623 public List<ResolveInfo> queryIntentContentProviders( 3624 Intent intent, String resolvedType, int flags, int userId) { 3625 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3626 ComponentName comp = intent.getComponent(); 3627 if (comp == null) { 3628 if (intent.getSelector() != null) { 3629 intent = intent.getSelector(); 3630 comp = intent.getComponent(); 3631 } 3632 } 3633 if (comp != null) { 3634 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3635 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 3636 if (pi != null) { 3637 final ResolveInfo ri = new ResolveInfo(); 3638 ri.providerInfo = pi; 3639 list.add(ri); 3640 } 3641 return list; 3642 } 3643 3644 // reader 3645 synchronized (mPackages) { 3646 String pkgName = intent.getPackage(); 3647 if (pkgName == null) { 3648 return mProviders.queryIntent(intent, resolvedType, flags, userId); 3649 } 3650 final PackageParser.Package pkg = mPackages.get(pkgName); 3651 if (pkg != null) { 3652 return mProviders.queryIntentForPackage( 3653 intent, resolvedType, flags, pkg.providers, userId); 3654 } 3655 return null; 3656 } 3657 } 3658 3659 @Override 3660 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 3661 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3662 3663 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 3664 3665 // writer 3666 synchronized (mPackages) { 3667 ArrayList<PackageInfo> list; 3668 if (listUninstalled) { 3669 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 3670 for (PackageSetting ps : mSettings.mPackages.values()) { 3671 PackageInfo pi; 3672 if (ps.pkg != null) { 3673 pi = generatePackageInfo(ps.pkg, flags, userId); 3674 } else { 3675 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3676 } 3677 if (pi != null) { 3678 list.add(pi); 3679 } 3680 } 3681 } else { 3682 list = new ArrayList<PackageInfo>(mPackages.size()); 3683 for (PackageParser.Package p : mPackages.values()) { 3684 PackageInfo pi = generatePackageInfo(p, flags, userId); 3685 if (pi != null) { 3686 list.add(pi); 3687 } 3688 } 3689 } 3690 3691 return new ParceledListSlice<PackageInfo>(list); 3692 } 3693 } 3694 3695 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 3696 String[] permissions, boolean[] tmp, int flags, int userId) { 3697 int numMatch = 0; 3698 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 3699 for (int i=0; i<permissions.length; i++) { 3700 if (gp.grantedPermissions.contains(permissions[i])) { 3701 tmp[i] = true; 3702 numMatch++; 3703 } else { 3704 tmp[i] = false; 3705 } 3706 } 3707 if (numMatch == 0) { 3708 return; 3709 } 3710 PackageInfo pi; 3711 if (ps.pkg != null) { 3712 pi = generatePackageInfo(ps.pkg, flags, userId); 3713 } else { 3714 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3715 } 3716 // The above might return null in cases of uninstalled apps or install-state 3717 // skew across users/profiles. 3718 if (pi != null) { 3719 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 3720 if (numMatch == permissions.length) { 3721 pi.requestedPermissions = permissions; 3722 } else { 3723 pi.requestedPermissions = new String[numMatch]; 3724 numMatch = 0; 3725 for (int i=0; i<permissions.length; i++) { 3726 if (tmp[i]) { 3727 pi.requestedPermissions[numMatch] = permissions[i]; 3728 numMatch++; 3729 } 3730 } 3731 } 3732 } 3733 list.add(pi); 3734 } 3735 } 3736 3737 @Override 3738 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 3739 String[] permissions, int flags, int userId) { 3740 if (!sUserManager.exists(userId)) return null; 3741 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3742 3743 // writer 3744 synchronized (mPackages) { 3745 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 3746 boolean[] tmpBools = new boolean[permissions.length]; 3747 if (listUninstalled) { 3748 for (PackageSetting ps : mSettings.mPackages.values()) { 3749 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 3750 } 3751 } else { 3752 for (PackageParser.Package pkg : mPackages.values()) { 3753 PackageSetting ps = (PackageSetting)pkg.mExtras; 3754 if (ps != null) { 3755 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 3756 userId); 3757 } 3758 } 3759 } 3760 3761 return new ParceledListSlice<PackageInfo>(list); 3762 } 3763 } 3764 3765 @Override 3766 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 3767 if (!sUserManager.exists(userId)) return null; 3768 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3769 3770 // writer 3771 synchronized (mPackages) { 3772 ArrayList<ApplicationInfo> list; 3773 if (listUninstalled) { 3774 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 3775 for (PackageSetting ps : mSettings.mPackages.values()) { 3776 ApplicationInfo ai; 3777 if (ps.pkg != null) { 3778 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3779 ps.readUserState(userId), userId); 3780 } else { 3781 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 3782 } 3783 if (ai != null) { 3784 list.add(ai); 3785 } 3786 } 3787 } else { 3788 list = new ArrayList<ApplicationInfo>(mPackages.size()); 3789 for (PackageParser.Package p : mPackages.values()) { 3790 if (p.mExtras != null) { 3791 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3792 ((PackageSetting)p.mExtras).readUserState(userId), userId); 3793 if (ai != null) { 3794 list.add(ai); 3795 } 3796 } 3797 } 3798 } 3799 3800 return new ParceledListSlice<ApplicationInfo>(list); 3801 } 3802 } 3803 3804 public List<ApplicationInfo> getPersistentApplications(int flags) { 3805 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 3806 3807 // reader 3808 synchronized (mPackages) { 3809 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 3810 final int userId = UserHandle.getCallingUserId(); 3811 while (i.hasNext()) { 3812 final PackageParser.Package p = i.next(); 3813 if (p.applicationInfo != null 3814 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 3815 && (!mSafeMode || isSystemApp(p))) { 3816 PackageSetting ps = mSettings.mPackages.get(p.packageName); 3817 if (ps != null) { 3818 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3819 ps.readUserState(userId), userId); 3820 if (ai != null) { 3821 finalList.add(ai); 3822 } 3823 } 3824 } 3825 } 3826 } 3827 3828 return finalList; 3829 } 3830 3831 @Override 3832 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 3833 if (!sUserManager.exists(userId)) return null; 3834 // reader 3835 synchronized (mPackages) { 3836 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 3837 PackageSetting ps = provider != null 3838 ? mSettings.mPackages.get(provider.owner.packageName) 3839 : null; 3840 return ps != null 3841 && mSettings.isEnabledLPr(provider.info, flags, userId) 3842 && (!mSafeMode || (provider.info.applicationInfo.flags 3843 &ApplicationInfo.FLAG_SYSTEM) != 0) 3844 ? PackageParser.generateProviderInfo(provider, flags, 3845 ps.readUserState(userId), userId) 3846 : null; 3847 } 3848 } 3849 3850 /** 3851 * @deprecated 3852 */ 3853 @Deprecated 3854 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 3855 // reader 3856 synchronized (mPackages) { 3857 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 3858 .entrySet().iterator(); 3859 final int userId = UserHandle.getCallingUserId(); 3860 while (i.hasNext()) { 3861 Map.Entry<String, PackageParser.Provider> entry = i.next(); 3862 PackageParser.Provider p = entry.getValue(); 3863 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3864 3865 if (ps != null && p.syncable 3866 && (!mSafeMode || (p.info.applicationInfo.flags 3867 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 3868 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 3869 ps.readUserState(userId), userId); 3870 if (info != null) { 3871 outNames.add(entry.getKey()); 3872 outInfo.add(info); 3873 } 3874 } 3875 } 3876 } 3877 } 3878 3879 @Override 3880 public List<ProviderInfo> queryContentProviders(String processName, 3881 int uid, int flags) { 3882 ArrayList<ProviderInfo> finalList = null; 3883 // reader 3884 synchronized (mPackages) { 3885 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 3886 final int userId = processName != null ? 3887 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 3888 while (i.hasNext()) { 3889 final PackageParser.Provider p = i.next(); 3890 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3891 if (ps != null && p.info.authority != null 3892 && (processName == null 3893 || (p.info.processName.equals(processName) 3894 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 3895 && mSettings.isEnabledLPr(p.info, flags, userId) 3896 && (!mSafeMode 3897 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 3898 if (finalList == null) { 3899 finalList = new ArrayList<ProviderInfo>(3); 3900 } 3901 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 3902 ps.readUserState(userId), userId); 3903 if (info != null) { 3904 finalList.add(info); 3905 } 3906 } 3907 } 3908 } 3909 3910 if (finalList != null) { 3911 Collections.sort(finalList, mProviderInitOrderSorter); 3912 } 3913 3914 return finalList; 3915 } 3916 3917 @Override 3918 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 3919 int flags) { 3920 // reader 3921 synchronized (mPackages) { 3922 final PackageParser.Instrumentation i = mInstrumentation.get(name); 3923 return PackageParser.generateInstrumentationInfo(i, flags); 3924 } 3925 } 3926 3927 @Override 3928 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 3929 int flags) { 3930 ArrayList<InstrumentationInfo> finalList = 3931 new ArrayList<InstrumentationInfo>(); 3932 3933 // reader 3934 synchronized (mPackages) { 3935 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 3936 while (i.hasNext()) { 3937 final PackageParser.Instrumentation p = i.next(); 3938 if (targetPackage == null 3939 || targetPackage.equals(p.info.targetPackage)) { 3940 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 3941 flags); 3942 if (ii != null) { 3943 finalList.add(ii); 3944 } 3945 } 3946 } 3947 } 3948 3949 return finalList; 3950 } 3951 3952 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 3953 HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 3954 if (overlays == null) { 3955 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 3956 return; 3957 } 3958 for (PackageParser.Package opkg : overlays.values()) { 3959 // Not much to do if idmap fails: we already logged the error 3960 // and we certainly don't want to abort installation of pkg simply 3961 // because an overlay didn't fit properly. For these reasons, 3962 // ignore the return value of createIdmapForPackagePairLI. 3963 createIdmapForPackagePairLI(pkg, opkg); 3964 } 3965 } 3966 3967 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 3968 PackageParser.Package opkg) { 3969 if (!opkg.mTrustedOverlay) { 3970 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 3971 opkg.baseCodePath + ": overlay not trusted"); 3972 return false; 3973 } 3974 HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 3975 if (overlaySet == null) { 3976 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 3977 opkg.baseCodePath + " but target package has no known overlays"); 3978 return false; 3979 } 3980 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 3981 // TODO: generate idmap for split APKs 3982 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 3983 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 3984 + opkg.baseCodePath); 3985 return false; 3986 } 3987 PackageParser.Package[] overlayArray = 3988 overlaySet.values().toArray(new PackageParser.Package[0]); 3989 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 3990 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 3991 return p1.mOverlayPriority - p2.mOverlayPriority; 3992 } 3993 }; 3994 Arrays.sort(overlayArray, cmp); 3995 3996 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 3997 int i = 0; 3998 for (PackageParser.Package p : overlayArray) { 3999 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4000 } 4001 return true; 4002 } 4003 4004 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 4005 final File[] files = dir.listFiles(); 4006 if (ArrayUtils.isEmpty(files)) { 4007 Log.d(TAG, "No files in app dir " + dir); 4008 return; 4009 } 4010 4011 if (DEBUG_PACKAGE_SCANNING) { 4012 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 4013 + " flags=0x" + Integer.toHexString(parseFlags)); 4014 } 4015 4016 for (File file : files) { 4017 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 4018 && !PackageInstallerService.isStageName(file.getName()); 4019 if (!isPackage) { 4020 // Ignore entries which are not packages 4021 continue; 4022 } 4023 try { 4024 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 4025 scanFlags, currentTime, null); 4026 } catch (PackageManagerException e) { 4027 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4028 4029 // Delete invalid userdata apps 4030 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4031 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4032 Slog.w(TAG, "Deleting invalid package at " + file); 4033 if (file.isDirectory()) { 4034 FileUtils.deleteContents(file); 4035 } 4036 file.delete(); 4037 } 4038 } 4039 } 4040 } 4041 4042 private static File getSettingsProblemFile() { 4043 File dataDir = Environment.getDataDirectory(); 4044 File systemDir = new File(dataDir, "system"); 4045 File fname = new File(systemDir, "uiderrors.txt"); 4046 return fname; 4047 } 4048 4049 static void reportSettingsProblem(int priority, String msg) { 4050 try { 4051 File fname = getSettingsProblemFile(); 4052 FileOutputStream out = new FileOutputStream(fname, true); 4053 PrintWriter pw = new FastPrintWriter(out); 4054 SimpleDateFormat formatter = new SimpleDateFormat(); 4055 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4056 pw.println(dateString + ": " + msg); 4057 pw.close(); 4058 FileUtils.setPermissions( 4059 fname.toString(), 4060 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4061 -1, -1); 4062 } catch (java.io.IOException e) { 4063 } 4064 Slog.println(priority, TAG, msg); 4065 } 4066 4067 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 4068 PackageParser.Package pkg, File srcFile, int parseFlags) 4069 throws PackageManagerException { 4070 if (ps != null 4071 && ps.codePath.equals(srcFile) 4072 && ps.timeStamp == srcFile.lastModified() 4073 && !isCompatSignatureUpdateNeeded(pkg)) { 4074 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4075 if (ps.signatures.mSignatures != null 4076 && ps.signatures.mSignatures.length != 0 4077 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4078 // Optimization: reuse the existing cached certificates 4079 // if the package appears to be unchanged. 4080 pkg.mSignatures = ps.signatures.mSignatures; 4081 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4082 synchronized (mPackages) { 4083 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 4084 } 4085 return; 4086 } 4087 4088 Slog.w(TAG, "PackageSetting for " + ps.name 4089 + " is missing signatures. Collecting certs again to recover them."); 4090 } else { 4091 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4092 } 4093 4094 try { 4095 pp.collectCertificates(pkg, parseFlags); 4096 pp.collectManifestDigest(pkg); 4097 } catch (PackageParserException e) { 4098 throw PackageManagerException.from(e); 4099 } 4100 } 4101 4102 /* 4103 * Scan a package and return the newly parsed package. 4104 * Returns null in case of errors and the error code is stored in mLastScanError 4105 */ 4106 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 4107 long currentTime, UserHandle user) throws PackageManagerException { 4108 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4109 parseFlags |= mDefParseFlags; 4110 PackageParser pp = new PackageParser(); 4111 pp.setSeparateProcesses(mSeparateProcesses); 4112 pp.setOnlyCoreApps(mOnlyCore); 4113 pp.setDisplayMetrics(mMetrics); 4114 4115 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 4116 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4117 } 4118 4119 final PackageParser.Package pkg; 4120 try { 4121 pkg = pp.parsePackage(scanFile, parseFlags); 4122 } catch (PackageParserException e) { 4123 throw PackageManagerException.from(e); 4124 } 4125 4126 PackageSetting ps = null; 4127 PackageSetting updatedPkg; 4128 // reader 4129 synchronized (mPackages) { 4130 // Look to see if we already know about this package. 4131 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4132 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4133 // This package has been renamed to its original name. Let's 4134 // use that. 4135 ps = mSettings.peekPackageLPr(oldName); 4136 } 4137 // If there was no original package, see one for the real package name. 4138 if (ps == null) { 4139 ps = mSettings.peekPackageLPr(pkg.packageName); 4140 } 4141 // Check to see if this package could be hiding/updating a system 4142 // package. Must look for it either under the original or real 4143 // package name depending on our state. 4144 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4145 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4146 } 4147 boolean updatedPkgBetter = false; 4148 // First check if this is a system package that may involve an update 4149 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4150 if (ps != null && !ps.codePath.equals(scanFile)) { 4151 // The path has changed from what was last scanned... check the 4152 // version of the new path against what we have stored to determine 4153 // what to do. 4154 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4155 if (pkg.mVersionCode < ps.versionCode) { 4156 // The system package has been updated and the code path does not match 4157 // Ignore entry. Skip it. 4158 Log.i(TAG, "Package " + ps.name + " at " + scanFile 4159 + " ignored: updated version " + ps.versionCode 4160 + " better than this " + pkg.mVersionCode); 4161 if (!updatedPkg.codePath.equals(scanFile)) { 4162 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4163 + ps.name + " changing from " + updatedPkg.codePathString 4164 + " to " + scanFile); 4165 updatedPkg.codePath = scanFile; 4166 updatedPkg.codePathString = scanFile.toString(); 4167 // This is the point at which we know that the system-disk APK 4168 // for this package has moved during a reboot (e.g. due to an OTA), 4169 // so we need to reevaluate it for privilege policy. 4170 if (locationIsPrivileged(scanFile)) { 4171 updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED; 4172 } 4173 } 4174 updatedPkg.pkg = pkg; 4175 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 4176 } else { 4177 // The current app on the system partition is better than 4178 // what we have updated to on the data partition; switch 4179 // back to the system partition version. 4180 // At this point, its safely assumed that package installation for 4181 // apps in system partition will go through. If not there won't be a working 4182 // version of the app 4183 // writer 4184 synchronized (mPackages) { 4185 // Just remove the loaded entries from package lists. 4186 mPackages.remove(ps.name); 4187 } 4188 Slog.w(TAG, "Package " + ps.name + " at " + scanFile 4189 + "reverting from " + ps.codePathString 4190 + ": new version " + pkg.mVersionCode 4191 + " better than installed " + ps.versionCode); 4192 4193 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4194 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4195 getAppDexInstructionSets(ps)); 4196 synchronized (mInstallLock) { 4197 args.cleanUpResourcesLI(); 4198 } 4199 synchronized (mPackages) { 4200 mSettings.enableSystemPackageLPw(ps.name); 4201 } 4202 updatedPkgBetter = true; 4203 } 4204 } 4205 } 4206 4207 if (updatedPkg != null) { 4208 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4209 // initially 4210 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4211 4212 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4213 // flag set initially 4214 if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) { 4215 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4216 } 4217 } 4218 4219 // Verify certificates against what was last scanned 4220 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 4221 4222 /* 4223 * A new system app appeared, but we already had a non-system one of the 4224 * same name installed earlier. 4225 */ 4226 boolean shouldHideSystemApp = false; 4227 if (updatedPkg == null && ps != null 4228 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4229 /* 4230 * Check to make sure the signatures match first. If they don't, 4231 * wipe the installed application and its data. 4232 */ 4233 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4234 != PackageManager.SIGNATURE_MATCH) { 4235 if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!"); 4236 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4237 ps = null; 4238 } else { 4239 /* 4240 * If the newly-added system app is an older version than the 4241 * already installed version, hide it. It will be scanned later 4242 * and re-added like an update. 4243 */ 4244 if (pkg.mVersionCode < ps.versionCode) { 4245 shouldHideSystemApp = true; 4246 } else { 4247 /* 4248 * The newly found system app is a newer version that the 4249 * one previously installed. Simply remove the 4250 * already-installed application and replace it with our own 4251 * while keeping the application data. 4252 */ 4253 Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from " 4254 + ps.codePathString + ": new version " + pkg.mVersionCode 4255 + " better than installed " + ps.versionCode); 4256 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4257 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4258 getAppDexInstructionSets(ps)); 4259 synchronized (mInstallLock) { 4260 args.cleanUpResourcesLI(); 4261 } 4262 } 4263 } 4264 } 4265 4266 // The apk is forward locked (not public) if its code and resources 4267 // are kept in different files. (except for app in either system or 4268 // vendor path). 4269 // TODO grab this value from PackageSettings 4270 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4271 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4272 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 4273 } 4274 } 4275 4276 // TODO: extend to support forward-locked splits 4277 String resourcePath = null; 4278 String baseResourcePath = null; 4279 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 4280 if (ps != null && ps.resourcePathString != null) { 4281 resourcePath = ps.resourcePathString; 4282 baseResourcePath = ps.resourcePathString; 4283 } else { 4284 // Should not happen at all. Just log an error. 4285 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 4286 } 4287 } else { 4288 resourcePath = pkg.codePath; 4289 baseResourcePath = pkg.baseCodePath; 4290 } 4291 4292 // Set application objects path explicitly. 4293 pkg.applicationInfo.setCodePath(pkg.codePath); 4294 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 4295 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 4296 pkg.applicationInfo.setResourcePath(resourcePath); 4297 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 4298 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 4299 4300 // Note that we invoke the following method only if we are about to unpack an application 4301 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 4302 | SCAN_UPDATE_SIGNATURE, currentTime, user); 4303 4304 /* 4305 * If the system app should be overridden by a previously installed 4306 * data, hide the system app now and let the /data/app scan pick it up 4307 * again. 4308 */ 4309 if (shouldHideSystemApp) { 4310 synchronized (mPackages) { 4311 /* 4312 * We have to grant systems permissions before we hide, because 4313 * grantPermissions will assume the package update is trying to 4314 * expand its permissions. 4315 */ 4316 grantPermissionsLPw(pkg, true); 4317 mSettings.disableSystemPackageLPw(pkg.packageName); 4318 } 4319 } 4320 4321 return scannedPkg; 4322 } 4323 4324 private static String fixProcessName(String defProcessName, 4325 String processName, int uid) { 4326 if (processName == null) { 4327 return defProcessName; 4328 } 4329 return processName; 4330 } 4331 4332 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 4333 throws PackageManagerException { 4334 if (pkgSetting.signatures.mSignatures != null) { 4335 // Already existing package. Make sure signatures match 4336 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 4337 == PackageManager.SIGNATURE_MATCH; 4338 if (!match) { 4339 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 4340 == PackageManager.SIGNATURE_MATCH; 4341 } 4342 if (!match) { 4343 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 4344 + pkg.packageName + " signatures do not match the " 4345 + "previously installed version; ignoring!"); 4346 } 4347 } 4348 4349 // Check for shared user signatures 4350 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 4351 // Already existing package. Make sure signatures match 4352 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4353 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 4354 if (!match) { 4355 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 4356 == PackageManager.SIGNATURE_MATCH; 4357 } 4358 if (!match) { 4359 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 4360 "Package " + pkg.packageName 4361 + " has no signatures that match those in shared user " 4362 + pkgSetting.sharedUser.name + "; ignoring!"); 4363 } 4364 } 4365 } 4366 4367 /** 4368 * Enforces that only the system UID or root's UID can call a method exposed 4369 * via Binder. 4370 * 4371 * @param message used as message if SecurityException is thrown 4372 * @throws SecurityException if the caller is not system or root 4373 */ 4374 private static final void enforceSystemOrRoot(String message) { 4375 final int uid = Binder.getCallingUid(); 4376 if (uid != Process.SYSTEM_UID && uid != 0) { 4377 throw new SecurityException(message); 4378 } 4379 } 4380 4381 @Override 4382 public void performBootDexOpt() { 4383 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4384 4385 final HashSet<PackageParser.Package> pkgs; 4386 synchronized (mPackages) { 4387 pkgs = mDeferredDexOpt; 4388 mDeferredDexOpt = null; 4389 } 4390 4391 if (pkgs != null) { 4392 // Filter out packages that aren't recently used. 4393 // 4394 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 4395 // should do a full dexopt. 4396 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 4397 // TODO: add a property to control this? 4398 long dexOptLRUThresholdInMinutes; 4399 if (mLazyDexOpt) { 4400 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 4401 } else { 4402 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 4403 } 4404 long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 4405 4406 int total = pkgs.size(); 4407 int skipped = 0; 4408 long now = System.currentTimeMillis(); 4409 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 4410 PackageParser.Package pkg = i.next(); 4411 long then = pkg.mLastPackageUsageTimeInMills; 4412 if (then + dexOptLRUThresholdInMills < now) { 4413 if (DEBUG_DEXOPT) { 4414 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 4415 ((then == 0) ? "never" : new Date(then))); 4416 } 4417 i.remove(); 4418 skipped++; 4419 } 4420 } 4421 if (DEBUG_DEXOPT) { 4422 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 4423 } 4424 } 4425 4426 int i = 0; 4427 for (PackageParser.Package pkg : pkgs) { 4428 i++; 4429 if (DEBUG_DEXOPT) { 4430 Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size() 4431 + ": " + pkg.packageName); 4432 } 4433 if (!isFirstBoot()) { 4434 try { 4435 ActivityManagerNative.getDefault().showBootMessage( 4436 mContext.getResources().getString( 4437 R.string.android_upgrading_apk, 4438 i, pkgs.size()), true); 4439 } catch (RemoteException e) { 4440 } 4441 } 4442 PackageParser.Package p = pkg; 4443 synchronized (mInstallLock) { 4444 performDexOptLI(p, null /* instruction sets */, false /* force dex */, false /* defer */, 4445 true /* include dependencies */); 4446 } 4447 } 4448 } 4449 } 4450 4451 @Override 4452 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 4453 return performDexOpt(packageName, instructionSet, false); 4454 } 4455 4456 private static String getPrimaryInstructionSet(ApplicationInfo info) { 4457 if (info.primaryCpuAbi == null) { 4458 return getPreferredInstructionSet(); 4459 } 4460 4461 return VMRuntime.getInstructionSet(info.primaryCpuAbi); 4462 } 4463 4464 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 4465 boolean dexopt = mLazyDexOpt || backgroundDexopt; 4466 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 4467 if (!dexopt && !updateUsage) { 4468 // We aren't going to dexopt or update usage, so bail early. 4469 return false; 4470 } 4471 PackageParser.Package p; 4472 final String targetInstructionSet; 4473 synchronized (mPackages) { 4474 p = mPackages.get(packageName); 4475 if (p == null) { 4476 return false; 4477 } 4478 if (updateUsage) { 4479 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 4480 } 4481 mPackageUsage.write(false); 4482 if (!dexopt) { 4483 // We aren't going to dexopt, so bail early. 4484 return false; 4485 } 4486 4487 targetInstructionSet = instructionSet != null ? instructionSet : 4488 getPrimaryInstructionSet(p.applicationInfo); 4489 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 4490 return false; 4491 } 4492 } 4493 4494 synchronized (mInstallLock) { 4495 final String[] instructionSets = new String[] { targetInstructionSet }; 4496 return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */, 4497 true /* include dependencies */) == DEX_OPT_PERFORMED; 4498 } 4499 } 4500 4501 public HashSet<String> getPackagesThatNeedDexOpt() { 4502 HashSet<String> pkgs = null; 4503 synchronized (mPackages) { 4504 for (PackageParser.Package p : mPackages.values()) { 4505 if (DEBUG_DEXOPT) { 4506 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 4507 } 4508 if (!p.mDexOptPerformed.isEmpty()) { 4509 continue; 4510 } 4511 if (pkgs == null) { 4512 pkgs = new HashSet<String>(); 4513 } 4514 pkgs.add(p.packageName); 4515 } 4516 } 4517 return pkgs; 4518 } 4519 4520 public void shutdown() { 4521 mPackageUsage.write(true); 4522 } 4523 4524 private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets, 4525 boolean forceDex, boolean defer, HashSet<String> done) { 4526 for (int i=0; i<libs.size(); i++) { 4527 PackageParser.Package libPkg; 4528 String libName; 4529 synchronized (mPackages) { 4530 libName = libs.get(i); 4531 SharedLibraryEntry lib = mSharedLibraries.get(libName); 4532 if (lib != null && lib.apk != null) { 4533 libPkg = mPackages.get(lib.apk); 4534 } else { 4535 libPkg = null; 4536 } 4537 } 4538 if (libPkg != null && !done.contains(libName)) { 4539 performDexOptLI(libPkg, instructionSets, forceDex, defer, done); 4540 } 4541 } 4542 } 4543 4544 static final int DEX_OPT_SKIPPED = 0; 4545 static final int DEX_OPT_PERFORMED = 1; 4546 static final int DEX_OPT_DEFERRED = 2; 4547 static final int DEX_OPT_FAILED = -1; 4548 4549 private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets, 4550 boolean forceDex, boolean defer, HashSet<String> done) { 4551 final String[] instructionSets = targetInstructionSets != null ? 4552 targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo); 4553 4554 if (done != null) { 4555 done.add(pkg.packageName); 4556 if (pkg.usesLibraries != null) { 4557 performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done); 4558 } 4559 if (pkg.usesOptionalLibraries != null) { 4560 performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done); 4561 } 4562 } 4563 4564 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) { 4565 return DEX_OPT_SKIPPED; 4566 } 4567 4568 final boolean vmSafeMode = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0; 4569 4570 final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly(); 4571 boolean performedDexOpt = false; 4572 // There are three basic cases here: 4573 // 1.) we need to dexopt, either because we are forced or it is needed 4574 // 2.) we are defering a needed dexopt 4575 // 3.) we are skipping an unneeded dexopt 4576 final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 4577 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 4578 if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) { 4579 continue; 4580 } 4581 4582 for (String path : paths) { 4583 try { 4584 // This will return DEXOPT_NEEDED if we either cannot find any odex file for this 4585 // patckage or the one we find does not match the image checksum (i.e. it was 4586 // compiled against an old image). It will return PATCHOAT_NEEDED if we can find a 4587 // odex file and it matches the checksum of the image but not its base address, 4588 // meaning we need to move it. 4589 final byte isDexOptNeeded = DexFile.isDexOptNeededInternal(path, 4590 pkg.packageName, dexCodeInstructionSet, defer); 4591 if (forceDex || (!defer && isDexOptNeeded == DexFile.DEXOPT_NEEDED)) { 4592 Log.i(TAG, "Running dexopt on: " + path + " pkg=" 4593 + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet 4594 + " vmSafeMode=" + vmSafeMode); 4595 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4596 final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg), 4597 pkg.packageName, dexCodeInstructionSet, vmSafeMode); 4598 4599 if (ret < 0) { 4600 // Don't bother running dexopt again if we failed, it will probably 4601 // just result in an error again. Also, don't bother dexopting for other 4602 // paths & ISAs. 4603 return DEX_OPT_FAILED; 4604 } 4605 4606 performedDexOpt = true; 4607 } else if (!defer && isDexOptNeeded == DexFile.PATCHOAT_NEEDED) { 4608 Log.i(TAG, "Running patchoat on: " + pkg.applicationInfo.packageName); 4609 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4610 final int ret = mInstaller.patchoat(path, sharedGid, !isForwardLocked(pkg), 4611 pkg.packageName, dexCodeInstructionSet); 4612 4613 if (ret < 0) { 4614 // Don't bother running patchoat again if we failed, it will probably 4615 // just result in an error again. Also, don't bother dexopting for other 4616 // paths & ISAs. 4617 return DEX_OPT_FAILED; 4618 } 4619 4620 performedDexOpt = true; 4621 } 4622 4623 // We're deciding to defer a needed dexopt. Don't bother dexopting for other 4624 // paths and instruction sets. We'll deal with them all together when we process 4625 // our list of deferred dexopts. 4626 if (defer && isDexOptNeeded != DexFile.UP_TO_DATE) { 4627 if (mDeferredDexOpt == null) { 4628 mDeferredDexOpt = new HashSet<PackageParser.Package>(); 4629 } 4630 mDeferredDexOpt.add(pkg); 4631 return DEX_OPT_DEFERRED; 4632 } 4633 } catch (FileNotFoundException e) { 4634 Slog.w(TAG, "Apk not found for dexopt: " + path); 4635 return DEX_OPT_FAILED; 4636 } catch (IOException e) { 4637 Slog.w(TAG, "IOException reading apk: " + path, e); 4638 return DEX_OPT_FAILED; 4639 } catch (StaleDexCacheError e) { 4640 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e); 4641 return DEX_OPT_FAILED; 4642 } catch (Exception e) { 4643 Slog.w(TAG, "Exception when doing dexopt : ", e); 4644 return DEX_OPT_FAILED; 4645 } 4646 } 4647 4648 // At this point we haven't failed dexopt and we haven't deferred dexopt. We must 4649 // either have either succeeded dexopt, or have had isDexOptNeededInternal tell us 4650 // it isn't required. We therefore mark that this package doesn't need dexopt unless 4651 // it's forced. performedDexOpt will tell us whether we performed dex-opt or skipped 4652 // it. 4653 pkg.mDexOptPerformed.add(dexCodeInstructionSet); 4654 } 4655 4656 // If we've gotten here, we're sure that no error occurred and that we haven't 4657 // deferred dex-opt. We've either dex-opted one more paths or instruction sets or 4658 // we've skipped all of them because they are up to date. In both cases this 4659 // package doesn't need dexopt any longer. 4660 return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED; 4661 } 4662 4663 private static String[] getAppDexInstructionSets(ApplicationInfo info) { 4664 if (info.primaryCpuAbi != null) { 4665 if (info.secondaryCpuAbi != null) { 4666 return new String[] { 4667 VMRuntime.getInstructionSet(info.primaryCpuAbi), 4668 VMRuntime.getInstructionSet(info.secondaryCpuAbi) }; 4669 } else { 4670 return new String[] { 4671 VMRuntime.getInstructionSet(info.primaryCpuAbi) }; 4672 } 4673 } 4674 4675 return new String[] { getPreferredInstructionSet() }; 4676 } 4677 4678 private static String[] getAppDexInstructionSets(PackageSetting ps) { 4679 if (ps.primaryCpuAbiString != null) { 4680 if (ps.secondaryCpuAbiString != null) { 4681 return new String[] { 4682 VMRuntime.getInstructionSet(ps.primaryCpuAbiString), 4683 VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) }; 4684 } else { 4685 return new String[] { 4686 VMRuntime.getInstructionSet(ps.primaryCpuAbiString) }; 4687 } 4688 } 4689 4690 return new String[] { getPreferredInstructionSet() }; 4691 } 4692 4693 private static String getPreferredInstructionSet() { 4694 if (sPreferredInstructionSet == null) { 4695 sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]); 4696 } 4697 4698 return sPreferredInstructionSet; 4699 } 4700 4701 private static List<String> getAllInstructionSets() { 4702 final String[] allAbis = Build.SUPPORTED_ABIS; 4703 final List<String> allInstructionSets = new ArrayList<String>(allAbis.length); 4704 4705 for (String abi : allAbis) { 4706 final String instructionSet = VMRuntime.getInstructionSet(abi); 4707 if (!allInstructionSets.contains(instructionSet)) { 4708 allInstructionSets.add(instructionSet); 4709 } 4710 } 4711 4712 return allInstructionSets; 4713 } 4714 4715 /** 4716 * Returns the instruction set that should be used to compile dex code. In the presence of 4717 * a native bridge this might be different than the one shared libraries use. 4718 */ 4719 private static String getDexCodeInstructionSet(String sharedLibraryIsa) { 4720 String dexCodeIsa = SystemProperties.get("ro.dalvik.vm.isa." + sharedLibraryIsa); 4721 return (dexCodeIsa.isEmpty() ? sharedLibraryIsa : dexCodeIsa); 4722 } 4723 4724 private static String[] getDexCodeInstructionSets(String[] instructionSets) { 4725 HashSet<String> dexCodeInstructionSets = new HashSet<String>(instructionSets.length); 4726 for (String instructionSet : instructionSets) { 4727 dexCodeInstructionSets.add(getDexCodeInstructionSet(instructionSet)); 4728 } 4729 return dexCodeInstructionSets.toArray(new String[dexCodeInstructionSets.size()]); 4730 } 4731 4732 @Override 4733 public void forceDexOpt(String packageName) { 4734 enforceSystemOrRoot("forceDexOpt"); 4735 4736 PackageParser.Package pkg; 4737 synchronized (mPackages) { 4738 pkg = mPackages.get(packageName); 4739 if (pkg == null) { 4740 throw new IllegalArgumentException("Missing package: " + packageName); 4741 } 4742 } 4743 4744 synchronized (mInstallLock) { 4745 final String[] instructionSets = new String[] { 4746 getPrimaryInstructionSet(pkg.applicationInfo) }; 4747 final int res = performDexOptLI(pkg, instructionSets, true, false, true); 4748 if (res != DEX_OPT_PERFORMED) { 4749 throw new IllegalStateException("Failed to dexopt: " + res); 4750 } 4751 } 4752 } 4753 4754 private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets, 4755 boolean forceDex, boolean defer, boolean inclDependencies) { 4756 HashSet<String> done; 4757 if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) { 4758 done = new HashSet<String>(); 4759 done.add(pkg.packageName); 4760 } else { 4761 done = null; 4762 } 4763 return performDexOptLI(pkg, instructionSets, forceDex, defer, done); 4764 } 4765 4766 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 4767 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 4768 Slog.w(TAG, "Unable to update from " + oldPkg.name 4769 + " to " + newPkg.packageName 4770 + ": old package not in system partition"); 4771 return false; 4772 } else if (mPackages.get(oldPkg.name) != null) { 4773 Slog.w(TAG, "Unable to update from " + oldPkg.name 4774 + " to " + newPkg.packageName 4775 + ": old package still exists"); 4776 return false; 4777 } 4778 return true; 4779 } 4780 4781 File getDataPathForUser(int userId) { 4782 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId); 4783 } 4784 4785 private File getDataPathForPackage(String packageName, int userId) { 4786 /* 4787 * Until we fully support multiple users, return the directory we 4788 * previously would have. The PackageManagerTests will need to be 4789 * revised when this is changed back.. 4790 */ 4791 if (userId == 0) { 4792 return new File(mAppDataDir, packageName); 4793 } else { 4794 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 4795 + File.separator + packageName); 4796 } 4797 } 4798 4799 private int createDataDirsLI(String packageName, int uid, String seinfo) { 4800 int[] users = sUserManager.getUserIds(); 4801 int res = mInstaller.install(packageName, uid, uid, seinfo); 4802 if (res < 0) { 4803 return res; 4804 } 4805 for (int user : users) { 4806 if (user != 0) { 4807 res = mInstaller.createUserData(packageName, 4808 UserHandle.getUid(user, uid), user, seinfo); 4809 if (res < 0) { 4810 return res; 4811 } 4812 } 4813 } 4814 return res; 4815 } 4816 4817 private int removeDataDirsLI(String packageName) { 4818 int[] users = sUserManager.getUserIds(); 4819 int res = 0; 4820 for (int user : users) { 4821 int resInner = mInstaller.remove(packageName, user); 4822 if (resInner < 0) { 4823 res = resInner; 4824 } 4825 } 4826 4827 return res; 4828 } 4829 4830 private int deleteCodeCacheDirsLI(String packageName) { 4831 int[] users = sUserManager.getUserIds(); 4832 int res = 0; 4833 for (int user : users) { 4834 int resInner = mInstaller.deleteCodeCacheFiles(packageName, user); 4835 if (resInner < 0) { 4836 res = resInner; 4837 } 4838 } 4839 return res; 4840 } 4841 4842 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 4843 PackageParser.Package changingLib) { 4844 if (file.path != null) { 4845 usesLibraryFiles.add(file.path); 4846 return; 4847 } 4848 PackageParser.Package p = mPackages.get(file.apk); 4849 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 4850 // If we are doing this while in the middle of updating a library apk, 4851 // then we need to make sure to use that new apk for determining the 4852 // dependencies here. (We haven't yet finished committing the new apk 4853 // to the package manager state.) 4854 if (p == null || p.packageName.equals(changingLib.packageName)) { 4855 p = changingLib; 4856 } 4857 } 4858 if (p != null) { 4859 usesLibraryFiles.addAll(p.getAllCodePaths()); 4860 } 4861 } 4862 4863 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 4864 PackageParser.Package changingLib) throws PackageManagerException { 4865 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 4866 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 4867 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 4868 for (int i=0; i<N; i++) { 4869 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 4870 if (file == null) { 4871 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 4872 "Package " + pkg.packageName + " requires unavailable shared library " 4873 + pkg.usesLibraries.get(i) + "; failing!"); 4874 } 4875 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4876 } 4877 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 4878 for (int i=0; i<N; i++) { 4879 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 4880 if (file == null) { 4881 Slog.w(TAG, "Package " + pkg.packageName 4882 + " desires unavailable shared library " 4883 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 4884 } else { 4885 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4886 } 4887 } 4888 N = usesLibraryFiles.size(); 4889 if (N > 0) { 4890 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 4891 } else { 4892 pkg.usesLibraryFiles = null; 4893 } 4894 } 4895 } 4896 4897 private static boolean hasString(List<String> list, List<String> which) { 4898 if (list == null) { 4899 return false; 4900 } 4901 for (int i=list.size()-1; i>=0; i--) { 4902 for (int j=which.size()-1; j>=0; j--) { 4903 if (which.get(j).equals(list.get(i))) { 4904 return true; 4905 } 4906 } 4907 } 4908 return false; 4909 } 4910 4911 private void updateAllSharedLibrariesLPw() { 4912 for (PackageParser.Package pkg : mPackages.values()) { 4913 try { 4914 updateSharedLibrariesLPw(pkg, null); 4915 } catch (PackageManagerException e) { 4916 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 4917 } 4918 } 4919 } 4920 4921 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 4922 PackageParser.Package changingPkg) { 4923 ArrayList<PackageParser.Package> res = null; 4924 for (PackageParser.Package pkg : mPackages.values()) { 4925 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 4926 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 4927 if (res == null) { 4928 res = new ArrayList<PackageParser.Package>(); 4929 } 4930 res.add(pkg); 4931 try { 4932 updateSharedLibrariesLPw(pkg, changingPkg); 4933 } catch (PackageManagerException e) { 4934 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 4935 } 4936 } 4937 } 4938 return res; 4939 } 4940 4941 /** 4942 * Derive the value of the {@code cpuAbiOverride} based on the provided 4943 * value and an optional stored value from the package settings. 4944 */ 4945 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 4946 String cpuAbiOverride = null; 4947 4948 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 4949 cpuAbiOverride = null; 4950 } else if (abiOverride != null) { 4951 cpuAbiOverride = abiOverride; 4952 } else if (settings != null) { 4953 cpuAbiOverride = settings.cpuAbiOverrideString; 4954 } 4955 4956 return cpuAbiOverride; 4957 } 4958 4959 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 4960 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 4961 final File scanFile = new File(pkg.codePath); 4962 if (pkg.applicationInfo.getCodePath() == null || 4963 pkg.applicationInfo.getResourcePath() == null) { 4964 // Bail out. The resource and code paths haven't been set. 4965 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 4966 "Code and resource paths haven't been set correctly"); 4967 } 4968 4969 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4970 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 4971 } 4972 4973 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 4974 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED; 4975 } 4976 4977 if (mCustomResolverComponentName != null && 4978 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 4979 setUpCustomResolverActivity(pkg); 4980 } 4981 4982 if (pkg.packageName.equals("android")) { 4983 synchronized (mPackages) { 4984 if (mAndroidApplication != null) { 4985 Slog.w(TAG, "*************************************************"); 4986 Slog.w(TAG, "Core android package being redefined. Skipping."); 4987 Slog.w(TAG, " file=" + scanFile); 4988 Slog.w(TAG, "*************************************************"); 4989 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 4990 "Core android package being redefined. Skipping."); 4991 } 4992 4993 // Set up information for our fall-back user intent resolution activity. 4994 mPlatformPackage = pkg; 4995 pkg.mVersionCode = mSdkVersion; 4996 mAndroidApplication = pkg.applicationInfo; 4997 4998 if (!mResolverReplaced) { 4999 mResolveActivity.applicationInfo = mAndroidApplication; 5000 mResolveActivity.name = ResolverActivity.class.getName(); 5001 mResolveActivity.packageName = mAndroidApplication.packageName; 5002 mResolveActivity.processName = "system:ui"; 5003 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5004 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5005 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5006 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5007 mResolveActivity.exported = true; 5008 mResolveActivity.enabled = true; 5009 mResolveInfo.activityInfo = mResolveActivity; 5010 mResolveInfo.priority = 0; 5011 mResolveInfo.preferredOrder = 0; 5012 mResolveInfo.match = 0; 5013 mResolveComponentName = new ComponentName( 5014 mAndroidApplication.packageName, mResolveActivity.name); 5015 } 5016 } 5017 } 5018 5019 if (DEBUG_PACKAGE_SCANNING) { 5020 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5021 Log.d(TAG, "Scanning package " + pkg.packageName); 5022 } 5023 5024 if (mPackages.containsKey(pkg.packageName) 5025 || mSharedLibraries.containsKey(pkg.packageName)) { 5026 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5027 "Application package " + pkg.packageName 5028 + " already installed. Skipping duplicate."); 5029 } 5030 5031 // Initialize package source and resource directories 5032 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5033 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5034 5035 SharedUserSetting suid = null; 5036 PackageSetting pkgSetting = null; 5037 5038 if (!isSystemApp(pkg)) { 5039 // Only system apps can use these features. 5040 pkg.mOriginalPackages = null; 5041 pkg.mRealPackage = null; 5042 pkg.mAdoptPermissions = null; 5043 } 5044 5045 // writer 5046 synchronized (mPackages) { 5047 if (pkg.mSharedUserId != null) { 5048 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true); 5049 if (suid == null) { 5050 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5051 "Creating application package " + pkg.packageName 5052 + " for shared user failed"); 5053 } 5054 if (DEBUG_PACKAGE_SCANNING) { 5055 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5056 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5057 + "): packages=" + suid.packages); 5058 } 5059 } 5060 5061 // Check if we are renaming from an original package name. 5062 PackageSetting origPackage = null; 5063 String realName = null; 5064 if (pkg.mOriginalPackages != null) { 5065 // This package may need to be renamed to a previously 5066 // installed name. Let's check on that... 5067 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5068 if (pkg.mOriginalPackages.contains(renamed)) { 5069 // This package had originally been installed as the 5070 // original name, and we have already taken care of 5071 // transitioning to the new one. Just update the new 5072 // one to continue using the old name. 5073 realName = pkg.mRealPackage; 5074 if (!pkg.packageName.equals(renamed)) { 5075 // Callers into this function may have already taken 5076 // care of renaming the package; only do it here if 5077 // it is not already done. 5078 pkg.setPackageName(renamed); 5079 } 5080 5081 } else { 5082 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5083 if ((origPackage = mSettings.peekPackageLPr( 5084 pkg.mOriginalPackages.get(i))) != null) { 5085 // We do have the package already installed under its 5086 // original name... should we use it? 5087 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5088 // New package is not compatible with original. 5089 origPackage = null; 5090 continue; 5091 } else if (origPackage.sharedUser != null) { 5092 // Make sure uid is compatible between packages. 5093 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5094 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5095 + " to " + pkg.packageName + ": old uid " 5096 + origPackage.sharedUser.name 5097 + " differs from " + pkg.mSharedUserId); 5098 origPackage = null; 5099 continue; 5100 } 5101 } else { 5102 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5103 + pkg.packageName + " to old name " + origPackage.name); 5104 } 5105 break; 5106 } 5107 } 5108 } 5109 } 5110 5111 if (mTransferedPackages.contains(pkg.packageName)) { 5112 Slog.w(TAG, "Package " + pkg.packageName 5113 + " was transferred to another, but its .apk remains"); 5114 } 5115 5116 // Just create the setting, don't add it yet. For already existing packages 5117 // the PkgSetting exists already and doesn't have to be created. 5118 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5119 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 5120 pkg.applicationInfo.primaryCpuAbi, 5121 pkg.applicationInfo.secondaryCpuAbi, 5122 pkg.applicationInfo.flags, user, false); 5123 if (pkgSetting == null) { 5124 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5125 "Creating application package " + pkg.packageName + " failed"); 5126 } 5127 5128 if (pkgSetting.origPackage != null) { 5129 // If we are first transitioning from an original package, 5130 // fix up the new package's name now. We need to do this after 5131 // looking up the package under its new name, so getPackageLP 5132 // can take care of fiddling things correctly. 5133 pkg.setPackageName(origPackage.name); 5134 5135 // File a report about this. 5136 String msg = "New package " + pkgSetting.realName 5137 + " renamed to replace old package " + pkgSetting.name; 5138 reportSettingsProblem(Log.WARN, msg); 5139 5140 // Make a note of it. 5141 mTransferedPackages.add(origPackage.name); 5142 5143 // No longer need to retain this. 5144 pkgSetting.origPackage = null; 5145 } 5146 5147 if (realName != null) { 5148 // Make a note of it. 5149 mTransferedPackages.add(pkg.packageName); 5150 } 5151 5152 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5153 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5154 } 5155 5156 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5157 // Check all shared libraries and map to their actual file path. 5158 // We only do this here for apps not on a system dir, because those 5159 // are the only ones that can fail an install due to this. We 5160 // will take care of the system apps by updating all of their 5161 // library paths after the scan is done. 5162 updateSharedLibrariesLPw(pkg, null); 5163 } 5164 5165 if (mFoundPolicyFile) { 5166 SELinuxMMAC.assignSeinfoValue(pkg); 5167 } 5168 5169 pkg.applicationInfo.uid = pkgSetting.appId; 5170 pkg.mExtras = pkgSetting; 5171 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5172 try { 5173 verifySignaturesLP(pkgSetting, pkg); 5174 } catch (PackageManagerException e) { 5175 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5176 throw e; 5177 } 5178 // The signature has changed, but this package is in the system 5179 // image... let's recover! 5180 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5181 // However... if this package is part of a shared user, but it 5182 // doesn't match the signature of the shared user, let's fail. 5183 // What this means is that you can't change the signatures 5184 // associated with an overall shared user, which doesn't seem all 5185 // that unreasonable. 5186 if (pkgSetting.sharedUser != null) { 5187 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5188 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5189 throw new PackageManagerException( 5190 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 5191 "Signature mismatch for shared user : " 5192 + pkgSetting.sharedUser); 5193 } 5194 } 5195 // File a report about this. 5196 String msg = "System package " + pkg.packageName 5197 + " signature changed; retaining data."; 5198 reportSettingsProblem(Log.WARN, msg); 5199 } 5200 } else { 5201 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 5202 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5203 + pkg.packageName + " upgrade keys do not match the " 5204 + "previously installed version"); 5205 } else { 5206 // signatures may have changed as result of upgrade 5207 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5208 } 5209 } 5210 // Verify that this new package doesn't have any content providers 5211 // that conflict with existing packages. Only do this if the 5212 // package isn't already installed, since we don't want to break 5213 // things that are installed. 5214 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 5215 final int N = pkg.providers.size(); 5216 int i; 5217 for (i=0; i<N; i++) { 5218 PackageParser.Provider p = pkg.providers.get(i); 5219 if (p.info.authority != null) { 5220 String names[] = p.info.authority.split(";"); 5221 for (int j = 0; j < names.length; j++) { 5222 if (mProvidersByAuthority.containsKey(names[j])) { 5223 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5224 final String otherPackageName = 5225 ((other != null && other.getComponentName() != null) ? 5226 other.getComponentName().getPackageName() : "?"); 5227 throw new PackageManagerException( 5228 INSTALL_FAILED_CONFLICTING_PROVIDER, 5229 "Can't install because provider name " + names[j] 5230 + " (in package " + pkg.applicationInfo.packageName 5231 + ") is already used by " + otherPackageName); 5232 } 5233 } 5234 } 5235 } 5236 } 5237 5238 if (pkg.mAdoptPermissions != null) { 5239 // This package wants to adopt ownership of permissions from 5240 // another package. 5241 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 5242 final String origName = pkg.mAdoptPermissions.get(i); 5243 final PackageSetting orig = mSettings.peekPackageLPr(origName); 5244 if (orig != null) { 5245 if (verifyPackageUpdateLPr(orig, pkg)) { 5246 Slog.i(TAG, "Adopting permissions from " + origName + " to " 5247 + pkg.packageName); 5248 mSettings.transferPermissionsLPw(origName, pkg.packageName); 5249 } 5250 } 5251 } 5252 } 5253 } 5254 5255 final String pkgName = pkg.packageName; 5256 5257 final long scanFileTime = scanFile.lastModified(); 5258 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 5259 pkg.applicationInfo.processName = fixProcessName( 5260 pkg.applicationInfo.packageName, 5261 pkg.applicationInfo.processName, 5262 pkg.applicationInfo.uid); 5263 5264 File dataPath; 5265 if (mPlatformPackage == pkg) { 5266 // The system package is special. 5267 dataPath = new File (Environment.getDataDirectory(), "system"); 5268 pkg.applicationInfo.dataDir = dataPath.getPath(); 5269 5270 } else { 5271 // This is a normal package, need to make its data directory. 5272 dataPath = getDataPathForPackage(pkg.packageName, 0); 5273 5274 boolean uidError = false; 5275 5276 if (dataPath.exists()) { 5277 int currentUid = 0; 5278 try { 5279 StructStat stat = Os.stat(dataPath.getPath()); 5280 currentUid = stat.st_uid; 5281 } catch (ErrnoException e) { 5282 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 5283 } 5284 5285 // If we have mismatched owners for the data path, we have a problem. 5286 if (currentUid != pkg.applicationInfo.uid) { 5287 boolean recovered = false; 5288 if (currentUid == 0) { 5289 // The directory somehow became owned by root. Wow. 5290 // This is probably because the system was stopped while 5291 // installd was in the middle of messing with its libs 5292 // directory. Ask installd to fix that. 5293 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 5294 pkg.applicationInfo.uid); 5295 if (ret >= 0) { 5296 recovered = true; 5297 String msg = "Package " + pkg.packageName 5298 + " unexpectedly changed to uid 0; recovered to " + 5299 + pkg.applicationInfo.uid; 5300 reportSettingsProblem(Log.WARN, msg); 5301 } 5302 } 5303 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5304 || (scanFlags&SCAN_BOOTING) != 0)) { 5305 // If this is a system app, we can at least delete its 5306 // current data so the application will still work. 5307 int ret = removeDataDirsLI(pkgName); 5308 if (ret >= 0) { 5309 // TODO: Kill the processes first 5310 // Old data gone! 5311 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5312 ? "System package " : "Third party package "; 5313 String msg = prefix + pkg.packageName 5314 + " has changed from uid: " 5315 + currentUid + " to " 5316 + pkg.applicationInfo.uid + "; old data erased"; 5317 reportSettingsProblem(Log.WARN, msg); 5318 recovered = true; 5319 5320 // And now re-install the app. 5321 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5322 pkg.applicationInfo.seinfo); 5323 if (ret == -1) { 5324 // Ack should not happen! 5325 msg = prefix + pkg.packageName 5326 + " could not have data directory re-created after delete."; 5327 reportSettingsProblem(Log.WARN, msg); 5328 throw new PackageManagerException( 5329 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 5330 } 5331 } 5332 if (!recovered) { 5333 mHasSystemUidErrors = true; 5334 } 5335 } else if (!recovered) { 5336 // If we allow this install to proceed, we will be broken. 5337 // Abort, abort! 5338 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 5339 "scanPackageLI"); 5340 } 5341 if (!recovered) { 5342 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 5343 + pkg.applicationInfo.uid + "/fs_" 5344 + currentUid; 5345 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 5346 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 5347 String msg = "Package " + pkg.packageName 5348 + " has mismatched uid: " 5349 + currentUid + " on disk, " 5350 + pkg.applicationInfo.uid + " in settings"; 5351 // writer 5352 synchronized (mPackages) { 5353 mSettings.mReadMessages.append(msg); 5354 mSettings.mReadMessages.append('\n'); 5355 uidError = true; 5356 if (!pkgSetting.uidError) { 5357 reportSettingsProblem(Log.ERROR, msg); 5358 } 5359 } 5360 } 5361 } 5362 pkg.applicationInfo.dataDir = dataPath.getPath(); 5363 if (mShouldRestoreconData) { 5364 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 5365 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 5366 pkg.applicationInfo.uid); 5367 } 5368 } else { 5369 if (DEBUG_PACKAGE_SCANNING) { 5370 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5371 Log.v(TAG, "Want this data dir: " + dataPath); 5372 } 5373 //invoke installer to do the actual installation 5374 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5375 pkg.applicationInfo.seinfo); 5376 if (ret < 0) { 5377 // Error from installer 5378 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5379 "Unable to create data dirs [errorCode=" + ret + "]"); 5380 } 5381 5382 if (dataPath.exists()) { 5383 pkg.applicationInfo.dataDir = dataPath.getPath(); 5384 } else { 5385 Slog.w(TAG, "Unable to create data directory: " + dataPath); 5386 pkg.applicationInfo.dataDir = null; 5387 } 5388 } 5389 5390 pkgSetting.uidError = uidError; 5391 } 5392 5393 final String path = scanFile.getPath(); 5394 final String codePath = pkg.applicationInfo.getCodePath(); 5395 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 5396 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 5397 setBundledAppAbisAndRoots(pkg, pkgSetting); 5398 5399 // If we haven't found any native libraries for the app, check if it has 5400 // renderscript code. We'll need to force the app to 32 bit if it has 5401 // renderscript bitcode. 5402 if (pkg.applicationInfo.primaryCpuAbi == null 5403 && pkg.applicationInfo.secondaryCpuAbi == null 5404 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5405 NativeLibraryHelper.Handle handle = null; 5406 try { 5407 handle = NativeLibraryHelper.Handle.create(scanFile); 5408 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5409 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 5410 } 5411 } catch (IOException ioe) { 5412 Slog.w(TAG, "Error scanning system app : " + ioe); 5413 } finally { 5414 IoUtils.closeQuietly(handle); 5415 } 5416 } 5417 5418 setNativeLibraryPaths(pkg); 5419 } else { 5420 // TODO: We can probably be smarter about this stuff. For installed apps, 5421 // we can calculate this information at install time once and for all. For 5422 // system apps, we can probably assume that this information doesn't change 5423 // after the first boot scan. As things stand, we do lots of unnecessary work. 5424 5425 // Give ourselves some initial paths; we'll come back for another 5426 // pass once we've determined ABI below. 5427 setNativeLibraryPaths(pkg); 5428 5429 final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg); 5430 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 5431 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 5432 5433 NativeLibraryHelper.Handle handle = null; 5434 try { 5435 handle = NativeLibraryHelper.Handle.create(scanFile); 5436 // TODO(multiArch): This can be null for apps that didn't go through the 5437 // usual installation process. We can calculate it again, like we 5438 // do during install time. 5439 // 5440 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 5441 // unnecessary. 5442 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 5443 5444 // Null out the abis so that they can be recalculated. 5445 pkg.applicationInfo.primaryCpuAbi = null; 5446 pkg.applicationInfo.secondaryCpuAbi = null; 5447 if (isMultiArch(pkg.applicationInfo)) { 5448 // Warn if we've set an abiOverride for multi-lib packages.. 5449 // By definition, we need to copy both 32 and 64 bit libraries for 5450 // such packages. 5451 if (pkg.cpuAbiOverride != null 5452 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 5453 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 5454 } 5455 5456 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 5457 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 5458 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 5459 if (isAsec) { 5460 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 5461 } else { 5462 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5463 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 5464 useIsaSpecificSubdirs); 5465 } 5466 } 5467 5468 maybeThrowExceptionForMultiArchCopy( 5469 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 5470 5471 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5472 if (isAsec) { 5473 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 5474 } else { 5475 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5476 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 5477 useIsaSpecificSubdirs); 5478 } 5479 } 5480 5481 maybeThrowExceptionForMultiArchCopy( 5482 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 5483 5484 if (abi64 >= 0) { 5485 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 5486 } 5487 5488 if (abi32 >= 0) { 5489 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 5490 if (abi64 >= 0) { 5491 pkg.applicationInfo.secondaryCpuAbi = abi; 5492 } else { 5493 pkg.applicationInfo.primaryCpuAbi = abi; 5494 } 5495 } 5496 } else { 5497 String[] abiList = (cpuAbiOverride != null) ? 5498 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 5499 5500 // Enable gross and lame hacks for apps that are built with old 5501 // SDK tools. We must scan their APKs for renderscript bitcode and 5502 // not launch them if it's present. Don't bother checking on devices 5503 // that don't have 64 bit support. 5504 boolean needsRenderScriptOverride = false; 5505 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 5506 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5507 abiList = Build.SUPPORTED_32_BIT_ABIS; 5508 needsRenderScriptOverride = true; 5509 } 5510 5511 final int copyRet; 5512 if (isAsec) { 5513 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 5514 } else { 5515 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5516 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 5517 } 5518 5519 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5520 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5521 "Error unpackaging native libs for app, errorCode=" + copyRet); 5522 } 5523 5524 if (copyRet >= 0) { 5525 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 5526 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 5527 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 5528 } else if (needsRenderScriptOverride) { 5529 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 5530 } 5531 } 5532 } catch (IOException ioe) { 5533 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 5534 } finally { 5535 IoUtils.closeQuietly(handle); 5536 } 5537 5538 // Now that we've calculated the ABIs and determined if it's an internal app, 5539 // we will go ahead and populate the nativeLibraryPath. 5540 setNativeLibraryPaths(pkg); 5541 5542 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 5543 final int[] userIds = sUserManager.getUserIds(); 5544 synchronized (mInstallLock) { 5545 // Create a native library symlink only if we have native libraries 5546 // and if the native libraries are 32 bit libraries. We do not provide 5547 // this symlink for 64 bit libraries. 5548 if (pkg.applicationInfo.primaryCpuAbi != null && 5549 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 5550 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 5551 for (int userId : userIds) { 5552 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 5553 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5554 "Failed linking native library dir (user=" + userId + ")"); 5555 } 5556 } 5557 } 5558 } 5559 } 5560 5561 // This is a special case for the "system" package, where the ABI is 5562 // dictated by the zygote configuration (and init.rc). We should keep track 5563 // of this ABI so that we can deal with "normal" applications that run under 5564 // the same UID correctly. 5565 if (mPlatformPackage == pkg) { 5566 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 5567 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 5568 } 5569 5570 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 5571 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 5572 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 5573 // Copy the derived override back to the parsed package, so that we can 5574 // update the package settings accordingly. 5575 pkg.cpuAbiOverride = cpuAbiOverride; 5576 5577 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 5578 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 5579 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 5580 5581 // Push the derived path down into PackageSettings so we know what to 5582 // clean up at uninstall time. 5583 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 5584 5585 if (DEBUG_ABI_SELECTION) { 5586 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 5587 " primary=" + pkg.applicationInfo.primaryCpuAbi + 5588 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 5589 } 5590 5591 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 5592 // We don't do this here during boot because we can do it all 5593 // at once after scanning all existing packages. 5594 // 5595 // We also do this *before* we perform dexopt on this package, so that 5596 // we can avoid redundant dexopts, and also to make sure we've got the 5597 // code and package path correct. 5598 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 5599 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 5600 } 5601 5602 if ((scanFlags&SCAN_NO_DEX) == 0) { 5603 if (performDexOptLI(pkg, null /* instruction sets */, forceDex, (scanFlags&SCAN_DEFER_DEX) != 0, false) 5604 == DEX_OPT_FAILED) { 5605 if ((scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5606 removeDataDirsLI(pkg.packageName); 5607 } 5608 5609 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 5610 } 5611 } 5612 5613 if (mFactoryTest && pkg.requestedPermissions.contains( 5614 android.Manifest.permission.FACTORY_TEST)) { 5615 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 5616 } 5617 5618 ArrayList<PackageParser.Package> clientLibPkgs = null; 5619 5620 // writer 5621 synchronized (mPackages) { 5622 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5623 // Only system apps can add new shared libraries. 5624 if (pkg.libraryNames != null) { 5625 for (int i=0; i<pkg.libraryNames.size(); i++) { 5626 String name = pkg.libraryNames.get(i); 5627 boolean allowed = false; 5628 if (isUpdatedSystemApp(pkg)) { 5629 // New library entries can only be added through the 5630 // system image. This is important to get rid of a lot 5631 // of nasty edge cases: for example if we allowed a non- 5632 // system update of the app to add a library, then uninstalling 5633 // the update would make the library go away, and assumptions 5634 // we made such as through app install filtering would now 5635 // have allowed apps on the device which aren't compatible 5636 // with it. Better to just have the restriction here, be 5637 // conservative, and create many fewer cases that can negatively 5638 // impact the user experience. 5639 final PackageSetting sysPs = mSettings 5640 .getDisabledSystemPkgLPr(pkg.packageName); 5641 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 5642 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 5643 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 5644 allowed = true; 5645 allowed = true; 5646 break; 5647 } 5648 } 5649 } 5650 } else { 5651 allowed = true; 5652 } 5653 if (allowed) { 5654 if (!mSharedLibraries.containsKey(name)) { 5655 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 5656 } else if (!name.equals(pkg.packageName)) { 5657 Slog.w(TAG, "Package " + pkg.packageName + " library " 5658 + name + " already exists; skipping"); 5659 } 5660 } else { 5661 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 5662 + name + " that is not declared on system image; skipping"); 5663 } 5664 } 5665 if ((scanFlags&SCAN_BOOTING) == 0) { 5666 // If we are not booting, we need to update any applications 5667 // that are clients of our shared library. If we are booting, 5668 // this will all be done once the scan is complete. 5669 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 5670 } 5671 } 5672 } 5673 } 5674 5675 // We also need to dexopt any apps that are dependent on this library. Note that 5676 // if these fail, we should abort the install since installing the library will 5677 // result in some apps being broken. 5678 if (clientLibPkgs != null) { 5679 if ((scanFlags&SCAN_NO_DEX) == 0) { 5680 for (int i=0; i<clientLibPkgs.size(); i++) { 5681 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5682 if (performDexOptLI(clientPkg, null /* instruction sets */, 5683 forceDex, (scanFlags&SCAN_DEFER_DEX) != 0, false) 5684 == DEX_OPT_FAILED) { 5685 if ((scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5686 removeDataDirsLI(pkg.packageName); 5687 } 5688 5689 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 5690 "scanPackageLI failed to dexopt clientLibPkgs"); 5691 } 5692 } 5693 } 5694 } 5695 5696 // Request the ActivityManager to kill the process(only for existing packages) 5697 // so that we do not end up in a confused state while the user is still using the older 5698 // version of the application while the new one gets installed. 5699 if ((scanFlags & SCAN_REPLACING) != 0) { 5700 killApplication(pkg.applicationInfo.packageName, 5701 pkg.applicationInfo.uid, "update pkg"); 5702 } 5703 5704 // Also need to kill any apps that are dependent on the library. 5705 if (clientLibPkgs != null) { 5706 for (int i=0; i<clientLibPkgs.size(); i++) { 5707 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5708 killApplication(clientPkg.applicationInfo.packageName, 5709 clientPkg.applicationInfo.uid, "update lib"); 5710 } 5711 } 5712 5713 // writer 5714 synchronized (mPackages) { 5715 // We don't expect installation to fail beyond this point 5716 5717 // Add the new setting to mSettings 5718 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 5719 // Add the new setting to mPackages 5720 mPackages.put(pkg.applicationInfo.packageName, pkg); 5721 // Make sure we don't accidentally delete its data. 5722 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 5723 while (iter.hasNext()) { 5724 PackageCleanItem item = iter.next(); 5725 if (pkgName.equals(item.packageName)) { 5726 iter.remove(); 5727 } 5728 } 5729 5730 // Take care of first install / last update times. 5731 if (currentTime != 0) { 5732 if (pkgSetting.firstInstallTime == 0) { 5733 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 5734 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 5735 pkgSetting.lastUpdateTime = currentTime; 5736 } 5737 } else if (pkgSetting.firstInstallTime == 0) { 5738 // We need *something*. Take time time stamp of the file. 5739 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 5740 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 5741 if (scanFileTime != pkgSetting.timeStamp) { 5742 // A package on the system image has changed; consider this 5743 // to be an update. 5744 pkgSetting.lastUpdateTime = scanFileTime; 5745 } 5746 } 5747 5748 // Add the package's KeySets to the global KeySetManagerService 5749 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5750 try { 5751 // Old KeySetData no longer valid. 5752 ksms.removeAppKeySetDataLPw(pkg.packageName); 5753 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 5754 if (pkg.mKeySetMapping != null) { 5755 for (Map.Entry<String, ArraySet<PublicKey>> entry : 5756 pkg.mKeySetMapping.entrySet()) { 5757 if (entry.getValue() != null) { 5758 ksms.addDefinedKeySetToPackageLPw(pkg.packageName, 5759 entry.getValue(), entry.getKey()); 5760 } 5761 } 5762 if (pkg.mUpgradeKeySets != null) { 5763 for (String upgradeAlias : pkg.mUpgradeKeySets) { 5764 ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias); 5765 } 5766 } 5767 } 5768 } catch (NullPointerException e) { 5769 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 5770 } catch (IllegalArgumentException e) { 5771 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 5772 } 5773 5774 int N = pkg.providers.size(); 5775 StringBuilder r = null; 5776 int i; 5777 for (i=0; i<N; i++) { 5778 PackageParser.Provider p = pkg.providers.get(i); 5779 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 5780 p.info.processName, pkg.applicationInfo.uid); 5781 mProviders.addProvider(p); 5782 p.syncable = p.info.isSyncable; 5783 if (p.info.authority != null) { 5784 String names[] = p.info.authority.split(";"); 5785 p.info.authority = null; 5786 for (int j = 0; j < names.length; j++) { 5787 if (j == 1 && p.syncable) { 5788 // We only want the first authority for a provider to possibly be 5789 // syncable, so if we already added this provider using a different 5790 // authority clear the syncable flag. We copy the provider before 5791 // changing it because the mProviders object contains a reference 5792 // to a provider that we don't want to change. 5793 // Only do this for the second authority since the resulting provider 5794 // object can be the same for all future authorities for this provider. 5795 p = new PackageParser.Provider(p); 5796 p.syncable = false; 5797 } 5798 if (!mProvidersByAuthority.containsKey(names[j])) { 5799 mProvidersByAuthority.put(names[j], p); 5800 if (p.info.authority == null) { 5801 p.info.authority = names[j]; 5802 } else { 5803 p.info.authority = p.info.authority + ";" + names[j]; 5804 } 5805 if (DEBUG_PACKAGE_SCANNING) { 5806 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5807 Log.d(TAG, "Registered content provider: " + names[j] 5808 + ", className = " + p.info.name + ", isSyncable = " 5809 + p.info.isSyncable); 5810 } 5811 } else { 5812 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5813 Slog.w(TAG, "Skipping provider name " + names[j] + 5814 " (in package " + pkg.applicationInfo.packageName + 5815 "): name already used by " 5816 + ((other != null && other.getComponentName() != null) 5817 ? other.getComponentName().getPackageName() : "?")); 5818 } 5819 } 5820 } 5821 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5822 if (r == null) { 5823 r = new StringBuilder(256); 5824 } else { 5825 r.append(' '); 5826 } 5827 r.append(p.info.name); 5828 } 5829 } 5830 if (r != null) { 5831 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 5832 } 5833 5834 N = pkg.services.size(); 5835 r = null; 5836 for (i=0; i<N; i++) { 5837 PackageParser.Service s = pkg.services.get(i); 5838 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 5839 s.info.processName, pkg.applicationInfo.uid); 5840 mServices.addService(s); 5841 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5842 if (r == null) { 5843 r = new StringBuilder(256); 5844 } else { 5845 r.append(' '); 5846 } 5847 r.append(s.info.name); 5848 } 5849 } 5850 if (r != null) { 5851 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 5852 } 5853 5854 N = pkg.receivers.size(); 5855 r = null; 5856 for (i=0; i<N; i++) { 5857 PackageParser.Activity a = pkg.receivers.get(i); 5858 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5859 a.info.processName, pkg.applicationInfo.uid); 5860 mReceivers.addActivity(a, "receiver"); 5861 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5862 if (r == null) { 5863 r = new StringBuilder(256); 5864 } else { 5865 r.append(' '); 5866 } 5867 r.append(a.info.name); 5868 } 5869 } 5870 if (r != null) { 5871 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 5872 } 5873 5874 N = pkg.activities.size(); 5875 r = null; 5876 for (i=0; i<N; i++) { 5877 PackageParser.Activity a = pkg.activities.get(i); 5878 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5879 a.info.processName, pkg.applicationInfo.uid); 5880 mActivities.addActivity(a, "activity"); 5881 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5882 if (r == null) { 5883 r = new StringBuilder(256); 5884 } else { 5885 r.append(' '); 5886 } 5887 r.append(a.info.name); 5888 } 5889 } 5890 if (r != null) { 5891 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 5892 } 5893 5894 N = pkg.permissionGroups.size(); 5895 r = null; 5896 for (i=0; i<N; i++) { 5897 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 5898 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 5899 if (cur == null) { 5900 mPermissionGroups.put(pg.info.name, pg); 5901 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5902 if (r == null) { 5903 r = new StringBuilder(256); 5904 } else { 5905 r.append(' '); 5906 } 5907 r.append(pg.info.name); 5908 } 5909 } else { 5910 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 5911 + pg.info.packageName + " ignored: original from " 5912 + cur.info.packageName); 5913 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5914 if (r == null) { 5915 r = new StringBuilder(256); 5916 } else { 5917 r.append(' '); 5918 } 5919 r.append("DUP:"); 5920 r.append(pg.info.name); 5921 } 5922 } 5923 } 5924 if (r != null) { 5925 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 5926 } 5927 5928 N = pkg.permissions.size(); 5929 r = null; 5930 for (i=0; i<N; i++) { 5931 PackageParser.Permission p = pkg.permissions.get(i); 5932 HashMap<String, BasePermission> permissionMap = 5933 p.tree ? mSettings.mPermissionTrees 5934 : mSettings.mPermissions; 5935 p.group = mPermissionGroups.get(p.info.group); 5936 if (p.info.group == null || p.group != null) { 5937 BasePermission bp = permissionMap.get(p.info.name); 5938 if (bp == null) { 5939 bp = new BasePermission(p.info.name, p.info.packageName, 5940 BasePermission.TYPE_NORMAL); 5941 permissionMap.put(p.info.name, bp); 5942 } 5943 if (bp.perm == null) { 5944 if (bp.sourcePackage != null 5945 && !bp.sourcePackage.equals(p.info.packageName)) { 5946 // If this is a permission that was formerly defined by a non-system 5947 // app, but is now defined by a system app (following an upgrade), 5948 // discard the previous declaration and consider the system's to be 5949 // canonical. 5950 if (isSystemApp(p.owner)) { 5951 String msg = "New decl " + p.owner + " of permission " 5952 + p.info.name + " is system"; 5953 reportSettingsProblem(Log.WARN, msg); 5954 bp.sourcePackage = null; 5955 } 5956 } 5957 if (bp.sourcePackage == null 5958 || bp.sourcePackage.equals(p.info.packageName)) { 5959 BasePermission tree = findPermissionTreeLP(p.info.name); 5960 if (tree == null 5961 || tree.sourcePackage.equals(p.info.packageName)) { 5962 bp.packageSetting = pkgSetting; 5963 bp.perm = p; 5964 bp.uid = pkg.applicationInfo.uid; 5965 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5966 if (r == null) { 5967 r = new StringBuilder(256); 5968 } else { 5969 r.append(' '); 5970 } 5971 r.append(p.info.name); 5972 } 5973 } else { 5974 Slog.w(TAG, "Permission " + p.info.name + " from package " 5975 + p.info.packageName + " ignored: base tree " 5976 + tree.name + " is from package " 5977 + tree.sourcePackage); 5978 } 5979 } else { 5980 Slog.w(TAG, "Permission " + p.info.name + " from package " 5981 + p.info.packageName + " ignored: original from " 5982 + bp.sourcePackage); 5983 } 5984 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5985 if (r == null) { 5986 r = new StringBuilder(256); 5987 } else { 5988 r.append(' '); 5989 } 5990 r.append("DUP:"); 5991 r.append(p.info.name); 5992 } 5993 if (bp.perm == p) { 5994 bp.protectionLevel = p.info.protectionLevel; 5995 } 5996 } else { 5997 Slog.w(TAG, "Permission " + p.info.name + " from package " 5998 + p.info.packageName + " ignored: no group " 5999 + p.group); 6000 } 6001 } 6002 if (r != null) { 6003 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6004 } 6005 6006 N = pkg.instrumentation.size(); 6007 r = null; 6008 for (i=0; i<N; i++) { 6009 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6010 a.info.packageName = pkg.applicationInfo.packageName; 6011 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6012 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6013 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6014 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6015 a.info.dataDir = pkg.applicationInfo.dataDir; 6016 6017 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6018 // need other information about the application, like the ABI and what not ? 6019 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6020 mInstrumentation.put(a.getComponentName(), a); 6021 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6022 if (r == null) { 6023 r = new StringBuilder(256); 6024 } else { 6025 r.append(' '); 6026 } 6027 r.append(a.info.name); 6028 } 6029 } 6030 if (r != null) { 6031 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6032 } 6033 6034 if (pkg.protectedBroadcasts != null) { 6035 N = pkg.protectedBroadcasts.size(); 6036 for (i=0; i<N; i++) { 6037 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6038 } 6039 } 6040 6041 pkgSetting.setTimeStamp(scanFileTime); 6042 6043 // Create idmap files for pairs of (packages, overlay packages). 6044 // Note: "android", ie framework-res.apk, is handled by native layers. 6045 if (pkg.mOverlayTarget != null) { 6046 // This is an overlay package. 6047 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6048 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6049 mOverlays.put(pkg.mOverlayTarget, 6050 new HashMap<String, PackageParser.Package>()); 6051 } 6052 HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6053 map.put(pkg.packageName, pkg); 6054 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6055 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6056 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6057 "scanPackageLI failed to createIdmap"); 6058 } 6059 } 6060 } else if (mOverlays.containsKey(pkg.packageName) && 6061 !pkg.packageName.equals("android")) { 6062 // This is a regular package, with one or more known overlay packages. 6063 createIdmapsForPackageLI(pkg); 6064 } 6065 } 6066 6067 return pkg; 6068 } 6069 6070 /** 6071 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6072 * i.e, so that all packages can be run inside a single process if required. 6073 * 6074 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6075 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6076 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6077 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6078 * updating a package that belongs to a shared user. 6079 * 6080 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6081 * adds unnecessary complexity. 6082 */ 6083 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6084 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6085 String requiredInstructionSet = null; 6086 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6087 requiredInstructionSet = VMRuntime.getInstructionSet( 6088 scannedPackage.applicationInfo.primaryCpuAbi); 6089 } 6090 6091 PackageSetting requirer = null; 6092 for (PackageSetting ps : packagesForUser) { 6093 // If packagesForUser contains scannedPackage, we skip it. This will happen 6094 // when scannedPackage is an update of an existing package. Without this check, 6095 // we will never be able to change the ABI of any package belonging to a shared 6096 // user, even if it's compatible with other packages. 6097 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6098 if (ps.primaryCpuAbiString == null) { 6099 continue; 6100 } 6101 6102 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6103 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6104 // We have a mismatch between instruction sets (say arm vs arm64) warn about 6105 // this but there's not much we can do. 6106 String errorMessage = "Instruction set mismatch, " 6107 + ((requirer == null) ? "[caller]" : requirer) 6108 + " requires " + requiredInstructionSet + " whereas " + ps 6109 + " requires " + instructionSet; 6110 Slog.w(TAG, errorMessage); 6111 } 6112 6113 if (requiredInstructionSet == null) { 6114 requiredInstructionSet = instructionSet; 6115 requirer = ps; 6116 } 6117 } 6118 } 6119 6120 if (requiredInstructionSet != null) { 6121 String adjustedAbi; 6122 if (requirer != null) { 6123 // requirer != null implies that either scannedPackage was null or that scannedPackage 6124 // did not require an ABI, in which case we have to adjust scannedPackage to match 6125 // the ABI of the set (which is the same as requirer's ABI) 6126 adjustedAbi = requirer.primaryCpuAbiString; 6127 if (scannedPackage != null) { 6128 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6129 } 6130 } else { 6131 // requirer == null implies that we're updating all ABIs in the set to 6132 // match scannedPackage. 6133 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6134 } 6135 6136 for (PackageSetting ps : packagesForUser) { 6137 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6138 if (ps.primaryCpuAbiString != null) { 6139 continue; 6140 } 6141 6142 ps.primaryCpuAbiString = adjustedAbi; 6143 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6144 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6145 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6146 6147 if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt, 6148 deferDexOpt, true) == DEX_OPT_FAILED) { 6149 ps.primaryCpuAbiString = null; 6150 ps.pkg.applicationInfo.primaryCpuAbi = null; 6151 return; 6152 } else { 6153 mInstaller.rmdex(ps.codePathString, 6154 getDexCodeInstructionSet(getPreferredInstructionSet())); 6155 } 6156 } 6157 } 6158 } 6159 } 6160 } 6161 6162 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6163 synchronized (mPackages) { 6164 mResolverReplaced = true; 6165 // Set up information for custom user intent resolution activity. 6166 mResolveActivity.applicationInfo = pkg.applicationInfo; 6167 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6168 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6169 mResolveActivity.processName = null; 6170 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6171 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6172 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6173 mResolveActivity.theme = 0; 6174 mResolveActivity.exported = true; 6175 mResolveActivity.enabled = true; 6176 mResolveInfo.activityInfo = mResolveActivity; 6177 mResolveInfo.priority = 0; 6178 mResolveInfo.preferredOrder = 0; 6179 mResolveInfo.match = 0; 6180 mResolveComponentName = mCustomResolverComponentName; 6181 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6182 mResolveComponentName); 6183 } 6184 } 6185 6186 private static String calculateBundledApkRoot(final String codePathString) { 6187 final File codePath = new File(codePathString); 6188 final File codeRoot; 6189 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6190 codeRoot = Environment.getRootDirectory(); 6191 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6192 codeRoot = Environment.getOemDirectory(); 6193 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6194 codeRoot = Environment.getVendorDirectory(); 6195 } else { 6196 // Unrecognized code path; take its top real segment as the apk root: 6197 // e.g. /something/app/blah.apk => /something 6198 try { 6199 File f = codePath.getCanonicalFile(); 6200 File parent = f.getParentFile(); // non-null because codePath is a file 6201 File tmp; 6202 while ((tmp = parent.getParentFile()) != null) { 6203 f = parent; 6204 parent = tmp; 6205 } 6206 codeRoot = f; 6207 Slog.w(TAG, "Unrecognized code path " 6208 + codePath + " - using " + codeRoot); 6209 } catch (IOException e) { 6210 // Can't canonicalize the code path -- shenanigans? 6211 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6212 return Environment.getRootDirectory().getPath(); 6213 } 6214 } 6215 return codeRoot.getPath(); 6216 } 6217 6218 /** 6219 * Derive and set the location of native libraries for the given package, 6220 * which varies depending on where and how the package was installed. 6221 */ 6222 private void setNativeLibraryPaths(PackageParser.Package pkg) { 6223 final ApplicationInfo info = pkg.applicationInfo; 6224 final String codePath = pkg.codePath; 6225 final File codeFile = new File(codePath); 6226 final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info); 6227 final boolean asecApp = isForwardLocked(info) || isExternal(info); 6228 6229 info.nativeLibraryRootDir = null; 6230 info.nativeLibraryRootRequiresIsa = false; 6231 info.nativeLibraryDir = null; 6232 info.secondaryNativeLibraryDir = null; 6233 6234 if (isApkFile(codeFile)) { 6235 // Monolithic install 6236 if (bundledApp) { 6237 // If "/system/lib64/apkname" exists, assume that is the per-package 6238 // native library directory to use; otherwise use "/system/lib/apkname". 6239 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 6240 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 6241 getPrimaryInstructionSet(info)); 6242 6243 // This is a bundled system app so choose the path based on the ABI. 6244 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 6245 // is just the default path. 6246 final String apkName = deriveCodePathName(codePath); 6247 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 6248 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 6249 apkName).getAbsolutePath(); 6250 6251 if (info.secondaryCpuAbi != null) { 6252 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 6253 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 6254 secondaryLibDir, apkName).getAbsolutePath(); 6255 } 6256 } else if (asecApp) { 6257 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 6258 .getAbsolutePath(); 6259 } else { 6260 final String apkName = deriveCodePathName(codePath); 6261 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 6262 .getAbsolutePath(); 6263 } 6264 6265 info.nativeLibraryRootRequiresIsa = false; 6266 info.nativeLibraryDir = info.nativeLibraryRootDir; 6267 } else { 6268 // Cluster install 6269 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 6270 info.nativeLibraryRootRequiresIsa = true; 6271 6272 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 6273 getPrimaryInstructionSet(info)).getAbsolutePath(); 6274 6275 if (info.secondaryCpuAbi != null) { 6276 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 6277 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 6278 } 6279 } 6280 } 6281 6282 /** 6283 * Calculate the abis and roots for a bundled app. These can uniquely 6284 * be determined from the contents of the system partition, i.e whether 6285 * it contains 64 or 32 bit shared libraries etc. We do not validate any 6286 * of this information, and instead assume that the system was built 6287 * sensibly. 6288 */ 6289 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 6290 PackageSetting pkgSetting) { 6291 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 6292 6293 // If "/system/lib64/apkname" exists, assume that is the per-package 6294 // native library directory to use; otherwise use "/system/lib/apkname". 6295 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 6296 setBundledAppAbi(pkg, apkRoot, apkName); 6297 // pkgSetting might be null during rescan following uninstall of updates 6298 // to a bundled app, so accommodate that possibility. The settings in 6299 // that case will be established later from the parsed package. 6300 // 6301 // If the settings aren't null, sync them up with what we've just derived. 6302 // note that apkRoot isn't stored in the package settings. 6303 if (pkgSetting != null) { 6304 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6305 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6306 } 6307 } 6308 6309 /** 6310 * Deduces the ABI of a bundled app and sets the relevant fields on the 6311 * parsed pkg object. 6312 * 6313 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 6314 * under which system libraries are installed. 6315 * @param apkName the name of the installed package. 6316 */ 6317 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 6318 final File codeFile = new File(pkg.codePath); 6319 6320 final boolean has64BitLibs; 6321 final boolean has32BitLibs; 6322 if (isApkFile(codeFile)) { 6323 // Monolithic install 6324 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 6325 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 6326 } else { 6327 // Cluster install 6328 final File rootDir = new File(codeFile, LIB_DIR_NAME); 6329 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 6330 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 6331 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 6332 has64BitLibs = (new File(rootDir, isa)).exists(); 6333 } else { 6334 has64BitLibs = false; 6335 } 6336 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 6337 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 6338 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 6339 has32BitLibs = (new File(rootDir, isa)).exists(); 6340 } else { 6341 has32BitLibs = false; 6342 } 6343 } 6344 6345 if (has64BitLibs && !has32BitLibs) { 6346 // The package has 64 bit libs, but not 32 bit libs. Its primary 6347 // ABI should be 64 bit. We can safely assume here that the bundled 6348 // native libraries correspond to the most preferred ABI in the list. 6349 6350 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6351 pkg.applicationInfo.secondaryCpuAbi = null; 6352 } else if (has32BitLibs && !has64BitLibs) { 6353 // The package has 32 bit libs but not 64 bit libs. Its primary 6354 // ABI should be 32 bit. 6355 6356 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6357 pkg.applicationInfo.secondaryCpuAbi = null; 6358 } else if (has32BitLibs && has64BitLibs) { 6359 // The application has both 64 and 32 bit bundled libraries. We check 6360 // here that the app declares multiArch support, and warn if it doesn't. 6361 // 6362 // We will be lenient here and record both ABIs. The primary will be the 6363 // ABI that's higher on the list, i.e, a device that's configured to prefer 6364 // 64 bit apps will see a 64 bit primary ABI, 6365 6366 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 6367 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 6368 } 6369 6370 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 6371 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6372 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6373 } else { 6374 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6375 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6376 } 6377 } else { 6378 pkg.applicationInfo.primaryCpuAbi = null; 6379 pkg.applicationInfo.secondaryCpuAbi = null; 6380 } 6381 } 6382 6383 private void killApplication(String pkgName, int appId, String reason) { 6384 // Request the ActivityManager to kill the process(only for existing packages) 6385 // so that we do not end up in a confused state while the user is still using the older 6386 // version of the application while the new one gets installed. 6387 IActivityManager am = ActivityManagerNative.getDefault(); 6388 if (am != null) { 6389 try { 6390 am.killApplicationWithAppId(pkgName, appId, reason); 6391 } catch (RemoteException e) { 6392 } 6393 } 6394 } 6395 6396 void removePackageLI(PackageSetting ps, boolean chatty) { 6397 if (DEBUG_INSTALL) { 6398 if (chatty) 6399 Log.d(TAG, "Removing package " + ps.name); 6400 } 6401 6402 // writer 6403 synchronized (mPackages) { 6404 mPackages.remove(ps.name); 6405 final PackageParser.Package pkg = ps.pkg; 6406 if (pkg != null) { 6407 cleanPackageDataStructuresLILPw(pkg, chatty); 6408 } 6409 } 6410 } 6411 6412 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 6413 if (DEBUG_INSTALL) { 6414 if (chatty) 6415 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 6416 } 6417 6418 // writer 6419 synchronized (mPackages) { 6420 mPackages.remove(pkg.applicationInfo.packageName); 6421 cleanPackageDataStructuresLILPw(pkg, chatty); 6422 } 6423 } 6424 6425 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 6426 int N = pkg.providers.size(); 6427 StringBuilder r = null; 6428 int i; 6429 for (i=0; i<N; i++) { 6430 PackageParser.Provider p = pkg.providers.get(i); 6431 mProviders.removeProvider(p); 6432 if (p.info.authority == null) { 6433 6434 /* There was another ContentProvider with this authority when 6435 * this app was installed so this authority is null, 6436 * Ignore it as we don't have to unregister the provider. 6437 */ 6438 continue; 6439 } 6440 String names[] = p.info.authority.split(";"); 6441 for (int j = 0; j < names.length; j++) { 6442 if (mProvidersByAuthority.get(names[j]) == p) { 6443 mProvidersByAuthority.remove(names[j]); 6444 if (DEBUG_REMOVE) { 6445 if (chatty) 6446 Log.d(TAG, "Unregistered content provider: " + names[j] 6447 + ", className = " + p.info.name + ", isSyncable = " 6448 + p.info.isSyncable); 6449 } 6450 } 6451 } 6452 if (DEBUG_REMOVE && chatty) { 6453 if (r == null) { 6454 r = new StringBuilder(256); 6455 } else { 6456 r.append(' '); 6457 } 6458 r.append(p.info.name); 6459 } 6460 } 6461 if (r != null) { 6462 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 6463 } 6464 6465 N = pkg.services.size(); 6466 r = null; 6467 for (i=0; i<N; i++) { 6468 PackageParser.Service s = pkg.services.get(i); 6469 mServices.removeService(s); 6470 if (chatty) { 6471 if (r == null) { 6472 r = new StringBuilder(256); 6473 } else { 6474 r.append(' '); 6475 } 6476 r.append(s.info.name); 6477 } 6478 } 6479 if (r != null) { 6480 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 6481 } 6482 6483 N = pkg.receivers.size(); 6484 r = null; 6485 for (i=0; i<N; i++) { 6486 PackageParser.Activity a = pkg.receivers.get(i); 6487 mReceivers.removeActivity(a, "receiver"); 6488 if (DEBUG_REMOVE && chatty) { 6489 if (r == null) { 6490 r = new StringBuilder(256); 6491 } else { 6492 r.append(' '); 6493 } 6494 r.append(a.info.name); 6495 } 6496 } 6497 if (r != null) { 6498 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 6499 } 6500 6501 N = pkg.activities.size(); 6502 r = null; 6503 for (i=0; i<N; i++) { 6504 PackageParser.Activity a = pkg.activities.get(i); 6505 mActivities.removeActivity(a, "activity"); 6506 if (DEBUG_REMOVE && chatty) { 6507 if (r == null) { 6508 r = new StringBuilder(256); 6509 } else { 6510 r.append(' '); 6511 } 6512 r.append(a.info.name); 6513 } 6514 } 6515 if (r != null) { 6516 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 6517 } 6518 6519 N = pkg.permissions.size(); 6520 r = null; 6521 for (i=0; i<N; i++) { 6522 PackageParser.Permission p = pkg.permissions.get(i); 6523 BasePermission bp = mSettings.mPermissions.get(p.info.name); 6524 if (bp == null) { 6525 bp = mSettings.mPermissionTrees.get(p.info.name); 6526 } 6527 if (bp != null && bp.perm == p) { 6528 bp.perm = null; 6529 if (DEBUG_REMOVE && chatty) { 6530 if (r == null) { 6531 r = new StringBuilder(256); 6532 } else { 6533 r.append(' '); 6534 } 6535 r.append(p.info.name); 6536 } 6537 } 6538 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6539 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 6540 if (appOpPerms != null) { 6541 appOpPerms.remove(pkg.packageName); 6542 } 6543 } 6544 } 6545 if (r != null) { 6546 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6547 } 6548 6549 N = pkg.requestedPermissions.size(); 6550 r = null; 6551 for (i=0; i<N; i++) { 6552 String perm = pkg.requestedPermissions.get(i); 6553 BasePermission bp = mSettings.mPermissions.get(perm); 6554 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6555 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 6556 if (appOpPerms != null) { 6557 appOpPerms.remove(pkg.packageName); 6558 if (appOpPerms.isEmpty()) { 6559 mAppOpPermissionPackages.remove(perm); 6560 } 6561 } 6562 } 6563 } 6564 if (r != null) { 6565 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6566 } 6567 6568 N = pkg.instrumentation.size(); 6569 r = null; 6570 for (i=0; i<N; i++) { 6571 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6572 mInstrumentation.remove(a.getComponentName()); 6573 if (DEBUG_REMOVE && chatty) { 6574 if (r == null) { 6575 r = new StringBuilder(256); 6576 } else { 6577 r.append(' '); 6578 } 6579 r.append(a.info.name); 6580 } 6581 } 6582 if (r != null) { 6583 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 6584 } 6585 6586 r = null; 6587 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6588 // Only system apps can hold shared libraries. 6589 if (pkg.libraryNames != null) { 6590 for (i=0; i<pkg.libraryNames.size(); i++) { 6591 String name = pkg.libraryNames.get(i); 6592 SharedLibraryEntry cur = mSharedLibraries.get(name); 6593 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 6594 mSharedLibraries.remove(name); 6595 if (DEBUG_REMOVE && chatty) { 6596 if (r == null) { 6597 r = new StringBuilder(256); 6598 } else { 6599 r.append(' '); 6600 } 6601 r.append(name); 6602 } 6603 } 6604 } 6605 } 6606 } 6607 if (r != null) { 6608 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 6609 } 6610 } 6611 6612 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 6613 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 6614 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 6615 return true; 6616 } 6617 } 6618 return false; 6619 } 6620 6621 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 6622 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 6623 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 6624 6625 private void updatePermissionsLPw(String changingPkg, 6626 PackageParser.Package pkgInfo, int flags) { 6627 // Make sure there are no dangling permission trees. 6628 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 6629 while (it.hasNext()) { 6630 final BasePermission bp = it.next(); 6631 if (bp.packageSetting == null) { 6632 // We may not yet have parsed the package, so just see if 6633 // we still know about its settings. 6634 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6635 } 6636 if (bp.packageSetting == null) { 6637 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 6638 + " from package " + bp.sourcePackage); 6639 it.remove(); 6640 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6641 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6642 Slog.i(TAG, "Removing old permission tree: " + bp.name 6643 + " from package " + bp.sourcePackage); 6644 flags |= UPDATE_PERMISSIONS_ALL; 6645 it.remove(); 6646 } 6647 } 6648 } 6649 6650 // Make sure all dynamic permissions have been assigned to a package, 6651 // and make sure there are no dangling permissions. 6652 it = mSettings.mPermissions.values().iterator(); 6653 while (it.hasNext()) { 6654 final BasePermission bp = it.next(); 6655 if (bp.type == BasePermission.TYPE_DYNAMIC) { 6656 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 6657 + bp.name + " pkg=" + bp.sourcePackage 6658 + " info=" + bp.pendingInfo); 6659 if (bp.packageSetting == null && bp.pendingInfo != null) { 6660 final BasePermission tree = findPermissionTreeLP(bp.name); 6661 if (tree != null && tree.perm != null) { 6662 bp.packageSetting = tree.packageSetting; 6663 bp.perm = new PackageParser.Permission(tree.perm.owner, 6664 new PermissionInfo(bp.pendingInfo)); 6665 bp.perm.info.packageName = tree.perm.info.packageName; 6666 bp.perm.info.name = bp.name; 6667 bp.uid = tree.uid; 6668 } 6669 } 6670 } 6671 if (bp.packageSetting == null) { 6672 // We may not yet have parsed the package, so just see if 6673 // we still know about its settings. 6674 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6675 } 6676 if (bp.packageSetting == null) { 6677 Slog.w(TAG, "Removing dangling permission: " + bp.name 6678 + " from package " + bp.sourcePackage); 6679 it.remove(); 6680 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6681 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6682 Slog.i(TAG, "Removing old permission: " + bp.name 6683 + " from package " + bp.sourcePackage); 6684 flags |= UPDATE_PERMISSIONS_ALL; 6685 it.remove(); 6686 } 6687 } 6688 } 6689 6690 // Now update the permissions for all packages, in particular 6691 // replace the granted permissions of the system packages. 6692 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 6693 for (PackageParser.Package pkg : mPackages.values()) { 6694 if (pkg != pkgInfo) { 6695 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0); 6696 } 6697 } 6698 } 6699 6700 if (pkgInfo != null) { 6701 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0); 6702 } 6703 } 6704 6705 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) { 6706 final PackageSetting ps = (PackageSetting) pkg.mExtras; 6707 if (ps == null) { 6708 return; 6709 } 6710 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 6711 HashSet<String> origPermissions = gp.grantedPermissions; 6712 boolean changedPermission = false; 6713 6714 if (replace) { 6715 ps.permissionsFixed = false; 6716 if (gp == ps) { 6717 origPermissions = new HashSet<String>(gp.grantedPermissions); 6718 gp.grantedPermissions.clear(); 6719 gp.gids = mGlobalGids; 6720 } 6721 } 6722 6723 if (gp.gids == null) { 6724 gp.gids = mGlobalGids; 6725 } 6726 6727 final int N = pkg.requestedPermissions.size(); 6728 for (int i=0; i<N; i++) { 6729 final String name = pkg.requestedPermissions.get(i); 6730 final boolean required = pkg.requestedPermissionsRequired.get(i); 6731 final BasePermission bp = mSettings.mPermissions.get(name); 6732 if (DEBUG_INSTALL) { 6733 if (gp != ps) { 6734 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 6735 } 6736 } 6737 6738 if (bp == null || bp.packageSetting == null) { 6739 Slog.w(TAG, "Unknown permission " + name 6740 + " in package " + pkg.packageName); 6741 continue; 6742 } 6743 6744 final String perm = bp.name; 6745 boolean allowed; 6746 boolean allowedSig = false; 6747 if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6748 // Keep track of app op permissions. 6749 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 6750 if (pkgs == null) { 6751 pkgs = new ArraySet<>(); 6752 mAppOpPermissionPackages.put(bp.name, pkgs); 6753 } 6754 pkgs.add(pkg.packageName); 6755 } 6756 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 6757 if (level == PermissionInfo.PROTECTION_NORMAL 6758 || level == PermissionInfo.PROTECTION_DANGEROUS) { 6759 // We grant a normal or dangerous permission if any of the following 6760 // are true: 6761 // 1) The permission is required 6762 // 2) The permission is optional, but was granted in the past 6763 // 3) The permission is optional, but was requested by an 6764 // app in /system (not /data) 6765 // 6766 // Otherwise, reject the permission. 6767 allowed = (required || origPermissions.contains(perm) 6768 || (isSystemApp(ps) && !isUpdatedSystemApp(ps))); 6769 } else if (bp.packageSetting == null) { 6770 // This permission is invalid; skip it. 6771 allowed = false; 6772 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 6773 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions); 6774 if (allowed) { 6775 allowedSig = true; 6776 } 6777 } else { 6778 allowed = false; 6779 } 6780 if (DEBUG_INSTALL) { 6781 if (gp != ps) { 6782 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 6783 } 6784 } 6785 if (allowed) { 6786 if (!isSystemApp(ps) && ps.permissionsFixed) { 6787 // If this is an existing, non-system package, then 6788 // we can't add any new permissions to it. 6789 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 6790 // Except... if this is a permission that was added 6791 // to the platform (note: need to only do this when 6792 // updating the platform). 6793 allowed = isNewPlatformPermissionForPackage(perm, pkg); 6794 } 6795 } 6796 if (allowed) { 6797 if (!gp.grantedPermissions.contains(perm)) { 6798 changedPermission = true; 6799 gp.grantedPermissions.add(perm); 6800 gp.gids = appendInts(gp.gids, bp.gids); 6801 } else if (!ps.haveGids) { 6802 gp.gids = appendInts(gp.gids, bp.gids); 6803 } 6804 } else { 6805 Slog.w(TAG, "Not granting permission " + perm 6806 + " to package " + pkg.packageName 6807 + " because it was previously installed without"); 6808 } 6809 } else { 6810 if (gp.grantedPermissions.remove(perm)) { 6811 changedPermission = true; 6812 gp.gids = removeInts(gp.gids, bp.gids); 6813 Slog.i(TAG, "Un-granting permission " + perm 6814 + " from package " + pkg.packageName 6815 + " (protectionLevel=" + bp.protectionLevel 6816 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6817 + ")"); 6818 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 6819 // Don't print warning for app op permissions, since it is fine for them 6820 // not to be granted, there is a UI for the user to decide. 6821 Slog.w(TAG, "Not granting permission " + perm 6822 + " to package " + pkg.packageName 6823 + " (protectionLevel=" + bp.protectionLevel 6824 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6825 + ")"); 6826 } 6827 } 6828 } 6829 6830 if ((changedPermission || replace) && !ps.permissionsFixed && 6831 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 6832 // This is the first that we have heard about this package, so the 6833 // permissions we have now selected are fixed until explicitly 6834 // changed. 6835 ps.permissionsFixed = true; 6836 } 6837 ps.haveGids = true; 6838 } 6839 6840 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 6841 boolean allowed = false; 6842 final int NP = PackageParser.NEW_PERMISSIONS.length; 6843 for (int ip=0; ip<NP; ip++) { 6844 final PackageParser.NewPermissionInfo npi 6845 = PackageParser.NEW_PERMISSIONS[ip]; 6846 if (npi.name.equals(perm) 6847 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 6848 allowed = true; 6849 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 6850 + pkg.packageName); 6851 break; 6852 } 6853 } 6854 return allowed; 6855 } 6856 6857 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 6858 BasePermission bp, HashSet<String> origPermissions) { 6859 boolean allowed; 6860 allowed = (compareSignatures( 6861 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 6862 == PackageManager.SIGNATURE_MATCH) 6863 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 6864 == PackageManager.SIGNATURE_MATCH); 6865 if (!allowed && (bp.protectionLevel 6866 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 6867 if (isSystemApp(pkg)) { 6868 // For updated system applications, a system permission 6869 // is granted only if it had been defined by the original application. 6870 if (isUpdatedSystemApp(pkg)) { 6871 final PackageSetting sysPs = mSettings 6872 .getDisabledSystemPkgLPr(pkg.packageName); 6873 final GrantedPermissions origGp = sysPs.sharedUser != null 6874 ? sysPs.sharedUser : sysPs; 6875 6876 if (origGp.grantedPermissions.contains(perm)) { 6877 // If the original was granted this permission, we take 6878 // that grant decision as read and propagate it to the 6879 // update. 6880 allowed = true; 6881 } else { 6882 // The system apk may have been updated with an older 6883 // version of the one on the data partition, but which 6884 // granted a new system permission that it didn't have 6885 // before. In this case we do want to allow the app to 6886 // now get the new permission if the ancestral apk is 6887 // privileged to get it. 6888 if (sysPs.pkg != null && sysPs.isPrivileged()) { 6889 for (int j=0; 6890 j<sysPs.pkg.requestedPermissions.size(); j++) { 6891 if (perm.equals( 6892 sysPs.pkg.requestedPermissions.get(j))) { 6893 allowed = true; 6894 break; 6895 } 6896 } 6897 } 6898 } 6899 } else { 6900 allowed = isPrivilegedApp(pkg); 6901 } 6902 } 6903 } 6904 if (!allowed && (bp.protectionLevel 6905 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 6906 // For development permissions, a development permission 6907 // is granted only if it was already granted. 6908 allowed = origPermissions.contains(perm); 6909 } 6910 return allowed; 6911 } 6912 6913 final class ActivityIntentResolver 6914 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 6915 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 6916 boolean defaultOnly, int userId) { 6917 if (!sUserManager.exists(userId)) return null; 6918 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 6919 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 6920 } 6921 6922 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 6923 int userId) { 6924 if (!sUserManager.exists(userId)) return null; 6925 mFlags = flags; 6926 return super.queryIntent(intent, resolvedType, 6927 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 6928 } 6929 6930 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 6931 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 6932 if (!sUserManager.exists(userId)) return null; 6933 if (packageActivities == null) { 6934 return null; 6935 } 6936 mFlags = flags; 6937 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 6938 final int N = packageActivities.size(); 6939 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 6940 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 6941 6942 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 6943 for (int i = 0; i < N; ++i) { 6944 intentFilters = packageActivities.get(i).intents; 6945 if (intentFilters != null && intentFilters.size() > 0) { 6946 PackageParser.ActivityIntentInfo[] array = 6947 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 6948 intentFilters.toArray(array); 6949 listCut.add(array); 6950 } 6951 } 6952 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 6953 } 6954 6955 public final void addActivity(PackageParser.Activity a, String type) { 6956 final boolean systemApp = isSystemApp(a.info.applicationInfo); 6957 mActivities.put(a.getComponentName(), a); 6958 if (DEBUG_SHOW_INFO) 6959 Log.v( 6960 TAG, " " + type + " " + 6961 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 6962 if (DEBUG_SHOW_INFO) 6963 Log.v(TAG, " Class=" + a.info.name); 6964 final int NI = a.intents.size(); 6965 for (int j=0; j<NI; j++) { 6966 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 6967 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 6968 intent.setPriority(0); 6969 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 6970 + a.className + " with priority > 0, forcing to 0"); 6971 } 6972 if (DEBUG_SHOW_INFO) { 6973 Log.v(TAG, " IntentFilter:"); 6974 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6975 } 6976 if (!intent.debugCheck()) { 6977 Log.w(TAG, "==> For Activity " + a.info.name); 6978 } 6979 addFilter(intent); 6980 } 6981 } 6982 6983 public final void removeActivity(PackageParser.Activity a, String type) { 6984 mActivities.remove(a.getComponentName()); 6985 if (DEBUG_SHOW_INFO) { 6986 Log.v(TAG, " " + type + " " 6987 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 6988 : a.info.name) + ":"); 6989 Log.v(TAG, " Class=" + a.info.name); 6990 } 6991 final int NI = a.intents.size(); 6992 for (int j=0; j<NI; j++) { 6993 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 6994 if (DEBUG_SHOW_INFO) { 6995 Log.v(TAG, " IntentFilter:"); 6996 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6997 } 6998 removeFilter(intent); 6999 } 7000 } 7001 7002 @Override 7003 protected boolean allowFilterResult( 7004 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 7005 ActivityInfo filterAi = filter.activity.info; 7006 for (int i=dest.size()-1; i>=0; i--) { 7007 ActivityInfo destAi = dest.get(i).activityInfo; 7008 if (destAi.name == filterAi.name 7009 && destAi.packageName == filterAi.packageName) { 7010 return false; 7011 } 7012 } 7013 return true; 7014 } 7015 7016 @Override 7017 protected ActivityIntentInfo[] newArray(int size) { 7018 return new ActivityIntentInfo[size]; 7019 } 7020 7021 @Override 7022 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 7023 if (!sUserManager.exists(userId)) return true; 7024 PackageParser.Package p = filter.activity.owner; 7025 if (p != null) { 7026 PackageSetting ps = (PackageSetting)p.mExtras; 7027 if (ps != null) { 7028 // System apps are never considered stopped for purposes of 7029 // filtering, because there may be no way for the user to 7030 // actually re-launch them. 7031 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 7032 && ps.getStopped(userId); 7033 } 7034 } 7035 return false; 7036 } 7037 7038 @Override 7039 protected boolean isPackageForFilter(String packageName, 7040 PackageParser.ActivityIntentInfo info) { 7041 return packageName.equals(info.activity.owner.packageName); 7042 } 7043 7044 @Override 7045 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7046 int match, int userId) { 7047 if (!sUserManager.exists(userId)) return null; 7048 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7049 return null; 7050 } 7051 final PackageParser.Activity activity = info.activity; 7052 if (mSafeMode && (activity.info.applicationInfo.flags 7053 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7054 return null; 7055 } 7056 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7057 if (ps == null) { 7058 return null; 7059 } 7060 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7061 ps.readUserState(userId), userId); 7062 if (ai == null) { 7063 return null; 7064 } 7065 final ResolveInfo res = new ResolveInfo(); 7066 res.activityInfo = ai; 7067 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7068 res.filter = info; 7069 } 7070 res.priority = info.getPriority(); 7071 res.preferredOrder = activity.owner.mPreferredOrder; 7072 //System.out.println("Result: " + res.activityInfo.className + 7073 // " = " + res.priority); 7074 res.match = match; 7075 res.isDefault = info.hasDefault; 7076 res.labelRes = info.labelRes; 7077 res.nonLocalizedLabel = info.nonLocalizedLabel; 7078 if (userNeedsBadging(userId)) { 7079 res.noResourceId = true; 7080 } else { 7081 res.icon = info.icon; 7082 } 7083 res.system = isSystemApp(res.activityInfo.applicationInfo); 7084 return res; 7085 } 7086 7087 @Override 7088 protected void sortResults(List<ResolveInfo> results) { 7089 Collections.sort(results, mResolvePrioritySorter); 7090 } 7091 7092 @Override 7093 protected void dumpFilter(PrintWriter out, String prefix, 7094 PackageParser.ActivityIntentInfo filter) { 7095 out.print(prefix); out.print( 7096 Integer.toHexString(System.identityHashCode(filter.activity))); 7097 out.print(' '); 7098 filter.activity.printComponentShortName(out); 7099 out.print(" filter "); 7100 out.println(Integer.toHexString(System.identityHashCode(filter))); 7101 } 7102 7103// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7104// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7105// final List<ResolveInfo> retList = Lists.newArrayList(); 7106// while (i.hasNext()) { 7107// final ResolveInfo resolveInfo = i.next(); 7108// if (isEnabledLP(resolveInfo.activityInfo)) { 7109// retList.add(resolveInfo); 7110// } 7111// } 7112// return retList; 7113// } 7114 7115 // Keys are String (activity class name), values are Activity. 7116 private final HashMap<ComponentName, PackageParser.Activity> mActivities 7117 = new HashMap<ComponentName, PackageParser.Activity>(); 7118 private int mFlags; 7119 } 7120 7121 private final class ServiceIntentResolver 7122 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 7123 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7124 boolean defaultOnly, int userId) { 7125 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7126 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7127 } 7128 7129 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7130 int userId) { 7131 if (!sUserManager.exists(userId)) return null; 7132 mFlags = flags; 7133 return super.queryIntent(intent, resolvedType, 7134 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7135 } 7136 7137 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7138 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 7139 if (!sUserManager.exists(userId)) return null; 7140 if (packageServices == null) { 7141 return null; 7142 } 7143 mFlags = flags; 7144 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7145 final int N = packageServices.size(); 7146 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 7147 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 7148 7149 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 7150 for (int i = 0; i < N; ++i) { 7151 intentFilters = packageServices.get(i).intents; 7152 if (intentFilters != null && intentFilters.size() > 0) { 7153 PackageParser.ServiceIntentInfo[] array = 7154 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 7155 intentFilters.toArray(array); 7156 listCut.add(array); 7157 } 7158 } 7159 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7160 } 7161 7162 public final void addService(PackageParser.Service s) { 7163 mServices.put(s.getComponentName(), s); 7164 if (DEBUG_SHOW_INFO) { 7165 Log.v(TAG, " " 7166 + (s.info.nonLocalizedLabel != null 7167 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7168 Log.v(TAG, " Class=" + s.info.name); 7169 } 7170 final int NI = s.intents.size(); 7171 int j; 7172 for (j=0; j<NI; j++) { 7173 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7174 if (DEBUG_SHOW_INFO) { 7175 Log.v(TAG, " IntentFilter:"); 7176 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7177 } 7178 if (!intent.debugCheck()) { 7179 Log.w(TAG, "==> For Service " + s.info.name); 7180 } 7181 addFilter(intent); 7182 } 7183 } 7184 7185 public final void removeService(PackageParser.Service s) { 7186 mServices.remove(s.getComponentName()); 7187 if (DEBUG_SHOW_INFO) { 7188 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 7189 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7190 Log.v(TAG, " Class=" + s.info.name); 7191 } 7192 final int NI = s.intents.size(); 7193 int j; 7194 for (j=0; j<NI; j++) { 7195 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7196 if (DEBUG_SHOW_INFO) { 7197 Log.v(TAG, " IntentFilter:"); 7198 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7199 } 7200 removeFilter(intent); 7201 } 7202 } 7203 7204 @Override 7205 protected boolean allowFilterResult( 7206 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 7207 ServiceInfo filterSi = filter.service.info; 7208 for (int i=dest.size()-1; i>=0; i--) { 7209 ServiceInfo destAi = dest.get(i).serviceInfo; 7210 if (destAi.name == filterSi.name 7211 && destAi.packageName == filterSi.packageName) { 7212 return false; 7213 } 7214 } 7215 return true; 7216 } 7217 7218 @Override 7219 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 7220 return new PackageParser.ServiceIntentInfo[size]; 7221 } 7222 7223 @Override 7224 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 7225 if (!sUserManager.exists(userId)) return true; 7226 PackageParser.Package p = filter.service.owner; 7227 if (p != null) { 7228 PackageSetting ps = (PackageSetting)p.mExtras; 7229 if (ps != null) { 7230 // System apps are never considered stopped for purposes of 7231 // filtering, because there may be no way for the user to 7232 // actually re-launch them. 7233 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7234 && ps.getStopped(userId); 7235 } 7236 } 7237 return false; 7238 } 7239 7240 @Override 7241 protected boolean isPackageForFilter(String packageName, 7242 PackageParser.ServiceIntentInfo info) { 7243 return packageName.equals(info.service.owner.packageName); 7244 } 7245 7246 @Override 7247 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 7248 int match, int userId) { 7249 if (!sUserManager.exists(userId)) return null; 7250 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 7251 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 7252 return null; 7253 } 7254 final PackageParser.Service service = info.service; 7255 if (mSafeMode && (service.info.applicationInfo.flags 7256 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7257 return null; 7258 } 7259 PackageSetting ps = (PackageSetting) service.owner.mExtras; 7260 if (ps == null) { 7261 return null; 7262 } 7263 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 7264 ps.readUserState(userId), userId); 7265 if (si == null) { 7266 return null; 7267 } 7268 final ResolveInfo res = new ResolveInfo(); 7269 res.serviceInfo = si; 7270 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7271 res.filter = filter; 7272 } 7273 res.priority = info.getPriority(); 7274 res.preferredOrder = service.owner.mPreferredOrder; 7275 //System.out.println("Result: " + res.activityInfo.className + 7276 // " = " + res.priority); 7277 res.match = match; 7278 res.isDefault = info.hasDefault; 7279 res.labelRes = info.labelRes; 7280 res.nonLocalizedLabel = info.nonLocalizedLabel; 7281 res.icon = info.icon; 7282 res.system = isSystemApp(res.serviceInfo.applicationInfo); 7283 return res; 7284 } 7285 7286 @Override 7287 protected void sortResults(List<ResolveInfo> results) { 7288 Collections.sort(results, mResolvePrioritySorter); 7289 } 7290 7291 @Override 7292 protected void dumpFilter(PrintWriter out, String prefix, 7293 PackageParser.ServiceIntentInfo filter) { 7294 out.print(prefix); out.print( 7295 Integer.toHexString(System.identityHashCode(filter.service))); 7296 out.print(' '); 7297 filter.service.printComponentShortName(out); 7298 out.print(" filter "); 7299 out.println(Integer.toHexString(System.identityHashCode(filter))); 7300 } 7301 7302// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7303// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7304// final List<ResolveInfo> retList = Lists.newArrayList(); 7305// while (i.hasNext()) { 7306// final ResolveInfo resolveInfo = (ResolveInfo) i; 7307// if (isEnabledLP(resolveInfo.serviceInfo)) { 7308// retList.add(resolveInfo); 7309// } 7310// } 7311// return retList; 7312// } 7313 7314 // Keys are String (activity class name), values are Activity. 7315 private final HashMap<ComponentName, PackageParser.Service> mServices 7316 = new HashMap<ComponentName, PackageParser.Service>(); 7317 private int mFlags; 7318 }; 7319 7320 private final class ProviderIntentResolver 7321 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 7322 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7323 boolean defaultOnly, int userId) { 7324 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7325 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7326 } 7327 7328 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7329 int userId) { 7330 if (!sUserManager.exists(userId)) 7331 return null; 7332 mFlags = flags; 7333 return super.queryIntent(intent, resolvedType, 7334 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7335 } 7336 7337 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7338 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 7339 if (!sUserManager.exists(userId)) 7340 return null; 7341 if (packageProviders == null) { 7342 return null; 7343 } 7344 mFlags = flags; 7345 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 7346 final int N = packageProviders.size(); 7347 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 7348 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 7349 7350 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 7351 for (int i = 0; i < N; ++i) { 7352 intentFilters = packageProviders.get(i).intents; 7353 if (intentFilters != null && intentFilters.size() > 0) { 7354 PackageParser.ProviderIntentInfo[] array = 7355 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 7356 intentFilters.toArray(array); 7357 listCut.add(array); 7358 } 7359 } 7360 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7361 } 7362 7363 public final void addProvider(PackageParser.Provider p) { 7364 if (mProviders.containsKey(p.getComponentName())) { 7365 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 7366 return; 7367 } 7368 7369 mProviders.put(p.getComponentName(), p); 7370 if (DEBUG_SHOW_INFO) { 7371 Log.v(TAG, " " 7372 + (p.info.nonLocalizedLabel != null 7373 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7374 Log.v(TAG, " Class=" + p.info.name); 7375 } 7376 final int NI = p.intents.size(); 7377 int j; 7378 for (j = 0; j < NI; j++) { 7379 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7380 if (DEBUG_SHOW_INFO) { 7381 Log.v(TAG, " IntentFilter:"); 7382 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7383 } 7384 if (!intent.debugCheck()) { 7385 Log.w(TAG, "==> For Provider " + p.info.name); 7386 } 7387 addFilter(intent); 7388 } 7389 } 7390 7391 public final void removeProvider(PackageParser.Provider p) { 7392 mProviders.remove(p.getComponentName()); 7393 if (DEBUG_SHOW_INFO) { 7394 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 7395 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7396 Log.v(TAG, " Class=" + p.info.name); 7397 } 7398 final int NI = p.intents.size(); 7399 int j; 7400 for (j = 0; j < NI; j++) { 7401 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7402 if (DEBUG_SHOW_INFO) { 7403 Log.v(TAG, " IntentFilter:"); 7404 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7405 } 7406 removeFilter(intent); 7407 } 7408 } 7409 7410 @Override 7411 protected boolean allowFilterResult( 7412 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 7413 ProviderInfo filterPi = filter.provider.info; 7414 for (int i = dest.size() - 1; i >= 0; i--) { 7415 ProviderInfo destPi = dest.get(i).providerInfo; 7416 if (destPi.name == filterPi.name 7417 && destPi.packageName == filterPi.packageName) { 7418 return false; 7419 } 7420 } 7421 return true; 7422 } 7423 7424 @Override 7425 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 7426 return new PackageParser.ProviderIntentInfo[size]; 7427 } 7428 7429 @Override 7430 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 7431 if (!sUserManager.exists(userId)) 7432 return true; 7433 PackageParser.Package p = filter.provider.owner; 7434 if (p != null) { 7435 PackageSetting ps = (PackageSetting) p.mExtras; 7436 if (ps != null) { 7437 // System apps are never considered stopped for purposes of 7438 // filtering, because there may be no way for the user to 7439 // actually re-launch them. 7440 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7441 && ps.getStopped(userId); 7442 } 7443 } 7444 return false; 7445 } 7446 7447 @Override 7448 protected boolean isPackageForFilter(String packageName, 7449 PackageParser.ProviderIntentInfo info) { 7450 return packageName.equals(info.provider.owner.packageName); 7451 } 7452 7453 @Override 7454 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 7455 int match, int userId) { 7456 if (!sUserManager.exists(userId)) 7457 return null; 7458 final PackageParser.ProviderIntentInfo info = filter; 7459 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 7460 return null; 7461 } 7462 final PackageParser.Provider provider = info.provider; 7463 if (mSafeMode && (provider.info.applicationInfo.flags 7464 & ApplicationInfo.FLAG_SYSTEM) == 0) { 7465 return null; 7466 } 7467 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 7468 if (ps == null) { 7469 return null; 7470 } 7471 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 7472 ps.readUserState(userId), userId); 7473 if (pi == null) { 7474 return null; 7475 } 7476 final ResolveInfo res = new ResolveInfo(); 7477 res.providerInfo = pi; 7478 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 7479 res.filter = filter; 7480 } 7481 res.priority = info.getPriority(); 7482 res.preferredOrder = provider.owner.mPreferredOrder; 7483 res.match = match; 7484 res.isDefault = info.hasDefault; 7485 res.labelRes = info.labelRes; 7486 res.nonLocalizedLabel = info.nonLocalizedLabel; 7487 res.icon = info.icon; 7488 res.system = isSystemApp(res.providerInfo.applicationInfo); 7489 return res; 7490 } 7491 7492 @Override 7493 protected void sortResults(List<ResolveInfo> results) { 7494 Collections.sort(results, mResolvePrioritySorter); 7495 } 7496 7497 @Override 7498 protected void dumpFilter(PrintWriter out, String prefix, 7499 PackageParser.ProviderIntentInfo filter) { 7500 out.print(prefix); 7501 out.print( 7502 Integer.toHexString(System.identityHashCode(filter.provider))); 7503 out.print(' '); 7504 filter.provider.printComponentShortName(out); 7505 out.print(" filter "); 7506 out.println(Integer.toHexString(System.identityHashCode(filter))); 7507 } 7508 7509 private final HashMap<ComponentName, PackageParser.Provider> mProviders 7510 = new HashMap<ComponentName, PackageParser.Provider>(); 7511 private int mFlags; 7512 }; 7513 7514 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 7515 new Comparator<ResolveInfo>() { 7516 public int compare(ResolveInfo r1, ResolveInfo r2) { 7517 int v1 = r1.priority; 7518 int v2 = r2.priority; 7519 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 7520 if (v1 != v2) { 7521 return (v1 > v2) ? -1 : 1; 7522 } 7523 v1 = r1.preferredOrder; 7524 v2 = r2.preferredOrder; 7525 if (v1 != v2) { 7526 return (v1 > v2) ? -1 : 1; 7527 } 7528 if (r1.isDefault != r2.isDefault) { 7529 return r1.isDefault ? -1 : 1; 7530 } 7531 v1 = r1.match; 7532 v2 = r2.match; 7533 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 7534 if (v1 != v2) { 7535 return (v1 > v2) ? -1 : 1; 7536 } 7537 if (r1.system != r2.system) { 7538 return r1.system ? -1 : 1; 7539 } 7540 return 0; 7541 } 7542 }; 7543 7544 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 7545 new Comparator<ProviderInfo>() { 7546 public int compare(ProviderInfo p1, ProviderInfo p2) { 7547 final int v1 = p1.initOrder; 7548 final int v2 = p2.initOrder; 7549 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 7550 } 7551 }; 7552 7553 static final void sendPackageBroadcast(String action, String pkg, 7554 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 7555 int[] userIds) { 7556 IActivityManager am = ActivityManagerNative.getDefault(); 7557 if (am != null) { 7558 try { 7559 if (userIds == null) { 7560 userIds = am.getRunningUserIds(); 7561 } 7562 for (int id : userIds) { 7563 final Intent intent = new Intent(action, 7564 pkg != null ? Uri.fromParts("package", pkg, null) : null); 7565 if (extras != null) { 7566 intent.putExtras(extras); 7567 } 7568 if (targetPkg != null) { 7569 intent.setPackage(targetPkg); 7570 } 7571 // Modify the UID when posting to other users 7572 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 7573 if (uid > 0 && UserHandle.getUserId(uid) != id) { 7574 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 7575 intent.putExtra(Intent.EXTRA_UID, uid); 7576 } 7577 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 7578 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 7579 if (DEBUG_BROADCASTS) { 7580 RuntimeException here = new RuntimeException("here"); 7581 here.fillInStackTrace(); 7582 Slog.d(TAG, "Sending to user " + id + ": " 7583 + intent.toShortString(false, true, false, false) 7584 + " " + intent.getExtras(), here); 7585 } 7586 am.broadcastIntent(null, intent, null, finishedReceiver, 7587 0, null, null, null, android.app.AppOpsManager.OP_NONE, 7588 finishedReceiver != null, false, id); 7589 } 7590 } catch (RemoteException ex) { 7591 } 7592 } 7593 } 7594 7595 /** 7596 * Check if the external storage media is available. This is true if there 7597 * is a mounted external storage medium or if the external storage is 7598 * emulated. 7599 */ 7600 private boolean isExternalMediaAvailable() { 7601 return mMediaMounted || Environment.isExternalStorageEmulated(); 7602 } 7603 7604 @Override 7605 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 7606 // writer 7607 synchronized (mPackages) { 7608 if (!isExternalMediaAvailable()) { 7609 // If the external storage is no longer mounted at this point, 7610 // the caller may not have been able to delete all of this 7611 // packages files and can not delete any more. Bail. 7612 return null; 7613 } 7614 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 7615 if (lastPackage != null) { 7616 pkgs.remove(lastPackage); 7617 } 7618 if (pkgs.size() > 0) { 7619 return pkgs.get(0); 7620 } 7621 } 7622 return null; 7623 } 7624 7625 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 7626 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 7627 userId, andCode ? 1 : 0, packageName); 7628 if (mSystemReady) { 7629 msg.sendToTarget(); 7630 } else { 7631 if (mPostSystemReadyMessages == null) { 7632 mPostSystemReadyMessages = new ArrayList<>(); 7633 } 7634 mPostSystemReadyMessages.add(msg); 7635 } 7636 } 7637 7638 void startCleaningPackages() { 7639 // reader 7640 synchronized (mPackages) { 7641 if (!isExternalMediaAvailable()) { 7642 return; 7643 } 7644 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 7645 return; 7646 } 7647 } 7648 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 7649 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 7650 IActivityManager am = ActivityManagerNative.getDefault(); 7651 if (am != null) { 7652 try { 7653 am.startService(null, intent, null, UserHandle.USER_OWNER); 7654 } catch (RemoteException e) { 7655 } 7656 } 7657 } 7658 7659 @Override 7660 public void installPackage(String originPath, IPackageInstallObserver2 observer, 7661 int installFlags, String installerPackageName, VerificationParams verificationParams, 7662 String packageAbiOverride) { 7663 installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams, 7664 packageAbiOverride, UserHandle.getCallingUserId()); 7665 } 7666 7667 @Override 7668 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 7669 int installFlags, String installerPackageName, VerificationParams verificationParams, 7670 String packageAbiOverride, int userId) { 7671 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 7672 7673 final int callingUid = Binder.getCallingUid(); 7674 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 7675 7676 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 7677 try { 7678 if (observer != null) { 7679 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 7680 } 7681 } catch (RemoteException re) { 7682 } 7683 return; 7684 } 7685 7686 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 7687 installFlags |= PackageManager.INSTALL_FROM_ADB; 7688 7689 } else { 7690 // Caller holds INSTALL_PACKAGES permission, so we're less strict 7691 // about installerPackageName. 7692 7693 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 7694 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 7695 } 7696 7697 UserHandle user; 7698 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 7699 user = UserHandle.ALL; 7700 } else { 7701 user = new UserHandle(userId); 7702 } 7703 7704 verificationParams.setInstallerUid(callingUid); 7705 7706 final File originFile = new File(originPath); 7707 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 7708 7709 final Message msg = mHandler.obtainMessage(INIT_COPY); 7710 msg.obj = new InstallParams(origin, observer, installFlags, 7711 installerPackageName, verificationParams, user, packageAbiOverride); 7712 mHandler.sendMessage(msg); 7713 } 7714 7715 void installStage(String packageName, File stagedDir, String stagedCid, 7716 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 7717 String installerPackageName, int installerUid, UserHandle user) { 7718 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 7719 params.referrerUri, installerUid, null); 7720 7721 final OriginInfo origin; 7722 if (stagedDir != null) { 7723 origin = OriginInfo.fromStagedFile(stagedDir); 7724 } else { 7725 origin = OriginInfo.fromStagedContainer(stagedCid); 7726 } 7727 7728 final Message msg = mHandler.obtainMessage(INIT_COPY); 7729 msg.obj = new InstallParams(origin, observer, params.installFlags, 7730 installerPackageName, verifParams, user, params.abiOverride); 7731 mHandler.sendMessage(msg); 7732 } 7733 7734 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 7735 Bundle extras = new Bundle(1); 7736 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 7737 7738 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 7739 packageName, extras, null, null, new int[] {userId}); 7740 try { 7741 IActivityManager am = ActivityManagerNative.getDefault(); 7742 final boolean isSystem = 7743 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 7744 if (isSystem && am.isUserRunning(userId, false)) { 7745 // The just-installed/enabled app is bundled on the system, so presumed 7746 // to be able to run automatically without needing an explicit launch. 7747 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 7748 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 7749 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 7750 .setPackage(packageName); 7751 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 7752 android.app.AppOpsManager.OP_NONE, false, false, userId); 7753 } 7754 } catch (RemoteException e) { 7755 // shouldn't happen 7756 Slog.w(TAG, "Unable to bootstrap installed package", e); 7757 } 7758 } 7759 7760 @Override 7761 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 7762 int userId) { 7763 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7764 PackageSetting pkgSetting; 7765 final int uid = Binder.getCallingUid(); 7766 enforceCrossUserPermission(uid, userId, true, true, 7767 "setApplicationHiddenSetting for user " + userId); 7768 7769 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 7770 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 7771 return false; 7772 } 7773 7774 long callingId = Binder.clearCallingIdentity(); 7775 try { 7776 boolean sendAdded = false; 7777 boolean sendRemoved = false; 7778 // writer 7779 synchronized (mPackages) { 7780 pkgSetting = mSettings.mPackages.get(packageName); 7781 if (pkgSetting == null) { 7782 return false; 7783 } 7784 if (pkgSetting.getHidden(userId) != hidden) { 7785 pkgSetting.setHidden(hidden, userId); 7786 mSettings.writePackageRestrictionsLPr(userId); 7787 if (hidden) { 7788 sendRemoved = true; 7789 } else { 7790 sendAdded = true; 7791 } 7792 } 7793 } 7794 if (sendAdded) { 7795 sendPackageAddedForUser(packageName, pkgSetting, userId); 7796 return true; 7797 } 7798 if (sendRemoved) { 7799 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 7800 "hiding pkg"); 7801 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 7802 } 7803 } finally { 7804 Binder.restoreCallingIdentity(callingId); 7805 } 7806 return false; 7807 } 7808 7809 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 7810 int userId) { 7811 final PackageRemovedInfo info = new PackageRemovedInfo(); 7812 info.removedPackage = packageName; 7813 info.removedUsers = new int[] {userId}; 7814 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 7815 info.sendBroadcast(false, false, false); 7816 } 7817 7818 /** 7819 * Returns true if application is not found or there was an error. Otherwise it returns 7820 * the hidden state of the package for the given user. 7821 */ 7822 @Override 7823 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 7824 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7825 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 7826 false, "getApplicationHidden for user " + userId); 7827 PackageSetting pkgSetting; 7828 long callingId = Binder.clearCallingIdentity(); 7829 try { 7830 // writer 7831 synchronized (mPackages) { 7832 pkgSetting = mSettings.mPackages.get(packageName); 7833 if (pkgSetting == null) { 7834 return true; 7835 } 7836 return pkgSetting.getHidden(userId); 7837 } 7838 } finally { 7839 Binder.restoreCallingIdentity(callingId); 7840 } 7841 } 7842 7843 /** 7844 * @hide 7845 */ 7846 @Override 7847 public int installExistingPackageAsUser(String packageName, int userId) { 7848 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7849 null); 7850 PackageSetting pkgSetting; 7851 final int uid = Binder.getCallingUid(); 7852 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 7853 + userId); 7854 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 7855 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 7856 } 7857 7858 long callingId = Binder.clearCallingIdentity(); 7859 try { 7860 boolean sendAdded = false; 7861 Bundle extras = new Bundle(1); 7862 7863 // writer 7864 synchronized (mPackages) { 7865 pkgSetting = mSettings.mPackages.get(packageName); 7866 if (pkgSetting == null) { 7867 return PackageManager.INSTALL_FAILED_INVALID_URI; 7868 } 7869 if (!pkgSetting.getInstalled(userId)) { 7870 pkgSetting.setInstalled(true, userId); 7871 pkgSetting.setHidden(false, userId); 7872 mSettings.writePackageRestrictionsLPr(userId); 7873 sendAdded = true; 7874 } 7875 } 7876 7877 if (sendAdded) { 7878 sendPackageAddedForUser(packageName, pkgSetting, userId); 7879 } 7880 } finally { 7881 Binder.restoreCallingIdentity(callingId); 7882 } 7883 7884 return PackageManager.INSTALL_SUCCEEDED; 7885 } 7886 7887 boolean isUserRestricted(int userId, String restrictionKey) { 7888 Bundle restrictions = sUserManager.getUserRestrictions(userId); 7889 if (restrictions.getBoolean(restrictionKey, false)) { 7890 Log.w(TAG, "User is restricted: " + restrictionKey); 7891 return true; 7892 } 7893 return false; 7894 } 7895 7896 @Override 7897 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 7898 mContext.enforceCallingOrSelfPermission( 7899 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7900 "Only package verification agents can verify applications"); 7901 7902 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7903 final PackageVerificationResponse response = new PackageVerificationResponse( 7904 verificationCode, Binder.getCallingUid()); 7905 msg.arg1 = id; 7906 msg.obj = response; 7907 mHandler.sendMessage(msg); 7908 } 7909 7910 @Override 7911 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 7912 long millisecondsToDelay) { 7913 mContext.enforceCallingOrSelfPermission( 7914 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7915 "Only package verification agents can extend verification timeouts"); 7916 7917 final PackageVerificationState state = mPendingVerification.get(id); 7918 final PackageVerificationResponse response = new PackageVerificationResponse( 7919 verificationCodeAtTimeout, Binder.getCallingUid()); 7920 7921 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 7922 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 7923 } 7924 if (millisecondsToDelay < 0) { 7925 millisecondsToDelay = 0; 7926 } 7927 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 7928 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 7929 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 7930 } 7931 7932 if ((state != null) && !state.timeoutExtended()) { 7933 state.extendTimeout(); 7934 7935 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7936 msg.arg1 = id; 7937 msg.obj = response; 7938 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 7939 } 7940 } 7941 7942 private void broadcastPackageVerified(int verificationId, Uri packageUri, 7943 int verificationCode, UserHandle user) { 7944 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 7945 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 7946 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 7947 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 7948 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 7949 7950 mContext.sendBroadcastAsUser(intent, user, 7951 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 7952 } 7953 7954 private ComponentName matchComponentForVerifier(String packageName, 7955 List<ResolveInfo> receivers) { 7956 ActivityInfo targetReceiver = null; 7957 7958 final int NR = receivers.size(); 7959 for (int i = 0; i < NR; i++) { 7960 final ResolveInfo info = receivers.get(i); 7961 if (info.activityInfo == null) { 7962 continue; 7963 } 7964 7965 if (packageName.equals(info.activityInfo.packageName)) { 7966 targetReceiver = info.activityInfo; 7967 break; 7968 } 7969 } 7970 7971 if (targetReceiver == null) { 7972 return null; 7973 } 7974 7975 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 7976 } 7977 7978 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 7979 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 7980 if (pkgInfo.verifiers.length == 0) { 7981 return null; 7982 } 7983 7984 final int N = pkgInfo.verifiers.length; 7985 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 7986 for (int i = 0; i < N; i++) { 7987 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 7988 7989 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 7990 receivers); 7991 if (comp == null) { 7992 continue; 7993 } 7994 7995 final int verifierUid = getUidForVerifier(verifierInfo); 7996 if (verifierUid == -1) { 7997 continue; 7998 } 7999 8000 if (DEBUG_VERIFY) { 8001 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8002 + " with the correct signature"); 8003 } 8004 sufficientVerifiers.add(comp); 8005 verificationState.addSufficientVerifier(verifierUid); 8006 } 8007 8008 return sufficientVerifiers; 8009 } 8010 8011 private int getUidForVerifier(VerifierInfo verifierInfo) { 8012 synchronized (mPackages) { 8013 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8014 if (pkg == null) { 8015 return -1; 8016 } else if (pkg.mSignatures.length != 1) { 8017 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8018 + " has more than one signature; ignoring"); 8019 return -1; 8020 } 8021 8022 /* 8023 * If the public key of the package's signature does not match 8024 * our expected public key, then this is a different package and 8025 * we should skip. 8026 */ 8027 8028 final byte[] expectedPublicKey; 8029 try { 8030 final Signature verifierSig = pkg.mSignatures[0]; 8031 final PublicKey publicKey = verifierSig.getPublicKey(); 8032 expectedPublicKey = publicKey.getEncoded(); 8033 } catch (CertificateException e) { 8034 return -1; 8035 } 8036 8037 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8038 8039 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8040 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8041 + " does not have the expected public key; ignoring"); 8042 return -1; 8043 } 8044 8045 return pkg.applicationInfo.uid; 8046 } 8047 } 8048 8049 @Override 8050 public void finishPackageInstall(int token) { 8051 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8052 8053 if (DEBUG_INSTALL) { 8054 Slog.v(TAG, "BM finishing package install for " + token); 8055 } 8056 8057 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8058 mHandler.sendMessage(msg); 8059 } 8060 8061 /** 8062 * Get the verification agent timeout. 8063 * 8064 * @return verification timeout in milliseconds 8065 */ 8066 private long getVerificationTimeout() { 8067 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8068 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8069 DEFAULT_VERIFICATION_TIMEOUT); 8070 } 8071 8072 /** 8073 * Get the default verification agent response code. 8074 * 8075 * @return default verification response code 8076 */ 8077 private int getDefaultVerificationResponse() { 8078 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8079 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8080 DEFAULT_VERIFICATION_RESPONSE); 8081 } 8082 8083 /** 8084 * Check whether or not package verification has been enabled. 8085 * 8086 * @return true if verification should be performed 8087 */ 8088 private boolean isVerificationEnabled(int userId, int installFlags) { 8089 if (!DEFAULT_VERIFY_ENABLE) { 8090 return false; 8091 } 8092 8093 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 8094 8095 // Check if installing from ADB 8096 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 8097 // Do not run verification in a test harness environment 8098 if (ActivityManager.isRunningInTestHarness()) { 8099 return false; 8100 } 8101 if (ensureVerifyAppsEnabled) { 8102 return true; 8103 } 8104 // Check if the developer does not want package verification for ADB installs 8105 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8106 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8107 return false; 8108 } 8109 } 8110 8111 if (ensureVerifyAppsEnabled) { 8112 return true; 8113 } 8114 8115 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8116 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8117 } 8118 8119 /** 8120 * Get the "allow unknown sources" setting. 8121 * 8122 * @return the current "allow unknown sources" setting 8123 */ 8124 private int getUnknownSourcesSettings() { 8125 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8126 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 8127 -1); 8128 } 8129 8130 @Override 8131 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 8132 final int uid = Binder.getCallingUid(); 8133 // writer 8134 synchronized (mPackages) { 8135 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 8136 if (targetPackageSetting == null) { 8137 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 8138 } 8139 8140 PackageSetting installerPackageSetting; 8141 if (installerPackageName != null) { 8142 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 8143 if (installerPackageSetting == null) { 8144 throw new IllegalArgumentException("Unknown installer package: " 8145 + installerPackageName); 8146 } 8147 } else { 8148 installerPackageSetting = null; 8149 } 8150 8151 Signature[] callerSignature; 8152 Object obj = mSettings.getUserIdLPr(uid); 8153 if (obj != null) { 8154 if (obj instanceof SharedUserSetting) { 8155 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 8156 } else if (obj instanceof PackageSetting) { 8157 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 8158 } else { 8159 throw new SecurityException("Bad object " + obj + " for uid " + uid); 8160 } 8161 } else { 8162 throw new SecurityException("Unknown calling uid " + uid); 8163 } 8164 8165 // Verify: can't set installerPackageName to a package that is 8166 // not signed with the same cert as the caller. 8167 if (installerPackageSetting != null) { 8168 if (compareSignatures(callerSignature, 8169 installerPackageSetting.signatures.mSignatures) 8170 != PackageManager.SIGNATURE_MATCH) { 8171 throw new SecurityException( 8172 "Caller does not have same cert as new installer package " 8173 + installerPackageName); 8174 } 8175 } 8176 8177 // Verify: if target already has an installer package, it must 8178 // be signed with the same cert as the caller. 8179 if (targetPackageSetting.installerPackageName != null) { 8180 PackageSetting setting = mSettings.mPackages.get( 8181 targetPackageSetting.installerPackageName); 8182 // If the currently set package isn't valid, then it's always 8183 // okay to change it. 8184 if (setting != null) { 8185 if (compareSignatures(callerSignature, 8186 setting.signatures.mSignatures) 8187 != PackageManager.SIGNATURE_MATCH) { 8188 throw new SecurityException( 8189 "Caller does not have same cert as old installer package " 8190 + targetPackageSetting.installerPackageName); 8191 } 8192 } 8193 } 8194 8195 // Okay! 8196 targetPackageSetting.installerPackageName = installerPackageName; 8197 scheduleWriteSettingsLocked(); 8198 } 8199 } 8200 8201 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 8202 // Queue up an async operation since the package installation may take a little while. 8203 mHandler.post(new Runnable() { 8204 public void run() { 8205 mHandler.removeCallbacks(this); 8206 // Result object to be returned 8207 PackageInstalledInfo res = new PackageInstalledInfo(); 8208 res.returnCode = currentStatus; 8209 res.uid = -1; 8210 res.pkg = null; 8211 res.removedInfo = new PackageRemovedInfo(); 8212 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 8213 args.doPreInstall(res.returnCode); 8214 synchronized (mInstallLock) { 8215 installPackageLI(args, res); 8216 } 8217 args.doPostInstall(res.returnCode, res.uid); 8218 } 8219 8220 // A restore should be performed at this point if (a) the install 8221 // succeeded, (b) the operation is not an update, and (c) the new 8222 // package has not opted out of backup participation. 8223 final boolean update = res.removedInfo.removedPackage != null; 8224 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 8225 boolean doRestore = !update 8226 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 8227 8228 // Set up the post-install work request bookkeeping. This will be used 8229 // and cleaned up by the post-install event handling regardless of whether 8230 // there's a restore pass performed. Token values are >= 1. 8231 int token; 8232 if (mNextInstallToken < 0) mNextInstallToken = 1; 8233 token = mNextInstallToken++; 8234 8235 PostInstallData data = new PostInstallData(args, res); 8236 mRunningInstalls.put(token, data); 8237 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 8238 8239 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 8240 // Pass responsibility to the Backup Manager. It will perform a 8241 // restore if appropriate, then pass responsibility back to the 8242 // Package Manager to run the post-install observer callbacks 8243 // and broadcasts. 8244 IBackupManager bm = IBackupManager.Stub.asInterface( 8245 ServiceManager.getService(Context.BACKUP_SERVICE)); 8246 if (bm != null) { 8247 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 8248 + " to BM for possible restore"); 8249 try { 8250 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 8251 } catch (RemoteException e) { 8252 // can't happen; the backup manager is local 8253 } catch (Exception e) { 8254 Slog.e(TAG, "Exception trying to enqueue restore", e); 8255 doRestore = false; 8256 } 8257 } else { 8258 Slog.e(TAG, "Backup Manager not found!"); 8259 doRestore = false; 8260 } 8261 } 8262 8263 if (!doRestore) { 8264 // No restore possible, or the Backup Manager was mysteriously not 8265 // available -- just fire the post-install work request directly. 8266 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 8267 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8268 mHandler.sendMessage(msg); 8269 } 8270 } 8271 }); 8272 } 8273 8274 private abstract class HandlerParams { 8275 private static final int MAX_RETRIES = 4; 8276 8277 /** 8278 * Number of times startCopy() has been attempted and had a non-fatal 8279 * error. 8280 */ 8281 private int mRetries = 0; 8282 8283 /** User handle for the user requesting the information or installation. */ 8284 private final UserHandle mUser; 8285 8286 HandlerParams(UserHandle user) { 8287 mUser = user; 8288 } 8289 8290 UserHandle getUser() { 8291 return mUser; 8292 } 8293 8294 final boolean startCopy() { 8295 boolean res; 8296 try { 8297 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 8298 8299 if (++mRetries > MAX_RETRIES) { 8300 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 8301 mHandler.sendEmptyMessage(MCS_GIVE_UP); 8302 handleServiceError(); 8303 return false; 8304 } else { 8305 handleStartCopy(); 8306 res = true; 8307 } 8308 } catch (RemoteException e) { 8309 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 8310 mHandler.sendEmptyMessage(MCS_RECONNECT); 8311 res = false; 8312 } 8313 handleReturnCode(); 8314 return res; 8315 } 8316 8317 final void serviceError() { 8318 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 8319 handleServiceError(); 8320 handleReturnCode(); 8321 } 8322 8323 abstract void handleStartCopy() throws RemoteException; 8324 abstract void handleServiceError(); 8325 abstract void handleReturnCode(); 8326 } 8327 8328 class MeasureParams extends HandlerParams { 8329 private final PackageStats mStats; 8330 private boolean mSuccess; 8331 8332 private final IPackageStatsObserver mObserver; 8333 8334 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 8335 super(new UserHandle(stats.userHandle)); 8336 mObserver = observer; 8337 mStats = stats; 8338 } 8339 8340 @Override 8341 public String toString() { 8342 return "MeasureParams{" 8343 + Integer.toHexString(System.identityHashCode(this)) 8344 + " " + mStats.packageName + "}"; 8345 } 8346 8347 @Override 8348 void handleStartCopy() throws RemoteException { 8349 synchronized (mInstallLock) { 8350 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 8351 } 8352 8353 if (mSuccess) { 8354 final boolean mounted; 8355 if (Environment.isExternalStorageEmulated()) { 8356 mounted = true; 8357 } else { 8358 final String status = Environment.getExternalStorageState(); 8359 mounted = (Environment.MEDIA_MOUNTED.equals(status) 8360 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 8361 } 8362 8363 if (mounted) { 8364 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 8365 8366 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 8367 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 8368 8369 mStats.externalDataSize = calculateDirectorySize(mContainerService, 8370 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 8371 8372 // Always subtract cache size, since it's a subdirectory 8373 mStats.externalDataSize -= mStats.externalCacheSize; 8374 8375 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 8376 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 8377 8378 mStats.externalObbSize = calculateDirectorySize(mContainerService, 8379 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 8380 } 8381 } 8382 } 8383 8384 @Override 8385 void handleReturnCode() { 8386 if (mObserver != null) { 8387 try { 8388 mObserver.onGetStatsCompleted(mStats, mSuccess); 8389 } catch (RemoteException e) { 8390 Slog.i(TAG, "Observer no longer exists."); 8391 } 8392 } 8393 } 8394 8395 @Override 8396 void handleServiceError() { 8397 Slog.e(TAG, "Could not measure application " + mStats.packageName 8398 + " external storage"); 8399 } 8400 } 8401 8402 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 8403 throws RemoteException { 8404 long result = 0; 8405 for (File path : paths) { 8406 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 8407 } 8408 return result; 8409 } 8410 8411 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 8412 for (File path : paths) { 8413 try { 8414 mcs.clearDirectory(path.getAbsolutePath()); 8415 } catch (RemoteException e) { 8416 } 8417 } 8418 } 8419 8420 static class OriginInfo { 8421 /** 8422 * Location where install is coming from, before it has been 8423 * copied/renamed into place. This could be a single monolithic APK 8424 * file, or a cluster directory. This location may be untrusted. 8425 */ 8426 final File file; 8427 final String cid; 8428 8429 /** 8430 * Flag indicating that {@link #file} or {@link #cid} has already been 8431 * staged, meaning downstream users don't need to defensively copy the 8432 * contents. 8433 */ 8434 final boolean staged; 8435 8436 /** 8437 * Flag indicating that {@link #file} or {@link #cid} is an already 8438 * installed app that is being moved. 8439 */ 8440 final boolean existing; 8441 8442 final String resolvedPath; 8443 final File resolvedFile; 8444 8445 static OriginInfo fromNothing() { 8446 return new OriginInfo(null, null, false, false); 8447 } 8448 8449 static OriginInfo fromUntrustedFile(File file) { 8450 return new OriginInfo(file, null, false, false); 8451 } 8452 8453 static OriginInfo fromExistingFile(File file) { 8454 return new OriginInfo(file, null, false, true); 8455 } 8456 8457 static OriginInfo fromStagedFile(File file) { 8458 return new OriginInfo(file, null, true, false); 8459 } 8460 8461 static OriginInfo fromStagedContainer(String cid) { 8462 return new OriginInfo(null, cid, true, false); 8463 } 8464 8465 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 8466 this.file = file; 8467 this.cid = cid; 8468 this.staged = staged; 8469 this.existing = existing; 8470 8471 if (cid != null) { 8472 resolvedPath = PackageHelper.getSdDir(cid); 8473 resolvedFile = new File(resolvedPath); 8474 } else if (file != null) { 8475 resolvedPath = file.getAbsolutePath(); 8476 resolvedFile = file; 8477 } else { 8478 resolvedPath = null; 8479 resolvedFile = null; 8480 } 8481 } 8482 } 8483 8484 class InstallParams extends HandlerParams { 8485 final OriginInfo origin; 8486 final IPackageInstallObserver2 observer; 8487 int installFlags; 8488 final String installerPackageName; 8489 final VerificationParams verificationParams; 8490 private InstallArgs mArgs; 8491 private int mRet; 8492 final String packageAbiOverride; 8493 8494 InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 8495 String installerPackageName, VerificationParams verificationParams, UserHandle user, 8496 String packageAbiOverride) { 8497 super(user); 8498 this.origin = origin; 8499 this.observer = observer; 8500 this.installFlags = installFlags; 8501 this.installerPackageName = installerPackageName; 8502 this.verificationParams = verificationParams; 8503 this.packageAbiOverride = packageAbiOverride; 8504 } 8505 8506 @Override 8507 public String toString() { 8508 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 8509 + " file=" + origin.file + " cid=" + origin.cid + "}"; 8510 } 8511 8512 public ManifestDigest getManifestDigest() { 8513 if (verificationParams == null) { 8514 return null; 8515 } 8516 return verificationParams.getManifestDigest(); 8517 } 8518 8519 private int installLocationPolicy(PackageInfoLite pkgLite) { 8520 String packageName = pkgLite.packageName; 8521 int installLocation = pkgLite.installLocation; 8522 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 8523 // reader 8524 synchronized (mPackages) { 8525 PackageParser.Package pkg = mPackages.get(packageName); 8526 if (pkg != null) { 8527 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 8528 // Check for downgrading. 8529 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 8530 if (pkgLite.versionCode < pkg.mVersionCode) { 8531 Slog.w(TAG, "Can't install update of " + packageName 8532 + " update version " + pkgLite.versionCode 8533 + " is older than installed version " 8534 + pkg.mVersionCode); 8535 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 8536 } 8537 } 8538 // Check for updated system application. 8539 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8540 if (onSd) { 8541 Slog.w(TAG, "Cannot install update to system app on sdcard"); 8542 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 8543 } 8544 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8545 } else { 8546 if (onSd) { 8547 // Install flag overrides everything. 8548 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8549 } 8550 // If current upgrade specifies particular preference 8551 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 8552 // Application explicitly specified internal. 8553 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8554 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 8555 // App explictly prefers external. Let policy decide 8556 } else { 8557 // Prefer previous location 8558 if (isExternal(pkg)) { 8559 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8560 } 8561 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8562 } 8563 } 8564 } else { 8565 // Invalid install. Return error code 8566 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 8567 } 8568 } 8569 } 8570 // All the special cases have been taken care of. 8571 // Return result based on recommended install location. 8572 if (onSd) { 8573 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8574 } 8575 return pkgLite.recommendedInstallLocation; 8576 } 8577 8578 /* 8579 * Invoke remote method to get package information and install 8580 * location values. Override install location based on default 8581 * policy if needed and then create install arguments based 8582 * on the install location. 8583 */ 8584 public void handleStartCopy() throws RemoteException { 8585 int ret = PackageManager.INSTALL_SUCCEEDED; 8586 8587 // If we're already staged, we've firmly committed to an install location 8588 if (origin.staged) { 8589 if (origin.file != null) { 8590 installFlags |= PackageManager.INSTALL_INTERNAL; 8591 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 8592 } else if (origin.cid != null) { 8593 installFlags |= PackageManager.INSTALL_EXTERNAL; 8594 installFlags &= ~PackageManager.INSTALL_INTERNAL; 8595 } else { 8596 throw new IllegalStateException("Invalid stage location"); 8597 } 8598 } 8599 8600 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 8601 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 8602 8603 PackageInfoLite pkgLite = null; 8604 8605 if (onInt && onSd) { 8606 // Check if both bits are set. 8607 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 8608 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8609 } else { 8610 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 8611 packageAbiOverride); 8612 8613 /* 8614 * If we have too little free space, try to free cache 8615 * before giving up. 8616 */ 8617 if (!origin.staged && pkgLite.recommendedInstallLocation 8618 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8619 // TODO: focus freeing disk space on the target device 8620 final StorageManager storage = StorageManager.from(mContext); 8621 final long lowThreshold = storage.getStorageLowBytes( 8622 Environment.getDataDirectory()); 8623 8624 final long sizeBytes = mContainerService.calculateInstalledSize( 8625 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 8626 8627 if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) { 8628 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 8629 installFlags, packageAbiOverride); 8630 } 8631 8632 /* 8633 * The cache free must have deleted the file we 8634 * downloaded to install. 8635 * 8636 * TODO: fix the "freeCache" call to not delete 8637 * the file we care about. 8638 */ 8639 if (pkgLite.recommendedInstallLocation 8640 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8641 pkgLite.recommendedInstallLocation 8642 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 8643 } 8644 } 8645 } 8646 8647 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8648 int loc = pkgLite.recommendedInstallLocation; 8649 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 8650 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8651 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 8652 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 8653 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8654 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8655 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 8656 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 8657 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8658 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 8659 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 8660 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 8661 } else { 8662 // Override with defaults if needed. 8663 loc = installLocationPolicy(pkgLite); 8664 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 8665 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 8666 } else if (!onSd && !onInt) { 8667 // Override install location with flags 8668 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 8669 // Set the flag to install on external media. 8670 installFlags |= PackageManager.INSTALL_EXTERNAL; 8671 installFlags &= ~PackageManager.INSTALL_INTERNAL; 8672 } else { 8673 // Make sure the flag for installing on external 8674 // media is unset 8675 installFlags |= PackageManager.INSTALL_INTERNAL; 8676 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 8677 } 8678 } 8679 } 8680 } 8681 8682 final InstallArgs args = createInstallArgs(this); 8683 mArgs = args; 8684 8685 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8686 /* 8687 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 8688 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 8689 */ 8690 int userIdentifier = getUser().getIdentifier(); 8691 if (userIdentifier == UserHandle.USER_ALL 8692 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 8693 userIdentifier = UserHandle.USER_OWNER; 8694 } 8695 8696 /* 8697 * Determine if we have any installed package verifiers. If we 8698 * do, then we'll defer to them to verify the packages. 8699 */ 8700 final int requiredUid = mRequiredVerifierPackage == null ? -1 8701 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 8702 if (!origin.existing && requiredUid != -1 8703 && isVerificationEnabled(userIdentifier, installFlags)) { 8704 final Intent verification = new Intent( 8705 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 8706 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 8707 PACKAGE_MIME_TYPE); 8708 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8709 8710 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 8711 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 8712 0 /* TODO: Which userId? */); 8713 8714 if (DEBUG_VERIFY) { 8715 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 8716 + verification.toString() + " with " + pkgLite.verifiers.length 8717 + " optional verifiers"); 8718 } 8719 8720 final int verificationId = mPendingVerificationToken++; 8721 8722 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8723 8724 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 8725 installerPackageName); 8726 8727 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 8728 installFlags); 8729 8730 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 8731 pkgLite.packageName); 8732 8733 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 8734 pkgLite.versionCode); 8735 8736 if (verificationParams != null) { 8737 if (verificationParams.getVerificationURI() != null) { 8738 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 8739 verificationParams.getVerificationURI()); 8740 } 8741 if (verificationParams.getOriginatingURI() != null) { 8742 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 8743 verificationParams.getOriginatingURI()); 8744 } 8745 if (verificationParams.getReferrer() != null) { 8746 verification.putExtra(Intent.EXTRA_REFERRER, 8747 verificationParams.getReferrer()); 8748 } 8749 if (verificationParams.getOriginatingUid() >= 0) { 8750 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 8751 verificationParams.getOriginatingUid()); 8752 } 8753 if (verificationParams.getInstallerUid() >= 0) { 8754 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 8755 verificationParams.getInstallerUid()); 8756 } 8757 } 8758 8759 final PackageVerificationState verificationState = new PackageVerificationState( 8760 requiredUid, args); 8761 8762 mPendingVerification.append(verificationId, verificationState); 8763 8764 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 8765 receivers, verificationState); 8766 8767 /* 8768 * If any sufficient verifiers were listed in the package 8769 * manifest, attempt to ask them. 8770 */ 8771 if (sufficientVerifiers != null) { 8772 final int N = sufficientVerifiers.size(); 8773 if (N == 0) { 8774 Slog.i(TAG, "Additional verifiers required, but none installed."); 8775 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 8776 } else { 8777 for (int i = 0; i < N; i++) { 8778 final ComponentName verifierComponent = sufficientVerifiers.get(i); 8779 8780 final Intent sufficientIntent = new Intent(verification); 8781 sufficientIntent.setComponent(verifierComponent); 8782 8783 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 8784 } 8785 } 8786 } 8787 8788 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 8789 mRequiredVerifierPackage, receivers); 8790 if (ret == PackageManager.INSTALL_SUCCEEDED 8791 && mRequiredVerifierPackage != null) { 8792 /* 8793 * Send the intent to the required verification agent, 8794 * but only start the verification timeout after the 8795 * target BroadcastReceivers have run. 8796 */ 8797 verification.setComponent(requiredVerifierComponent); 8798 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 8799 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8800 new BroadcastReceiver() { 8801 @Override 8802 public void onReceive(Context context, Intent intent) { 8803 final Message msg = mHandler 8804 .obtainMessage(CHECK_PENDING_VERIFICATION); 8805 msg.arg1 = verificationId; 8806 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 8807 } 8808 }, null, 0, null, null); 8809 8810 /* 8811 * We don't want the copy to proceed until verification 8812 * succeeds, so null out this field. 8813 */ 8814 mArgs = null; 8815 } 8816 } else { 8817 /* 8818 * No package verification is enabled, so immediately start 8819 * the remote call to initiate copy using temporary file. 8820 */ 8821 ret = args.copyApk(mContainerService, true); 8822 } 8823 } 8824 8825 mRet = ret; 8826 } 8827 8828 @Override 8829 void handleReturnCode() { 8830 // If mArgs is null, then MCS couldn't be reached. When it 8831 // reconnects, it will try again to install. At that point, this 8832 // will succeed. 8833 if (mArgs != null) { 8834 processPendingInstall(mArgs, mRet); 8835 } 8836 } 8837 8838 @Override 8839 void handleServiceError() { 8840 mArgs = createInstallArgs(this); 8841 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8842 } 8843 8844 public boolean isForwardLocked() { 8845 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8846 } 8847 } 8848 8849 /** 8850 * Used during creation of InstallArgs 8851 * 8852 * @param installFlags package installation flags 8853 * @return true if should be installed on external storage 8854 */ 8855 private static boolean installOnSd(int installFlags) { 8856 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 8857 return false; 8858 } 8859 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 8860 return true; 8861 } 8862 return false; 8863 } 8864 8865 /** 8866 * Used during creation of InstallArgs 8867 * 8868 * @param installFlags package installation flags 8869 * @return true if should be installed as forward locked 8870 */ 8871 private static boolean installForwardLocked(int installFlags) { 8872 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8873 } 8874 8875 private InstallArgs createInstallArgs(InstallParams params) { 8876 if (installOnSd(params.installFlags) || params.isForwardLocked()) { 8877 return new AsecInstallArgs(params); 8878 } else { 8879 return new FileInstallArgs(params); 8880 } 8881 } 8882 8883 /** 8884 * Create args that describe an existing installed package. Typically used 8885 * when cleaning up old installs, or used as a move source. 8886 */ 8887 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 8888 String resourcePath, String nativeLibraryRoot, String[] instructionSets) { 8889 final boolean isInAsec; 8890 if (installOnSd(installFlags)) { 8891 /* Apps on SD card are always in ASEC containers. */ 8892 isInAsec = true; 8893 } else if (installForwardLocked(installFlags) 8894 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 8895 /* 8896 * Forward-locked apps are only in ASEC containers if they're the 8897 * new style 8898 */ 8899 isInAsec = true; 8900 } else { 8901 isInAsec = false; 8902 } 8903 8904 if (isInAsec) { 8905 return new AsecInstallArgs(codePath, instructionSets, 8906 installOnSd(installFlags), installForwardLocked(installFlags)); 8907 } else { 8908 return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot, 8909 instructionSets); 8910 } 8911 } 8912 8913 static abstract class InstallArgs { 8914 /** @see InstallParams#origin */ 8915 final OriginInfo origin; 8916 8917 final IPackageInstallObserver2 observer; 8918 // Always refers to PackageManager flags only 8919 final int installFlags; 8920 final String installerPackageName; 8921 final ManifestDigest manifestDigest; 8922 final UserHandle user; 8923 final String abiOverride; 8924 8925 // The list of instruction sets supported by this app. This is currently 8926 // only used during the rmdex() phase to clean up resources. We can get rid of this 8927 // if we move dex files under the common app path. 8928 /* nullable */ String[] instructionSets; 8929 8930 InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 8931 String installerPackageName, ManifestDigest manifestDigest, UserHandle user, 8932 String[] instructionSets, String abiOverride) { 8933 this.origin = origin; 8934 this.installFlags = installFlags; 8935 this.observer = observer; 8936 this.installerPackageName = installerPackageName; 8937 this.manifestDigest = manifestDigest; 8938 this.user = user; 8939 this.instructionSets = instructionSets; 8940 this.abiOverride = abiOverride; 8941 } 8942 8943 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 8944 abstract int doPreInstall(int status); 8945 8946 /** 8947 * Rename package into final resting place. All paths on the given 8948 * scanned package should be updated to reflect the rename. 8949 */ 8950 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 8951 abstract int doPostInstall(int status, int uid); 8952 8953 /** @see PackageSettingBase#codePathString */ 8954 abstract String getCodePath(); 8955 /** @see PackageSettingBase#resourcePathString */ 8956 abstract String getResourcePath(); 8957 abstract String getLegacyNativeLibraryPath(); 8958 8959 // Need installer lock especially for dex file removal. 8960 abstract void cleanUpResourcesLI(); 8961 abstract boolean doPostDeleteLI(boolean delete); 8962 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 8963 8964 /** 8965 * Called before the source arguments are copied. This is used mostly 8966 * for MoveParams when it needs to read the source file to put it in the 8967 * destination. 8968 */ 8969 int doPreCopy() { 8970 return PackageManager.INSTALL_SUCCEEDED; 8971 } 8972 8973 /** 8974 * Called after the source arguments are copied. This is used mostly for 8975 * MoveParams when it needs to read the source file to put it in the 8976 * destination. 8977 * 8978 * @return 8979 */ 8980 int doPostCopy(int uid) { 8981 return PackageManager.INSTALL_SUCCEEDED; 8982 } 8983 8984 protected boolean isFwdLocked() { 8985 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8986 } 8987 8988 protected boolean isExternal() { 8989 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 8990 } 8991 8992 UserHandle getUser() { 8993 return user; 8994 } 8995 } 8996 8997 /** 8998 * Logic to handle installation of non-ASEC applications, including copying 8999 * and renaming logic. 9000 */ 9001 class FileInstallArgs extends InstallArgs { 9002 private File codeFile; 9003 private File resourceFile; 9004 private File legacyNativeLibraryPath; 9005 9006 // Example topology: 9007 // /data/app/com.example/base.apk 9008 // /data/app/com.example/split_foo.apk 9009 // /data/app/com.example/lib/arm/libfoo.so 9010 // /data/app/com.example/lib/arm64/libfoo.so 9011 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 9012 9013 /** New install */ 9014 FileInstallArgs(InstallParams params) { 9015 super(params.origin, params.observer, params.installFlags, 9016 params.installerPackageName, params.getManifestDigest(), params.getUser(), 9017 null /* instruction sets */, params.packageAbiOverride); 9018 if (isFwdLocked()) { 9019 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 9020 } 9021 } 9022 9023 /** Existing install */ 9024 FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath, 9025 String[] instructionSets) { 9026 super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null); 9027 this.codeFile = (codePath != null) ? new File(codePath) : null; 9028 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 9029 this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ? 9030 new File(legacyNativeLibraryPath) : null; 9031 } 9032 9033 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9034 final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(), 9035 isFwdLocked(), abiOverride); 9036 9037 final StorageManager storage = StorageManager.from(mContext); 9038 return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory())); 9039 } 9040 9041 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9042 if (origin.staged) { 9043 Slog.d(TAG, origin.file + " already staged; skipping copy"); 9044 codeFile = origin.file; 9045 resourceFile = origin.file; 9046 return PackageManager.INSTALL_SUCCEEDED; 9047 } 9048 9049 try { 9050 final File tempDir = mInstallerService.allocateInternalStageDirLegacy(); 9051 codeFile = tempDir; 9052 resourceFile = tempDir; 9053 } catch (IOException e) { 9054 Slog.w(TAG, "Failed to create copy file: " + e); 9055 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9056 } 9057 9058 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 9059 @Override 9060 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 9061 if (!FileUtils.isValidExtFilename(name)) { 9062 throw new IllegalArgumentException("Invalid filename: " + name); 9063 } 9064 try { 9065 final File file = new File(codeFile, name); 9066 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 9067 O_RDWR | O_CREAT, 0644); 9068 Os.chmod(file.getAbsolutePath(), 0644); 9069 return new ParcelFileDescriptor(fd); 9070 } catch (ErrnoException e) { 9071 throw new RemoteException("Failed to open: " + e.getMessage()); 9072 } 9073 } 9074 }; 9075 9076 int ret = PackageManager.INSTALL_SUCCEEDED; 9077 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 9078 if (ret != PackageManager.INSTALL_SUCCEEDED) { 9079 Slog.e(TAG, "Failed to copy package"); 9080 return ret; 9081 } 9082 9083 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 9084 NativeLibraryHelper.Handle handle = null; 9085 try { 9086 handle = NativeLibraryHelper.Handle.create(codeFile); 9087 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 9088 abiOverride); 9089 } catch (IOException e) { 9090 Slog.e(TAG, "Copying native libraries failed", e); 9091 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9092 } finally { 9093 IoUtils.closeQuietly(handle); 9094 } 9095 9096 return ret; 9097 } 9098 9099 int doPreInstall(int status) { 9100 if (status != PackageManager.INSTALL_SUCCEEDED) { 9101 cleanUp(); 9102 } 9103 return status; 9104 } 9105 9106 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9107 if (status != PackageManager.INSTALL_SUCCEEDED) { 9108 cleanUp(); 9109 return false; 9110 } else { 9111 final File beforeCodeFile = codeFile; 9112 final File afterCodeFile = getNextCodePath(pkg.packageName); 9113 9114 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 9115 try { 9116 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 9117 } catch (ErrnoException e) { 9118 Slog.d(TAG, "Failed to rename", e); 9119 return false; 9120 } 9121 9122 if (!SELinux.restoreconRecursive(afterCodeFile)) { 9123 Slog.d(TAG, "Failed to restorecon"); 9124 return false; 9125 } 9126 9127 // Reflect the rename internally 9128 codeFile = afterCodeFile; 9129 resourceFile = afterCodeFile; 9130 9131 // Reflect the rename in scanned details 9132 pkg.codePath = afterCodeFile.getAbsolutePath(); 9133 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9134 pkg.baseCodePath); 9135 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9136 pkg.splitCodePaths); 9137 9138 // Reflect the rename in app info 9139 pkg.applicationInfo.setCodePath(pkg.codePath); 9140 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9141 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9142 pkg.applicationInfo.setResourcePath(pkg.codePath); 9143 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9144 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9145 9146 return true; 9147 } 9148 } 9149 9150 int doPostInstall(int status, int uid) { 9151 if (status != PackageManager.INSTALL_SUCCEEDED) { 9152 cleanUp(); 9153 } 9154 return status; 9155 } 9156 9157 @Override 9158 String getCodePath() { 9159 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 9160 } 9161 9162 @Override 9163 String getResourcePath() { 9164 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 9165 } 9166 9167 @Override 9168 String getLegacyNativeLibraryPath() { 9169 return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null; 9170 } 9171 9172 private boolean cleanUp() { 9173 if (codeFile == null || !codeFile.exists()) { 9174 return false; 9175 } 9176 9177 if (codeFile.isDirectory()) { 9178 FileUtils.deleteContents(codeFile); 9179 } 9180 codeFile.delete(); 9181 9182 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 9183 resourceFile.delete(); 9184 } 9185 9186 if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) { 9187 if (!FileUtils.deleteContents(legacyNativeLibraryPath)) { 9188 Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath); 9189 } 9190 legacyNativeLibraryPath.delete(); 9191 } 9192 9193 return true; 9194 } 9195 9196 void cleanUpResourcesLI() { 9197 // Try enumerating all code paths before deleting 9198 List<String> allCodePaths = Collections.EMPTY_LIST; 9199 if (codeFile != null && codeFile.exists()) { 9200 try { 9201 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9202 allCodePaths = pkg.getAllCodePaths(); 9203 } catch (PackageParserException e) { 9204 // Ignored; we tried our best 9205 } 9206 } 9207 9208 cleanUp(); 9209 9210 if (!allCodePaths.isEmpty()) { 9211 if (instructionSets == null) { 9212 throw new IllegalStateException("instructionSet == null"); 9213 } 9214 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9215 for (String codePath : allCodePaths) { 9216 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9217 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9218 if (retCode < 0) { 9219 Slog.w(TAG, "Couldn't remove dex file for package: " 9220 + " at location " + codePath + ", retcode=" + retCode); 9221 // we don't consider this to be a failure of the core package deletion 9222 } 9223 } 9224 } 9225 } 9226 } 9227 9228 boolean doPostDeleteLI(boolean delete) { 9229 // XXX err, shouldn't we respect the delete flag? 9230 cleanUpResourcesLI(); 9231 return true; 9232 } 9233 } 9234 9235 private boolean isAsecExternal(String cid) { 9236 final String asecPath = PackageHelper.getSdFilesystem(cid); 9237 return !asecPath.startsWith(mAsecInternalPath); 9238 } 9239 9240 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 9241 PackageManagerException { 9242 if (copyRet < 0) { 9243 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 9244 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 9245 throw new PackageManagerException(copyRet, message); 9246 } 9247 } 9248 } 9249 9250 /** 9251 * Extract the MountService "container ID" from the full code path of an 9252 * .apk. 9253 */ 9254 static String cidFromCodePath(String fullCodePath) { 9255 int eidx = fullCodePath.lastIndexOf("/"); 9256 String subStr1 = fullCodePath.substring(0, eidx); 9257 int sidx = subStr1.lastIndexOf("/"); 9258 return subStr1.substring(sidx+1, eidx); 9259 } 9260 9261 /** 9262 * Logic to handle installation of ASEC applications, including copying and 9263 * renaming logic. 9264 */ 9265 class AsecInstallArgs extends InstallArgs { 9266 static final String RES_FILE_NAME = "pkg.apk"; 9267 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 9268 9269 String cid; 9270 String packagePath; 9271 String resourcePath; 9272 String legacyNativeLibraryDir; 9273 9274 /** New install */ 9275 AsecInstallArgs(InstallParams params) { 9276 super(params.origin, params.observer, params.installFlags, 9277 params.installerPackageName, params.getManifestDigest(), 9278 params.getUser(), null /* instruction sets */, 9279 params.packageAbiOverride); 9280 } 9281 9282 /** Existing install */ 9283 AsecInstallArgs(String fullCodePath, String[] instructionSets, 9284 boolean isExternal, boolean isForwardLocked) { 9285 super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0) 9286 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9287 instructionSets, null); 9288 // Hackily pretend we're still looking at a full code path 9289 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 9290 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 9291 } 9292 9293 // Extract cid from fullCodePath 9294 int eidx = fullCodePath.lastIndexOf("/"); 9295 String subStr1 = fullCodePath.substring(0, eidx); 9296 int sidx = subStr1.lastIndexOf("/"); 9297 cid = subStr1.substring(sidx+1, eidx); 9298 setMountPath(subStr1); 9299 } 9300 9301 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 9302 super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 9303 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9304 instructionSets, null); 9305 this.cid = cid; 9306 setMountPath(PackageHelper.getSdDir(cid)); 9307 } 9308 9309 void createCopyFile() { 9310 cid = mInstallerService.allocateExternalStageCidLegacy(); 9311 } 9312 9313 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9314 final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(), 9315 abiOverride); 9316 9317 final File target; 9318 if (isExternal()) { 9319 target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory(); 9320 } else { 9321 target = Environment.getDataDirectory(); 9322 } 9323 9324 final StorageManager storage = StorageManager.from(mContext); 9325 return (sizeBytes <= storage.getStorageBytesUntilLow(target)); 9326 } 9327 9328 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9329 if (origin.staged) { 9330 Slog.d(TAG, origin.cid + " already staged; skipping copy"); 9331 cid = origin.cid; 9332 setMountPath(PackageHelper.getSdDir(cid)); 9333 return PackageManager.INSTALL_SUCCEEDED; 9334 } 9335 9336 if (temp) { 9337 createCopyFile(); 9338 } else { 9339 /* 9340 * Pre-emptively destroy the container since it's destroyed if 9341 * copying fails due to it existing anyway. 9342 */ 9343 PackageHelper.destroySdDir(cid); 9344 } 9345 9346 final String newMountPath = imcs.copyPackageToContainer( 9347 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(), 9348 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 9349 9350 if (newMountPath != null) { 9351 setMountPath(newMountPath); 9352 return PackageManager.INSTALL_SUCCEEDED; 9353 } else { 9354 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9355 } 9356 } 9357 9358 @Override 9359 String getCodePath() { 9360 return packagePath; 9361 } 9362 9363 @Override 9364 String getResourcePath() { 9365 return resourcePath; 9366 } 9367 9368 @Override 9369 String getLegacyNativeLibraryPath() { 9370 return legacyNativeLibraryDir; 9371 } 9372 9373 int doPreInstall(int status) { 9374 if (status != PackageManager.INSTALL_SUCCEEDED) { 9375 // Destroy container 9376 PackageHelper.destroySdDir(cid); 9377 } else { 9378 boolean mounted = PackageHelper.isContainerMounted(cid); 9379 if (!mounted) { 9380 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 9381 Process.SYSTEM_UID); 9382 if (newMountPath != null) { 9383 setMountPath(newMountPath); 9384 } else { 9385 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9386 } 9387 } 9388 } 9389 return status; 9390 } 9391 9392 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9393 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 9394 String newMountPath = null; 9395 if (PackageHelper.isContainerMounted(cid)) { 9396 // Unmount the container 9397 if (!PackageHelper.unMountSdDir(cid)) { 9398 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9399 return false; 9400 } 9401 } 9402 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9403 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9404 " which might be stale. Will try to clean up."); 9405 // Clean up the stale container and proceed to recreate. 9406 if (!PackageHelper.destroySdDir(newCacheId)) { 9407 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9408 return false; 9409 } 9410 // Successfully cleaned up stale container. Try to rename again. 9411 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9412 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9413 + " inspite of cleaning it up."); 9414 return false; 9415 } 9416 } 9417 if (!PackageHelper.isContainerMounted(newCacheId)) { 9418 Slog.w(TAG, "Mounting container " + newCacheId); 9419 newMountPath = PackageHelper.mountSdDir(newCacheId, 9420 getEncryptKey(), Process.SYSTEM_UID); 9421 } else { 9422 newMountPath = PackageHelper.getSdDir(newCacheId); 9423 } 9424 if (newMountPath == null) { 9425 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9426 return false; 9427 } 9428 Log.i(TAG, "Succesfully renamed " + cid + 9429 " to " + newCacheId + 9430 " at new path: " + newMountPath); 9431 cid = newCacheId; 9432 9433 final File beforeCodeFile = new File(packagePath); 9434 setMountPath(newMountPath); 9435 final File afterCodeFile = new File(packagePath); 9436 9437 // Reflect the rename in scanned details 9438 pkg.codePath = afterCodeFile.getAbsolutePath(); 9439 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9440 pkg.baseCodePath); 9441 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9442 pkg.splitCodePaths); 9443 9444 // Reflect the rename in app info 9445 pkg.applicationInfo.setCodePath(pkg.codePath); 9446 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9447 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9448 pkg.applicationInfo.setResourcePath(pkg.codePath); 9449 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9450 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9451 9452 return true; 9453 } 9454 9455 private void setMountPath(String mountPath) { 9456 final File mountFile = new File(mountPath); 9457 9458 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 9459 if (monolithicFile.exists()) { 9460 packagePath = monolithicFile.getAbsolutePath(); 9461 if (isFwdLocked()) { 9462 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 9463 } else { 9464 resourcePath = packagePath; 9465 } 9466 } else { 9467 packagePath = mountFile.getAbsolutePath(); 9468 resourcePath = packagePath; 9469 } 9470 9471 legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath(); 9472 } 9473 9474 int doPostInstall(int status, int uid) { 9475 if (status != PackageManager.INSTALL_SUCCEEDED) { 9476 cleanUp(); 9477 } else { 9478 final int groupOwner; 9479 final String protectedFile; 9480 if (isFwdLocked()) { 9481 groupOwner = UserHandle.getSharedAppGid(uid); 9482 protectedFile = RES_FILE_NAME; 9483 } else { 9484 groupOwner = -1; 9485 protectedFile = null; 9486 } 9487 9488 if (uid < Process.FIRST_APPLICATION_UID 9489 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9490 Slog.e(TAG, "Failed to finalize " + cid); 9491 PackageHelper.destroySdDir(cid); 9492 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9493 } 9494 9495 boolean mounted = PackageHelper.isContainerMounted(cid); 9496 if (!mounted) { 9497 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9498 } 9499 } 9500 return status; 9501 } 9502 9503 private void cleanUp() { 9504 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9505 9506 // Destroy secure container 9507 PackageHelper.destroySdDir(cid); 9508 } 9509 9510 private List<String> getAllCodePaths() { 9511 final File codeFile = new File(getCodePath()); 9512 if (codeFile != null && codeFile.exists()) { 9513 try { 9514 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9515 return pkg.getAllCodePaths(); 9516 } catch (PackageParserException e) { 9517 // Ignored; we tried our best 9518 } 9519 } 9520 return Collections.EMPTY_LIST; 9521 } 9522 9523 void cleanUpResourcesLI() { 9524 // Enumerate all code paths before deleting 9525 cleanUpResourcesLI(getAllCodePaths()); 9526 } 9527 9528 private void cleanUpResourcesLI(List<String> allCodePaths) { 9529 cleanUp(); 9530 9531 if (!allCodePaths.isEmpty()) { 9532 if (instructionSets == null) { 9533 throw new IllegalStateException("instructionSet == null"); 9534 } 9535 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9536 for (String codePath : allCodePaths) { 9537 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9538 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9539 if (retCode < 0) { 9540 Slog.w(TAG, "Couldn't remove dex file for package: " 9541 + " at location " + codePath + ", retcode=" + retCode); 9542 // we don't consider this to be a failure of the core package deletion 9543 } 9544 } 9545 } 9546 } 9547 } 9548 9549 boolean matchContainer(String app) { 9550 if (cid.startsWith(app)) { 9551 return true; 9552 } 9553 return false; 9554 } 9555 9556 String getPackageName() { 9557 return getAsecPackageName(cid); 9558 } 9559 9560 boolean doPostDeleteLI(boolean delete) { 9561 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 9562 final List<String> allCodePaths = getAllCodePaths(); 9563 boolean mounted = PackageHelper.isContainerMounted(cid); 9564 if (mounted) { 9565 // Unmount first 9566 if (PackageHelper.unMountSdDir(cid)) { 9567 mounted = false; 9568 } 9569 } 9570 if (!mounted && delete) { 9571 cleanUpResourcesLI(allCodePaths); 9572 } 9573 return !mounted; 9574 } 9575 9576 @Override 9577 int doPreCopy() { 9578 if (isFwdLocked()) { 9579 if (!PackageHelper.fixSdPermissions(cid, 9580 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 9581 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9582 } 9583 } 9584 9585 return PackageManager.INSTALL_SUCCEEDED; 9586 } 9587 9588 @Override 9589 int doPostCopy(int uid) { 9590 if (isFwdLocked()) { 9591 if (uid < Process.FIRST_APPLICATION_UID 9592 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 9593 RES_FILE_NAME)) { 9594 Slog.e(TAG, "Failed to finalize " + cid); 9595 PackageHelper.destroySdDir(cid); 9596 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9597 } 9598 } 9599 9600 return PackageManager.INSTALL_SUCCEEDED; 9601 } 9602 } 9603 9604 static String getAsecPackageName(String packageCid) { 9605 int idx = packageCid.lastIndexOf("-"); 9606 if (idx == -1) { 9607 return packageCid; 9608 } 9609 return packageCid.substring(0, idx); 9610 } 9611 9612 // Utility method used to create code paths based on package name and available index. 9613 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 9614 String idxStr = ""; 9615 int idx = 1; 9616 // Fall back to default value of idx=1 if prefix is not 9617 // part of oldCodePath 9618 if (oldCodePath != null) { 9619 String subStr = oldCodePath; 9620 // Drop the suffix right away 9621 if (suffix != null && subStr.endsWith(suffix)) { 9622 subStr = subStr.substring(0, subStr.length() - suffix.length()); 9623 } 9624 // If oldCodePath already contains prefix find out the 9625 // ending index to either increment or decrement. 9626 int sidx = subStr.lastIndexOf(prefix); 9627 if (sidx != -1) { 9628 subStr = subStr.substring(sidx + prefix.length()); 9629 if (subStr != null) { 9630 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 9631 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 9632 } 9633 try { 9634 idx = Integer.parseInt(subStr); 9635 if (idx <= 1) { 9636 idx++; 9637 } else { 9638 idx--; 9639 } 9640 } catch(NumberFormatException e) { 9641 } 9642 } 9643 } 9644 } 9645 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 9646 return prefix + idxStr; 9647 } 9648 9649 private File getNextCodePath(String packageName) { 9650 int suffix = 1; 9651 File result; 9652 do { 9653 result = new File(mAppInstallDir, packageName + "-" + suffix); 9654 suffix++; 9655 } while (result.exists()); 9656 return result; 9657 } 9658 9659 // Utility method used to ignore ADD/REMOVE events 9660 // by directory observer. 9661 private static boolean ignoreCodePath(String fullPathStr) { 9662 String apkName = deriveCodePathName(fullPathStr); 9663 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 9664 if (idx != -1 && ((idx+1) < apkName.length())) { 9665 // Make sure the package ends with a numeral 9666 String version = apkName.substring(idx+1); 9667 try { 9668 Integer.parseInt(version); 9669 return true; 9670 } catch (NumberFormatException e) {} 9671 } 9672 return false; 9673 } 9674 9675 // Utility method that returns the relative package path with respect 9676 // to the installation directory. Like say for /data/data/com.test-1.apk 9677 // string com.test-1 is returned. 9678 static String deriveCodePathName(String codePath) { 9679 if (codePath == null) { 9680 return null; 9681 } 9682 final File codeFile = new File(codePath); 9683 final String name = codeFile.getName(); 9684 if (codeFile.isDirectory()) { 9685 return name; 9686 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 9687 final int lastDot = name.lastIndexOf('.'); 9688 return name.substring(0, lastDot); 9689 } else { 9690 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 9691 return null; 9692 } 9693 } 9694 9695 class PackageInstalledInfo { 9696 String name; 9697 int uid; 9698 // The set of users that originally had this package installed. 9699 int[] origUsers; 9700 // The set of users that now have this package installed. 9701 int[] newUsers; 9702 PackageParser.Package pkg; 9703 int returnCode; 9704 String returnMsg; 9705 PackageRemovedInfo removedInfo; 9706 9707 public void setError(int code, String msg) { 9708 returnCode = code; 9709 returnMsg = msg; 9710 Slog.w(TAG, msg); 9711 } 9712 9713 public void setError(String msg, PackageParserException e) { 9714 returnCode = e.error; 9715 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9716 Slog.w(TAG, msg, e); 9717 } 9718 9719 public void setError(String msg, PackageManagerException e) { 9720 returnCode = e.error; 9721 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9722 Slog.w(TAG, msg, e); 9723 } 9724 9725 // In some error cases we want to convey more info back to the observer 9726 String origPackage; 9727 String origPermission; 9728 } 9729 9730 /* 9731 * Install a non-existing package. 9732 */ 9733 private void installNewPackageLI(PackageParser.Package pkg, 9734 int parseFlags, int scanFlags, UserHandle user, 9735 String installerPackageName, PackageInstalledInfo res) { 9736 // Remember this for later, in case we need to rollback this install 9737 String pkgName = pkg.packageName; 9738 9739 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 9740 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 9741 synchronized(mPackages) { 9742 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 9743 // A package with the same name is already installed, though 9744 // it has been renamed to an older name. The package we 9745 // are trying to install should be installed as an update to 9746 // the existing one, but that has not been requested, so bail. 9747 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9748 + " without first uninstalling package running as " 9749 + mSettings.mRenamedPackages.get(pkgName)); 9750 return; 9751 } 9752 if (mPackages.containsKey(pkgName)) { 9753 // Don't allow installation over an existing package with the same name. 9754 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9755 + " without first uninstalling."); 9756 return; 9757 } 9758 } 9759 9760 try { 9761 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 9762 System.currentTimeMillis(), user); 9763 9764 updateSettingsLI(newPackage, installerPackageName, null, null, res); 9765 // delete the partially installed application. the data directory will have to be 9766 // restored if it was already existing 9767 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9768 // remove package from internal structures. Note that we want deletePackageX to 9769 // delete the package data and cache directories that it created in 9770 // scanPackageLocked, unless those directories existed before we even tried to 9771 // install. 9772 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 9773 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 9774 res.removedInfo, true); 9775 } 9776 9777 } catch (PackageManagerException e) { 9778 res.setError("Package couldn't be installed in " + pkg.codePath, e); 9779 } 9780 } 9781 9782 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 9783 // Upgrade keysets are being used. Determine if new package has a superset of the 9784 // required keys. 9785 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 9786 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9787 for (int i = 0; i < upgradeKeySets.length; i++) { 9788 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 9789 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 9790 return true; 9791 } 9792 } 9793 return false; 9794 } 9795 9796 private void replacePackageLI(PackageParser.Package pkg, 9797 int parseFlags, int scanFlags, UserHandle user, 9798 String installerPackageName, PackageInstalledInfo res) { 9799 PackageParser.Package oldPackage; 9800 String pkgName = pkg.packageName; 9801 int[] allUsers; 9802 boolean[] perUserInstalled; 9803 9804 // First find the old package info and check signatures 9805 synchronized(mPackages) { 9806 oldPackage = mPackages.get(pkgName); 9807 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 9808 PackageSetting ps = mSettings.mPackages.get(pkgName); 9809 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 9810 // default to original signature matching 9811 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 9812 != PackageManager.SIGNATURE_MATCH) { 9813 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9814 "New package has a different signature: " + pkgName); 9815 return; 9816 } 9817 } else { 9818 if(!checkUpgradeKeySetLP(ps, pkg)) { 9819 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9820 "New package not signed by keys specified by upgrade-keysets: " 9821 + pkgName); 9822 return; 9823 } 9824 } 9825 9826 // In case of rollback, remember per-user/profile install state 9827 allUsers = sUserManager.getUserIds(); 9828 perUserInstalled = new boolean[allUsers.length]; 9829 for (int i = 0; i < allUsers.length; i++) { 9830 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 9831 } 9832 } 9833 9834 boolean sysPkg = (isSystemApp(oldPackage)); 9835 if (sysPkg) { 9836 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 9837 user, allUsers, perUserInstalled, installerPackageName, res); 9838 } else { 9839 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 9840 user, allUsers, perUserInstalled, installerPackageName, res); 9841 } 9842 } 9843 9844 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 9845 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 9846 int[] allUsers, boolean[] perUserInstalled, 9847 String installerPackageName, PackageInstalledInfo res) { 9848 String pkgName = deletedPackage.packageName; 9849 boolean deletedPkg = true; 9850 boolean updatedSettings = false; 9851 9852 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 9853 + deletedPackage); 9854 long origUpdateTime; 9855 if (pkg.mExtras != null) { 9856 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 9857 } else { 9858 origUpdateTime = 0; 9859 } 9860 9861 // First delete the existing package while retaining the data directory 9862 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 9863 res.removedInfo, true)) { 9864 // If the existing package wasn't successfully deleted 9865 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 9866 deletedPkg = false; 9867 } else { 9868 // Successfully deleted the old package; proceed with replace. 9869 9870 // If deleted package lived in a container, give users a chance to 9871 // relinquish resources before killing. 9872 if (isForwardLocked(deletedPackage) || isExternal(deletedPackage)) { 9873 if (DEBUG_INSTALL) { 9874 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 9875 } 9876 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 9877 final ArrayList<String> pkgList = new ArrayList<String>(1); 9878 pkgList.add(deletedPackage.applicationInfo.packageName); 9879 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 9880 } 9881 9882 deleteCodeCacheDirsLI(pkgName); 9883 try { 9884 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 9885 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 9886 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 9887 updatedSettings = true; 9888 } catch (PackageManagerException e) { 9889 res.setError("Package couldn't be installed in " + pkg.codePath, e); 9890 } 9891 } 9892 9893 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9894 // remove package from internal structures. Note that we want deletePackageX to 9895 // delete the package data and cache directories that it created in 9896 // scanPackageLocked, unless those directories existed before we even tried to 9897 // install. 9898 if(updatedSettings) { 9899 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 9900 deletePackageLI( 9901 pkgName, null, true, allUsers, perUserInstalled, 9902 PackageManager.DELETE_KEEP_DATA, 9903 res.removedInfo, true); 9904 } 9905 // Since we failed to install the new package we need to restore the old 9906 // package that we deleted. 9907 if (deletedPkg) { 9908 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 9909 File restoreFile = new File(deletedPackage.codePath); 9910 // Parse old package 9911 boolean oldOnSd = isExternal(deletedPackage); 9912 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 9913 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) | 9914 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 9915 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 9916 try { 9917 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 9918 } catch (PackageManagerException e) { 9919 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 9920 + e.getMessage()); 9921 return; 9922 } 9923 // Restore of old package succeeded. Update permissions. 9924 // writer 9925 synchronized (mPackages) { 9926 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 9927 UPDATE_PERMISSIONS_ALL); 9928 // can downgrade to reader 9929 mSettings.writeLPr(); 9930 } 9931 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 9932 } 9933 } 9934 } 9935 9936 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 9937 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 9938 int[] allUsers, boolean[] perUserInstalled, 9939 String installerPackageName, PackageInstalledInfo res) { 9940 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 9941 + ", old=" + deletedPackage); 9942 boolean updatedSettings = false; 9943 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 9944 if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) { 9945 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 9946 } 9947 String packageName = deletedPackage.packageName; 9948 if (packageName == null) { 9949 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 9950 "Attempt to delete null packageName."); 9951 return; 9952 } 9953 PackageParser.Package oldPkg; 9954 PackageSetting oldPkgSetting; 9955 // reader 9956 synchronized (mPackages) { 9957 oldPkg = mPackages.get(packageName); 9958 oldPkgSetting = mSettings.mPackages.get(packageName); 9959 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 9960 (oldPkgSetting == null)) { 9961 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 9962 "Couldn't find package:" + packageName + " information"); 9963 return; 9964 } 9965 } 9966 9967 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 9968 9969 res.removedInfo.uid = oldPkg.applicationInfo.uid; 9970 res.removedInfo.removedPackage = packageName; 9971 // Remove existing system package 9972 removePackageLI(oldPkgSetting, true); 9973 // writer 9974 synchronized (mPackages) { 9975 if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) { 9976 // We didn't need to disable the .apk as a current system package, 9977 // which means we are replacing another update that is already 9978 // installed. We need to make sure to delete the older one's .apk. 9979 res.removedInfo.args = createInstallArgsForExisting(0, 9980 deletedPackage.applicationInfo.getCodePath(), 9981 deletedPackage.applicationInfo.getResourcePath(), 9982 deletedPackage.applicationInfo.nativeLibraryRootDir, 9983 getAppDexInstructionSets(deletedPackage.applicationInfo)); 9984 } else { 9985 res.removedInfo.args = null; 9986 } 9987 } 9988 9989 // Successfully disabled the old package. Now proceed with re-installation 9990 deleteCodeCacheDirsLI(packageName); 9991 9992 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 9993 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 9994 9995 PackageParser.Package newPackage = null; 9996 try { 9997 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 9998 if (newPackage.mExtras != null) { 9999 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 10000 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10001 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10002 10003 // is the update attempting to change shared user? that isn't going to work... 10004 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10005 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 10006 "Forbidding shared user change from " + oldPkgSetting.sharedUser 10007 + " to " + newPkgSetting.sharedUser); 10008 updatedSettings = true; 10009 } 10010 } 10011 10012 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10013 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10014 updatedSettings = true; 10015 } 10016 10017 } catch (PackageManagerException e) { 10018 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10019 } 10020 10021 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10022 // Re installation failed. Restore old information 10023 // Remove new pkg information 10024 if (newPackage != null) { 10025 removeInstalledPackageLI(newPackage, true); 10026 } 10027 // Add back the old system package 10028 try { 10029 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 10030 } catch (PackageManagerException e) { 10031 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 10032 } 10033 // Restore the old system information in Settings 10034 synchronized(mPackages) { 10035 if (updatedSettings) { 10036 mSettings.enableSystemPackageLPw(packageName); 10037 mSettings.setInstallerPackageName(packageName, 10038 oldPkgSetting.installerPackageName); 10039 } 10040 mSettings.writeLPr(); 10041 } 10042 } 10043 } 10044 10045 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10046 int[] allUsers, boolean[] perUserInstalled, 10047 PackageInstalledInfo res) { 10048 String pkgName = newPackage.packageName; 10049 synchronized (mPackages) { 10050 //write settings. the installStatus will be incomplete at this stage. 10051 //note that the new package setting would have already been 10052 //added to mPackages. It hasn't been persisted yet. 10053 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10054 mSettings.writeLPr(); 10055 } 10056 10057 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10058 10059 synchronized (mPackages) { 10060 updatePermissionsLPw(newPackage.packageName, newPackage, 10061 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10062 ? UPDATE_PERMISSIONS_ALL : 0)); 10063 // For system-bundled packages, we assume that installing an upgraded version 10064 // of the package implies that the user actually wants to run that new code, 10065 // so we enable the package. 10066 if (isSystemApp(newPackage)) { 10067 // NB: implicit assumption that system package upgrades apply to all users 10068 if (DEBUG_INSTALL) { 10069 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10070 } 10071 PackageSetting ps = mSettings.mPackages.get(pkgName); 10072 if (ps != null) { 10073 if (res.origUsers != null) { 10074 for (int userHandle : res.origUsers) { 10075 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10076 userHandle, installerPackageName); 10077 } 10078 } 10079 // Also convey the prior install/uninstall state 10080 if (allUsers != null && perUserInstalled != null) { 10081 for (int i = 0; i < allUsers.length; i++) { 10082 if (DEBUG_INSTALL) { 10083 Slog.d(TAG, " user " + allUsers[i] 10084 + " => " + perUserInstalled[i]); 10085 } 10086 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10087 } 10088 // these install state changes will be persisted in the 10089 // upcoming call to mSettings.writeLPr(). 10090 } 10091 } 10092 } 10093 res.name = pkgName; 10094 res.uid = newPackage.applicationInfo.uid; 10095 res.pkg = newPackage; 10096 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10097 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10098 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10099 //to update install status 10100 mSettings.writeLPr(); 10101 } 10102 } 10103 10104 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 10105 final int installFlags = args.installFlags; 10106 String installerPackageName = args.installerPackageName; 10107 File tmpPackageFile = new File(args.getCodePath()); 10108 boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10109 boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0); 10110 boolean replace = false; 10111 final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE; 10112 // Result object to be returned 10113 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10114 10115 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10116 // Retrieve PackageSettings and parse package 10117 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10118 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10119 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 10120 PackageParser pp = new PackageParser(); 10121 pp.setSeparateProcesses(mSeparateProcesses); 10122 pp.setDisplayMetrics(mMetrics); 10123 10124 final PackageParser.Package pkg; 10125 try { 10126 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 10127 } catch (PackageParserException e) { 10128 res.setError("Failed parse during installPackageLI", e); 10129 return; 10130 } 10131 10132 // Mark that we have an install time CPU ABI override. 10133 pkg.cpuAbiOverride = args.abiOverride; 10134 10135 String pkgName = res.name = pkg.packageName; 10136 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 10137 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 10138 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 10139 return; 10140 } 10141 } 10142 10143 try { 10144 pp.collectCertificates(pkg, parseFlags); 10145 pp.collectManifestDigest(pkg); 10146 } catch (PackageParserException e) { 10147 res.setError("Failed collect during installPackageLI", e); 10148 return; 10149 } 10150 10151 /* If the installer passed in a manifest digest, compare it now. */ 10152 if (args.manifestDigest != null) { 10153 if (DEBUG_INSTALL) { 10154 final String parsedManifest = pkg.manifestDigest == null ? "null" 10155 : pkg.manifestDigest.toString(); 10156 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 10157 + parsedManifest); 10158 } 10159 10160 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 10161 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 10162 return; 10163 } 10164 } else if (DEBUG_INSTALL) { 10165 final String parsedManifest = pkg.manifestDigest == null 10166 ? "null" : pkg.manifestDigest.toString(); 10167 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 10168 } 10169 10170 // Get rid of all references to package scan path via parser. 10171 pp = null; 10172 String oldCodePath = null; 10173 boolean systemApp = false; 10174 synchronized (mPackages) { 10175 // Check whether the newly-scanned package wants to define an already-defined perm 10176 int N = pkg.permissions.size(); 10177 for (int i = N-1; i >= 0; i--) { 10178 PackageParser.Permission perm = pkg.permissions.get(i); 10179 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 10180 if (bp != null) { 10181 // If the defining package is signed with our cert, it's okay. This 10182 // also includes the "updating the same package" case, of course. 10183 // "updating same package" could also involve key-rotation. 10184 final boolean sigsOk; 10185 if (!bp.sourcePackage.equals(pkg.packageName) 10186 || !(bp.packageSetting instanceof PackageSetting) 10187 || !bp.packageSetting.keySetData.isUsingUpgradeKeySets() 10188 || ((PackageSetting) bp.packageSetting).sharedUser != null) { 10189 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 10190 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 10191 } else { 10192 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 10193 } 10194 if (!sigsOk) { 10195 // If the owning package is the system itself, we log but allow 10196 // install to proceed; we fail the install on all other permission 10197 // redefinitions. 10198 if (!bp.sourcePackage.equals("android")) { 10199 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 10200 + pkg.packageName + " attempting to redeclare permission " 10201 + perm.info.name + " already owned by " + bp.sourcePackage); 10202 res.origPermission = perm.info.name; 10203 res.origPackage = bp.sourcePackage; 10204 return; 10205 } else { 10206 Slog.w(TAG, "Package " + pkg.packageName 10207 + " attempting to redeclare system permission " 10208 + perm.info.name + "; ignoring new declaration"); 10209 pkg.permissions.remove(i); 10210 } 10211 } 10212 } 10213 } 10214 10215 // Check if installing already existing package 10216 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10217 String oldName = mSettings.mRenamedPackages.get(pkgName); 10218 if (pkg.mOriginalPackages != null 10219 && pkg.mOriginalPackages.contains(oldName) 10220 && mPackages.containsKey(oldName)) { 10221 // This package is derived from an original package, 10222 // and this device has been updating from that original 10223 // name. We must continue using the original name, so 10224 // rename the new package here. 10225 pkg.setPackageName(oldName); 10226 pkgName = pkg.packageName; 10227 replace = true; 10228 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 10229 + oldName + " pkgName=" + pkgName); 10230 } else if (mPackages.containsKey(pkgName)) { 10231 // This package, under its official name, already exists 10232 // on the device; we should replace it. 10233 replace = true; 10234 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 10235 } 10236 } 10237 PackageSetting ps = mSettings.mPackages.get(pkgName); 10238 if (ps != null) { 10239 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 10240 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 10241 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 10242 systemApp = (ps.pkg.applicationInfo.flags & 10243 ApplicationInfo.FLAG_SYSTEM) != 0; 10244 } 10245 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10246 } 10247 } 10248 10249 if (systemApp && onSd) { 10250 // Disable updates to system apps on sdcard 10251 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 10252 "Cannot install updates to system apps on sdcard"); 10253 return; 10254 } 10255 10256 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 10257 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 10258 return; 10259 } 10260 10261 if (replace) { 10262 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 10263 installerPackageName, res); 10264 } else { 10265 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 10266 args.user, installerPackageName, res); 10267 } 10268 synchronized (mPackages) { 10269 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10270 if (ps != null) { 10271 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10272 } 10273 } 10274 } 10275 10276 private static boolean isForwardLocked(PackageParser.Package pkg) { 10277 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10278 } 10279 10280 private static boolean isForwardLocked(ApplicationInfo info) { 10281 return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10282 } 10283 10284 private boolean isForwardLocked(PackageSetting ps) { 10285 return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10286 } 10287 10288 private static boolean isMultiArch(PackageSetting ps) { 10289 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10290 } 10291 10292 private static boolean isMultiArch(ApplicationInfo info) { 10293 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10294 } 10295 10296 private static boolean isExternal(PackageParser.Package pkg) { 10297 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10298 } 10299 10300 private static boolean isExternal(PackageSetting ps) { 10301 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10302 } 10303 10304 private static boolean isExternal(ApplicationInfo info) { 10305 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10306 } 10307 10308 private static boolean isSystemApp(PackageParser.Package pkg) { 10309 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10310 } 10311 10312 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 10313 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0; 10314 } 10315 10316 private static boolean isSystemApp(ApplicationInfo info) { 10317 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10318 } 10319 10320 private static boolean isSystemApp(PackageSetting ps) { 10321 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 10322 } 10323 10324 private static boolean isUpdatedSystemApp(PackageSetting ps) { 10325 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10326 } 10327 10328 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 10329 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10330 } 10331 10332 private static boolean isUpdatedSystemApp(ApplicationInfo info) { 10333 return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10334 } 10335 10336 private int packageFlagsToInstallFlags(PackageSetting ps) { 10337 int installFlags = 0; 10338 if (isExternal(ps)) { 10339 installFlags |= PackageManager.INSTALL_EXTERNAL; 10340 } 10341 if (isForwardLocked(ps)) { 10342 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 10343 } 10344 return installFlags; 10345 } 10346 10347 private void deleteTempPackageFiles() { 10348 final FilenameFilter filter = new FilenameFilter() { 10349 public boolean accept(File dir, String name) { 10350 return name.startsWith("vmdl") && name.endsWith(".tmp"); 10351 } 10352 }; 10353 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 10354 file.delete(); 10355 } 10356 } 10357 10358 @Override 10359 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 10360 int flags) { 10361 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 10362 flags); 10363 } 10364 10365 @Override 10366 public void deletePackage(final String packageName, 10367 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 10368 mContext.enforceCallingOrSelfPermission( 10369 android.Manifest.permission.DELETE_PACKAGES, null); 10370 final int uid = Binder.getCallingUid(); 10371 if (UserHandle.getUserId(uid) != userId) { 10372 mContext.enforceCallingPermission( 10373 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 10374 "deletePackage for user " + userId); 10375 } 10376 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 10377 try { 10378 observer.onPackageDeleted(packageName, 10379 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 10380 } catch (RemoteException re) { 10381 } 10382 return; 10383 } 10384 10385 boolean uninstallBlocked = false; 10386 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 10387 int[] users = sUserManager.getUserIds(); 10388 for (int i = 0; i < users.length; ++i) { 10389 if (getBlockUninstallForUser(packageName, users[i])) { 10390 uninstallBlocked = true; 10391 break; 10392 } 10393 } 10394 } else { 10395 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 10396 } 10397 if (uninstallBlocked) { 10398 try { 10399 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 10400 null); 10401 } catch (RemoteException re) { 10402 } 10403 return; 10404 } 10405 10406 if (DEBUG_REMOVE) { 10407 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 10408 } 10409 // Queue up an async operation since the package deletion may take a little while. 10410 mHandler.post(new Runnable() { 10411 public void run() { 10412 mHandler.removeCallbacks(this); 10413 final int returnCode = deletePackageX(packageName, userId, flags); 10414 if (observer != null) { 10415 try { 10416 observer.onPackageDeleted(packageName, returnCode, null); 10417 } catch (RemoteException e) { 10418 Log.i(TAG, "Observer no longer exists."); 10419 } //end catch 10420 } //end if 10421 } //end run 10422 }); 10423 } 10424 10425 private boolean isPackageDeviceAdmin(String packageName, int userId) { 10426 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 10427 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 10428 try { 10429 if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId) 10430 || dpm.isDeviceOwner(packageName))) { 10431 return true; 10432 } 10433 } catch (RemoteException e) { 10434 } 10435 return false; 10436 } 10437 10438 /** 10439 * This method is an internal method that could be get invoked either 10440 * to delete an installed package or to clean up a failed installation. 10441 * After deleting an installed package, a broadcast is sent to notify any 10442 * listeners that the package has been installed. For cleaning up a failed 10443 * installation, the broadcast is not necessary since the package's 10444 * installation wouldn't have sent the initial broadcast either 10445 * The key steps in deleting a package are 10446 * deleting the package information in internal structures like mPackages, 10447 * deleting the packages base directories through installd 10448 * updating mSettings to reflect current status 10449 * persisting settings for later use 10450 * sending a broadcast if necessary 10451 */ 10452 private int deletePackageX(String packageName, int userId, int flags) { 10453 final PackageRemovedInfo info = new PackageRemovedInfo(); 10454 final boolean res; 10455 10456 if (isPackageDeviceAdmin(packageName, userId)) { 10457 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 10458 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 10459 } 10460 10461 boolean removedForAllUsers = false; 10462 boolean systemUpdate = false; 10463 10464 // for the uninstall-updates case and restricted profiles, remember the per- 10465 // userhandle installed state 10466 int[] allUsers; 10467 boolean[] perUserInstalled; 10468 synchronized (mPackages) { 10469 PackageSetting ps = mSettings.mPackages.get(packageName); 10470 allUsers = sUserManager.getUserIds(); 10471 perUserInstalled = new boolean[allUsers.length]; 10472 for (int i = 0; i < allUsers.length; i++) { 10473 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10474 } 10475 } 10476 10477 synchronized (mInstallLock) { 10478 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 10479 res = deletePackageLI(packageName, 10480 (flags & PackageManager.DELETE_ALL_USERS) != 0 10481 ? UserHandle.ALL : new UserHandle(userId), 10482 true, allUsers, perUserInstalled, 10483 flags | REMOVE_CHATTY, info, true); 10484 systemUpdate = info.isRemovedPackageSystemUpdate; 10485 if (res && !systemUpdate && mPackages.get(packageName) == null) { 10486 removedForAllUsers = true; 10487 } 10488 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 10489 + " removedForAllUsers=" + removedForAllUsers); 10490 } 10491 10492 if (res) { 10493 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 10494 10495 // If the removed package was a system update, the old system package 10496 // was re-enabled; we need to broadcast this information 10497 if (systemUpdate) { 10498 Bundle extras = new Bundle(1); 10499 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 10500 ? info.removedAppId : info.uid); 10501 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10502 10503 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 10504 extras, null, null, null); 10505 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 10506 extras, null, null, null); 10507 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 10508 null, packageName, null, null); 10509 } 10510 } 10511 // Force a gc here. 10512 Runtime.getRuntime().gc(); 10513 // Delete the resources here after sending the broadcast to let 10514 // other processes clean up before deleting resources. 10515 if (info.args != null) { 10516 synchronized (mInstallLock) { 10517 info.args.doPostDeleteLI(true); 10518 } 10519 } 10520 10521 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10522 } 10523 10524 static class PackageRemovedInfo { 10525 String removedPackage; 10526 int uid = -1; 10527 int removedAppId = -1; 10528 int[] removedUsers = null; 10529 boolean isRemovedPackageSystemUpdate = false; 10530 // Clean up resources deleted packages. 10531 InstallArgs args = null; 10532 10533 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 10534 Bundle extras = new Bundle(1); 10535 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 10536 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 10537 if (replacing) { 10538 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10539 } 10540 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 10541 if (removedPackage != null) { 10542 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 10543 extras, null, null, removedUsers); 10544 if (fullRemove && !replacing) { 10545 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 10546 extras, null, null, removedUsers); 10547 } 10548 } 10549 if (removedAppId >= 0) { 10550 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 10551 removedUsers); 10552 } 10553 } 10554 } 10555 10556 /* 10557 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 10558 * flag is not set, the data directory is removed as well. 10559 * make sure this flag is set for partially installed apps. If not its meaningless to 10560 * delete a partially installed application. 10561 */ 10562 private void removePackageDataLI(PackageSetting ps, 10563 int[] allUserHandles, boolean[] perUserInstalled, 10564 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 10565 String packageName = ps.name; 10566 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 10567 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 10568 // Retrieve object to delete permissions for shared user later on 10569 final PackageSetting deletedPs; 10570 // reader 10571 synchronized (mPackages) { 10572 deletedPs = mSettings.mPackages.get(packageName); 10573 if (outInfo != null) { 10574 outInfo.removedPackage = packageName; 10575 outInfo.removedUsers = deletedPs != null 10576 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 10577 : null; 10578 } 10579 } 10580 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10581 removeDataDirsLI(packageName); 10582 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 10583 } 10584 // writer 10585 synchronized (mPackages) { 10586 if (deletedPs != null) { 10587 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10588 if (outInfo != null) { 10589 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 10590 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 10591 } 10592 if (deletedPs != null) { 10593 updatePermissionsLPw(deletedPs.name, null, 0); 10594 if (deletedPs.sharedUser != null) { 10595 // remove permissions associated with package 10596 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 10597 } 10598 } 10599 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 10600 } 10601 // make sure to preserve per-user disabled state if this removal was just 10602 // a downgrade of a system app to the factory package 10603 if (allUserHandles != null && perUserInstalled != null) { 10604 if (DEBUG_REMOVE) { 10605 Slog.d(TAG, "Propagating install state across downgrade"); 10606 } 10607 for (int i = 0; i < allUserHandles.length; i++) { 10608 if (DEBUG_REMOVE) { 10609 Slog.d(TAG, " user " + allUserHandles[i] 10610 + " => " + perUserInstalled[i]); 10611 } 10612 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10613 } 10614 } 10615 } 10616 // can downgrade to reader 10617 if (writeSettings) { 10618 // Save settings now 10619 mSettings.writeLPr(); 10620 } 10621 } 10622 if (outInfo != null) { 10623 // A user ID was deleted here. Go through all users and remove it 10624 // from KeyStore. 10625 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 10626 } 10627 } 10628 10629 static boolean locationIsPrivileged(File path) { 10630 try { 10631 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 10632 .getCanonicalPath(); 10633 return path.getCanonicalPath().startsWith(privilegedAppDir); 10634 } catch (IOException e) { 10635 Slog.e(TAG, "Unable to access code path " + path); 10636 } 10637 return false; 10638 } 10639 10640 /* 10641 * Tries to delete system package. 10642 */ 10643 private boolean deleteSystemPackageLI(PackageSetting newPs, 10644 int[] allUserHandles, boolean[] perUserInstalled, 10645 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 10646 final boolean applyUserRestrictions 10647 = (allUserHandles != null) && (perUserInstalled != null); 10648 PackageSetting disabledPs = null; 10649 // Confirm if the system package has been updated 10650 // An updated system app can be deleted. This will also have to restore 10651 // the system pkg from system partition 10652 // reader 10653 synchronized (mPackages) { 10654 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 10655 } 10656 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 10657 + " disabledPs=" + disabledPs); 10658 if (disabledPs == null) { 10659 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 10660 return false; 10661 } else if (DEBUG_REMOVE) { 10662 Slog.d(TAG, "Deleting system pkg from data partition"); 10663 } 10664 if (DEBUG_REMOVE) { 10665 if (applyUserRestrictions) { 10666 Slog.d(TAG, "Remembering install states:"); 10667 for (int i = 0; i < allUserHandles.length; i++) { 10668 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 10669 } 10670 } 10671 } 10672 // Delete the updated package 10673 outInfo.isRemovedPackageSystemUpdate = true; 10674 if (disabledPs.versionCode < newPs.versionCode) { 10675 // Delete data for downgrades 10676 flags &= ~PackageManager.DELETE_KEEP_DATA; 10677 } else { 10678 // Preserve data by setting flag 10679 flags |= PackageManager.DELETE_KEEP_DATA; 10680 } 10681 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 10682 allUserHandles, perUserInstalled, outInfo, writeSettings); 10683 if (!ret) { 10684 return false; 10685 } 10686 // writer 10687 synchronized (mPackages) { 10688 // Reinstate the old system package 10689 mSettings.enableSystemPackageLPw(newPs.name); 10690 // Remove any native libraries from the upgraded package. 10691 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 10692 } 10693 // Install the system package 10694 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 10695 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 10696 if (locationIsPrivileged(disabledPs.codePath)) { 10697 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10698 } 10699 10700 final PackageParser.Package newPkg; 10701 try { 10702 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 10703 } catch (PackageManagerException e) { 10704 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 10705 return false; 10706 } 10707 10708 // writer 10709 synchronized (mPackages) { 10710 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 10711 updatePermissionsLPw(newPkg.packageName, newPkg, 10712 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 10713 if (applyUserRestrictions) { 10714 if (DEBUG_REMOVE) { 10715 Slog.d(TAG, "Propagating install state across reinstall"); 10716 } 10717 for (int i = 0; i < allUserHandles.length; i++) { 10718 if (DEBUG_REMOVE) { 10719 Slog.d(TAG, " user " + allUserHandles[i] 10720 + " => " + perUserInstalled[i]); 10721 } 10722 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10723 } 10724 // Regardless of writeSettings we need to ensure that this restriction 10725 // state propagation is persisted 10726 mSettings.writeAllUsersPackageRestrictionsLPr(); 10727 } 10728 // can downgrade to reader here 10729 if (writeSettings) { 10730 mSettings.writeLPr(); 10731 } 10732 } 10733 return true; 10734 } 10735 10736 private boolean deleteInstalledPackageLI(PackageSetting ps, 10737 boolean deleteCodeAndResources, int flags, 10738 int[] allUserHandles, boolean[] perUserInstalled, 10739 PackageRemovedInfo outInfo, boolean writeSettings) { 10740 if (outInfo != null) { 10741 outInfo.uid = ps.appId; 10742 } 10743 10744 // Delete package data from internal structures and also remove data if flag is set 10745 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 10746 10747 // Delete application code and resources 10748 if (deleteCodeAndResources && (outInfo != null)) { 10749 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 10750 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 10751 getAppDexInstructionSets(ps)); 10752 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 10753 } 10754 return true; 10755 } 10756 10757 @Override 10758 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 10759 int userId) { 10760 mContext.enforceCallingOrSelfPermission( 10761 android.Manifest.permission.DELETE_PACKAGES, null); 10762 synchronized (mPackages) { 10763 PackageSetting ps = mSettings.mPackages.get(packageName); 10764 if (ps == null) { 10765 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 10766 return false; 10767 } 10768 if (!ps.getInstalled(userId)) { 10769 // Can't block uninstall for an app that is not installed or enabled. 10770 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 10771 return false; 10772 } 10773 ps.setBlockUninstall(blockUninstall, userId); 10774 mSettings.writePackageRestrictionsLPr(userId); 10775 } 10776 return true; 10777 } 10778 10779 @Override 10780 public boolean getBlockUninstallForUser(String packageName, int userId) { 10781 synchronized (mPackages) { 10782 PackageSetting ps = mSettings.mPackages.get(packageName); 10783 if (ps == null) { 10784 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 10785 return false; 10786 } 10787 return ps.getBlockUninstall(userId); 10788 } 10789 } 10790 10791 /* 10792 * This method handles package deletion in general 10793 */ 10794 private boolean deletePackageLI(String packageName, UserHandle user, 10795 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 10796 int flags, PackageRemovedInfo outInfo, 10797 boolean writeSettings) { 10798 if (packageName == null) { 10799 Slog.w(TAG, "Attempt to delete null packageName."); 10800 return false; 10801 } 10802 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 10803 PackageSetting ps; 10804 boolean dataOnly = false; 10805 int removeUser = -1; 10806 int appId = -1; 10807 synchronized (mPackages) { 10808 ps = mSettings.mPackages.get(packageName); 10809 if (ps == null) { 10810 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 10811 return false; 10812 } 10813 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 10814 && user.getIdentifier() != UserHandle.USER_ALL) { 10815 // The caller is asking that the package only be deleted for a single 10816 // user. To do this, we just mark its uninstalled state and delete 10817 // its data. If this is a system app, we only allow this to happen if 10818 // they have set the special DELETE_SYSTEM_APP which requests different 10819 // semantics than normal for uninstalling system apps. 10820 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 10821 ps.setUserState(user.getIdentifier(), 10822 COMPONENT_ENABLED_STATE_DEFAULT, 10823 false, //installed 10824 true, //stopped 10825 true, //notLaunched 10826 false, //hidden 10827 null, null, null, 10828 false // blockUninstall 10829 ); 10830 if (!isSystemApp(ps)) { 10831 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 10832 // Other user still have this package installed, so all 10833 // we need to do is clear this user's data and save that 10834 // it is uninstalled. 10835 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 10836 removeUser = user.getIdentifier(); 10837 appId = ps.appId; 10838 mSettings.writePackageRestrictionsLPr(removeUser); 10839 } else { 10840 // We need to set it back to 'installed' so the uninstall 10841 // broadcasts will be sent correctly. 10842 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 10843 ps.setInstalled(true, user.getIdentifier()); 10844 } 10845 } else { 10846 // This is a system app, so we assume that the 10847 // other users still have this package installed, so all 10848 // we need to do is clear this user's data and save that 10849 // it is uninstalled. 10850 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 10851 removeUser = user.getIdentifier(); 10852 appId = ps.appId; 10853 mSettings.writePackageRestrictionsLPr(removeUser); 10854 } 10855 } 10856 } 10857 10858 if (removeUser >= 0) { 10859 // From above, we determined that we are deleting this only 10860 // for a single user. Continue the work here. 10861 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 10862 if (outInfo != null) { 10863 outInfo.removedPackage = packageName; 10864 outInfo.removedAppId = appId; 10865 outInfo.removedUsers = new int[] {removeUser}; 10866 } 10867 mInstaller.clearUserData(packageName, removeUser); 10868 removeKeystoreDataIfNeeded(removeUser, appId); 10869 schedulePackageCleaning(packageName, removeUser, false); 10870 return true; 10871 } 10872 10873 if (dataOnly) { 10874 // Delete application data first 10875 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 10876 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 10877 return true; 10878 } 10879 10880 boolean ret = false; 10881 if (isSystemApp(ps)) { 10882 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 10883 // When an updated system application is deleted we delete the existing resources as well and 10884 // fall back to existing code in system partition 10885 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 10886 flags, outInfo, writeSettings); 10887 } else { 10888 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 10889 // Kill application pre-emptively especially for apps on sd. 10890 killApplication(packageName, ps.appId, "uninstall pkg"); 10891 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 10892 allUserHandles, perUserInstalled, 10893 outInfo, writeSettings); 10894 } 10895 10896 return ret; 10897 } 10898 10899 private final class ClearStorageConnection implements ServiceConnection { 10900 IMediaContainerService mContainerService; 10901 10902 @Override 10903 public void onServiceConnected(ComponentName name, IBinder service) { 10904 synchronized (this) { 10905 mContainerService = IMediaContainerService.Stub.asInterface(service); 10906 notifyAll(); 10907 } 10908 } 10909 10910 @Override 10911 public void onServiceDisconnected(ComponentName name) { 10912 } 10913 } 10914 10915 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 10916 final boolean mounted; 10917 if (Environment.isExternalStorageEmulated()) { 10918 mounted = true; 10919 } else { 10920 final String status = Environment.getExternalStorageState(); 10921 10922 mounted = status.equals(Environment.MEDIA_MOUNTED) 10923 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 10924 } 10925 10926 if (!mounted) { 10927 return; 10928 } 10929 10930 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 10931 int[] users; 10932 if (userId == UserHandle.USER_ALL) { 10933 users = sUserManager.getUserIds(); 10934 } else { 10935 users = new int[] { userId }; 10936 } 10937 final ClearStorageConnection conn = new ClearStorageConnection(); 10938 if (mContext.bindServiceAsUser( 10939 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 10940 try { 10941 for (int curUser : users) { 10942 long timeout = SystemClock.uptimeMillis() + 5000; 10943 synchronized (conn) { 10944 long now = SystemClock.uptimeMillis(); 10945 while (conn.mContainerService == null && now < timeout) { 10946 try { 10947 conn.wait(timeout - now); 10948 } catch (InterruptedException e) { 10949 } 10950 } 10951 } 10952 if (conn.mContainerService == null) { 10953 return; 10954 } 10955 10956 final UserEnvironment userEnv = new UserEnvironment(curUser); 10957 clearDirectory(conn.mContainerService, 10958 userEnv.buildExternalStorageAppCacheDirs(packageName)); 10959 if (allData) { 10960 clearDirectory(conn.mContainerService, 10961 userEnv.buildExternalStorageAppDataDirs(packageName)); 10962 clearDirectory(conn.mContainerService, 10963 userEnv.buildExternalStorageAppMediaDirs(packageName)); 10964 } 10965 } 10966 } finally { 10967 mContext.unbindService(conn); 10968 } 10969 } 10970 } 10971 10972 @Override 10973 public void clearApplicationUserData(final String packageName, 10974 final IPackageDataObserver observer, final int userId) { 10975 mContext.enforceCallingOrSelfPermission( 10976 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 10977 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 10978 // Queue up an async operation since the package deletion may take a little while. 10979 mHandler.post(new Runnable() { 10980 public void run() { 10981 mHandler.removeCallbacks(this); 10982 final boolean succeeded; 10983 synchronized (mInstallLock) { 10984 succeeded = clearApplicationUserDataLI(packageName, userId); 10985 } 10986 clearExternalStorageDataSync(packageName, userId, true); 10987 if (succeeded) { 10988 // invoke DeviceStorageMonitor's update method to clear any notifications 10989 DeviceStorageMonitorInternal 10990 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 10991 if (dsm != null) { 10992 dsm.checkMemory(); 10993 } 10994 } 10995 if(observer != null) { 10996 try { 10997 observer.onRemoveCompleted(packageName, succeeded); 10998 } catch (RemoteException e) { 10999 Log.i(TAG, "Observer no longer exists."); 11000 } 11001 } //end if observer 11002 } //end run 11003 }); 11004 } 11005 11006 private boolean clearApplicationUserDataLI(String packageName, int userId) { 11007 if (packageName == null) { 11008 Slog.w(TAG, "Attempt to delete null packageName."); 11009 return false; 11010 } 11011 PackageParser.Package pkg; 11012 boolean dataOnly = false; 11013 final int appId; 11014 synchronized (mPackages) { 11015 pkg = mPackages.get(packageName); 11016 if (pkg == null) { 11017 dataOnly = true; 11018 PackageSetting ps = mSettings.mPackages.get(packageName); 11019 if ((ps == null) || (ps.pkg == null)) { 11020 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11021 return false; 11022 } 11023 pkg = ps.pkg; 11024 } 11025 if (!dataOnly) { 11026 // need to check this only for fully installed applications 11027 if (pkg == null) { 11028 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11029 return false; 11030 } 11031 final ApplicationInfo applicationInfo = pkg.applicationInfo; 11032 if (applicationInfo == null) { 11033 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11034 return false; 11035 } 11036 } 11037 if (pkg != null && pkg.applicationInfo != null) { 11038 appId = pkg.applicationInfo.uid; 11039 } else { 11040 appId = -1; 11041 } 11042 } 11043 int retCode = mInstaller.clearUserData(packageName, userId); 11044 if (retCode < 0) { 11045 Slog.w(TAG, "Couldn't remove cache files for package: " 11046 + packageName); 11047 return false; 11048 } 11049 removeKeystoreDataIfNeeded(userId, appId); 11050 11051 // Create a native library symlink only if we have native libraries 11052 // and if the native libraries are 32 bit libraries. We do not provide 11053 // this symlink for 64 bit libraries. 11054 if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null && 11055 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 11056 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 11057 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 11058 Slog.w(TAG, "Failed linking native library dir"); 11059 return false; 11060 } 11061 } 11062 11063 return true; 11064 } 11065 11066 /** 11067 * Remove entries from the keystore daemon. Will only remove it if the 11068 * {@code appId} is valid. 11069 */ 11070 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 11071 if (appId < 0) { 11072 return; 11073 } 11074 11075 final KeyStore keyStore = KeyStore.getInstance(); 11076 if (keyStore != null) { 11077 if (userId == UserHandle.USER_ALL) { 11078 for (final int individual : sUserManager.getUserIds()) { 11079 keyStore.clearUid(UserHandle.getUid(individual, appId)); 11080 } 11081 } else { 11082 keyStore.clearUid(UserHandle.getUid(userId, appId)); 11083 } 11084 } else { 11085 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 11086 } 11087 } 11088 11089 @Override 11090 public void deleteApplicationCacheFiles(final String packageName, 11091 final IPackageDataObserver observer) { 11092 mContext.enforceCallingOrSelfPermission( 11093 android.Manifest.permission.DELETE_CACHE_FILES, null); 11094 // Queue up an async operation since the package deletion may take a little while. 11095 final int userId = UserHandle.getCallingUserId(); 11096 mHandler.post(new Runnable() { 11097 public void run() { 11098 mHandler.removeCallbacks(this); 11099 final boolean succeded; 11100 synchronized (mInstallLock) { 11101 succeded = deleteApplicationCacheFilesLI(packageName, userId); 11102 } 11103 clearExternalStorageDataSync(packageName, userId, false); 11104 if(observer != null) { 11105 try { 11106 observer.onRemoveCompleted(packageName, succeded); 11107 } catch (RemoteException e) { 11108 Log.i(TAG, "Observer no longer exists."); 11109 } 11110 } //end if observer 11111 } //end run 11112 }); 11113 } 11114 11115 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 11116 if (packageName == null) { 11117 Slog.w(TAG, "Attempt to delete null packageName."); 11118 return false; 11119 } 11120 PackageParser.Package p; 11121 synchronized (mPackages) { 11122 p = mPackages.get(packageName); 11123 } 11124 if (p == null) { 11125 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11126 return false; 11127 } 11128 final ApplicationInfo applicationInfo = p.applicationInfo; 11129 if (applicationInfo == null) { 11130 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11131 return false; 11132 } 11133 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 11134 if (retCode < 0) { 11135 Slog.w(TAG, "Couldn't remove cache files for package: " 11136 + packageName + " u" + userId); 11137 return false; 11138 } 11139 return true; 11140 } 11141 11142 @Override 11143 public void getPackageSizeInfo(final String packageName, int userHandle, 11144 final IPackageStatsObserver observer) { 11145 mContext.enforceCallingOrSelfPermission( 11146 android.Manifest.permission.GET_PACKAGE_SIZE, null); 11147 if (packageName == null) { 11148 throw new IllegalArgumentException("Attempt to get size of null packageName"); 11149 } 11150 11151 PackageStats stats = new PackageStats(packageName, userHandle); 11152 11153 /* 11154 * Queue up an async operation since the package measurement may take a 11155 * little while. 11156 */ 11157 Message msg = mHandler.obtainMessage(INIT_COPY); 11158 msg.obj = new MeasureParams(stats, observer); 11159 mHandler.sendMessage(msg); 11160 } 11161 11162 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 11163 PackageStats pStats) { 11164 if (packageName == null) { 11165 Slog.w(TAG, "Attempt to get size of null packageName."); 11166 return false; 11167 } 11168 PackageParser.Package p; 11169 boolean dataOnly = false; 11170 String libDirRoot = null; 11171 String asecPath = null; 11172 PackageSetting ps = null; 11173 synchronized (mPackages) { 11174 p = mPackages.get(packageName); 11175 ps = mSettings.mPackages.get(packageName); 11176 if(p == null) { 11177 dataOnly = true; 11178 if((ps == null) || (ps.pkg == null)) { 11179 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11180 return false; 11181 } 11182 p = ps.pkg; 11183 } 11184 if (ps != null) { 11185 libDirRoot = ps.legacyNativeLibraryPathString; 11186 } 11187 if (p != null && (isExternal(p) || isForwardLocked(p))) { 11188 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 11189 if (secureContainerId != null) { 11190 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 11191 } 11192 } 11193 } 11194 String publicSrcDir = null; 11195 if(!dataOnly) { 11196 final ApplicationInfo applicationInfo = p.applicationInfo; 11197 if (applicationInfo == null) { 11198 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11199 return false; 11200 } 11201 if (isForwardLocked(p)) { 11202 publicSrcDir = applicationInfo.getBaseResourcePath(); 11203 } 11204 } 11205 // TODO: extend to measure size of split APKs 11206 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 11207 // not just the first level. 11208 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 11209 // just the primary. 11210 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 11211 int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot, 11212 publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 11213 if (res < 0) { 11214 return false; 11215 } 11216 11217 // Fix-up for forward-locked applications in ASEC containers. 11218 if (!isExternal(p)) { 11219 pStats.codeSize += pStats.externalCodeSize; 11220 pStats.externalCodeSize = 0L; 11221 } 11222 11223 return true; 11224 } 11225 11226 11227 @Override 11228 public void addPackageToPreferred(String packageName) { 11229 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 11230 } 11231 11232 @Override 11233 public void removePackageFromPreferred(String packageName) { 11234 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 11235 } 11236 11237 @Override 11238 public List<PackageInfo> getPreferredPackages(int flags) { 11239 return new ArrayList<PackageInfo>(); 11240 } 11241 11242 private int getUidTargetSdkVersionLockedLPr(int uid) { 11243 Object obj = mSettings.getUserIdLPr(uid); 11244 if (obj instanceof SharedUserSetting) { 11245 final SharedUserSetting sus = (SharedUserSetting) obj; 11246 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 11247 final Iterator<PackageSetting> it = sus.packages.iterator(); 11248 while (it.hasNext()) { 11249 final PackageSetting ps = it.next(); 11250 if (ps.pkg != null) { 11251 int v = ps.pkg.applicationInfo.targetSdkVersion; 11252 if (v < vers) vers = v; 11253 } 11254 } 11255 return vers; 11256 } else if (obj instanceof PackageSetting) { 11257 final PackageSetting ps = (PackageSetting) obj; 11258 if (ps.pkg != null) { 11259 return ps.pkg.applicationInfo.targetSdkVersion; 11260 } 11261 } 11262 return Build.VERSION_CODES.CUR_DEVELOPMENT; 11263 } 11264 11265 @Override 11266 public void addPreferredActivity(IntentFilter filter, int match, 11267 ComponentName[] set, ComponentName activity, int userId) { 11268 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11269 "Adding preferred"); 11270 } 11271 11272 private void addPreferredActivityInternal(IntentFilter filter, int match, 11273 ComponentName[] set, ComponentName activity, boolean always, int userId, 11274 String opname) { 11275 // writer 11276 int callingUid = Binder.getCallingUid(); 11277 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 11278 if (filter.countActions() == 0) { 11279 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11280 return; 11281 } 11282 synchronized (mPackages) { 11283 if (mContext.checkCallingOrSelfPermission( 11284 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11285 != PackageManager.PERMISSION_GRANTED) { 11286 if (getUidTargetSdkVersionLockedLPr(callingUid) 11287 < Build.VERSION_CODES.FROYO) { 11288 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 11289 + callingUid); 11290 return; 11291 } 11292 mContext.enforceCallingOrSelfPermission( 11293 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11294 } 11295 11296 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 11297 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 11298 + userId + ":"); 11299 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11300 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 11301 mSettings.writePackageRestrictionsLPr(userId); 11302 } 11303 } 11304 11305 @Override 11306 public void replacePreferredActivity(IntentFilter filter, int match, 11307 ComponentName[] set, ComponentName activity, int userId) { 11308 if (filter.countActions() != 1) { 11309 throw new IllegalArgumentException( 11310 "replacePreferredActivity expects filter to have only 1 action."); 11311 } 11312 if (filter.countDataAuthorities() != 0 11313 || filter.countDataPaths() != 0 11314 || filter.countDataSchemes() > 1 11315 || filter.countDataTypes() != 0) { 11316 throw new IllegalArgumentException( 11317 "replacePreferredActivity expects filter to have no data authorities, " + 11318 "paths, or types; and at most one scheme."); 11319 } 11320 11321 final int callingUid = Binder.getCallingUid(); 11322 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 11323 synchronized (mPackages) { 11324 if (mContext.checkCallingOrSelfPermission( 11325 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11326 != PackageManager.PERMISSION_GRANTED) { 11327 if (getUidTargetSdkVersionLockedLPr(callingUid) 11328 < Build.VERSION_CODES.FROYO) { 11329 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 11330 + Binder.getCallingUid()); 11331 return; 11332 } 11333 mContext.enforceCallingOrSelfPermission( 11334 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11335 } 11336 11337 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11338 if (pir != null) { 11339 // Get all of the existing entries that exactly match this filter. 11340 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 11341 if (existing != null && existing.size() == 1) { 11342 PreferredActivity cur = existing.get(0); 11343 if (DEBUG_PREFERRED) { 11344 Slog.i(TAG, "Checking replace of preferred:"); 11345 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11346 if (!cur.mPref.mAlways) { 11347 Slog.i(TAG, " -- CUR; not mAlways!"); 11348 } else { 11349 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 11350 Slog.i(TAG, " -- CUR: mSet=" 11351 + Arrays.toString(cur.mPref.mSetComponents)); 11352 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 11353 Slog.i(TAG, " -- NEW: mMatch=" 11354 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 11355 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 11356 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 11357 } 11358 } 11359 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 11360 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 11361 && cur.mPref.sameSet(set)) { 11362 if (DEBUG_PREFERRED) { 11363 Slog.i(TAG, "Replacing with same preferred activity " 11364 + cur.mPref.mShortComponent + " for user " 11365 + userId + ":"); 11366 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11367 } else { 11368 Slog.i(TAG, "Replacing with same preferred activity " 11369 + cur.mPref.mShortComponent + " for user " 11370 + userId); 11371 } 11372 return; 11373 } 11374 } 11375 11376 if (existing != null) { 11377 if (DEBUG_PREFERRED) { 11378 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 11379 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11380 } 11381 for (int i = 0; i < existing.size(); i++) { 11382 PreferredActivity pa = existing.get(i); 11383 if (DEBUG_PREFERRED) { 11384 Slog.i(TAG, "Removing existing preferred activity " 11385 + pa.mPref.mComponent + ":"); 11386 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 11387 } 11388 pir.removeFilter(pa); 11389 } 11390 } 11391 } 11392 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11393 "Replacing preferred"); 11394 } 11395 } 11396 11397 @Override 11398 public void clearPackagePreferredActivities(String packageName) { 11399 final int uid = Binder.getCallingUid(); 11400 // writer 11401 synchronized (mPackages) { 11402 PackageParser.Package pkg = mPackages.get(packageName); 11403 if (pkg == null || pkg.applicationInfo.uid != uid) { 11404 if (mContext.checkCallingOrSelfPermission( 11405 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11406 != PackageManager.PERMISSION_GRANTED) { 11407 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11408 < Build.VERSION_CODES.FROYO) { 11409 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 11410 + Binder.getCallingUid()); 11411 return; 11412 } 11413 mContext.enforceCallingOrSelfPermission( 11414 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11415 } 11416 } 11417 11418 int user = UserHandle.getCallingUserId(); 11419 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 11420 mSettings.writePackageRestrictionsLPr(user); 11421 scheduleWriteSettingsLocked(); 11422 } 11423 } 11424 } 11425 11426 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 11427 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 11428 ArrayList<PreferredActivity> removed = null; 11429 boolean changed = false; 11430 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11431 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 11432 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11433 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 11434 continue; 11435 } 11436 Iterator<PreferredActivity> it = pir.filterIterator(); 11437 while (it.hasNext()) { 11438 PreferredActivity pa = it.next(); 11439 // Mark entry for removal only if it matches the package name 11440 // and the entry is of type "always". 11441 if (packageName == null || 11442 (pa.mPref.mComponent.getPackageName().equals(packageName) 11443 && pa.mPref.mAlways)) { 11444 if (removed == null) { 11445 removed = new ArrayList<PreferredActivity>(); 11446 } 11447 removed.add(pa); 11448 } 11449 } 11450 if (removed != null) { 11451 for (int j=0; j<removed.size(); j++) { 11452 PreferredActivity pa = removed.get(j); 11453 pir.removeFilter(pa); 11454 } 11455 changed = true; 11456 } 11457 } 11458 return changed; 11459 } 11460 11461 @Override 11462 public void resetPreferredActivities(int userId) { 11463 /* TODO: Actually use userId. Why is it being passed in? */ 11464 mContext.enforceCallingOrSelfPermission( 11465 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11466 // writer 11467 synchronized (mPackages) { 11468 int user = UserHandle.getCallingUserId(); 11469 clearPackagePreferredActivitiesLPw(null, user); 11470 mSettings.readDefaultPreferredAppsLPw(this, user); 11471 mSettings.writePackageRestrictionsLPr(user); 11472 scheduleWriteSettingsLocked(); 11473 } 11474 } 11475 11476 @Override 11477 public int getPreferredActivities(List<IntentFilter> outFilters, 11478 List<ComponentName> outActivities, String packageName) { 11479 11480 int num = 0; 11481 final int userId = UserHandle.getCallingUserId(); 11482 // reader 11483 synchronized (mPackages) { 11484 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11485 if (pir != null) { 11486 final Iterator<PreferredActivity> it = pir.filterIterator(); 11487 while (it.hasNext()) { 11488 final PreferredActivity pa = it.next(); 11489 if (packageName == null 11490 || (pa.mPref.mComponent.getPackageName().equals(packageName) 11491 && pa.mPref.mAlways)) { 11492 if (outFilters != null) { 11493 outFilters.add(new IntentFilter(pa)); 11494 } 11495 if (outActivities != null) { 11496 outActivities.add(pa.mPref.mComponent); 11497 } 11498 } 11499 } 11500 } 11501 } 11502 11503 return num; 11504 } 11505 11506 @Override 11507 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 11508 int userId) { 11509 int callingUid = Binder.getCallingUid(); 11510 if (callingUid != Process.SYSTEM_UID) { 11511 throw new SecurityException( 11512 "addPersistentPreferredActivity can only be run by the system"); 11513 } 11514 if (filter.countActions() == 0) { 11515 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11516 return; 11517 } 11518 synchronized (mPackages) { 11519 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 11520 " :"); 11521 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11522 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 11523 new PersistentPreferredActivity(filter, activity)); 11524 mSettings.writePackageRestrictionsLPr(userId); 11525 } 11526 } 11527 11528 @Override 11529 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 11530 int callingUid = Binder.getCallingUid(); 11531 if (callingUid != Process.SYSTEM_UID) { 11532 throw new SecurityException( 11533 "clearPackagePersistentPreferredActivities can only be run by the system"); 11534 } 11535 ArrayList<PersistentPreferredActivity> removed = null; 11536 boolean changed = false; 11537 synchronized (mPackages) { 11538 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 11539 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 11540 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 11541 .valueAt(i); 11542 if (userId != thisUserId) { 11543 continue; 11544 } 11545 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 11546 while (it.hasNext()) { 11547 PersistentPreferredActivity ppa = it.next(); 11548 // Mark entry for removal only if it matches the package name. 11549 if (ppa.mComponent.getPackageName().equals(packageName)) { 11550 if (removed == null) { 11551 removed = new ArrayList<PersistentPreferredActivity>(); 11552 } 11553 removed.add(ppa); 11554 } 11555 } 11556 if (removed != null) { 11557 for (int j=0; j<removed.size(); j++) { 11558 PersistentPreferredActivity ppa = removed.get(j); 11559 ppir.removeFilter(ppa); 11560 } 11561 changed = true; 11562 } 11563 } 11564 11565 if (changed) { 11566 mSettings.writePackageRestrictionsLPr(userId); 11567 } 11568 } 11569 } 11570 11571 @Override 11572 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 11573 int ownerUserId, int sourceUserId, int targetUserId, int flags) { 11574 mContext.enforceCallingOrSelfPermission( 11575 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11576 int callingUid = Binder.getCallingUid(); 11577 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11578 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 11579 if (intentFilter.countActions() == 0) { 11580 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 11581 return; 11582 } 11583 synchronized (mPackages) { 11584 CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter, 11585 ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags); 11586 mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter); 11587 mSettings.writePackageRestrictionsLPr(sourceUserId); 11588 } 11589 } 11590 11591 @Override 11592 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage, 11593 int ownerUserId) { 11594 mContext.enforceCallingOrSelfPermission( 11595 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11596 int callingUid = Binder.getCallingUid(); 11597 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11598 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 11599 int callingUserId = UserHandle.getUserId(callingUid); 11600 synchronized (mPackages) { 11601 CrossProfileIntentResolver resolver = 11602 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11603 HashSet<CrossProfileIntentFilter> set = 11604 new HashSet<CrossProfileIntentFilter>(resolver.filterSet()); 11605 for (CrossProfileIntentFilter filter : set) { 11606 if (filter.getOwnerPackage().equals(ownerPackage) 11607 && filter.getOwnerUserId() == callingUserId) { 11608 resolver.removeFilter(filter); 11609 } 11610 } 11611 mSettings.writePackageRestrictionsLPr(sourceUserId); 11612 } 11613 } 11614 11615 // Enforcing that callingUid is owning pkg on userId 11616 private void enforceOwnerRights(String pkg, int userId, int callingUid) { 11617 // The system owns everything. 11618 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 11619 return; 11620 } 11621 int callingUserId = UserHandle.getUserId(callingUid); 11622 if (callingUserId != userId) { 11623 throw new SecurityException("calling uid " + callingUid 11624 + " pretends to own " + pkg + " on user " + userId + " but belongs to user " 11625 + callingUserId); 11626 } 11627 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 11628 if (pi == null) { 11629 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 11630 + callingUserId); 11631 } 11632 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 11633 throw new SecurityException("Calling uid " + callingUid 11634 + " does not own package " + pkg); 11635 } 11636 } 11637 11638 @Override 11639 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 11640 Intent intent = new Intent(Intent.ACTION_MAIN); 11641 intent.addCategory(Intent.CATEGORY_HOME); 11642 11643 final int callingUserId = UserHandle.getCallingUserId(); 11644 List<ResolveInfo> list = queryIntentActivities(intent, null, 11645 PackageManager.GET_META_DATA, callingUserId); 11646 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 11647 true, false, false, callingUserId); 11648 11649 allHomeCandidates.clear(); 11650 if (list != null) { 11651 for (ResolveInfo ri : list) { 11652 allHomeCandidates.add(ri); 11653 } 11654 } 11655 return (preferred == null || preferred.activityInfo == null) 11656 ? null 11657 : new ComponentName(preferred.activityInfo.packageName, 11658 preferred.activityInfo.name); 11659 } 11660 11661 @Override 11662 public void setApplicationEnabledSetting(String appPackageName, 11663 int newState, int flags, int userId, String callingPackage) { 11664 if (!sUserManager.exists(userId)) return; 11665 if (callingPackage == null) { 11666 callingPackage = Integer.toString(Binder.getCallingUid()); 11667 } 11668 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 11669 } 11670 11671 @Override 11672 public void setComponentEnabledSetting(ComponentName componentName, 11673 int newState, int flags, int userId) { 11674 if (!sUserManager.exists(userId)) return; 11675 setEnabledSetting(componentName.getPackageName(), 11676 componentName.getClassName(), newState, flags, userId, null); 11677 } 11678 11679 private void setEnabledSetting(final String packageName, String className, int newState, 11680 final int flags, int userId, String callingPackage) { 11681 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 11682 || newState == COMPONENT_ENABLED_STATE_ENABLED 11683 || newState == COMPONENT_ENABLED_STATE_DISABLED 11684 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 11685 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 11686 throw new IllegalArgumentException("Invalid new component state: " 11687 + newState); 11688 } 11689 PackageSetting pkgSetting; 11690 final int uid = Binder.getCallingUid(); 11691 final int permission = mContext.checkCallingOrSelfPermission( 11692 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11693 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 11694 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11695 boolean sendNow = false; 11696 boolean isApp = (className == null); 11697 String componentName = isApp ? packageName : className; 11698 int packageUid = -1; 11699 ArrayList<String> components; 11700 11701 // writer 11702 synchronized (mPackages) { 11703 pkgSetting = mSettings.mPackages.get(packageName); 11704 if (pkgSetting == null) { 11705 if (className == null) { 11706 throw new IllegalArgumentException( 11707 "Unknown package: " + packageName); 11708 } 11709 throw new IllegalArgumentException( 11710 "Unknown component: " + packageName 11711 + "/" + className); 11712 } 11713 // Allow root and verify that userId is not being specified by a different user 11714 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 11715 throw new SecurityException( 11716 "Permission Denial: attempt to change component state from pid=" 11717 + Binder.getCallingPid() 11718 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 11719 } 11720 if (className == null) { 11721 // We're dealing with an application/package level state change 11722 if (pkgSetting.getEnabled(userId) == newState) { 11723 // Nothing to do 11724 return; 11725 } 11726 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 11727 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 11728 // Don't care about who enables an app. 11729 callingPackage = null; 11730 } 11731 pkgSetting.setEnabled(newState, userId, callingPackage); 11732 // pkgSetting.pkg.mSetEnabled = newState; 11733 } else { 11734 // We're dealing with a component level state change 11735 // First, verify that this is a valid class name. 11736 PackageParser.Package pkg = pkgSetting.pkg; 11737 if (pkg == null || !pkg.hasComponentClassName(className)) { 11738 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 11739 throw new IllegalArgumentException("Component class " + className 11740 + " does not exist in " + packageName); 11741 } else { 11742 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 11743 + className + " does not exist in " + packageName); 11744 } 11745 } 11746 switch (newState) { 11747 case COMPONENT_ENABLED_STATE_ENABLED: 11748 if (!pkgSetting.enableComponentLPw(className, userId)) { 11749 return; 11750 } 11751 break; 11752 case COMPONENT_ENABLED_STATE_DISABLED: 11753 if (!pkgSetting.disableComponentLPw(className, userId)) { 11754 return; 11755 } 11756 break; 11757 case COMPONENT_ENABLED_STATE_DEFAULT: 11758 if (!pkgSetting.restoreComponentLPw(className, userId)) { 11759 return; 11760 } 11761 break; 11762 default: 11763 Slog.e(TAG, "Invalid new component state: " + newState); 11764 return; 11765 } 11766 } 11767 mSettings.writePackageRestrictionsLPr(userId); 11768 components = mPendingBroadcasts.get(userId, packageName); 11769 final boolean newPackage = components == null; 11770 if (newPackage) { 11771 components = new ArrayList<String>(); 11772 } 11773 if (!components.contains(componentName)) { 11774 components.add(componentName); 11775 } 11776 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 11777 sendNow = true; 11778 // Purge entry from pending broadcast list if another one exists already 11779 // since we are sending one right away. 11780 mPendingBroadcasts.remove(userId, packageName); 11781 } else { 11782 if (newPackage) { 11783 mPendingBroadcasts.put(userId, packageName, components); 11784 } 11785 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 11786 // Schedule a message 11787 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 11788 } 11789 } 11790 } 11791 11792 long callingId = Binder.clearCallingIdentity(); 11793 try { 11794 if (sendNow) { 11795 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 11796 sendPackageChangedBroadcast(packageName, 11797 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 11798 } 11799 } finally { 11800 Binder.restoreCallingIdentity(callingId); 11801 } 11802 } 11803 11804 private void sendPackageChangedBroadcast(String packageName, 11805 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 11806 if (DEBUG_INSTALL) 11807 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 11808 + componentNames); 11809 Bundle extras = new Bundle(4); 11810 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 11811 String nameList[] = new String[componentNames.size()]; 11812 componentNames.toArray(nameList); 11813 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 11814 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 11815 extras.putInt(Intent.EXTRA_UID, packageUid); 11816 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 11817 new int[] {UserHandle.getUserId(packageUid)}); 11818 } 11819 11820 @Override 11821 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 11822 if (!sUserManager.exists(userId)) return; 11823 final int uid = Binder.getCallingUid(); 11824 final int permission = mContext.checkCallingOrSelfPermission( 11825 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11826 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11827 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 11828 // writer 11829 synchronized (mPackages) { 11830 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 11831 uid, userId)) { 11832 scheduleWritePackageRestrictionsLocked(userId); 11833 } 11834 } 11835 } 11836 11837 @Override 11838 public String getInstallerPackageName(String packageName) { 11839 // reader 11840 synchronized (mPackages) { 11841 return mSettings.getInstallerPackageNameLPr(packageName); 11842 } 11843 } 11844 11845 @Override 11846 public int getApplicationEnabledSetting(String packageName, int userId) { 11847 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11848 int uid = Binder.getCallingUid(); 11849 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 11850 // reader 11851 synchronized (mPackages) { 11852 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 11853 } 11854 } 11855 11856 @Override 11857 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 11858 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11859 int uid = Binder.getCallingUid(); 11860 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 11861 // reader 11862 synchronized (mPackages) { 11863 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 11864 } 11865 } 11866 11867 @Override 11868 public void enterSafeMode() { 11869 enforceSystemOrRoot("Only the system can request entering safe mode"); 11870 11871 if (!mSystemReady) { 11872 mSafeMode = true; 11873 } 11874 } 11875 11876 @Override 11877 public void systemReady() { 11878 mSystemReady = true; 11879 11880 // Read the compatibilty setting when the system is ready. 11881 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 11882 mContext.getContentResolver(), 11883 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 11884 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 11885 if (DEBUG_SETTINGS) { 11886 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 11887 } 11888 11889 synchronized (mPackages) { 11890 // Verify that all of the preferred activity components actually 11891 // exist. It is possible for applications to be updated and at 11892 // that point remove a previously declared activity component that 11893 // had been set as a preferred activity. We try to clean this up 11894 // the next time we encounter that preferred activity, but it is 11895 // possible for the user flow to never be able to return to that 11896 // situation so here we do a sanity check to make sure we haven't 11897 // left any junk around. 11898 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 11899 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11900 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11901 removed.clear(); 11902 for (PreferredActivity pa : pir.filterSet()) { 11903 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 11904 removed.add(pa); 11905 } 11906 } 11907 if (removed.size() > 0) { 11908 for (int r=0; r<removed.size(); r++) { 11909 PreferredActivity pa = removed.get(r); 11910 Slog.w(TAG, "Removing dangling preferred activity: " 11911 + pa.mPref.mComponent); 11912 pir.removeFilter(pa); 11913 } 11914 mSettings.writePackageRestrictionsLPr( 11915 mSettings.mPreferredActivities.keyAt(i)); 11916 } 11917 } 11918 } 11919 sUserManager.systemReady(); 11920 11921 // Kick off any messages waiting for system ready 11922 if (mPostSystemReadyMessages != null) { 11923 for (Message msg : mPostSystemReadyMessages) { 11924 msg.sendToTarget(); 11925 } 11926 mPostSystemReadyMessages = null; 11927 } 11928 } 11929 11930 @Override 11931 public boolean isSafeMode() { 11932 return mSafeMode; 11933 } 11934 11935 @Override 11936 public boolean hasSystemUidErrors() { 11937 return mHasSystemUidErrors; 11938 } 11939 11940 static String arrayToString(int[] array) { 11941 StringBuffer buf = new StringBuffer(128); 11942 buf.append('['); 11943 if (array != null) { 11944 for (int i=0; i<array.length; i++) { 11945 if (i > 0) buf.append(", "); 11946 buf.append(array[i]); 11947 } 11948 } 11949 buf.append(']'); 11950 return buf.toString(); 11951 } 11952 11953 static class DumpState { 11954 public static final int DUMP_LIBS = 1 << 0; 11955 public static final int DUMP_FEATURES = 1 << 1; 11956 public static final int DUMP_RESOLVERS = 1 << 2; 11957 public static final int DUMP_PERMISSIONS = 1 << 3; 11958 public static final int DUMP_PACKAGES = 1 << 4; 11959 public static final int DUMP_SHARED_USERS = 1 << 5; 11960 public static final int DUMP_MESSAGES = 1 << 6; 11961 public static final int DUMP_PROVIDERS = 1 << 7; 11962 public static final int DUMP_VERIFIERS = 1 << 8; 11963 public static final int DUMP_PREFERRED = 1 << 9; 11964 public static final int DUMP_PREFERRED_XML = 1 << 10; 11965 public static final int DUMP_KEYSETS = 1 << 11; 11966 public static final int DUMP_VERSION = 1 << 12; 11967 public static final int DUMP_INSTALLS = 1 << 13; 11968 11969 public static final int OPTION_SHOW_FILTERS = 1 << 0; 11970 11971 private int mTypes; 11972 11973 private int mOptions; 11974 11975 private boolean mTitlePrinted; 11976 11977 private SharedUserSetting mSharedUser; 11978 11979 public boolean isDumping(int type) { 11980 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 11981 return true; 11982 } 11983 11984 return (mTypes & type) != 0; 11985 } 11986 11987 public void setDump(int type) { 11988 mTypes |= type; 11989 } 11990 11991 public boolean isOptionEnabled(int option) { 11992 return (mOptions & option) != 0; 11993 } 11994 11995 public void setOptionEnabled(int option) { 11996 mOptions |= option; 11997 } 11998 11999 public boolean onTitlePrinted() { 12000 final boolean printed = mTitlePrinted; 12001 mTitlePrinted = true; 12002 return printed; 12003 } 12004 12005 public boolean getTitlePrinted() { 12006 return mTitlePrinted; 12007 } 12008 12009 public void setTitlePrinted(boolean enabled) { 12010 mTitlePrinted = enabled; 12011 } 12012 12013 public SharedUserSetting getSharedUser() { 12014 return mSharedUser; 12015 } 12016 12017 public void setSharedUser(SharedUserSetting user) { 12018 mSharedUser = user; 12019 } 12020 } 12021 12022 @Override 12023 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 12024 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 12025 != PackageManager.PERMISSION_GRANTED) { 12026 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 12027 + Binder.getCallingPid() 12028 + ", uid=" + Binder.getCallingUid() 12029 + " without permission " 12030 + android.Manifest.permission.DUMP); 12031 return; 12032 } 12033 12034 DumpState dumpState = new DumpState(); 12035 boolean fullPreferred = false; 12036 boolean checkin = false; 12037 12038 String packageName = null; 12039 12040 int opti = 0; 12041 while (opti < args.length) { 12042 String opt = args[opti]; 12043 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 12044 break; 12045 } 12046 opti++; 12047 if ("-a".equals(opt)) { 12048 // Right now we only know how to print all. 12049 } else if ("-h".equals(opt)) { 12050 pw.println("Package manager dump options:"); 12051 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 12052 pw.println(" --checkin: dump for a checkin"); 12053 pw.println(" -f: print details of intent filters"); 12054 pw.println(" -h: print this help"); 12055 pw.println(" cmd may be one of:"); 12056 pw.println(" l[ibraries]: list known shared libraries"); 12057 pw.println(" f[ibraries]: list device features"); 12058 pw.println(" k[eysets]: print known keysets"); 12059 pw.println(" r[esolvers]: dump intent resolvers"); 12060 pw.println(" perm[issions]: dump permissions"); 12061 pw.println(" pref[erred]: print preferred package settings"); 12062 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 12063 pw.println(" prov[iders]: dump content providers"); 12064 pw.println(" p[ackages]: dump installed packages"); 12065 pw.println(" s[hared-users]: dump shared user IDs"); 12066 pw.println(" m[essages]: print collected runtime messages"); 12067 pw.println(" v[erifiers]: print package verifier info"); 12068 pw.println(" version: print database version info"); 12069 pw.println(" write: write current settings now"); 12070 pw.println(" <package.name>: info about given package"); 12071 pw.println(" installs: details about install sessions"); 12072 return; 12073 } else if ("--checkin".equals(opt)) { 12074 checkin = true; 12075 } else if ("-f".equals(opt)) { 12076 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12077 } else { 12078 pw.println("Unknown argument: " + opt + "; use -h for help"); 12079 } 12080 } 12081 12082 // Is the caller requesting to dump a particular piece of data? 12083 if (opti < args.length) { 12084 String cmd = args[opti]; 12085 opti++; 12086 // Is this a package name? 12087 if ("android".equals(cmd) || cmd.contains(".")) { 12088 packageName = cmd; 12089 // When dumping a single package, we always dump all of its 12090 // filter information since the amount of data will be reasonable. 12091 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12092 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 12093 dumpState.setDump(DumpState.DUMP_LIBS); 12094 } else if ("f".equals(cmd) || "features".equals(cmd)) { 12095 dumpState.setDump(DumpState.DUMP_FEATURES); 12096 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 12097 dumpState.setDump(DumpState.DUMP_RESOLVERS); 12098 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 12099 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 12100 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 12101 dumpState.setDump(DumpState.DUMP_PREFERRED); 12102 } else if ("preferred-xml".equals(cmd)) { 12103 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 12104 if (opti < args.length && "--full".equals(args[opti])) { 12105 fullPreferred = true; 12106 opti++; 12107 } 12108 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 12109 dumpState.setDump(DumpState.DUMP_PACKAGES); 12110 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 12111 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 12112 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 12113 dumpState.setDump(DumpState.DUMP_PROVIDERS); 12114 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 12115 dumpState.setDump(DumpState.DUMP_MESSAGES); 12116 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 12117 dumpState.setDump(DumpState.DUMP_VERIFIERS); 12118 } else if ("version".equals(cmd)) { 12119 dumpState.setDump(DumpState.DUMP_VERSION); 12120 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 12121 dumpState.setDump(DumpState.DUMP_KEYSETS); 12122 } else if ("write".equals(cmd)) { 12123 synchronized (mPackages) { 12124 mSettings.writeLPr(); 12125 pw.println("Settings written."); 12126 return; 12127 } 12128 } else if ("installs".equals(cmd)) { 12129 dumpState.setDump(DumpState.DUMP_INSTALLS); 12130 } 12131 } 12132 12133 if (checkin) { 12134 pw.println("vers,1"); 12135 } 12136 12137 // reader 12138 synchronized (mPackages) { 12139 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 12140 if (!checkin) { 12141 if (dumpState.onTitlePrinted()) 12142 pw.println(); 12143 pw.println("Database versions:"); 12144 pw.print(" SDK Version:"); 12145 pw.print(" internal="); 12146 pw.print(mSettings.mInternalSdkPlatform); 12147 pw.print(" external="); 12148 pw.println(mSettings.mExternalSdkPlatform); 12149 pw.print(" DB Version:"); 12150 pw.print(" internal="); 12151 pw.print(mSettings.mInternalDatabaseVersion); 12152 pw.print(" external="); 12153 pw.println(mSettings.mExternalDatabaseVersion); 12154 } 12155 } 12156 12157 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 12158 if (!checkin) { 12159 if (dumpState.onTitlePrinted()) 12160 pw.println(); 12161 pw.println("Verifiers:"); 12162 pw.print(" Required: "); 12163 pw.print(mRequiredVerifierPackage); 12164 pw.print(" (uid="); 12165 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 12166 pw.println(")"); 12167 } else if (mRequiredVerifierPackage != null) { 12168 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 12169 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 12170 } 12171 } 12172 12173 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 12174 boolean printedHeader = false; 12175 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 12176 while (it.hasNext()) { 12177 String name = it.next(); 12178 SharedLibraryEntry ent = mSharedLibraries.get(name); 12179 if (!checkin) { 12180 if (!printedHeader) { 12181 if (dumpState.onTitlePrinted()) 12182 pw.println(); 12183 pw.println("Libraries:"); 12184 printedHeader = true; 12185 } 12186 pw.print(" "); 12187 } else { 12188 pw.print("lib,"); 12189 } 12190 pw.print(name); 12191 if (!checkin) { 12192 pw.print(" -> "); 12193 } 12194 if (ent.path != null) { 12195 if (!checkin) { 12196 pw.print("(jar) "); 12197 pw.print(ent.path); 12198 } else { 12199 pw.print(",jar,"); 12200 pw.print(ent.path); 12201 } 12202 } else { 12203 if (!checkin) { 12204 pw.print("(apk) "); 12205 pw.print(ent.apk); 12206 } else { 12207 pw.print(",apk,"); 12208 pw.print(ent.apk); 12209 } 12210 } 12211 pw.println(); 12212 } 12213 } 12214 12215 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 12216 if (dumpState.onTitlePrinted()) 12217 pw.println(); 12218 if (!checkin) { 12219 pw.println("Features:"); 12220 } 12221 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 12222 while (it.hasNext()) { 12223 String name = it.next(); 12224 if (!checkin) { 12225 pw.print(" "); 12226 } else { 12227 pw.print("feat,"); 12228 } 12229 pw.println(name); 12230 } 12231 } 12232 12233 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 12234 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 12235 : "Activity Resolver Table:", " ", packageName, 12236 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12237 dumpState.setTitlePrinted(true); 12238 } 12239 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 12240 : "Receiver Resolver Table:", " ", packageName, 12241 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12242 dumpState.setTitlePrinted(true); 12243 } 12244 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 12245 : "Service Resolver Table:", " ", packageName, 12246 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12247 dumpState.setTitlePrinted(true); 12248 } 12249 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 12250 : "Provider Resolver Table:", " ", packageName, 12251 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12252 dumpState.setTitlePrinted(true); 12253 } 12254 } 12255 12256 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 12257 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12258 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12259 int user = mSettings.mPreferredActivities.keyAt(i); 12260 if (pir.dump(pw, 12261 dumpState.getTitlePrinted() 12262 ? "\nPreferred Activities User " + user + ":" 12263 : "Preferred Activities User " + user + ":", " ", 12264 packageName, true)) { 12265 dumpState.setTitlePrinted(true); 12266 } 12267 } 12268 } 12269 12270 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 12271 pw.flush(); 12272 FileOutputStream fout = new FileOutputStream(fd); 12273 BufferedOutputStream str = new BufferedOutputStream(fout); 12274 XmlSerializer serializer = new FastXmlSerializer(); 12275 try { 12276 serializer.setOutput(str, "utf-8"); 12277 serializer.startDocument(null, true); 12278 serializer.setFeature( 12279 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 12280 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 12281 serializer.endDocument(); 12282 serializer.flush(); 12283 } catch (IllegalArgumentException e) { 12284 pw.println("Failed writing: " + e); 12285 } catch (IllegalStateException e) { 12286 pw.println("Failed writing: " + e); 12287 } catch (IOException e) { 12288 pw.println("Failed writing: " + e); 12289 } 12290 } 12291 12292 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 12293 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 12294 if (packageName == null) { 12295 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 12296 if (iperm == 0) { 12297 if (dumpState.onTitlePrinted()) 12298 pw.println(); 12299 pw.println("AppOp Permissions:"); 12300 } 12301 pw.print(" AppOp Permission "); 12302 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 12303 pw.println(":"); 12304 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 12305 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 12306 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 12307 } 12308 } 12309 } 12310 } 12311 12312 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 12313 boolean printedSomething = false; 12314 for (PackageParser.Provider p : mProviders.mProviders.values()) { 12315 if (packageName != null && !packageName.equals(p.info.packageName)) { 12316 continue; 12317 } 12318 if (!printedSomething) { 12319 if (dumpState.onTitlePrinted()) 12320 pw.println(); 12321 pw.println("Registered ContentProviders:"); 12322 printedSomething = true; 12323 } 12324 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 12325 pw.print(" "); pw.println(p.toString()); 12326 } 12327 printedSomething = false; 12328 for (Map.Entry<String, PackageParser.Provider> entry : 12329 mProvidersByAuthority.entrySet()) { 12330 PackageParser.Provider p = entry.getValue(); 12331 if (packageName != null && !packageName.equals(p.info.packageName)) { 12332 continue; 12333 } 12334 if (!printedSomething) { 12335 if (dumpState.onTitlePrinted()) 12336 pw.println(); 12337 pw.println("ContentProvider Authorities:"); 12338 printedSomething = true; 12339 } 12340 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 12341 pw.print(" "); pw.println(p.toString()); 12342 if (p.info != null && p.info.applicationInfo != null) { 12343 final String appInfo = p.info.applicationInfo.toString(); 12344 pw.print(" applicationInfo="); pw.println(appInfo); 12345 } 12346 } 12347 } 12348 12349 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 12350 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 12351 } 12352 12353 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 12354 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 12355 } 12356 12357 if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 12358 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState); 12359 } 12360 12361 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS)) { 12362 if (dumpState.onTitlePrinted()) pw.println(); 12363 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 12364 } 12365 12366 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 12367 if (dumpState.onTitlePrinted()) pw.println(); 12368 mSettings.dumpReadMessagesLPr(pw, dumpState); 12369 12370 pw.println(); 12371 pw.println("Package warning messages:"); 12372 final File fname = getSettingsProblemFile(); 12373 FileInputStream in = null; 12374 try { 12375 in = new FileInputStream(fname); 12376 final int avail = in.available(); 12377 final byte[] data = new byte[avail]; 12378 in.read(data); 12379 pw.print(new String(data)); 12380 } catch (FileNotFoundException e) { 12381 } catch (IOException e) { 12382 } finally { 12383 if (in != null) { 12384 try { 12385 in.close(); 12386 } catch (IOException e) { 12387 } 12388 } 12389 } 12390 } 12391 } 12392 } 12393 12394 // ------- apps on sdcard specific code ------- 12395 static final boolean DEBUG_SD_INSTALL = false; 12396 12397 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 12398 12399 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 12400 12401 private boolean mMediaMounted = false; 12402 12403 static String getEncryptKey() { 12404 try { 12405 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 12406 SD_ENCRYPTION_KEYSTORE_NAME); 12407 if (sdEncKey == null) { 12408 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 12409 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 12410 if (sdEncKey == null) { 12411 Slog.e(TAG, "Failed to create encryption keys"); 12412 return null; 12413 } 12414 } 12415 return sdEncKey; 12416 } catch (NoSuchAlgorithmException nsae) { 12417 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 12418 return null; 12419 } catch (IOException ioe) { 12420 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 12421 return null; 12422 } 12423 } 12424 12425 /* 12426 * Update media status on PackageManager. 12427 */ 12428 @Override 12429 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 12430 int callingUid = Binder.getCallingUid(); 12431 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 12432 throw new SecurityException("Media status can only be updated by the system"); 12433 } 12434 // reader; this apparently protects mMediaMounted, but should probably 12435 // be a different lock in that case. 12436 synchronized (mPackages) { 12437 Log.i(TAG, "Updating external media status from " 12438 + (mMediaMounted ? "mounted" : "unmounted") + " to " 12439 + (mediaStatus ? "mounted" : "unmounted")); 12440 if (DEBUG_SD_INSTALL) 12441 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 12442 + ", mMediaMounted=" + mMediaMounted); 12443 if (mediaStatus == mMediaMounted) { 12444 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 12445 : 0, -1); 12446 mHandler.sendMessage(msg); 12447 return; 12448 } 12449 mMediaMounted = mediaStatus; 12450 } 12451 // Queue up an async operation since the package installation may take a 12452 // little while. 12453 mHandler.post(new Runnable() { 12454 public void run() { 12455 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 12456 } 12457 }); 12458 } 12459 12460 /** 12461 * Called by MountService when the initial ASECs to scan are available. 12462 * Should block until all the ASEC containers are finished being scanned. 12463 */ 12464 public void scanAvailableAsecs() { 12465 updateExternalMediaStatusInner(true, false, false); 12466 if (mShouldRestoreconData) { 12467 SELinuxMMAC.setRestoreconDone(); 12468 mShouldRestoreconData = false; 12469 } 12470 } 12471 12472 /* 12473 * Collect information of applications on external media, map them against 12474 * existing containers and update information based on current mount status. 12475 * Please note that we always have to report status if reportStatus has been 12476 * set to true especially when unloading packages. 12477 */ 12478 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 12479 boolean externalStorage) { 12480 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 12481 int[] uidArr = EmptyArray.INT; 12482 12483 final String[] list = PackageHelper.getSecureContainerList(); 12484 if (ArrayUtils.isEmpty(list)) { 12485 Log.i(TAG, "No secure containers found"); 12486 } else { 12487 // Process list of secure containers and categorize them 12488 // as active or stale based on their package internal state. 12489 12490 // reader 12491 synchronized (mPackages) { 12492 for (String cid : list) { 12493 // Leave stages untouched for now; installer service owns them 12494 if (PackageInstallerService.isStageName(cid)) continue; 12495 12496 if (DEBUG_SD_INSTALL) 12497 Log.i(TAG, "Processing container " + cid); 12498 String pkgName = getAsecPackageName(cid); 12499 if (pkgName == null) { 12500 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 12501 continue; 12502 } 12503 if (DEBUG_SD_INSTALL) 12504 Log.i(TAG, "Looking for pkg : " + pkgName); 12505 12506 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12507 if (ps == null) { 12508 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 12509 continue; 12510 } 12511 12512 /* 12513 * Skip packages that are not external if we're unmounting 12514 * external storage. 12515 */ 12516 if (externalStorage && !isMounted && !isExternal(ps)) { 12517 continue; 12518 } 12519 12520 final AsecInstallArgs args = new AsecInstallArgs(cid, 12521 getAppDexInstructionSets(ps), isForwardLocked(ps)); 12522 // The package status is changed only if the code path 12523 // matches between settings and the container id. 12524 if (ps.codePathString != null 12525 && ps.codePathString.startsWith(args.getCodePath())) { 12526 if (DEBUG_SD_INSTALL) { 12527 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 12528 + " at code path: " + ps.codePathString); 12529 } 12530 12531 // We do have a valid package installed on sdcard 12532 processCids.put(args, ps.codePathString); 12533 final int uid = ps.appId; 12534 if (uid != -1) { 12535 uidArr = ArrayUtils.appendInt(uidArr, uid); 12536 } 12537 } else { 12538 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 12539 + ps.codePathString); 12540 } 12541 } 12542 } 12543 12544 Arrays.sort(uidArr); 12545 } 12546 12547 // Process packages with valid entries. 12548 if (isMounted) { 12549 if (DEBUG_SD_INSTALL) 12550 Log.i(TAG, "Loading packages"); 12551 loadMediaPackages(processCids, uidArr); 12552 startCleaningPackages(); 12553 mInstallerService.onSecureContainersAvailable(); 12554 } else { 12555 if (DEBUG_SD_INSTALL) 12556 Log.i(TAG, "Unloading packages"); 12557 unloadMediaPackages(processCids, uidArr, reportStatus); 12558 } 12559 } 12560 12561 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 12562 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 12563 int size = pkgList.size(); 12564 if (size > 0) { 12565 // Send broadcasts here 12566 Bundle extras = new Bundle(); 12567 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 12568 .toArray(new String[size])); 12569 if (uidArr != null) { 12570 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 12571 } 12572 if (replacing) { 12573 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 12574 } 12575 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 12576 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 12577 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 12578 } 12579 } 12580 12581 /* 12582 * Look at potentially valid container ids from processCids If package 12583 * information doesn't match the one on record or package scanning fails, 12584 * the cid is added to list of removeCids. We currently don't delete stale 12585 * containers. 12586 */ 12587 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 12588 ArrayList<String> pkgList = new ArrayList<String>(); 12589 Set<AsecInstallArgs> keys = processCids.keySet(); 12590 12591 for (AsecInstallArgs args : keys) { 12592 String codePath = processCids.get(args); 12593 if (DEBUG_SD_INSTALL) 12594 Log.i(TAG, "Loading container : " + args.cid); 12595 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12596 try { 12597 // Make sure there are no container errors first. 12598 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 12599 Slog.e(TAG, "Failed to mount cid : " + args.cid 12600 + " when installing from sdcard"); 12601 continue; 12602 } 12603 // Check code path here. 12604 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 12605 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 12606 + " does not match one in settings " + codePath); 12607 continue; 12608 } 12609 // Parse package 12610 int parseFlags = mDefParseFlags; 12611 if (args.isExternal()) { 12612 parseFlags |= PackageParser.PARSE_ON_SDCARD; 12613 } 12614 if (args.isFwdLocked()) { 12615 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 12616 } 12617 12618 synchronized (mInstallLock) { 12619 PackageParser.Package pkg = null; 12620 try { 12621 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 12622 } catch (PackageManagerException e) { 12623 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 12624 } 12625 // Scan the package 12626 if (pkg != null) { 12627 /* 12628 * TODO why is the lock being held? doPostInstall is 12629 * called in other places without the lock. This needs 12630 * to be straightened out. 12631 */ 12632 // writer 12633 synchronized (mPackages) { 12634 retCode = PackageManager.INSTALL_SUCCEEDED; 12635 pkgList.add(pkg.packageName); 12636 // Post process args 12637 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 12638 pkg.applicationInfo.uid); 12639 } 12640 } else { 12641 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 12642 } 12643 } 12644 12645 } finally { 12646 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 12647 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 12648 } 12649 } 12650 } 12651 // writer 12652 synchronized (mPackages) { 12653 // If the platform SDK has changed since the last time we booted, 12654 // we need to re-grant app permission to catch any new ones that 12655 // appear. This is really a hack, and means that apps can in some 12656 // cases get permissions that the user didn't initially explicitly 12657 // allow... it would be nice to have some better way to handle 12658 // this situation. 12659 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 12660 if (regrantPermissions) 12661 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 12662 + mSdkVersion + "; regranting permissions for external storage"); 12663 mSettings.mExternalSdkPlatform = mSdkVersion; 12664 12665 // Make sure group IDs have been assigned, and any permission 12666 // changes in other apps are accounted for 12667 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 12668 | (regrantPermissions 12669 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 12670 : 0)); 12671 12672 mSettings.updateExternalDatabaseVersion(); 12673 12674 // can downgrade to reader 12675 // Persist settings 12676 mSettings.writeLPr(); 12677 } 12678 // Send a broadcast to let everyone know we are done processing 12679 if (pkgList.size() > 0) { 12680 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12681 } 12682 } 12683 12684 /* 12685 * Utility method to unload a list of specified containers 12686 */ 12687 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 12688 // Just unmount all valid containers. 12689 for (AsecInstallArgs arg : cidArgs) { 12690 synchronized (mInstallLock) { 12691 arg.doPostDeleteLI(false); 12692 } 12693 } 12694 } 12695 12696 /* 12697 * Unload packages mounted on external media. This involves deleting package 12698 * data from internal structures, sending broadcasts about diabled packages, 12699 * gc'ing to free up references, unmounting all secure containers 12700 * corresponding to packages on external media, and posting a 12701 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 12702 * that we always have to post this message if status has been requested no 12703 * matter what. 12704 */ 12705 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 12706 final boolean reportStatus) { 12707 if (DEBUG_SD_INSTALL) 12708 Log.i(TAG, "unloading media packages"); 12709 ArrayList<String> pkgList = new ArrayList<String>(); 12710 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 12711 final Set<AsecInstallArgs> keys = processCids.keySet(); 12712 for (AsecInstallArgs args : keys) { 12713 String pkgName = args.getPackageName(); 12714 if (DEBUG_SD_INSTALL) 12715 Log.i(TAG, "Trying to unload pkg : " + pkgName); 12716 // Delete package internally 12717 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 12718 synchronized (mInstallLock) { 12719 boolean res = deletePackageLI(pkgName, null, false, null, null, 12720 PackageManager.DELETE_KEEP_DATA, outInfo, false); 12721 if (res) { 12722 pkgList.add(pkgName); 12723 } else { 12724 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 12725 failedList.add(args); 12726 } 12727 } 12728 } 12729 12730 // reader 12731 synchronized (mPackages) { 12732 // We didn't update the settings after removing each package; 12733 // write them now for all packages. 12734 mSettings.writeLPr(); 12735 } 12736 12737 // We have to absolutely send UPDATED_MEDIA_STATUS only 12738 // after confirming that all the receivers processed the ordered 12739 // broadcast when packages get disabled, force a gc to clean things up. 12740 // and unload all the containers. 12741 if (pkgList.size() > 0) { 12742 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 12743 new IIntentReceiver.Stub() { 12744 public void performReceive(Intent intent, int resultCode, String data, 12745 Bundle extras, boolean ordered, boolean sticky, 12746 int sendingUser) throws RemoteException { 12747 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 12748 reportStatus ? 1 : 0, 1, keys); 12749 mHandler.sendMessage(msg); 12750 } 12751 }); 12752 } else { 12753 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 12754 keys); 12755 mHandler.sendMessage(msg); 12756 } 12757 } 12758 12759 /** Binder call */ 12760 @Override 12761 public void movePackage(final String packageName, final IPackageMoveObserver observer, 12762 final int flags) { 12763 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 12764 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 12765 int returnCode = PackageManager.MOVE_SUCCEEDED; 12766 int currInstallFlags = 0; 12767 int newInstallFlags = 0; 12768 12769 File codeFile = null; 12770 String installerPackageName = null; 12771 String packageAbiOverride = null; 12772 12773 // reader 12774 synchronized (mPackages) { 12775 final PackageParser.Package pkg = mPackages.get(packageName); 12776 final PackageSetting ps = mSettings.mPackages.get(packageName); 12777 if (pkg == null || ps == null) { 12778 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12779 } else { 12780 // Disable moving fwd locked apps and system packages 12781 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 12782 Slog.w(TAG, "Cannot move system application"); 12783 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 12784 } else if (pkg.mOperationPending) { 12785 Slog.w(TAG, "Attempt to move package which has pending operations"); 12786 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 12787 } else { 12788 // Find install location first 12789 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 12790 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 12791 Slog.w(TAG, "Ambigous flags specified for move location."); 12792 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12793 } else { 12794 newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 12795 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 12796 currInstallFlags = isExternal(pkg) 12797 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 12798 12799 if (newInstallFlags == currInstallFlags) { 12800 Slog.w(TAG, "No move required. Trying to move to same location"); 12801 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12802 } else { 12803 if (isForwardLocked(pkg)) { 12804 currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12805 newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12806 } 12807 } 12808 } 12809 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12810 pkg.mOperationPending = true; 12811 } 12812 } 12813 12814 codeFile = new File(pkg.codePath); 12815 installerPackageName = ps.installerPackageName; 12816 packageAbiOverride = ps.cpuAbiOverrideString; 12817 } 12818 } 12819 12820 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 12821 try { 12822 observer.packageMoved(packageName, returnCode); 12823 } catch (RemoteException ignored) { 12824 } 12825 return; 12826 } 12827 12828 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 12829 @Override 12830 public void onUserActionRequired(Intent intent) throws RemoteException { 12831 throw new IllegalStateException(); 12832 } 12833 12834 @Override 12835 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 12836 Bundle extras) throws RemoteException { 12837 Slog.d(TAG, "Install result for move: " 12838 + PackageManager.installStatusToString(returnCode, msg)); 12839 12840 // We usually have a new package now after the install, but if 12841 // we failed we need to clear the pending flag on the original 12842 // package object. 12843 synchronized (mPackages) { 12844 final PackageParser.Package pkg = mPackages.get(packageName); 12845 if (pkg != null) { 12846 pkg.mOperationPending = false; 12847 } 12848 } 12849 12850 final int status = PackageManager.installStatusToPublicStatus(returnCode); 12851 switch (status) { 12852 case PackageInstaller.STATUS_SUCCESS: 12853 observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED); 12854 break; 12855 case PackageInstaller.STATUS_FAILURE_STORAGE: 12856 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 12857 break; 12858 default: 12859 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR); 12860 break; 12861 } 12862 } 12863 }; 12864 12865 // Treat a move like reinstalling an existing app, which ensures that we 12866 // process everythign uniformly, like unpacking native libraries. 12867 newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 12868 12869 final Message msg = mHandler.obtainMessage(INIT_COPY); 12870 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 12871 msg.obj = new InstallParams(origin, installObserver, newInstallFlags, 12872 installerPackageName, null, user, packageAbiOverride); 12873 mHandler.sendMessage(msg); 12874 } 12875 12876 @Override 12877 public boolean setInstallLocation(int loc) { 12878 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 12879 null); 12880 if (getInstallLocation() == loc) { 12881 return true; 12882 } 12883 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 12884 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 12885 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 12886 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 12887 return true; 12888 } 12889 return false; 12890 } 12891 12892 @Override 12893 public int getInstallLocation() { 12894 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12895 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 12896 PackageHelper.APP_INSTALL_AUTO); 12897 } 12898 12899 /** Called by UserManagerService */ 12900 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 12901 mDirtyUsers.remove(userHandle); 12902 mSettings.removeUserLPw(userHandle); 12903 mPendingBroadcasts.remove(userHandle); 12904 if (mInstaller != null) { 12905 // Technically, we shouldn't be doing this with the package lock 12906 // held. However, this is very rare, and there is already so much 12907 // other disk I/O going on, that we'll let it slide for now. 12908 mInstaller.removeUserDataDirs(userHandle); 12909 } 12910 mUserNeedsBadging.delete(userHandle); 12911 removeUnusedPackagesLILPw(userManager, userHandle); 12912 } 12913 12914 /** 12915 * We're removing userHandle and would like to remove any downloaded packages 12916 * that are no longer in use by any other user. 12917 * @param userHandle the user being removed 12918 */ 12919 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 12920 final boolean DEBUG_CLEAN_APKS = false; 12921 int [] users = userManager.getUserIdsLPr(); 12922 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 12923 while (psit.hasNext()) { 12924 PackageSetting ps = psit.next(); 12925 if (ps.pkg == null) { 12926 continue; 12927 } 12928 final String packageName = ps.pkg.packageName; 12929 // Skip over if system app 12930 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12931 continue; 12932 } 12933 if (DEBUG_CLEAN_APKS) { 12934 Slog.i(TAG, "Checking package " + packageName); 12935 } 12936 boolean keep = false; 12937 for (int i = 0; i < users.length; i++) { 12938 if (users[i] != userHandle && ps.getInstalled(users[i])) { 12939 keep = true; 12940 if (DEBUG_CLEAN_APKS) { 12941 Slog.i(TAG, " Keeping package " + packageName + " for user " 12942 + users[i]); 12943 } 12944 break; 12945 } 12946 } 12947 if (!keep) { 12948 if (DEBUG_CLEAN_APKS) { 12949 Slog.i(TAG, " Removing package " + packageName); 12950 } 12951 mHandler.post(new Runnable() { 12952 public void run() { 12953 deletePackageX(packageName, userHandle, 0); 12954 } //end run 12955 }); 12956 } 12957 } 12958 } 12959 12960 /** Called by UserManagerService */ 12961 void createNewUserLILPw(int userHandle, File path) { 12962 if (mInstaller != null) { 12963 mInstaller.createUserConfig(userHandle); 12964 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 12965 } 12966 } 12967 12968 @Override 12969 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 12970 mContext.enforceCallingOrSelfPermission( 12971 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12972 "Only package verification agents can read the verifier device identity"); 12973 12974 synchronized (mPackages) { 12975 return mSettings.getVerifierDeviceIdentityLPw(); 12976 } 12977 } 12978 12979 @Override 12980 public void setPermissionEnforced(String permission, boolean enforced) { 12981 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 12982 if (READ_EXTERNAL_STORAGE.equals(permission)) { 12983 synchronized (mPackages) { 12984 if (mSettings.mReadExternalStorageEnforced == null 12985 || mSettings.mReadExternalStorageEnforced != enforced) { 12986 mSettings.mReadExternalStorageEnforced = enforced; 12987 mSettings.writeLPr(); 12988 } 12989 } 12990 // kill any non-foreground processes so we restart them and 12991 // grant/revoke the GID. 12992 final IActivityManager am = ActivityManagerNative.getDefault(); 12993 if (am != null) { 12994 final long token = Binder.clearCallingIdentity(); 12995 try { 12996 am.killProcessesBelowForeground("setPermissionEnforcement"); 12997 } catch (RemoteException e) { 12998 } finally { 12999 Binder.restoreCallingIdentity(token); 13000 } 13001 } 13002 } else { 13003 throw new IllegalArgumentException("No selective enforcement for " + permission); 13004 } 13005 } 13006 13007 @Override 13008 @Deprecated 13009 public boolean isPermissionEnforced(String permission) { 13010 return true; 13011 } 13012 13013 @Override 13014 public boolean isStorageLow() { 13015 final long token = Binder.clearCallingIdentity(); 13016 try { 13017 final DeviceStorageMonitorInternal 13018 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13019 if (dsm != null) { 13020 return dsm.isMemoryLow(); 13021 } else { 13022 return false; 13023 } 13024 } finally { 13025 Binder.restoreCallingIdentity(token); 13026 } 13027 } 13028 13029 @Override 13030 public IPackageInstaller getPackageInstaller() { 13031 return mInstallerService; 13032 } 13033 13034 private boolean userNeedsBadging(int userId) { 13035 int index = mUserNeedsBadging.indexOfKey(userId); 13036 if (index < 0) { 13037 final UserInfo userInfo; 13038 final long token = Binder.clearCallingIdentity(); 13039 try { 13040 userInfo = sUserManager.getUserInfo(userId); 13041 } finally { 13042 Binder.restoreCallingIdentity(token); 13043 } 13044 final boolean b; 13045 if (userInfo != null && userInfo.isManagedProfile()) { 13046 b = true; 13047 } else { 13048 b = false; 13049 } 13050 mUserNeedsBadging.put(userId, b); 13051 return b; 13052 } 13053 return mUserNeedsBadging.valueAt(index); 13054 } 13055 13056 @Override 13057 public KeySet getKeySetByAlias(String packageName, String alias) { 13058 if (packageName == null || alias == null) { 13059 return null; 13060 } 13061 synchronized(mPackages) { 13062 final PackageParser.Package pkg = mPackages.get(packageName); 13063 if (pkg == null) { 13064 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13065 throw new IllegalArgumentException("Unknown package: " + packageName); 13066 } 13067 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13068 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 13069 } 13070 } 13071 13072 @Override 13073 public KeySet getSigningKeySet(String packageName) { 13074 if (packageName == null) { 13075 return null; 13076 } 13077 synchronized(mPackages) { 13078 final PackageParser.Package pkg = mPackages.get(packageName); 13079 if (pkg == null) { 13080 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13081 throw new IllegalArgumentException("Unknown package: " + packageName); 13082 } 13083 if (pkg.applicationInfo.uid != Binder.getCallingUid() 13084 && Process.SYSTEM_UID != Binder.getCallingUid()) { 13085 throw new SecurityException("May not access signing KeySet of other apps."); 13086 } 13087 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13088 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 13089 } 13090 } 13091 13092 @Override 13093 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 13094 if (packageName == null || ks == null) { 13095 return false; 13096 } 13097 synchronized(mPackages) { 13098 final PackageParser.Package pkg = mPackages.get(packageName); 13099 if (pkg == null) { 13100 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13101 throw new IllegalArgumentException("Unknown package: " + packageName); 13102 } 13103 IBinder ksh = ks.getToken(); 13104 if (ksh instanceof KeySetHandle) { 13105 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13106 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 13107 } 13108 return false; 13109 } 13110 } 13111 13112 @Override 13113 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 13114 if (packageName == null || ks == null) { 13115 return false; 13116 } 13117 synchronized(mPackages) { 13118 final PackageParser.Package pkg = mPackages.get(packageName); 13119 if (pkg == null) { 13120 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13121 throw new IllegalArgumentException("Unknown package: " + packageName); 13122 } 13123 IBinder ksh = ks.getToken(); 13124 if (ksh instanceof KeySetHandle) { 13125 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13126 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 13127 } 13128 return false; 13129 } 13130 } 13131} 13132