PackageManagerService.java revision 3933a5dc8c8c04458c5b8c01919d7449c6d00497
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.Objects; 205import java.util.Set; 206import java.util.concurrent.atomic.AtomicBoolean; 207import java.util.concurrent.atomic.AtomicLong; 208 209import dalvik.system.DexFile; 210import dalvik.system.StaleDexCacheError; 211import dalvik.system.VMRuntime; 212 213import libcore.io.IoUtils; 214import libcore.util.EmptyArray; 215 216/** 217 * Keep track of all those .apks everywhere. 218 * 219 * This is very central to the platform's security; please run the unit 220 * tests whenever making modifications here: 221 * 222mmm frameworks/base/tests/AndroidTests 223adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 224adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 225 * 226 * {@hide} 227 */ 228public class PackageManagerService extends IPackageManager.Stub { 229 static final String TAG = "PackageManager"; 230 static final boolean DEBUG_SETTINGS = false; 231 static final boolean DEBUG_PREFERRED = false; 232 static final boolean DEBUG_UPGRADE = false; 233 private static final boolean DEBUG_INSTALL = false; 234 private static final boolean DEBUG_REMOVE = false; 235 private static final boolean DEBUG_BROADCASTS = false; 236 private static final boolean DEBUG_SHOW_INFO = false; 237 private static final boolean DEBUG_PACKAGE_INFO = false; 238 private static final boolean DEBUG_INTENT_MATCHING = false; 239 private static final boolean DEBUG_PACKAGE_SCANNING = false; 240 private static final boolean DEBUG_VERIFY = false; 241 private static final boolean DEBUG_DEXOPT = false; 242 private static final boolean DEBUG_ABI_SELECTION = false; 243 244 private static final int RADIO_UID = Process.PHONE_UID; 245 private static final int LOG_UID = Process.LOG_UID; 246 private static final int NFC_UID = Process.NFC_UID; 247 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 248 private static final int SHELL_UID = Process.SHELL_UID; 249 250 // Cap the size of permission trees that 3rd party apps can define 251 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 252 253 // Suffix used during package installation when copying/moving 254 // package apks to install directory. 255 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 256 257 static final int SCAN_NO_DEX = 1<<1; 258 static final int SCAN_FORCE_DEX = 1<<2; 259 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 260 static final int SCAN_NEW_INSTALL = 1<<4; 261 static final int SCAN_NO_PATHS = 1<<5; 262 static final int SCAN_UPDATE_TIME = 1<<6; 263 static final int SCAN_DEFER_DEX = 1<<7; 264 static final int SCAN_BOOTING = 1<<8; 265 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 266 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 267 static final int SCAN_REPLACING = 1<<11; 268 269 static final int REMOVE_CHATTY = 1<<16; 270 271 /** 272 * Timeout (in milliseconds) after which the watchdog should declare that 273 * our handler thread is wedged. The usual default for such things is one 274 * minute but we sometimes do very lengthy I/O operations on this thread, 275 * such as installing multi-gigabyte applications, so ours needs to be longer. 276 */ 277 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 278 279 /** 280 * Whether verification is enabled by default. 281 */ 282 private static final boolean DEFAULT_VERIFY_ENABLE = true; 283 284 /** 285 * The default maximum time to wait for the verification agent to return in 286 * milliseconds. 287 */ 288 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 289 290 /** 291 * The default response for package verification timeout. 292 * 293 * This can be either PackageManager.VERIFICATION_ALLOW or 294 * PackageManager.VERIFICATION_REJECT. 295 */ 296 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 297 298 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 299 300 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 301 DEFAULT_CONTAINER_PACKAGE, 302 "com.android.defcontainer.DefaultContainerService"); 303 304 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 305 306 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 307 308 private static String sPreferredInstructionSet; 309 310 final ServiceThread mHandlerThread; 311 312 private static final String IDMAP_PREFIX = "/data/resource-cache/"; 313 private static final String IDMAP_SUFFIX = "@idmap"; 314 315 final PackageHandler mHandler; 316 317 /** 318 * Messages for {@link #mHandler} that need to wait for system ready before 319 * being dispatched. 320 */ 321 private ArrayList<Message> mPostSystemReadyMessages; 322 323 final int mSdkVersion = Build.VERSION.SDK_INT; 324 325 final Context mContext; 326 final boolean mFactoryTest; 327 final boolean mOnlyCore; 328 final boolean mLazyDexOpt; 329 final DisplayMetrics mMetrics; 330 final int mDefParseFlags; 331 final String[] mSeparateProcesses; 332 333 // This is where all application persistent data goes. 334 final File mAppDataDir; 335 336 // This is where all application persistent data goes for secondary users. 337 final File mUserAppDataDir; 338 339 /** The location for ASEC container files on internal storage. */ 340 final String mAsecInternalPath; 341 342 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 343 // LOCK HELD. Can be called with mInstallLock held. 344 final Installer mInstaller; 345 346 /** Directory where installed third-party apps stored */ 347 final File mAppInstallDir; 348 349 /** 350 * Directory to which applications installed internally have their 351 * 32 bit native libraries copied. 352 */ 353 private File mAppLib32InstallDir; 354 355 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 356 // apps. 357 final File mDrmAppPrivateInstallDir; 358 359 // ---------------------------------------------------------------- 360 361 // Lock for state used when installing and doing other long running 362 // operations. Methods that must be called with this lock held have 363 // the suffix "LI". 364 final Object mInstallLock = new Object(); 365 366 // ---------------------------------------------------------------- 367 368 // Keys are String (package name), values are Package. This also serves 369 // as the lock for the global state. Methods that must be called with 370 // this lock held have the prefix "LP". 371 final HashMap<String, PackageParser.Package> mPackages = 372 new HashMap<String, PackageParser.Package>(); 373 374 // Tracks available target package names -> overlay package paths. 375 final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays = 376 new HashMap<String, HashMap<String, PackageParser.Package>>(); 377 378 final Settings mSettings; 379 boolean mRestoredSettings; 380 381 // System configuration read by SystemConfig. 382 final int[] mGlobalGids; 383 final SparseArray<HashSet<String>> mSystemPermissions; 384 final HashMap<String, FeatureInfo> mAvailableFeatures; 385 386 // If mac_permissions.xml was found for seinfo labeling. 387 boolean mFoundPolicyFile; 388 389 // If a recursive restorecon of /data/data/<pkg> is needed. 390 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 391 392 public static final class SharedLibraryEntry { 393 public final String path; 394 public final String apk; 395 396 SharedLibraryEntry(String _path, String _apk) { 397 path = _path; 398 apk = _apk; 399 } 400 } 401 402 // Currently known shared libraries. 403 final HashMap<String, SharedLibraryEntry> mSharedLibraries = 404 new HashMap<String, SharedLibraryEntry>(); 405 406 // All available activities, for your resolving pleasure. 407 final ActivityIntentResolver mActivities = 408 new ActivityIntentResolver(); 409 410 // All available receivers, for your resolving pleasure. 411 final ActivityIntentResolver mReceivers = 412 new ActivityIntentResolver(); 413 414 // All available services, for your resolving pleasure. 415 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 416 417 // All available providers, for your resolving pleasure. 418 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 419 420 // Mapping from provider base names (first directory in content URI codePath) 421 // to the provider information. 422 final HashMap<String, PackageParser.Provider> mProvidersByAuthority = 423 new HashMap<String, PackageParser.Provider>(); 424 425 // Mapping from instrumentation class names to info about them. 426 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 427 new HashMap<ComponentName, PackageParser.Instrumentation>(); 428 429 // Mapping from permission names to info about them. 430 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups = 431 new HashMap<String, PackageParser.PermissionGroup>(); 432 433 // Packages whose data we have transfered into another package, thus 434 // should no longer exist. 435 final HashSet<String> mTransferedPackages = new HashSet<String>(); 436 437 // Broadcast actions that are only available to the system. 438 final HashSet<String> mProtectedBroadcasts = new HashSet<String>(); 439 440 /** List of packages waiting for verification. */ 441 final SparseArray<PackageVerificationState> mPendingVerification 442 = new SparseArray<PackageVerificationState>(); 443 444 /** Set of packages associated with each app op permission. */ 445 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 446 447 final PackageInstallerService mInstallerService; 448 449 HashSet<PackageParser.Package> mDeferredDexOpt = null; 450 451 // Cache of users who need badging. 452 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 453 454 /** Token for keys in mPendingVerification. */ 455 private int mPendingVerificationToken = 0; 456 457 volatile boolean mSystemReady; 458 volatile boolean mSafeMode; 459 volatile boolean mHasSystemUidErrors; 460 461 ApplicationInfo mAndroidApplication; 462 final ActivityInfo mResolveActivity = new ActivityInfo(); 463 final ResolveInfo mResolveInfo = new ResolveInfo(); 464 ComponentName mResolveComponentName; 465 PackageParser.Package mPlatformPackage; 466 ComponentName mCustomResolverComponentName; 467 468 boolean mResolverReplaced = false; 469 470 // Set of pending broadcasts for aggregating enable/disable of components. 471 static class PendingPackageBroadcasts { 472 // for each user id, a map of <package name -> components within that package> 473 final SparseArray<HashMap<String, ArrayList<String>>> mUidMap; 474 475 public PendingPackageBroadcasts() { 476 mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2); 477 } 478 479 public ArrayList<String> get(int userId, String packageName) { 480 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 481 return packages.get(packageName); 482 } 483 484 public void put(int userId, String packageName, ArrayList<String> components) { 485 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 486 packages.put(packageName, components); 487 } 488 489 public void remove(int userId, String packageName) { 490 HashMap<String, ArrayList<String>> packages = mUidMap.get(userId); 491 if (packages != null) { 492 packages.remove(packageName); 493 } 494 } 495 496 public void remove(int userId) { 497 mUidMap.remove(userId); 498 } 499 500 public int userIdCount() { 501 return mUidMap.size(); 502 } 503 504 public int userIdAt(int n) { 505 return mUidMap.keyAt(n); 506 } 507 508 public HashMap<String, ArrayList<String>> packagesForUserId(int userId) { 509 return mUidMap.get(userId); 510 } 511 512 public int size() { 513 // total number of pending broadcast entries across all userIds 514 int num = 0; 515 for (int i = 0; i< mUidMap.size(); i++) { 516 num += mUidMap.valueAt(i).size(); 517 } 518 return num; 519 } 520 521 public void clear() { 522 mUidMap.clear(); 523 } 524 525 private HashMap<String, ArrayList<String>> getOrAllocate(int userId) { 526 HashMap<String, ArrayList<String>> map = mUidMap.get(userId); 527 if (map == null) { 528 map = new HashMap<String, ArrayList<String>>(); 529 mUidMap.put(userId, map); 530 } 531 return map; 532 } 533 } 534 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 535 536 // Service Connection to remote media container service to copy 537 // package uri's from external media onto secure containers 538 // or internal storage. 539 private IMediaContainerService mContainerService = null; 540 541 static final int SEND_PENDING_BROADCAST = 1; 542 static final int MCS_BOUND = 3; 543 static final int END_COPY = 4; 544 static final int INIT_COPY = 5; 545 static final int MCS_UNBIND = 6; 546 static final int START_CLEANING_PACKAGE = 7; 547 static final int FIND_INSTALL_LOC = 8; 548 static final int POST_INSTALL = 9; 549 static final int MCS_RECONNECT = 10; 550 static final int MCS_GIVE_UP = 11; 551 static final int UPDATED_MEDIA_STATUS = 12; 552 static final int WRITE_SETTINGS = 13; 553 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 554 static final int PACKAGE_VERIFIED = 15; 555 static final int CHECK_PENDING_VERIFICATION = 16; 556 557 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 558 559 // Delay time in millisecs 560 static final int BROADCAST_DELAY = 10 * 1000; 561 562 static UserManagerService sUserManager; 563 564 // Stores a list of users whose package restrictions file needs to be updated 565 private HashSet<Integer> mDirtyUsers = new HashSet<Integer>(); 566 567 final private DefaultContainerConnection mDefContainerConn = 568 new DefaultContainerConnection(); 569 class DefaultContainerConnection implements ServiceConnection { 570 public void onServiceConnected(ComponentName name, IBinder service) { 571 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 572 IMediaContainerService imcs = 573 IMediaContainerService.Stub.asInterface(service); 574 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 575 } 576 577 public void onServiceDisconnected(ComponentName name) { 578 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 579 } 580 }; 581 582 // Recordkeeping of restore-after-install operations that are currently in flight 583 // between the Package Manager and the Backup Manager 584 class PostInstallData { 585 public InstallArgs args; 586 public PackageInstalledInfo res; 587 588 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 589 args = _a; 590 res = _r; 591 } 592 }; 593 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 594 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 595 596 private final String mRequiredVerifierPackage; 597 598 private final PackageUsage mPackageUsage = new PackageUsage(); 599 600 private class PackageUsage { 601 private static final int WRITE_INTERVAL 602 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 603 604 private final Object mFileLock = new Object(); 605 private final AtomicLong mLastWritten = new AtomicLong(0); 606 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 607 608 private boolean mIsHistoricalPackageUsageAvailable = true; 609 610 boolean isHistoricalPackageUsageAvailable() { 611 return mIsHistoricalPackageUsageAvailable; 612 } 613 614 void write(boolean force) { 615 if (force) { 616 writeInternal(); 617 return; 618 } 619 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 620 && !DEBUG_DEXOPT) { 621 return; 622 } 623 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 624 new Thread("PackageUsage_DiskWriter") { 625 @Override 626 public void run() { 627 try { 628 writeInternal(); 629 } finally { 630 mBackgroundWriteRunning.set(false); 631 } 632 } 633 }.start(); 634 } 635 } 636 637 private void writeInternal() { 638 synchronized (mPackages) { 639 synchronized (mFileLock) { 640 AtomicFile file = getFile(); 641 FileOutputStream f = null; 642 try { 643 f = file.startWrite(); 644 BufferedOutputStream out = new BufferedOutputStream(f); 645 FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID); 646 StringBuilder sb = new StringBuilder(); 647 for (PackageParser.Package pkg : mPackages.values()) { 648 if (pkg.mLastPackageUsageTimeInMills == 0) { 649 continue; 650 } 651 sb.setLength(0); 652 sb.append(pkg.packageName); 653 sb.append(' '); 654 sb.append((long)pkg.mLastPackageUsageTimeInMills); 655 sb.append('\n'); 656 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 657 } 658 out.flush(); 659 file.finishWrite(f); 660 } catch (IOException e) { 661 if (f != null) { 662 file.failWrite(f); 663 } 664 Log.e(TAG, "Failed to write package usage times", e); 665 } 666 } 667 } 668 mLastWritten.set(SystemClock.elapsedRealtime()); 669 } 670 671 void readLP() { 672 synchronized (mFileLock) { 673 AtomicFile file = getFile(); 674 BufferedInputStream in = null; 675 try { 676 in = new BufferedInputStream(file.openRead()); 677 StringBuffer sb = new StringBuffer(); 678 while (true) { 679 String packageName = readToken(in, sb, ' '); 680 if (packageName == null) { 681 break; 682 } 683 String timeInMillisString = readToken(in, sb, '\n'); 684 if (timeInMillisString == null) { 685 throw new IOException("Failed to find last usage time for package " 686 + packageName); 687 } 688 PackageParser.Package pkg = mPackages.get(packageName); 689 if (pkg == null) { 690 continue; 691 } 692 long timeInMillis; 693 try { 694 timeInMillis = Long.parseLong(timeInMillisString.toString()); 695 } catch (NumberFormatException e) { 696 throw new IOException("Failed to parse " + timeInMillisString 697 + " as a long.", e); 698 } 699 pkg.mLastPackageUsageTimeInMills = timeInMillis; 700 } 701 } catch (FileNotFoundException expected) { 702 mIsHistoricalPackageUsageAvailable = false; 703 } catch (IOException e) { 704 Log.w(TAG, "Failed to read package usage times", e); 705 } finally { 706 IoUtils.closeQuietly(in); 707 } 708 } 709 mLastWritten.set(SystemClock.elapsedRealtime()); 710 } 711 712 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 713 throws IOException { 714 sb.setLength(0); 715 while (true) { 716 int ch = in.read(); 717 if (ch == -1) { 718 if (sb.length() == 0) { 719 return null; 720 } 721 throw new IOException("Unexpected EOF"); 722 } 723 if (ch == endOfToken) { 724 return sb.toString(); 725 } 726 sb.append((char)ch); 727 } 728 } 729 730 private AtomicFile getFile() { 731 File dataDir = Environment.getDataDirectory(); 732 File systemDir = new File(dataDir, "system"); 733 File fname = new File(systemDir, "package-usage.list"); 734 return new AtomicFile(fname); 735 } 736 } 737 738 class PackageHandler extends Handler { 739 private boolean mBound = false; 740 final ArrayList<HandlerParams> mPendingInstalls = 741 new ArrayList<HandlerParams>(); 742 743 private boolean connectToService() { 744 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 745 " DefaultContainerService"); 746 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 747 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 748 if (mContext.bindServiceAsUser(service, mDefContainerConn, 749 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 750 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 751 mBound = true; 752 return true; 753 } 754 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 755 return false; 756 } 757 758 private void disconnectService() { 759 mContainerService = null; 760 mBound = false; 761 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 762 mContext.unbindService(mDefContainerConn); 763 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 764 } 765 766 PackageHandler(Looper looper) { 767 super(looper); 768 } 769 770 public void handleMessage(Message msg) { 771 try { 772 doHandleMessage(msg); 773 } finally { 774 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 775 } 776 } 777 778 void doHandleMessage(Message msg) { 779 switch (msg.what) { 780 case INIT_COPY: { 781 HandlerParams params = (HandlerParams) msg.obj; 782 int idx = mPendingInstalls.size(); 783 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 784 // If a bind was already initiated we dont really 785 // need to do anything. The pending install 786 // will be processed later on. 787 if (!mBound) { 788 // If this is the only one pending we might 789 // have to bind to the service again. 790 if (!connectToService()) { 791 Slog.e(TAG, "Failed to bind to media container service"); 792 params.serviceError(); 793 return; 794 } else { 795 // Once we bind to the service, the first 796 // pending request will be processed. 797 mPendingInstalls.add(idx, params); 798 } 799 } else { 800 mPendingInstalls.add(idx, params); 801 // Already bound to the service. Just make 802 // sure we trigger off processing the first request. 803 if (idx == 0) { 804 mHandler.sendEmptyMessage(MCS_BOUND); 805 } 806 } 807 break; 808 } 809 case MCS_BOUND: { 810 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 811 if (msg.obj != null) { 812 mContainerService = (IMediaContainerService) msg.obj; 813 } 814 if (mContainerService == null) { 815 // Something seriously wrong. Bail out 816 Slog.e(TAG, "Cannot bind to media container service"); 817 for (HandlerParams params : mPendingInstalls) { 818 // Indicate service bind error 819 params.serviceError(); 820 } 821 mPendingInstalls.clear(); 822 } else if (mPendingInstalls.size() > 0) { 823 HandlerParams params = mPendingInstalls.get(0); 824 if (params != null) { 825 if (params.startCopy()) { 826 // We are done... look for more work or to 827 // go idle. 828 if (DEBUG_SD_INSTALL) Log.i(TAG, 829 "Checking for more work or unbind..."); 830 // Delete pending install 831 if (mPendingInstalls.size() > 0) { 832 mPendingInstalls.remove(0); 833 } 834 if (mPendingInstalls.size() == 0) { 835 if (mBound) { 836 if (DEBUG_SD_INSTALL) Log.i(TAG, 837 "Posting delayed MCS_UNBIND"); 838 removeMessages(MCS_UNBIND); 839 Message ubmsg = obtainMessage(MCS_UNBIND); 840 // Unbind after a little delay, to avoid 841 // continual thrashing. 842 sendMessageDelayed(ubmsg, 10000); 843 } 844 } else { 845 // There are more pending requests in queue. 846 // Just post MCS_BOUND message to trigger processing 847 // of next pending install. 848 if (DEBUG_SD_INSTALL) Log.i(TAG, 849 "Posting MCS_BOUND for next work"); 850 mHandler.sendEmptyMessage(MCS_BOUND); 851 } 852 } 853 } 854 } else { 855 // Should never happen ideally. 856 Slog.w(TAG, "Empty queue"); 857 } 858 break; 859 } 860 case MCS_RECONNECT: { 861 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 862 if (mPendingInstalls.size() > 0) { 863 if (mBound) { 864 disconnectService(); 865 } 866 if (!connectToService()) { 867 Slog.e(TAG, "Failed to bind to media container service"); 868 for (HandlerParams params : mPendingInstalls) { 869 // Indicate service bind error 870 params.serviceError(); 871 } 872 mPendingInstalls.clear(); 873 } 874 } 875 break; 876 } 877 case MCS_UNBIND: { 878 // If there is no actual work left, then time to unbind. 879 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 880 881 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 882 if (mBound) { 883 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 884 885 disconnectService(); 886 } 887 } else if (mPendingInstalls.size() > 0) { 888 // There are more pending requests in queue. 889 // Just post MCS_BOUND message to trigger processing 890 // of next pending install. 891 mHandler.sendEmptyMessage(MCS_BOUND); 892 } 893 894 break; 895 } 896 case MCS_GIVE_UP: { 897 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 898 mPendingInstalls.remove(0); 899 break; 900 } 901 case SEND_PENDING_BROADCAST: { 902 String packages[]; 903 ArrayList<String> components[]; 904 int size = 0; 905 int uids[]; 906 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 907 synchronized (mPackages) { 908 if (mPendingBroadcasts == null) { 909 return; 910 } 911 size = mPendingBroadcasts.size(); 912 if (size <= 0) { 913 // Nothing to be done. Just return 914 return; 915 } 916 packages = new String[size]; 917 components = new ArrayList[size]; 918 uids = new int[size]; 919 int i = 0; // filling out the above arrays 920 921 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 922 int packageUserId = mPendingBroadcasts.userIdAt(n); 923 Iterator<Map.Entry<String, ArrayList<String>>> it 924 = mPendingBroadcasts.packagesForUserId(packageUserId) 925 .entrySet().iterator(); 926 while (it.hasNext() && i < size) { 927 Map.Entry<String, ArrayList<String>> ent = it.next(); 928 packages[i] = ent.getKey(); 929 components[i] = ent.getValue(); 930 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 931 uids[i] = (ps != null) 932 ? UserHandle.getUid(packageUserId, ps.appId) 933 : -1; 934 i++; 935 } 936 } 937 size = i; 938 mPendingBroadcasts.clear(); 939 } 940 // Send broadcasts 941 for (int i = 0; i < size; i++) { 942 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 943 } 944 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 945 break; 946 } 947 case START_CLEANING_PACKAGE: { 948 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 949 final String packageName = (String)msg.obj; 950 final int userId = msg.arg1; 951 final boolean andCode = msg.arg2 != 0; 952 synchronized (mPackages) { 953 if (userId == UserHandle.USER_ALL) { 954 int[] users = sUserManager.getUserIds(); 955 for (int user : users) { 956 mSettings.addPackageToCleanLPw( 957 new PackageCleanItem(user, packageName, andCode)); 958 } 959 } else { 960 mSettings.addPackageToCleanLPw( 961 new PackageCleanItem(userId, packageName, andCode)); 962 } 963 } 964 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 965 startCleaningPackages(); 966 } break; 967 case POST_INSTALL: { 968 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 969 PostInstallData data = mRunningInstalls.get(msg.arg1); 970 mRunningInstalls.delete(msg.arg1); 971 boolean deleteOld = false; 972 973 if (data != null) { 974 InstallArgs args = data.args; 975 PackageInstalledInfo res = data.res; 976 977 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 978 res.removedInfo.sendBroadcast(false, true, false); 979 Bundle extras = new Bundle(1); 980 extras.putInt(Intent.EXTRA_UID, res.uid); 981 // Determine the set of users who are adding this 982 // package for the first time vs. those who are seeing 983 // an update. 984 int[] firstUsers; 985 int[] updateUsers = new int[0]; 986 if (res.origUsers == null || res.origUsers.length == 0) { 987 firstUsers = res.newUsers; 988 } else { 989 firstUsers = new int[0]; 990 for (int i=0; i<res.newUsers.length; i++) { 991 int user = res.newUsers[i]; 992 boolean isNew = true; 993 for (int j=0; j<res.origUsers.length; j++) { 994 if (res.origUsers[j] == user) { 995 isNew = false; 996 break; 997 } 998 } 999 if (isNew) { 1000 int[] newFirst = new int[firstUsers.length+1]; 1001 System.arraycopy(firstUsers, 0, newFirst, 0, 1002 firstUsers.length); 1003 newFirst[firstUsers.length] = user; 1004 firstUsers = newFirst; 1005 } else { 1006 int[] newUpdate = new int[updateUsers.length+1]; 1007 System.arraycopy(updateUsers, 0, newUpdate, 0, 1008 updateUsers.length); 1009 newUpdate[updateUsers.length] = user; 1010 updateUsers = newUpdate; 1011 } 1012 } 1013 } 1014 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1015 res.pkg.applicationInfo.packageName, 1016 extras, null, null, firstUsers); 1017 final boolean update = res.removedInfo.removedPackage != null; 1018 if (update) { 1019 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1020 } 1021 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1022 res.pkg.applicationInfo.packageName, 1023 extras, null, null, updateUsers); 1024 if (update) { 1025 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1026 res.pkg.applicationInfo.packageName, 1027 extras, null, null, updateUsers); 1028 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1029 null, null, 1030 res.pkg.applicationInfo.packageName, null, updateUsers); 1031 1032 // treat asec-hosted packages like removable media on upgrade 1033 if (isForwardLocked(res.pkg) || isExternal(res.pkg)) { 1034 if (DEBUG_INSTALL) { 1035 Slog.i(TAG, "upgrading pkg " + res.pkg 1036 + " is ASEC-hosted -> AVAILABLE"); 1037 } 1038 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1039 ArrayList<String> pkgList = new ArrayList<String>(1); 1040 pkgList.add(res.pkg.applicationInfo.packageName); 1041 sendResourcesChangedBroadcast(true, true, 1042 pkgList,uidArray, null); 1043 } 1044 } 1045 if (res.removedInfo.args != null) { 1046 // Remove the replaced package's older resources safely now 1047 deleteOld = true; 1048 } 1049 1050 // Log current value of "unknown sources" setting 1051 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1052 getUnknownSourcesSettings()); 1053 } 1054 // Force a gc to clear up things 1055 Runtime.getRuntime().gc(); 1056 // We delete after a gc for applications on sdcard. 1057 if (deleteOld) { 1058 synchronized (mInstallLock) { 1059 res.removedInfo.args.doPostDeleteLI(true); 1060 } 1061 } 1062 if (args.observer != null) { 1063 try { 1064 Bundle extras = extrasForInstallResult(res); 1065 args.observer.onPackageInstalled(res.name, res.returnCode, 1066 res.returnMsg, extras); 1067 } catch (RemoteException e) { 1068 Slog.i(TAG, "Observer no longer exists."); 1069 } 1070 } 1071 } else { 1072 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1073 } 1074 } break; 1075 case UPDATED_MEDIA_STATUS: { 1076 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1077 boolean reportStatus = msg.arg1 == 1; 1078 boolean doGc = msg.arg2 == 1; 1079 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1080 if (doGc) { 1081 // Force a gc to clear up stale containers. 1082 Runtime.getRuntime().gc(); 1083 } 1084 if (msg.obj != null) { 1085 @SuppressWarnings("unchecked") 1086 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1087 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1088 // Unload containers 1089 unloadAllContainers(args); 1090 } 1091 if (reportStatus) { 1092 try { 1093 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1094 PackageHelper.getMountService().finishMediaUpdate(); 1095 } catch (RemoteException e) { 1096 Log.e(TAG, "MountService not running?"); 1097 } 1098 } 1099 } break; 1100 case WRITE_SETTINGS: { 1101 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1102 synchronized (mPackages) { 1103 removeMessages(WRITE_SETTINGS); 1104 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1105 mSettings.writeLPr(); 1106 mDirtyUsers.clear(); 1107 } 1108 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1109 } break; 1110 case WRITE_PACKAGE_RESTRICTIONS: { 1111 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1112 synchronized (mPackages) { 1113 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1114 for (int userId : mDirtyUsers) { 1115 mSettings.writePackageRestrictionsLPr(userId); 1116 } 1117 mDirtyUsers.clear(); 1118 } 1119 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1120 } break; 1121 case CHECK_PENDING_VERIFICATION: { 1122 final int verificationId = msg.arg1; 1123 final PackageVerificationState state = mPendingVerification.get(verificationId); 1124 1125 if ((state != null) && !state.timeoutExtended()) { 1126 final InstallArgs args = state.getInstallArgs(); 1127 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1128 1129 Slog.i(TAG, "Verification timed out for " + originUri); 1130 mPendingVerification.remove(verificationId); 1131 1132 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1133 1134 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1135 Slog.i(TAG, "Continuing with installation of " + originUri); 1136 state.setVerifierResponse(Binder.getCallingUid(), 1137 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1138 broadcastPackageVerified(verificationId, originUri, 1139 PackageManager.VERIFICATION_ALLOW, 1140 state.getInstallArgs().getUser()); 1141 try { 1142 ret = args.copyApk(mContainerService, true); 1143 } catch (RemoteException e) { 1144 Slog.e(TAG, "Could not contact the ContainerService"); 1145 } 1146 } else { 1147 broadcastPackageVerified(verificationId, originUri, 1148 PackageManager.VERIFICATION_REJECT, 1149 state.getInstallArgs().getUser()); 1150 } 1151 1152 processPendingInstall(args, ret); 1153 mHandler.sendEmptyMessage(MCS_UNBIND); 1154 } 1155 break; 1156 } 1157 case PACKAGE_VERIFIED: { 1158 final int verificationId = msg.arg1; 1159 1160 final PackageVerificationState state = mPendingVerification.get(verificationId); 1161 if (state == null) { 1162 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1163 break; 1164 } 1165 1166 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1167 1168 state.setVerifierResponse(response.callerUid, response.code); 1169 1170 if (state.isVerificationComplete()) { 1171 mPendingVerification.remove(verificationId); 1172 1173 final InstallArgs args = state.getInstallArgs(); 1174 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1175 1176 int ret; 1177 if (state.isInstallAllowed()) { 1178 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1179 broadcastPackageVerified(verificationId, originUri, 1180 response.code, state.getInstallArgs().getUser()); 1181 try { 1182 ret = args.copyApk(mContainerService, true); 1183 } catch (RemoteException e) { 1184 Slog.e(TAG, "Could not contact the ContainerService"); 1185 } 1186 } else { 1187 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1188 } 1189 1190 processPendingInstall(args, ret); 1191 1192 mHandler.sendEmptyMessage(MCS_UNBIND); 1193 } 1194 1195 break; 1196 } 1197 } 1198 } 1199 } 1200 1201 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1202 Bundle extras = null; 1203 switch (res.returnCode) { 1204 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1205 extras = new Bundle(); 1206 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1207 res.origPermission); 1208 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1209 res.origPackage); 1210 break; 1211 } 1212 } 1213 return extras; 1214 } 1215 1216 void scheduleWriteSettingsLocked() { 1217 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1218 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1219 } 1220 } 1221 1222 void scheduleWritePackageRestrictionsLocked(int userId) { 1223 if (!sUserManager.exists(userId)) return; 1224 mDirtyUsers.add(userId); 1225 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1226 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1227 } 1228 } 1229 1230 public static final PackageManagerService main(Context context, Installer installer, 1231 boolean factoryTest, boolean onlyCore) { 1232 PackageManagerService m = new PackageManagerService(context, installer, 1233 factoryTest, onlyCore); 1234 ServiceManager.addService("package", m); 1235 return m; 1236 } 1237 1238 static String[] splitString(String str, char sep) { 1239 int count = 1; 1240 int i = 0; 1241 while ((i=str.indexOf(sep, i)) >= 0) { 1242 count++; 1243 i++; 1244 } 1245 1246 String[] res = new String[count]; 1247 i=0; 1248 count = 0; 1249 int lastI=0; 1250 while ((i=str.indexOf(sep, i)) >= 0) { 1251 res[count] = str.substring(lastI, i); 1252 count++; 1253 i++; 1254 lastI = i; 1255 } 1256 res[count] = str.substring(lastI, str.length()); 1257 return res; 1258 } 1259 1260 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1261 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1262 Context.DISPLAY_SERVICE); 1263 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1264 } 1265 1266 public PackageManagerService(Context context, Installer installer, 1267 boolean factoryTest, boolean onlyCore) { 1268 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1269 SystemClock.uptimeMillis()); 1270 1271 if (mSdkVersion <= 0) { 1272 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1273 } 1274 1275 mContext = context; 1276 mFactoryTest = factoryTest; 1277 mOnlyCore = onlyCore; 1278 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1279 mMetrics = new DisplayMetrics(); 1280 mSettings = new Settings(context); 1281 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1282 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1283 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1284 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1285 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1286 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1287 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1288 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1289 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1290 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1291 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1292 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1293 1294 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1295 if (separateProcesses != null && separateProcesses.length() > 0) { 1296 if ("*".equals(separateProcesses)) { 1297 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1298 mSeparateProcesses = null; 1299 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1300 } else { 1301 mDefParseFlags = 0; 1302 mSeparateProcesses = separateProcesses.split(","); 1303 Slog.w(TAG, "Running with debug.separate_processes: " 1304 + separateProcesses); 1305 } 1306 } else { 1307 mDefParseFlags = 0; 1308 mSeparateProcesses = null; 1309 } 1310 1311 mInstaller = installer; 1312 1313 getDefaultDisplayMetrics(context, mMetrics); 1314 1315 SystemConfig systemConfig = SystemConfig.getInstance(); 1316 mGlobalGids = systemConfig.getGlobalGids(); 1317 mSystemPermissions = systemConfig.getSystemPermissions(); 1318 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1319 1320 synchronized (mInstallLock) { 1321 // writer 1322 synchronized (mPackages) { 1323 mHandlerThread = new ServiceThread(TAG, 1324 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1325 mHandlerThread.start(); 1326 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1327 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1328 1329 File dataDir = Environment.getDataDirectory(); 1330 mAppDataDir = new File(dataDir, "data"); 1331 mAppInstallDir = new File(dataDir, "app"); 1332 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1333 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1334 mUserAppDataDir = new File(dataDir, "user"); 1335 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1336 1337 sUserManager = new UserManagerService(context, this, 1338 mInstallLock, mPackages); 1339 1340 // Propagate permission configuration in to package manager. 1341 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1342 = systemConfig.getPermissions(); 1343 for (int i=0; i<permConfig.size(); i++) { 1344 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1345 BasePermission bp = mSettings.mPermissions.get(perm.name); 1346 if (bp == null) { 1347 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1348 mSettings.mPermissions.put(perm.name, bp); 1349 } 1350 if (perm.gids != null) { 1351 bp.gids = appendInts(bp.gids, perm.gids); 1352 } 1353 } 1354 1355 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1356 for (int i=0; i<libConfig.size(); i++) { 1357 mSharedLibraries.put(libConfig.keyAt(i), 1358 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1359 } 1360 1361 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1362 1363 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1364 mSdkVersion, mOnlyCore); 1365 1366 String customResolverActivity = Resources.getSystem().getString( 1367 R.string.config_customResolverActivity); 1368 if (TextUtils.isEmpty(customResolverActivity)) { 1369 customResolverActivity = null; 1370 } else { 1371 mCustomResolverComponentName = ComponentName.unflattenFromString( 1372 customResolverActivity); 1373 } 1374 1375 long startTime = SystemClock.uptimeMillis(); 1376 1377 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1378 startTime); 1379 1380 // Set flag to monitor and not change apk file paths when 1381 // scanning install directories. 1382 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1383 1384 final HashSet<String> alreadyDexOpted = new HashSet<String>(); 1385 1386 /** 1387 * Add everything in the in the boot class path to the 1388 * list of process files because dexopt will have been run 1389 * if necessary during zygote startup. 1390 */ 1391 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1392 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1393 1394 if (bootClassPath != null) { 1395 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1396 for (String element : bootClassPathElements) { 1397 alreadyDexOpted.add(element); 1398 } 1399 } else { 1400 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1401 } 1402 1403 if (systemServerClassPath != null) { 1404 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1405 for (String element : systemServerClassPathElements) { 1406 alreadyDexOpted.add(element); 1407 } 1408 } else { 1409 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1410 } 1411 1412 boolean didDexOptLibraryOrTool = false; 1413 1414 final List<String> allInstructionSets = getAllInstructionSets(); 1415 final String[] dexCodeInstructionSets = 1416 getDexCodeInstructionSets(allInstructionSets.toArray(new String[allInstructionSets.size()])); 1417 1418 /** 1419 * Ensure all external libraries have had dexopt run on them. 1420 */ 1421 if (mSharedLibraries.size() > 0) { 1422 // NOTE: For now, we're compiling these system "shared libraries" 1423 // (and framework jars) into all available architectures. It's possible 1424 // to compile them only when we come across an app that uses them (there's 1425 // already logic for that in scanPackageLI) but that adds some complexity. 1426 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1427 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1428 final String lib = libEntry.path; 1429 if (lib == null) { 1430 continue; 1431 } 1432 1433 try { 1434 byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null, 1435 dexCodeInstructionSet, 1436 false); 1437 if (dexoptRequired != DexFile.UP_TO_DATE) { 1438 alreadyDexOpted.add(lib); 1439 1440 // The list of "shared libraries" we have at this point is 1441 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1442 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1443 } else { 1444 mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1445 } 1446 didDexOptLibraryOrTool = true; 1447 } 1448 } catch (FileNotFoundException e) { 1449 Slog.w(TAG, "Library not found: " + lib); 1450 } catch (IOException e) { 1451 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1452 + e.getMessage()); 1453 } 1454 } 1455 } 1456 } 1457 1458 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1459 1460 // Gross hack for now: we know this file doesn't contain any 1461 // code, so don't dexopt it to avoid the resulting log spew. 1462 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1463 1464 // Gross hack for now: we know this file is only part of 1465 // the boot class path for art, so don't dexopt it to 1466 // avoid the resulting log spew. 1467 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1468 1469 /** 1470 * And there are a number of commands implemented in Java, which 1471 * we currently need to do the dexopt on so that they can be 1472 * run from a non-root shell. 1473 */ 1474 String[] frameworkFiles = frameworkDir.list(); 1475 if (frameworkFiles != null) { 1476 // TODO: We could compile these only for the most preferred ABI. We should 1477 // first double check that the dex files for these commands are not referenced 1478 // by other system apps. 1479 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1480 for (int i=0; i<frameworkFiles.length; i++) { 1481 File libPath = new File(frameworkDir, frameworkFiles[i]); 1482 String path = libPath.getPath(); 1483 // Skip the file if we already did it. 1484 if (alreadyDexOpted.contains(path)) { 1485 continue; 1486 } 1487 // Skip the file if it is not a type we want to dexopt. 1488 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1489 continue; 1490 } 1491 try { 1492 byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null, 1493 dexCodeInstructionSet, 1494 false); 1495 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1496 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1497 didDexOptLibraryOrTool = true; 1498 } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) { 1499 mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1500 didDexOptLibraryOrTool = true; 1501 } 1502 } catch (FileNotFoundException e) { 1503 Slog.w(TAG, "Jar not found: " + path); 1504 } catch (IOException e) { 1505 Slog.w(TAG, "Exception reading jar: " + path, e); 1506 } 1507 } 1508 } 1509 } 1510 1511 // Collect vendor overlay packages. 1512 // (Do this before scanning any apps.) 1513 // For security and version matching reason, only consider 1514 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1515 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1516 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1517 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1518 1519 // Find base frameworks (resource packages without code). 1520 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1521 | PackageParser.PARSE_IS_SYSTEM_DIR 1522 | PackageParser.PARSE_IS_PRIVILEGED, 1523 scanFlags | SCAN_NO_DEX, 0); 1524 1525 // Collected privileged system packages. 1526 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1527 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1528 | PackageParser.PARSE_IS_SYSTEM_DIR 1529 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1530 1531 // Collect ordinary system packages. 1532 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1533 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1534 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1535 1536 // Collect all vendor packages. 1537 File vendorAppDir = new File("/vendor/app"); 1538 try { 1539 vendorAppDir = vendorAppDir.getCanonicalFile(); 1540 } catch (IOException e) { 1541 // failed to look up canonical path, continue with original one 1542 } 1543 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1544 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1545 1546 // Collect all OEM packages. 1547 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1548 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1549 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1550 1551 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1552 mInstaller.moveFiles(); 1553 1554 // Prune any system packages that no longer exist. 1555 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1556 if (!mOnlyCore) { 1557 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1558 while (psit.hasNext()) { 1559 PackageSetting ps = psit.next(); 1560 1561 /* 1562 * If this is not a system app, it can't be a 1563 * disable system app. 1564 */ 1565 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1566 continue; 1567 } 1568 1569 /* 1570 * If the package is scanned, it's not erased. 1571 */ 1572 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1573 if (scannedPkg != null) { 1574 /* 1575 * If the system app is both scanned and in the 1576 * disabled packages list, then it must have been 1577 * added via OTA. Remove it from the currently 1578 * scanned package so the previously user-installed 1579 * application can be scanned. 1580 */ 1581 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1582 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 1583 + ps.name + "; removing system app. Last known codePath=" 1584 + ps.codePathString + ", installStatus=" + ps.installStatus 1585 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 1586 + scannedPkg.mVersionCode); 1587 removePackageLI(ps, true); 1588 } 1589 1590 continue; 1591 } 1592 1593 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1594 psit.remove(); 1595 logCriticalInfo(Log.WARN, "System package " + ps.name 1596 + " no longer exists; wiping its data"); 1597 removeDataDirsLI(ps.name); 1598 } else { 1599 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1600 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1601 possiblyDeletedUpdatedSystemApps.add(ps.name); 1602 } 1603 } 1604 } 1605 } 1606 1607 //look for any incomplete package installations 1608 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1609 //clean up list 1610 for(int i = 0; i < deletePkgsList.size(); i++) { 1611 //clean up here 1612 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1613 } 1614 //delete tmp files 1615 deleteTempPackageFiles(); 1616 1617 // Remove any shared userIDs that have no associated packages 1618 mSettings.pruneSharedUsersLPw(); 1619 1620 if (!mOnlyCore) { 1621 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 1622 SystemClock.uptimeMillis()); 1623 scanDirLI(mAppInstallDir, 0, scanFlags, 0); 1624 1625 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 1626 scanFlags, 0); 1627 1628 /** 1629 * Remove disable package settings for any updated system 1630 * apps that were removed via an OTA. If they're not a 1631 * previously-updated app, remove them completely. 1632 * Otherwise, just revoke their system-level permissions. 1633 */ 1634 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 1635 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 1636 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 1637 1638 String msg; 1639 if (deletedPkg == null) { 1640 msg = "Updated system package " + deletedAppName 1641 + " no longer exists; wiping its data"; 1642 removeDataDirsLI(deletedAppName); 1643 } else { 1644 msg = "Updated system app + " + deletedAppName 1645 + " no longer present; removing system privileges for " 1646 + deletedAppName; 1647 1648 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 1649 1650 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 1651 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 1652 } 1653 logCriticalInfo(Log.WARN, msg); 1654 } 1655 } 1656 1657 // Now that we know all of the shared libraries, update all clients to have 1658 // the correct library paths. 1659 updateAllSharedLibrariesLPw(); 1660 1661 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 1662 // NOTE: We ignore potential failures here during a system scan (like 1663 // the rest of the commands above) because there's precious little we 1664 // can do about it. A settings error is reported, though. 1665 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 1666 false /* force dexopt */, false /* defer dexopt */); 1667 } 1668 1669 // Now that we know all the packages we are keeping, 1670 // read and update their last usage times. 1671 mPackageUsage.readLP(); 1672 1673 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 1674 SystemClock.uptimeMillis()); 1675 Slog.i(TAG, "Time to scan packages: " 1676 + ((SystemClock.uptimeMillis()-startTime)/1000f) 1677 + " seconds"); 1678 1679 // If the platform SDK has changed since the last time we booted, 1680 // we need to re-grant app permission to catch any new ones that 1681 // appear. This is really a hack, and means that apps can in some 1682 // cases get permissions that the user didn't initially explicitly 1683 // allow... it would be nice to have some better way to handle 1684 // this situation. 1685 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 1686 != mSdkVersion; 1687 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 1688 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 1689 + "; regranting permissions for internal storage"); 1690 mSettings.mInternalSdkPlatform = mSdkVersion; 1691 1692 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 1693 | (regrantPermissions 1694 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 1695 : 0)); 1696 1697 // If this is the first boot, and it is a normal boot, then 1698 // we need to initialize the default preferred apps. 1699 if (!mRestoredSettings && !onlyCore) { 1700 mSettings.readDefaultPreferredAppsLPw(this, 0); 1701 } 1702 1703 // If this is first boot after an OTA, and a normal boot, then 1704 // we need to clear code cache directories. 1705 if (!Build.FINGERPRINT.equals(mSettings.mFingerprint) && !onlyCore) { 1706 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 1707 for (String pkgName : mSettings.mPackages.keySet()) { 1708 deleteCodeCacheDirsLI(pkgName); 1709 } 1710 mSettings.mFingerprint = Build.FINGERPRINT; 1711 } 1712 1713 // All the changes are done during package scanning. 1714 mSettings.updateInternalDatabaseVersion(); 1715 1716 // can downgrade to reader 1717 mSettings.writeLPr(); 1718 1719 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 1720 SystemClock.uptimeMillis()); 1721 1722 1723 mRequiredVerifierPackage = getRequiredVerifierLPr(); 1724 } // synchronized (mPackages) 1725 } // synchronized (mInstallLock) 1726 1727 mInstallerService = new PackageInstallerService(context, this, mAppInstallDir); 1728 1729 // Now after opening every single application zip, make sure they 1730 // are all flushed. Not really needed, but keeps things nice and 1731 // tidy. 1732 Runtime.getRuntime().gc(); 1733 } 1734 1735 @Override 1736 public boolean isFirstBoot() { 1737 return !mRestoredSettings; 1738 } 1739 1740 @Override 1741 public boolean isOnlyCoreApps() { 1742 return mOnlyCore; 1743 } 1744 1745 private String getRequiredVerifierLPr() { 1746 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 1747 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 1748 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 1749 1750 String requiredVerifier = null; 1751 1752 final int N = receivers.size(); 1753 for (int i = 0; i < N; i++) { 1754 final ResolveInfo info = receivers.get(i); 1755 1756 if (info.activityInfo == null) { 1757 continue; 1758 } 1759 1760 final String packageName = info.activityInfo.packageName; 1761 1762 final PackageSetting ps = mSettings.mPackages.get(packageName); 1763 if (ps == null) { 1764 continue; 1765 } 1766 1767 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1768 if (!gp.grantedPermissions 1769 .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) { 1770 continue; 1771 } 1772 1773 if (requiredVerifier != null) { 1774 throw new RuntimeException("There can be only one required verifier"); 1775 } 1776 1777 requiredVerifier = packageName; 1778 } 1779 1780 return requiredVerifier; 1781 } 1782 1783 @Override 1784 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 1785 throws RemoteException { 1786 try { 1787 return super.onTransact(code, data, reply, flags); 1788 } catch (RuntimeException e) { 1789 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 1790 Slog.wtf(TAG, "Package Manager Crash", e); 1791 } 1792 throw e; 1793 } 1794 } 1795 1796 void cleanupInstallFailedPackage(PackageSetting ps) { 1797 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 1798 1799 removeDataDirsLI(ps.name); 1800 if (ps.codePath != null) { 1801 if (ps.codePath.isDirectory()) { 1802 FileUtils.deleteContents(ps.codePath); 1803 } 1804 ps.codePath.delete(); 1805 } 1806 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 1807 if (ps.resourcePath.isDirectory()) { 1808 FileUtils.deleteContents(ps.resourcePath); 1809 } 1810 ps.resourcePath.delete(); 1811 } 1812 mSettings.removePackageLPw(ps.name); 1813 } 1814 1815 static int[] appendInts(int[] cur, int[] add) { 1816 if (add == null) return cur; 1817 if (cur == null) return add; 1818 final int N = add.length; 1819 for (int i=0; i<N; i++) { 1820 cur = appendInt(cur, add[i]); 1821 } 1822 return cur; 1823 } 1824 1825 static int[] removeInts(int[] cur, int[] rem) { 1826 if (rem == null) return cur; 1827 if (cur == null) return cur; 1828 final int N = rem.length; 1829 for (int i=0; i<N; i++) { 1830 cur = removeInt(cur, rem[i]); 1831 } 1832 return cur; 1833 } 1834 1835 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 1836 if (!sUserManager.exists(userId)) return null; 1837 final PackageSetting ps = (PackageSetting) p.mExtras; 1838 if (ps == null) { 1839 return null; 1840 } 1841 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1842 final PackageUserState state = ps.readUserState(userId); 1843 return PackageParser.generatePackageInfo(p, gp.gids, flags, 1844 ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions, 1845 state, userId); 1846 } 1847 1848 @Override 1849 public boolean isPackageAvailable(String packageName, int userId) { 1850 if (!sUserManager.exists(userId)) return false; 1851 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 1852 synchronized (mPackages) { 1853 PackageParser.Package p = mPackages.get(packageName); 1854 if (p != null) { 1855 final PackageSetting ps = (PackageSetting) p.mExtras; 1856 if (ps != null) { 1857 final PackageUserState state = ps.readUserState(userId); 1858 if (state != null) { 1859 return PackageParser.isAvailable(state); 1860 } 1861 } 1862 } 1863 } 1864 return false; 1865 } 1866 1867 @Override 1868 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 1869 if (!sUserManager.exists(userId)) return null; 1870 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 1871 // reader 1872 synchronized (mPackages) { 1873 PackageParser.Package p = mPackages.get(packageName); 1874 if (DEBUG_PACKAGE_INFO) 1875 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 1876 if (p != null) { 1877 return generatePackageInfo(p, flags, userId); 1878 } 1879 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 1880 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 1881 } 1882 } 1883 return null; 1884 } 1885 1886 @Override 1887 public String[] currentToCanonicalPackageNames(String[] names) { 1888 String[] out = new String[names.length]; 1889 // reader 1890 synchronized (mPackages) { 1891 for (int i=names.length-1; i>=0; i--) { 1892 PackageSetting ps = mSettings.mPackages.get(names[i]); 1893 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 1894 } 1895 } 1896 return out; 1897 } 1898 1899 @Override 1900 public String[] canonicalToCurrentPackageNames(String[] names) { 1901 String[] out = new String[names.length]; 1902 // reader 1903 synchronized (mPackages) { 1904 for (int i=names.length-1; i>=0; i--) { 1905 String cur = mSettings.mRenamedPackages.get(names[i]); 1906 out[i] = cur != null ? cur : names[i]; 1907 } 1908 } 1909 return out; 1910 } 1911 1912 @Override 1913 public int getPackageUid(String packageName, int userId) { 1914 if (!sUserManager.exists(userId)) return -1; 1915 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 1916 // reader 1917 synchronized (mPackages) { 1918 PackageParser.Package p = mPackages.get(packageName); 1919 if(p != null) { 1920 return UserHandle.getUid(userId, p.applicationInfo.uid); 1921 } 1922 PackageSetting ps = mSettings.mPackages.get(packageName); 1923 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 1924 return -1; 1925 } 1926 p = ps.pkg; 1927 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 1928 } 1929 } 1930 1931 @Override 1932 public int[] getPackageGids(String packageName) { 1933 // reader 1934 synchronized (mPackages) { 1935 PackageParser.Package p = mPackages.get(packageName); 1936 if (DEBUG_PACKAGE_INFO) 1937 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 1938 if (p != null) { 1939 final PackageSetting ps = (PackageSetting)p.mExtras; 1940 return ps.getGids(); 1941 } 1942 } 1943 // stupid thing to indicate an error. 1944 return new int[0]; 1945 } 1946 1947 static final PermissionInfo generatePermissionInfo( 1948 BasePermission bp, int flags) { 1949 if (bp.perm != null) { 1950 return PackageParser.generatePermissionInfo(bp.perm, flags); 1951 } 1952 PermissionInfo pi = new PermissionInfo(); 1953 pi.name = bp.name; 1954 pi.packageName = bp.sourcePackage; 1955 pi.nonLocalizedLabel = bp.name; 1956 pi.protectionLevel = bp.protectionLevel; 1957 return pi; 1958 } 1959 1960 @Override 1961 public PermissionInfo getPermissionInfo(String name, int flags) { 1962 // reader 1963 synchronized (mPackages) { 1964 final BasePermission p = mSettings.mPermissions.get(name); 1965 if (p != null) { 1966 return generatePermissionInfo(p, flags); 1967 } 1968 return null; 1969 } 1970 } 1971 1972 @Override 1973 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 1974 // reader 1975 synchronized (mPackages) { 1976 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 1977 for (BasePermission p : mSettings.mPermissions.values()) { 1978 if (group == null) { 1979 if (p.perm == null || p.perm.info.group == null) { 1980 out.add(generatePermissionInfo(p, flags)); 1981 } 1982 } else { 1983 if (p.perm != null && group.equals(p.perm.info.group)) { 1984 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 1985 } 1986 } 1987 } 1988 1989 if (out.size() > 0) { 1990 return out; 1991 } 1992 return mPermissionGroups.containsKey(group) ? out : null; 1993 } 1994 } 1995 1996 @Override 1997 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 1998 // reader 1999 synchronized (mPackages) { 2000 return PackageParser.generatePermissionGroupInfo( 2001 mPermissionGroups.get(name), flags); 2002 } 2003 } 2004 2005 @Override 2006 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2007 // reader 2008 synchronized (mPackages) { 2009 final int N = mPermissionGroups.size(); 2010 ArrayList<PermissionGroupInfo> out 2011 = new ArrayList<PermissionGroupInfo>(N); 2012 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2013 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2014 } 2015 return out; 2016 } 2017 } 2018 2019 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2020 int userId) { 2021 if (!sUserManager.exists(userId)) return null; 2022 PackageSetting ps = mSettings.mPackages.get(packageName); 2023 if (ps != null) { 2024 if (ps.pkg == null) { 2025 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2026 flags, userId); 2027 if (pInfo != null) { 2028 return pInfo.applicationInfo; 2029 } 2030 return null; 2031 } 2032 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2033 ps.readUserState(userId), userId); 2034 } 2035 return null; 2036 } 2037 2038 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2039 int userId) { 2040 if (!sUserManager.exists(userId)) return null; 2041 PackageSetting ps = mSettings.mPackages.get(packageName); 2042 if (ps != null) { 2043 PackageParser.Package pkg = ps.pkg; 2044 if (pkg == null) { 2045 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2046 return null; 2047 } 2048 // Only data remains, so we aren't worried about code paths 2049 pkg = new PackageParser.Package(packageName); 2050 pkg.applicationInfo.packageName = packageName; 2051 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2052 pkg.applicationInfo.dataDir = 2053 getDataPathForPackage(packageName, 0).getPath(); 2054 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2055 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2056 } 2057 return generatePackageInfo(pkg, flags, userId); 2058 } 2059 return null; 2060 } 2061 2062 @Override 2063 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2064 if (!sUserManager.exists(userId)) return null; 2065 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2066 // writer 2067 synchronized (mPackages) { 2068 PackageParser.Package p = mPackages.get(packageName); 2069 if (DEBUG_PACKAGE_INFO) Log.v( 2070 TAG, "getApplicationInfo " + packageName 2071 + ": " + p); 2072 if (p != null) { 2073 PackageSetting ps = mSettings.mPackages.get(packageName); 2074 if (ps == null) return null; 2075 // Note: isEnabledLP() does not apply here - always return info 2076 return PackageParser.generateApplicationInfo( 2077 p, flags, ps.readUserState(userId), userId); 2078 } 2079 if ("android".equals(packageName)||"system".equals(packageName)) { 2080 return mAndroidApplication; 2081 } 2082 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2083 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2084 } 2085 } 2086 return null; 2087 } 2088 2089 2090 @Override 2091 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2092 mContext.enforceCallingOrSelfPermission( 2093 android.Manifest.permission.CLEAR_APP_CACHE, null); 2094 // Queue up an async operation since clearing cache may take a little while. 2095 mHandler.post(new Runnable() { 2096 public void run() { 2097 mHandler.removeCallbacks(this); 2098 int retCode = -1; 2099 synchronized (mInstallLock) { 2100 retCode = mInstaller.freeCache(freeStorageSize); 2101 if (retCode < 0) { 2102 Slog.w(TAG, "Couldn't clear application caches"); 2103 } 2104 } 2105 if (observer != null) { 2106 try { 2107 observer.onRemoveCompleted(null, (retCode >= 0)); 2108 } catch (RemoteException e) { 2109 Slog.w(TAG, "RemoveException when invoking call back"); 2110 } 2111 } 2112 } 2113 }); 2114 } 2115 2116 @Override 2117 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2118 mContext.enforceCallingOrSelfPermission( 2119 android.Manifest.permission.CLEAR_APP_CACHE, null); 2120 // Queue up an async operation since clearing cache may take a little while. 2121 mHandler.post(new Runnable() { 2122 public void run() { 2123 mHandler.removeCallbacks(this); 2124 int retCode = -1; 2125 synchronized (mInstallLock) { 2126 retCode = mInstaller.freeCache(freeStorageSize); 2127 if (retCode < 0) { 2128 Slog.w(TAG, "Couldn't clear application caches"); 2129 } 2130 } 2131 if(pi != null) { 2132 try { 2133 // Callback via pending intent 2134 int code = (retCode >= 0) ? 1 : 0; 2135 pi.sendIntent(null, code, null, 2136 null, null); 2137 } catch (SendIntentException e1) { 2138 Slog.i(TAG, "Failed to send pending intent"); 2139 } 2140 } 2141 } 2142 }); 2143 } 2144 2145 void freeStorage(long freeStorageSize) throws IOException { 2146 synchronized (mInstallLock) { 2147 if (mInstaller.freeCache(freeStorageSize) < 0) { 2148 throw new IOException("Failed to free enough space"); 2149 } 2150 } 2151 } 2152 2153 @Override 2154 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2155 if (!sUserManager.exists(userId)) return null; 2156 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2157 synchronized (mPackages) { 2158 PackageParser.Activity a = mActivities.mActivities.get(component); 2159 2160 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2161 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2162 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2163 if (ps == null) return null; 2164 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2165 userId); 2166 } 2167 if (mResolveComponentName.equals(component)) { 2168 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2169 new PackageUserState(), userId); 2170 } 2171 } 2172 return null; 2173 } 2174 2175 @Override 2176 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2177 String resolvedType) { 2178 synchronized (mPackages) { 2179 PackageParser.Activity a = mActivities.mActivities.get(component); 2180 if (a == null) { 2181 return false; 2182 } 2183 for (int i=0; i<a.intents.size(); i++) { 2184 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2185 intent.getData(), intent.getCategories(), TAG) >= 0) { 2186 return true; 2187 } 2188 } 2189 return false; 2190 } 2191 } 2192 2193 @Override 2194 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2195 if (!sUserManager.exists(userId)) return null; 2196 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2197 synchronized (mPackages) { 2198 PackageParser.Activity a = mReceivers.mActivities.get(component); 2199 if (DEBUG_PACKAGE_INFO) Log.v( 2200 TAG, "getReceiverInfo " + component + ": " + a); 2201 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2202 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2203 if (ps == null) return null; 2204 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2205 userId); 2206 } 2207 } 2208 return null; 2209 } 2210 2211 @Override 2212 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2213 if (!sUserManager.exists(userId)) return null; 2214 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2215 synchronized (mPackages) { 2216 PackageParser.Service s = mServices.mServices.get(component); 2217 if (DEBUG_PACKAGE_INFO) Log.v( 2218 TAG, "getServiceInfo " + component + ": " + s); 2219 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2220 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2221 if (ps == null) return null; 2222 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2223 userId); 2224 } 2225 } 2226 return null; 2227 } 2228 2229 @Override 2230 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2231 if (!sUserManager.exists(userId)) return null; 2232 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2233 synchronized (mPackages) { 2234 PackageParser.Provider p = mProviders.mProviders.get(component); 2235 if (DEBUG_PACKAGE_INFO) Log.v( 2236 TAG, "getProviderInfo " + component + ": " + p); 2237 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2238 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2239 if (ps == null) return null; 2240 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2241 userId); 2242 } 2243 } 2244 return null; 2245 } 2246 2247 @Override 2248 public String[] getSystemSharedLibraryNames() { 2249 Set<String> libSet; 2250 synchronized (mPackages) { 2251 libSet = mSharedLibraries.keySet(); 2252 int size = libSet.size(); 2253 if (size > 0) { 2254 String[] libs = new String[size]; 2255 libSet.toArray(libs); 2256 return libs; 2257 } 2258 } 2259 return null; 2260 } 2261 2262 @Override 2263 public FeatureInfo[] getSystemAvailableFeatures() { 2264 Collection<FeatureInfo> featSet; 2265 synchronized (mPackages) { 2266 featSet = mAvailableFeatures.values(); 2267 int size = featSet.size(); 2268 if (size > 0) { 2269 FeatureInfo[] features = new FeatureInfo[size+1]; 2270 featSet.toArray(features); 2271 FeatureInfo fi = new FeatureInfo(); 2272 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2273 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2274 features[size] = fi; 2275 return features; 2276 } 2277 } 2278 return null; 2279 } 2280 2281 @Override 2282 public boolean hasSystemFeature(String name) { 2283 synchronized (mPackages) { 2284 return mAvailableFeatures.containsKey(name); 2285 } 2286 } 2287 2288 private void checkValidCaller(int uid, int userId) { 2289 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2290 return; 2291 2292 throw new SecurityException("Caller uid=" + uid 2293 + " is not privileged to communicate with user=" + userId); 2294 } 2295 2296 @Override 2297 public int checkPermission(String permName, String pkgName) { 2298 synchronized (mPackages) { 2299 PackageParser.Package p = mPackages.get(pkgName); 2300 if (p != null && p.mExtras != null) { 2301 PackageSetting ps = (PackageSetting)p.mExtras; 2302 if (ps.sharedUser != null) { 2303 if (ps.sharedUser.grantedPermissions.contains(permName)) { 2304 return PackageManager.PERMISSION_GRANTED; 2305 } 2306 } else if (ps.grantedPermissions.contains(permName)) { 2307 return PackageManager.PERMISSION_GRANTED; 2308 } 2309 } 2310 } 2311 return PackageManager.PERMISSION_DENIED; 2312 } 2313 2314 @Override 2315 public int checkUidPermission(String permName, int uid) { 2316 synchronized (mPackages) { 2317 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2318 if (obj != null) { 2319 GrantedPermissions gp = (GrantedPermissions)obj; 2320 if (gp.grantedPermissions.contains(permName)) { 2321 return PackageManager.PERMISSION_GRANTED; 2322 } 2323 } else { 2324 HashSet<String> perms = mSystemPermissions.get(uid); 2325 if (perms != null && perms.contains(permName)) { 2326 return PackageManager.PERMISSION_GRANTED; 2327 } 2328 } 2329 } 2330 return PackageManager.PERMISSION_DENIED; 2331 } 2332 2333 /** 2334 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2335 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2336 * @param checkShell TODO(yamasani): 2337 * @param message the message to log on security exception 2338 */ 2339 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2340 boolean checkShell, String message) { 2341 if (userId < 0) { 2342 throw new IllegalArgumentException("Invalid userId " + userId); 2343 } 2344 if (checkShell) { 2345 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 2346 } 2347 if (userId == UserHandle.getUserId(callingUid)) return; 2348 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2349 if (requireFullPermission) { 2350 mContext.enforceCallingOrSelfPermission( 2351 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2352 } else { 2353 try { 2354 mContext.enforceCallingOrSelfPermission( 2355 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2356 } catch (SecurityException se) { 2357 mContext.enforceCallingOrSelfPermission( 2358 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2359 } 2360 } 2361 } 2362 } 2363 2364 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 2365 if (callingUid == Process.SHELL_UID) { 2366 if (userHandle >= 0 2367 && sUserManager.hasUserRestriction(restriction, userHandle)) { 2368 throw new SecurityException("Shell does not have permission to access user " 2369 + userHandle); 2370 } else if (userHandle < 0) { 2371 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 2372 + Debug.getCallers(3)); 2373 } 2374 } 2375 } 2376 2377 private BasePermission findPermissionTreeLP(String permName) { 2378 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2379 if (permName.startsWith(bp.name) && 2380 permName.length() > bp.name.length() && 2381 permName.charAt(bp.name.length()) == '.') { 2382 return bp; 2383 } 2384 } 2385 return null; 2386 } 2387 2388 private BasePermission checkPermissionTreeLP(String permName) { 2389 if (permName != null) { 2390 BasePermission bp = findPermissionTreeLP(permName); 2391 if (bp != null) { 2392 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2393 return bp; 2394 } 2395 throw new SecurityException("Calling uid " 2396 + Binder.getCallingUid() 2397 + " is not allowed to add to permission tree " 2398 + bp.name + " owned by uid " + bp.uid); 2399 } 2400 } 2401 throw new SecurityException("No permission tree found for " + permName); 2402 } 2403 2404 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2405 if (s1 == null) { 2406 return s2 == null; 2407 } 2408 if (s2 == null) { 2409 return false; 2410 } 2411 if (s1.getClass() != s2.getClass()) { 2412 return false; 2413 } 2414 return s1.equals(s2); 2415 } 2416 2417 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2418 if (pi1.icon != pi2.icon) return false; 2419 if (pi1.logo != pi2.logo) return false; 2420 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2421 if (!compareStrings(pi1.name, pi2.name)) return false; 2422 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2423 // We'll take care of setting this one. 2424 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2425 // These are not currently stored in settings. 2426 //if (!compareStrings(pi1.group, pi2.group)) return false; 2427 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2428 //if (pi1.labelRes != pi2.labelRes) return false; 2429 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2430 return true; 2431 } 2432 2433 int permissionInfoFootprint(PermissionInfo info) { 2434 int size = info.name.length(); 2435 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2436 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2437 return size; 2438 } 2439 2440 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2441 int size = 0; 2442 for (BasePermission perm : mSettings.mPermissions.values()) { 2443 if (perm.uid == tree.uid) { 2444 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2445 } 2446 } 2447 return size; 2448 } 2449 2450 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2451 // We calculate the max size of permissions defined by this uid and throw 2452 // if that plus the size of 'info' would exceed our stated maximum. 2453 if (tree.uid != Process.SYSTEM_UID) { 2454 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2455 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2456 throw new SecurityException("Permission tree size cap exceeded"); 2457 } 2458 } 2459 } 2460 2461 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2462 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2463 throw new SecurityException("Label must be specified in permission"); 2464 } 2465 BasePermission tree = checkPermissionTreeLP(info.name); 2466 BasePermission bp = mSettings.mPermissions.get(info.name); 2467 boolean added = bp == null; 2468 boolean changed = true; 2469 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2470 if (added) { 2471 enforcePermissionCapLocked(info, tree); 2472 bp = new BasePermission(info.name, tree.sourcePackage, 2473 BasePermission.TYPE_DYNAMIC); 2474 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2475 throw new SecurityException( 2476 "Not allowed to modify non-dynamic permission " 2477 + info.name); 2478 } else { 2479 if (bp.protectionLevel == fixedLevel 2480 && bp.perm.owner.equals(tree.perm.owner) 2481 && bp.uid == tree.uid 2482 && comparePermissionInfos(bp.perm.info, info)) { 2483 changed = false; 2484 } 2485 } 2486 bp.protectionLevel = fixedLevel; 2487 info = new PermissionInfo(info); 2488 info.protectionLevel = fixedLevel; 2489 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 2490 bp.perm.info.packageName = tree.perm.info.packageName; 2491 bp.uid = tree.uid; 2492 if (added) { 2493 mSettings.mPermissions.put(info.name, bp); 2494 } 2495 if (changed) { 2496 if (!async) { 2497 mSettings.writeLPr(); 2498 } else { 2499 scheduleWriteSettingsLocked(); 2500 } 2501 } 2502 return added; 2503 } 2504 2505 @Override 2506 public boolean addPermission(PermissionInfo info) { 2507 synchronized (mPackages) { 2508 return addPermissionLocked(info, false); 2509 } 2510 } 2511 2512 @Override 2513 public boolean addPermissionAsync(PermissionInfo info) { 2514 synchronized (mPackages) { 2515 return addPermissionLocked(info, true); 2516 } 2517 } 2518 2519 @Override 2520 public void removePermission(String name) { 2521 synchronized (mPackages) { 2522 checkPermissionTreeLP(name); 2523 BasePermission bp = mSettings.mPermissions.get(name); 2524 if (bp != null) { 2525 if (bp.type != BasePermission.TYPE_DYNAMIC) { 2526 throw new SecurityException( 2527 "Not allowed to modify non-dynamic permission " 2528 + name); 2529 } 2530 mSettings.mPermissions.remove(name); 2531 mSettings.writeLPr(); 2532 } 2533 } 2534 } 2535 2536 private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) { 2537 int index = pkg.requestedPermissions.indexOf(bp.name); 2538 if (index == -1) { 2539 throw new SecurityException("Package " + pkg.packageName 2540 + " has not requested permission " + bp.name); 2541 } 2542 boolean isNormal = 2543 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2544 == PermissionInfo.PROTECTION_NORMAL); 2545 boolean isDangerous = 2546 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2547 == PermissionInfo.PROTECTION_DANGEROUS); 2548 boolean isDevelopment = 2549 ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0); 2550 2551 if (!isNormal && !isDangerous && !isDevelopment) { 2552 throw new SecurityException("Permission " + bp.name 2553 + " is not a changeable permission type"); 2554 } 2555 2556 if (isNormal || isDangerous) { 2557 if (pkg.requestedPermissionsRequired.get(index)) { 2558 throw new SecurityException("Can't change " + bp.name 2559 + ". It is required by the application"); 2560 } 2561 } 2562 } 2563 2564 @Override 2565 public void grantPermission(String packageName, String permissionName) { 2566 mContext.enforceCallingOrSelfPermission( 2567 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2568 synchronized (mPackages) { 2569 final PackageParser.Package pkg = mPackages.get(packageName); 2570 if (pkg == null) { 2571 throw new IllegalArgumentException("Unknown package: " + packageName); 2572 } 2573 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2574 if (bp == null) { 2575 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2576 } 2577 2578 checkGrantRevokePermissions(pkg, bp); 2579 2580 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2581 if (ps == null) { 2582 return; 2583 } 2584 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2585 if (gp.grantedPermissions.add(permissionName)) { 2586 if (ps.haveGids) { 2587 gp.gids = appendInts(gp.gids, bp.gids); 2588 } 2589 mSettings.writeLPr(); 2590 } 2591 } 2592 } 2593 2594 @Override 2595 public void revokePermission(String packageName, String permissionName) { 2596 int changedAppId = -1; 2597 2598 synchronized (mPackages) { 2599 final PackageParser.Package pkg = mPackages.get(packageName); 2600 if (pkg == null) { 2601 throw new IllegalArgumentException("Unknown package: " + packageName); 2602 } 2603 if (pkg.applicationInfo.uid != Binder.getCallingUid()) { 2604 mContext.enforceCallingOrSelfPermission( 2605 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2606 } 2607 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2608 if (bp == null) { 2609 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2610 } 2611 2612 checkGrantRevokePermissions(pkg, bp); 2613 2614 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2615 if (ps == null) { 2616 return; 2617 } 2618 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2619 if (gp.grantedPermissions.remove(permissionName)) { 2620 gp.grantedPermissions.remove(permissionName); 2621 if (ps.haveGids) { 2622 gp.gids = removeInts(gp.gids, bp.gids); 2623 } 2624 mSettings.writeLPr(); 2625 changedAppId = ps.appId; 2626 } 2627 } 2628 2629 if (changedAppId >= 0) { 2630 // We changed the perm on someone, kill its processes. 2631 IActivityManager am = ActivityManagerNative.getDefault(); 2632 if (am != null) { 2633 final int callingUserId = UserHandle.getCallingUserId(); 2634 final long ident = Binder.clearCallingIdentity(); 2635 try { 2636 //XXX we should only revoke for the calling user's app permissions, 2637 // but for now we impact all users. 2638 //am.killUid(UserHandle.getUid(callingUserId, changedAppId), 2639 // "revoke " + permissionName); 2640 int[] users = sUserManager.getUserIds(); 2641 for (int user : users) { 2642 am.killUid(UserHandle.getUid(user, changedAppId), 2643 "revoke " + permissionName); 2644 } 2645 } catch (RemoteException e) { 2646 } finally { 2647 Binder.restoreCallingIdentity(ident); 2648 } 2649 } 2650 } 2651 } 2652 2653 @Override 2654 public boolean isProtectedBroadcast(String actionName) { 2655 synchronized (mPackages) { 2656 return mProtectedBroadcasts.contains(actionName); 2657 } 2658 } 2659 2660 @Override 2661 public int checkSignatures(String pkg1, String pkg2) { 2662 synchronized (mPackages) { 2663 final PackageParser.Package p1 = mPackages.get(pkg1); 2664 final PackageParser.Package p2 = mPackages.get(pkg2); 2665 if (p1 == null || p1.mExtras == null 2666 || p2 == null || p2.mExtras == null) { 2667 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2668 } 2669 return compareSignatures(p1.mSignatures, p2.mSignatures); 2670 } 2671 } 2672 2673 @Override 2674 public int checkUidSignatures(int uid1, int uid2) { 2675 // Map to base uids. 2676 uid1 = UserHandle.getAppId(uid1); 2677 uid2 = UserHandle.getAppId(uid2); 2678 // reader 2679 synchronized (mPackages) { 2680 Signature[] s1; 2681 Signature[] s2; 2682 Object obj = mSettings.getUserIdLPr(uid1); 2683 if (obj != null) { 2684 if (obj instanceof SharedUserSetting) { 2685 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 2686 } else if (obj instanceof PackageSetting) { 2687 s1 = ((PackageSetting)obj).signatures.mSignatures; 2688 } else { 2689 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2690 } 2691 } else { 2692 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2693 } 2694 obj = mSettings.getUserIdLPr(uid2); 2695 if (obj != null) { 2696 if (obj instanceof SharedUserSetting) { 2697 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 2698 } else if (obj instanceof PackageSetting) { 2699 s2 = ((PackageSetting)obj).signatures.mSignatures; 2700 } else { 2701 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2702 } 2703 } else { 2704 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2705 } 2706 return compareSignatures(s1, s2); 2707 } 2708 } 2709 2710 /** 2711 * Compares two sets of signatures. Returns: 2712 * <br /> 2713 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 2714 * <br /> 2715 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 2716 * <br /> 2717 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 2718 * <br /> 2719 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 2720 * <br /> 2721 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 2722 */ 2723 static int compareSignatures(Signature[] s1, Signature[] s2) { 2724 if (s1 == null) { 2725 return s2 == null 2726 ? PackageManager.SIGNATURE_NEITHER_SIGNED 2727 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 2728 } 2729 2730 if (s2 == null) { 2731 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 2732 } 2733 2734 if (s1.length != s2.length) { 2735 return PackageManager.SIGNATURE_NO_MATCH; 2736 } 2737 2738 // Since both signature sets are of size 1, we can compare without HashSets. 2739 if (s1.length == 1) { 2740 return s1[0].equals(s2[0]) ? 2741 PackageManager.SIGNATURE_MATCH : 2742 PackageManager.SIGNATURE_NO_MATCH; 2743 } 2744 2745 HashSet<Signature> set1 = new HashSet<Signature>(); 2746 for (Signature sig : s1) { 2747 set1.add(sig); 2748 } 2749 HashSet<Signature> set2 = new HashSet<Signature>(); 2750 for (Signature sig : s2) { 2751 set2.add(sig); 2752 } 2753 // Make sure s2 contains all signatures in s1. 2754 if (set1.equals(set2)) { 2755 return PackageManager.SIGNATURE_MATCH; 2756 } 2757 return PackageManager.SIGNATURE_NO_MATCH; 2758 } 2759 2760 /** 2761 * If the database version for this type of package (internal storage or 2762 * external storage) is less than the version where package signatures 2763 * were updated, return true. 2764 */ 2765 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2766 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 2767 DatabaseVersion.SIGNATURE_END_ENTITY)) 2768 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 2769 DatabaseVersion.SIGNATURE_END_ENTITY)); 2770 } 2771 2772 /** 2773 * Used for backward compatibility to make sure any packages with 2774 * certificate chains get upgraded to the new style. {@code existingSigs} 2775 * will be in the old format (since they were stored on disk from before the 2776 * system upgrade) and {@code scannedSigs} will be in the newer format. 2777 */ 2778 private int compareSignaturesCompat(PackageSignatures existingSigs, 2779 PackageParser.Package scannedPkg) { 2780 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 2781 return PackageManager.SIGNATURE_NO_MATCH; 2782 } 2783 2784 HashSet<Signature> existingSet = new HashSet<Signature>(); 2785 for (Signature sig : existingSigs.mSignatures) { 2786 existingSet.add(sig); 2787 } 2788 HashSet<Signature> scannedCompatSet = new HashSet<Signature>(); 2789 for (Signature sig : scannedPkg.mSignatures) { 2790 try { 2791 Signature[] chainSignatures = sig.getChainSignatures(); 2792 for (Signature chainSig : chainSignatures) { 2793 scannedCompatSet.add(chainSig); 2794 } 2795 } catch (CertificateEncodingException e) { 2796 scannedCompatSet.add(sig); 2797 } 2798 } 2799 /* 2800 * Make sure the expanded scanned set contains all signatures in the 2801 * existing one. 2802 */ 2803 if (scannedCompatSet.equals(existingSet)) { 2804 // Migrate the old signatures to the new scheme. 2805 existingSigs.assignSignatures(scannedPkg.mSignatures); 2806 // The new KeySets will be re-added later in the scanning process. 2807 synchronized (mPackages) { 2808 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 2809 } 2810 return PackageManager.SIGNATURE_MATCH; 2811 } 2812 return PackageManager.SIGNATURE_NO_MATCH; 2813 } 2814 2815 @Override 2816 public String[] getPackagesForUid(int uid) { 2817 uid = UserHandle.getAppId(uid); 2818 // reader 2819 synchronized (mPackages) { 2820 Object obj = mSettings.getUserIdLPr(uid); 2821 if (obj instanceof SharedUserSetting) { 2822 final SharedUserSetting sus = (SharedUserSetting) obj; 2823 final int N = sus.packages.size(); 2824 final String[] res = new String[N]; 2825 final Iterator<PackageSetting> it = sus.packages.iterator(); 2826 int i = 0; 2827 while (it.hasNext()) { 2828 res[i++] = it.next().name; 2829 } 2830 return res; 2831 } else if (obj instanceof PackageSetting) { 2832 final PackageSetting ps = (PackageSetting) obj; 2833 return new String[] { ps.name }; 2834 } 2835 } 2836 return null; 2837 } 2838 2839 @Override 2840 public String getNameForUid(int uid) { 2841 // reader 2842 synchronized (mPackages) { 2843 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2844 if (obj instanceof SharedUserSetting) { 2845 final SharedUserSetting sus = (SharedUserSetting) obj; 2846 return sus.name + ":" + sus.userId; 2847 } else if (obj instanceof PackageSetting) { 2848 final PackageSetting ps = (PackageSetting) obj; 2849 return ps.name; 2850 } 2851 } 2852 return null; 2853 } 2854 2855 @Override 2856 public int getUidForSharedUser(String sharedUserName) { 2857 if(sharedUserName == null) { 2858 return -1; 2859 } 2860 // reader 2861 synchronized (mPackages) { 2862 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false); 2863 if (suid == null) { 2864 return -1; 2865 } 2866 return suid.userId; 2867 } 2868 } 2869 2870 @Override 2871 public int getFlagsForUid(int uid) { 2872 synchronized (mPackages) { 2873 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2874 if (obj instanceof SharedUserSetting) { 2875 final SharedUserSetting sus = (SharedUserSetting) obj; 2876 return sus.pkgFlags; 2877 } else if (obj instanceof PackageSetting) { 2878 final PackageSetting ps = (PackageSetting) obj; 2879 return ps.pkgFlags; 2880 } 2881 } 2882 return 0; 2883 } 2884 2885 @Override 2886 public String[] getAppOpPermissionPackages(String permissionName) { 2887 synchronized (mPackages) { 2888 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 2889 if (pkgs == null) { 2890 return null; 2891 } 2892 return pkgs.toArray(new String[pkgs.size()]); 2893 } 2894 } 2895 2896 @Override 2897 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 2898 int flags, int userId) { 2899 if (!sUserManager.exists(userId)) return null; 2900 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 2901 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2902 return chooseBestActivity(intent, resolvedType, flags, query, userId); 2903 } 2904 2905 @Override 2906 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 2907 IntentFilter filter, int match, ComponentName activity) { 2908 final int userId = UserHandle.getCallingUserId(); 2909 if (DEBUG_PREFERRED) { 2910 Log.v(TAG, "setLastChosenActivity intent=" + intent 2911 + " resolvedType=" + resolvedType 2912 + " flags=" + flags 2913 + " filter=" + filter 2914 + " match=" + match 2915 + " activity=" + activity); 2916 filter.dump(new PrintStreamPrinter(System.out), " "); 2917 } 2918 intent.setComponent(null); 2919 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2920 // Find any earlier preferred or last chosen entries and nuke them 2921 findPreferredActivity(intent, resolvedType, 2922 flags, query, 0, false, true, false, userId); 2923 // Add the new activity as the last chosen for this filter 2924 addPreferredActivityInternal(filter, match, null, activity, false, userId, 2925 "Setting last chosen"); 2926 } 2927 2928 @Override 2929 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 2930 final int userId = UserHandle.getCallingUserId(); 2931 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 2932 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2933 return findPreferredActivity(intent, resolvedType, flags, query, 0, 2934 false, false, false, userId); 2935 } 2936 2937 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 2938 int flags, List<ResolveInfo> query, int userId) { 2939 if (query != null) { 2940 final int N = query.size(); 2941 if (N == 1) { 2942 return query.get(0); 2943 } else if (N > 1) { 2944 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 2945 // If there is more than one activity with the same priority, 2946 // then let the user decide between them. 2947 ResolveInfo r0 = query.get(0); 2948 ResolveInfo r1 = query.get(1); 2949 if (DEBUG_INTENT_MATCHING || debug) { 2950 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 2951 + r1.activityInfo.name + "=" + r1.priority); 2952 } 2953 // If the first activity has a higher priority, or a different 2954 // default, then it is always desireable to pick it. 2955 if (r0.priority != r1.priority 2956 || r0.preferredOrder != r1.preferredOrder 2957 || r0.isDefault != r1.isDefault) { 2958 return query.get(0); 2959 } 2960 // If we have saved a preference for a preferred activity for 2961 // this Intent, use that. 2962 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 2963 flags, query, r0.priority, true, false, debug, userId); 2964 if (ri != null) { 2965 return ri; 2966 } 2967 if (userId != 0) { 2968 ri = new ResolveInfo(mResolveInfo); 2969 ri.activityInfo = new ActivityInfo(ri.activityInfo); 2970 ri.activityInfo.applicationInfo = new ApplicationInfo( 2971 ri.activityInfo.applicationInfo); 2972 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 2973 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 2974 return ri; 2975 } 2976 return mResolveInfo; 2977 } 2978 } 2979 return null; 2980 } 2981 2982 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 2983 int flags, List<ResolveInfo> query, boolean debug, int userId) { 2984 final int N = query.size(); 2985 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 2986 .get(userId); 2987 // Get the list of persistent preferred activities that handle the intent 2988 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 2989 List<PersistentPreferredActivity> pprefs = ppir != null 2990 ? ppir.queryIntent(intent, resolvedType, 2991 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 2992 : null; 2993 if (pprefs != null && pprefs.size() > 0) { 2994 final int M = pprefs.size(); 2995 for (int i=0; i<M; i++) { 2996 final PersistentPreferredActivity ppa = pprefs.get(i); 2997 if (DEBUG_PREFERRED || debug) { 2998 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 2999 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3000 + "\n component=" + ppa.mComponent); 3001 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3002 } 3003 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3004 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3005 if (DEBUG_PREFERRED || debug) { 3006 Slog.v(TAG, "Found persistent preferred activity:"); 3007 if (ai != null) { 3008 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3009 } else { 3010 Slog.v(TAG, " null"); 3011 } 3012 } 3013 if (ai == null) { 3014 // This previously registered persistent preferred activity 3015 // component is no longer known. Ignore it and do NOT remove it. 3016 continue; 3017 } 3018 for (int j=0; j<N; j++) { 3019 final ResolveInfo ri = query.get(j); 3020 if (!ri.activityInfo.applicationInfo.packageName 3021 .equals(ai.applicationInfo.packageName)) { 3022 continue; 3023 } 3024 if (!ri.activityInfo.name.equals(ai.name)) { 3025 continue; 3026 } 3027 // Found a persistent preference that can handle the intent. 3028 if (DEBUG_PREFERRED || debug) { 3029 Slog.v(TAG, "Returning persistent preferred activity: " + 3030 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3031 } 3032 return ri; 3033 } 3034 } 3035 } 3036 return null; 3037 } 3038 3039 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3040 List<ResolveInfo> query, int priority, boolean always, 3041 boolean removeMatches, boolean debug, int userId) { 3042 if (!sUserManager.exists(userId)) return null; 3043 // writer 3044 synchronized (mPackages) { 3045 if (intent.getSelector() != null) { 3046 intent = intent.getSelector(); 3047 } 3048 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3049 3050 // Try to find a matching persistent preferred activity. 3051 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3052 debug, userId); 3053 3054 // If a persistent preferred activity matched, use it. 3055 if (pri != null) { 3056 return pri; 3057 } 3058 3059 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3060 // Get the list of preferred activities that handle the intent 3061 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3062 List<PreferredActivity> prefs = pir != null 3063 ? pir.queryIntent(intent, resolvedType, 3064 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3065 : null; 3066 if (prefs != null && prefs.size() > 0) { 3067 boolean changed = false; 3068 try { 3069 // First figure out how good the original match set is. 3070 // We will only allow preferred activities that came 3071 // from the same match quality. 3072 int match = 0; 3073 3074 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3075 3076 final int N = query.size(); 3077 for (int j=0; j<N; j++) { 3078 final ResolveInfo ri = query.get(j); 3079 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3080 + ": 0x" + Integer.toHexString(match)); 3081 if (ri.match > match) { 3082 match = ri.match; 3083 } 3084 } 3085 3086 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3087 + Integer.toHexString(match)); 3088 3089 match &= IntentFilter.MATCH_CATEGORY_MASK; 3090 final int M = prefs.size(); 3091 for (int i=0; i<M; i++) { 3092 final PreferredActivity pa = prefs.get(i); 3093 if (DEBUG_PREFERRED || debug) { 3094 Slog.v(TAG, "Checking PreferredActivity ds=" 3095 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3096 + "\n component=" + pa.mPref.mComponent); 3097 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3098 } 3099 if (pa.mPref.mMatch != match) { 3100 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3101 + Integer.toHexString(pa.mPref.mMatch)); 3102 continue; 3103 } 3104 // If it's not an "always" type preferred activity and that's what we're 3105 // looking for, skip it. 3106 if (always && !pa.mPref.mAlways) { 3107 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3108 continue; 3109 } 3110 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3111 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3112 if (DEBUG_PREFERRED || debug) { 3113 Slog.v(TAG, "Found preferred activity:"); 3114 if (ai != null) { 3115 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3116 } else { 3117 Slog.v(TAG, " null"); 3118 } 3119 } 3120 if (ai == null) { 3121 // This previously registered preferred activity 3122 // component is no longer known. Most likely an update 3123 // to the app was installed and in the new version this 3124 // component no longer exists. Clean it up by removing 3125 // it from the preferred activities list, and skip it. 3126 Slog.w(TAG, "Removing dangling preferred activity: " 3127 + pa.mPref.mComponent); 3128 pir.removeFilter(pa); 3129 changed = true; 3130 continue; 3131 } 3132 for (int j=0; j<N; j++) { 3133 final ResolveInfo ri = query.get(j); 3134 if (!ri.activityInfo.applicationInfo.packageName 3135 .equals(ai.applicationInfo.packageName)) { 3136 continue; 3137 } 3138 if (!ri.activityInfo.name.equals(ai.name)) { 3139 continue; 3140 } 3141 3142 if (removeMatches) { 3143 pir.removeFilter(pa); 3144 changed = true; 3145 if (DEBUG_PREFERRED) { 3146 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3147 } 3148 break; 3149 } 3150 3151 // Okay we found a previously set preferred or last chosen app. 3152 // If the result set is different from when this 3153 // was created, we need to clear it and re-ask the 3154 // user their preference, if we're looking for an "always" type entry. 3155 if (always && !pa.mPref.sameSet(query, priority)) { 3156 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3157 + intent + " type " + resolvedType); 3158 if (DEBUG_PREFERRED) { 3159 Slog.v(TAG, "Removing preferred activity since set changed " 3160 + pa.mPref.mComponent); 3161 } 3162 pir.removeFilter(pa); 3163 // Re-add the filter as a "last chosen" entry (!always) 3164 PreferredActivity lastChosen = new PreferredActivity( 3165 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3166 pir.addFilter(lastChosen); 3167 changed = true; 3168 return null; 3169 } 3170 3171 // Yay! Either the set matched or we're looking for the last chosen 3172 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3173 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3174 return ri; 3175 } 3176 } 3177 } finally { 3178 if (changed) { 3179 if (DEBUG_PREFERRED) { 3180 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 3181 } 3182 mSettings.writePackageRestrictionsLPr(userId); 3183 } 3184 } 3185 } 3186 } 3187 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3188 return null; 3189 } 3190 3191 /* 3192 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3193 */ 3194 @Override 3195 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3196 int targetUserId) { 3197 mContext.enforceCallingOrSelfPermission( 3198 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3199 List<CrossProfileIntentFilter> matches = 3200 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3201 if (matches != null) { 3202 int size = matches.size(); 3203 for (int i = 0; i < size; i++) { 3204 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3205 } 3206 } 3207 return false; 3208 } 3209 3210 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3211 String resolvedType, int userId) { 3212 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3213 if (resolver != null) { 3214 return resolver.queryIntent(intent, resolvedType, false, userId); 3215 } 3216 return null; 3217 } 3218 3219 @Override 3220 public List<ResolveInfo> queryIntentActivities(Intent intent, 3221 String resolvedType, int flags, int userId) { 3222 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3223 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 3224 ComponentName comp = intent.getComponent(); 3225 if (comp == null) { 3226 if (intent.getSelector() != null) { 3227 intent = intent.getSelector(); 3228 comp = intent.getComponent(); 3229 } 3230 } 3231 3232 if (comp != null) { 3233 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3234 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3235 if (ai != null) { 3236 final ResolveInfo ri = new ResolveInfo(); 3237 ri.activityInfo = ai; 3238 list.add(ri); 3239 } 3240 return list; 3241 } 3242 3243 // reader 3244 synchronized (mPackages) { 3245 final String pkgName = intent.getPackage(); 3246 if (pkgName == null) { 3247 List<CrossProfileIntentFilter> matchingFilters = 3248 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3249 // Check for results that need to skip the current profile. 3250 ResolveInfo resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3251 resolvedType, flags, userId); 3252 if (resolveInfo != null) { 3253 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3254 result.add(resolveInfo); 3255 return result; 3256 } 3257 // Check for cross profile results. 3258 resolveInfo = queryCrossProfileIntents( 3259 matchingFilters, intent, resolvedType, flags, userId); 3260 3261 // Check for results in the current profile. 3262 List<ResolveInfo> result = mActivities.queryIntent( 3263 intent, resolvedType, flags, userId); 3264 if (resolveInfo != null) { 3265 result.add(resolveInfo); 3266 Collections.sort(result, mResolvePrioritySorter); 3267 } 3268 return result; 3269 } 3270 final PackageParser.Package pkg = mPackages.get(pkgName); 3271 if (pkg != null) { 3272 return mActivities.queryIntentForPackage(intent, resolvedType, flags, 3273 pkg.activities, userId); 3274 } 3275 return new ArrayList<ResolveInfo>(); 3276 } 3277 } 3278 3279 private ResolveInfo querySkipCurrentProfileIntents( 3280 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3281 int flags, int sourceUserId) { 3282 if (matchingFilters != null) { 3283 int size = matchingFilters.size(); 3284 for (int i = 0; i < size; i ++) { 3285 CrossProfileIntentFilter filter = matchingFilters.get(i); 3286 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 3287 // Checking if there are activities in the target user that can handle the 3288 // intent. 3289 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3290 flags, sourceUserId); 3291 if (resolveInfo != null) { 3292 return resolveInfo; 3293 } 3294 } 3295 } 3296 } 3297 return null; 3298 } 3299 3300 // Return matching ResolveInfo if any for skip current profile intent filters. 3301 private ResolveInfo queryCrossProfileIntents( 3302 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3303 int flags, int sourceUserId) { 3304 if (matchingFilters != null) { 3305 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 3306 // match the same intent. For performance reasons, it is better not to 3307 // run queryIntent twice for the same userId 3308 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 3309 int size = matchingFilters.size(); 3310 for (int i = 0; i < size; i++) { 3311 CrossProfileIntentFilter filter = matchingFilters.get(i); 3312 int targetUserId = filter.getTargetUserId(); 3313 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 3314 && !alreadyTriedUserIds.get(targetUserId)) { 3315 // Checking if there are activities in the target user that can handle the 3316 // intent. 3317 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3318 flags, sourceUserId); 3319 if (resolveInfo != null) return resolveInfo; 3320 alreadyTriedUserIds.put(targetUserId, true); 3321 } 3322 } 3323 } 3324 return null; 3325 } 3326 3327 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 3328 String resolvedType, int flags, int sourceUserId) { 3329 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 3330 resolvedType, flags, filter.getTargetUserId()); 3331 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 3332 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 3333 } 3334 return null; 3335 } 3336 3337 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 3338 int sourceUserId, int targetUserId) { 3339 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 3340 String className; 3341 if (targetUserId == UserHandle.USER_OWNER) { 3342 className = FORWARD_INTENT_TO_USER_OWNER; 3343 } else { 3344 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 3345 } 3346 ComponentName forwardingActivityComponentName = new ComponentName( 3347 mAndroidApplication.packageName, className); 3348 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 3349 sourceUserId); 3350 if (targetUserId == UserHandle.USER_OWNER) { 3351 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 3352 forwardingResolveInfo.noResourceId = true; 3353 } 3354 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 3355 forwardingResolveInfo.priority = 0; 3356 forwardingResolveInfo.preferredOrder = 0; 3357 forwardingResolveInfo.match = 0; 3358 forwardingResolveInfo.isDefault = true; 3359 forwardingResolveInfo.filter = filter; 3360 forwardingResolveInfo.targetUserId = targetUserId; 3361 return forwardingResolveInfo; 3362 } 3363 3364 @Override 3365 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 3366 Intent[] specifics, String[] specificTypes, Intent intent, 3367 String resolvedType, int flags, int userId) { 3368 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3369 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 3370 false, "query intent activity options"); 3371 final String resultsAction = intent.getAction(); 3372 3373 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 3374 | PackageManager.GET_RESOLVED_FILTER, userId); 3375 3376 if (DEBUG_INTENT_MATCHING) { 3377 Log.v(TAG, "Query " + intent + ": " + results); 3378 } 3379 3380 int specificsPos = 0; 3381 int N; 3382 3383 // todo: note that the algorithm used here is O(N^2). This 3384 // isn't a problem in our current environment, but if we start running 3385 // into situations where we have more than 5 or 10 matches then this 3386 // should probably be changed to something smarter... 3387 3388 // First we go through and resolve each of the specific items 3389 // that were supplied, taking care of removing any corresponding 3390 // duplicate items in the generic resolve list. 3391 if (specifics != null) { 3392 for (int i=0; i<specifics.length; i++) { 3393 final Intent sintent = specifics[i]; 3394 if (sintent == null) { 3395 continue; 3396 } 3397 3398 if (DEBUG_INTENT_MATCHING) { 3399 Log.v(TAG, "Specific #" + i + ": " + sintent); 3400 } 3401 3402 String action = sintent.getAction(); 3403 if (resultsAction != null && resultsAction.equals(action)) { 3404 // If this action was explicitly requested, then don't 3405 // remove things that have it. 3406 action = null; 3407 } 3408 3409 ResolveInfo ri = null; 3410 ActivityInfo ai = null; 3411 3412 ComponentName comp = sintent.getComponent(); 3413 if (comp == null) { 3414 ri = resolveIntent( 3415 sintent, 3416 specificTypes != null ? specificTypes[i] : null, 3417 flags, userId); 3418 if (ri == null) { 3419 continue; 3420 } 3421 if (ri == mResolveInfo) { 3422 // ACK! Must do something better with this. 3423 } 3424 ai = ri.activityInfo; 3425 comp = new ComponentName(ai.applicationInfo.packageName, 3426 ai.name); 3427 } else { 3428 ai = getActivityInfo(comp, flags, userId); 3429 if (ai == null) { 3430 continue; 3431 } 3432 } 3433 3434 // Look for any generic query activities that are duplicates 3435 // of this specific one, and remove them from the results. 3436 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 3437 N = results.size(); 3438 int j; 3439 for (j=specificsPos; j<N; j++) { 3440 ResolveInfo sri = results.get(j); 3441 if ((sri.activityInfo.name.equals(comp.getClassName()) 3442 && sri.activityInfo.applicationInfo.packageName.equals( 3443 comp.getPackageName())) 3444 || (action != null && sri.filter.matchAction(action))) { 3445 results.remove(j); 3446 if (DEBUG_INTENT_MATCHING) Log.v( 3447 TAG, "Removing duplicate item from " + j 3448 + " due to specific " + specificsPos); 3449 if (ri == null) { 3450 ri = sri; 3451 } 3452 j--; 3453 N--; 3454 } 3455 } 3456 3457 // Add this specific item to its proper place. 3458 if (ri == null) { 3459 ri = new ResolveInfo(); 3460 ri.activityInfo = ai; 3461 } 3462 results.add(specificsPos, ri); 3463 ri.specificIndex = i; 3464 specificsPos++; 3465 } 3466 } 3467 3468 // Now we go through the remaining generic results and remove any 3469 // duplicate actions that are found here. 3470 N = results.size(); 3471 for (int i=specificsPos; i<N-1; i++) { 3472 final ResolveInfo rii = results.get(i); 3473 if (rii.filter == null) { 3474 continue; 3475 } 3476 3477 // Iterate over all of the actions of this result's intent 3478 // filter... typically this should be just one. 3479 final Iterator<String> it = rii.filter.actionsIterator(); 3480 if (it == null) { 3481 continue; 3482 } 3483 while (it.hasNext()) { 3484 final String action = it.next(); 3485 if (resultsAction != null && resultsAction.equals(action)) { 3486 // If this action was explicitly requested, then don't 3487 // remove things that have it. 3488 continue; 3489 } 3490 for (int j=i+1; j<N; j++) { 3491 final ResolveInfo rij = results.get(j); 3492 if (rij.filter != null && rij.filter.hasAction(action)) { 3493 results.remove(j); 3494 if (DEBUG_INTENT_MATCHING) Log.v( 3495 TAG, "Removing duplicate item from " + j 3496 + " due to action " + action + " at " + i); 3497 j--; 3498 N--; 3499 } 3500 } 3501 } 3502 3503 // If the caller didn't request filter information, drop it now 3504 // so we don't have to marshall/unmarshall it. 3505 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3506 rii.filter = null; 3507 } 3508 } 3509 3510 // Filter out the caller activity if so requested. 3511 if (caller != null) { 3512 N = results.size(); 3513 for (int i=0; i<N; i++) { 3514 ActivityInfo ainfo = results.get(i).activityInfo; 3515 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 3516 && caller.getClassName().equals(ainfo.name)) { 3517 results.remove(i); 3518 break; 3519 } 3520 } 3521 } 3522 3523 // If the caller didn't request filter information, 3524 // drop them now so we don't have to 3525 // marshall/unmarshall it. 3526 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3527 N = results.size(); 3528 for (int i=0; i<N; i++) { 3529 results.get(i).filter = null; 3530 } 3531 } 3532 3533 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 3534 return results; 3535 } 3536 3537 @Override 3538 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 3539 int userId) { 3540 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3541 ComponentName comp = intent.getComponent(); 3542 if (comp == null) { 3543 if (intent.getSelector() != null) { 3544 intent = intent.getSelector(); 3545 comp = intent.getComponent(); 3546 } 3547 } 3548 if (comp != null) { 3549 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3550 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 3551 if (ai != null) { 3552 ResolveInfo ri = new ResolveInfo(); 3553 ri.activityInfo = ai; 3554 list.add(ri); 3555 } 3556 return list; 3557 } 3558 3559 // reader 3560 synchronized (mPackages) { 3561 String pkgName = intent.getPackage(); 3562 if (pkgName == null) { 3563 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 3564 } 3565 final PackageParser.Package pkg = mPackages.get(pkgName); 3566 if (pkg != null) { 3567 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 3568 userId); 3569 } 3570 return null; 3571 } 3572 } 3573 3574 @Override 3575 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 3576 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 3577 if (!sUserManager.exists(userId)) return null; 3578 if (query != null) { 3579 if (query.size() >= 1) { 3580 // If there is more than one service with the same priority, 3581 // just arbitrarily pick the first one. 3582 return query.get(0); 3583 } 3584 } 3585 return null; 3586 } 3587 3588 @Override 3589 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 3590 int userId) { 3591 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3592 ComponentName comp = intent.getComponent(); 3593 if (comp == null) { 3594 if (intent.getSelector() != null) { 3595 intent = intent.getSelector(); 3596 comp = intent.getComponent(); 3597 } 3598 } 3599 if (comp != null) { 3600 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3601 final ServiceInfo si = getServiceInfo(comp, flags, userId); 3602 if (si != null) { 3603 final ResolveInfo ri = new ResolveInfo(); 3604 ri.serviceInfo = si; 3605 list.add(ri); 3606 } 3607 return list; 3608 } 3609 3610 // reader 3611 synchronized (mPackages) { 3612 String pkgName = intent.getPackage(); 3613 if (pkgName == null) { 3614 return mServices.queryIntent(intent, resolvedType, flags, userId); 3615 } 3616 final PackageParser.Package pkg = mPackages.get(pkgName); 3617 if (pkg != null) { 3618 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 3619 userId); 3620 } 3621 return null; 3622 } 3623 } 3624 3625 @Override 3626 public List<ResolveInfo> queryIntentContentProviders( 3627 Intent intent, String resolvedType, int flags, int userId) { 3628 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3629 ComponentName comp = intent.getComponent(); 3630 if (comp == null) { 3631 if (intent.getSelector() != null) { 3632 intent = intent.getSelector(); 3633 comp = intent.getComponent(); 3634 } 3635 } 3636 if (comp != null) { 3637 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3638 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 3639 if (pi != null) { 3640 final ResolveInfo ri = new ResolveInfo(); 3641 ri.providerInfo = pi; 3642 list.add(ri); 3643 } 3644 return list; 3645 } 3646 3647 // reader 3648 synchronized (mPackages) { 3649 String pkgName = intent.getPackage(); 3650 if (pkgName == null) { 3651 return mProviders.queryIntent(intent, resolvedType, flags, userId); 3652 } 3653 final PackageParser.Package pkg = mPackages.get(pkgName); 3654 if (pkg != null) { 3655 return mProviders.queryIntentForPackage( 3656 intent, resolvedType, flags, pkg.providers, userId); 3657 } 3658 return null; 3659 } 3660 } 3661 3662 @Override 3663 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 3664 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3665 3666 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 3667 3668 // writer 3669 synchronized (mPackages) { 3670 ArrayList<PackageInfo> list; 3671 if (listUninstalled) { 3672 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 3673 for (PackageSetting ps : mSettings.mPackages.values()) { 3674 PackageInfo pi; 3675 if (ps.pkg != null) { 3676 pi = generatePackageInfo(ps.pkg, flags, userId); 3677 } else { 3678 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3679 } 3680 if (pi != null) { 3681 list.add(pi); 3682 } 3683 } 3684 } else { 3685 list = new ArrayList<PackageInfo>(mPackages.size()); 3686 for (PackageParser.Package p : mPackages.values()) { 3687 PackageInfo pi = generatePackageInfo(p, flags, userId); 3688 if (pi != null) { 3689 list.add(pi); 3690 } 3691 } 3692 } 3693 3694 return new ParceledListSlice<PackageInfo>(list); 3695 } 3696 } 3697 3698 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 3699 String[] permissions, boolean[] tmp, int flags, int userId) { 3700 int numMatch = 0; 3701 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 3702 for (int i=0; i<permissions.length; i++) { 3703 if (gp.grantedPermissions.contains(permissions[i])) { 3704 tmp[i] = true; 3705 numMatch++; 3706 } else { 3707 tmp[i] = false; 3708 } 3709 } 3710 if (numMatch == 0) { 3711 return; 3712 } 3713 PackageInfo pi; 3714 if (ps.pkg != null) { 3715 pi = generatePackageInfo(ps.pkg, flags, userId); 3716 } else { 3717 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3718 } 3719 // The above might return null in cases of uninstalled apps or install-state 3720 // skew across users/profiles. 3721 if (pi != null) { 3722 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 3723 if (numMatch == permissions.length) { 3724 pi.requestedPermissions = permissions; 3725 } else { 3726 pi.requestedPermissions = new String[numMatch]; 3727 numMatch = 0; 3728 for (int i=0; i<permissions.length; i++) { 3729 if (tmp[i]) { 3730 pi.requestedPermissions[numMatch] = permissions[i]; 3731 numMatch++; 3732 } 3733 } 3734 } 3735 } 3736 list.add(pi); 3737 } 3738 } 3739 3740 @Override 3741 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 3742 String[] permissions, int flags, int userId) { 3743 if (!sUserManager.exists(userId)) return null; 3744 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3745 3746 // writer 3747 synchronized (mPackages) { 3748 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 3749 boolean[] tmpBools = new boolean[permissions.length]; 3750 if (listUninstalled) { 3751 for (PackageSetting ps : mSettings.mPackages.values()) { 3752 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 3753 } 3754 } else { 3755 for (PackageParser.Package pkg : mPackages.values()) { 3756 PackageSetting ps = (PackageSetting)pkg.mExtras; 3757 if (ps != null) { 3758 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 3759 userId); 3760 } 3761 } 3762 } 3763 3764 return new ParceledListSlice<PackageInfo>(list); 3765 } 3766 } 3767 3768 @Override 3769 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 3770 if (!sUserManager.exists(userId)) return null; 3771 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3772 3773 // writer 3774 synchronized (mPackages) { 3775 ArrayList<ApplicationInfo> list; 3776 if (listUninstalled) { 3777 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 3778 for (PackageSetting ps : mSettings.mPackages.values()) { 3779 ApplicationInfo ai; 3780 if (ps.pkg != null) { 3781 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3782 ps.readUserState(userId), userId); 3783 } else { 3784 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 3785 } 3786 if (ai != null) { 3787 list.add(ai); 3788 } 3789 } 3790 } else { 3791 list = new ArrayList<ApplicationInfo>(mPackages.size()); 3792 for (PackageParser.Package p : mPackages.values()) { 3793 if (p.mExtras != null) { 3794 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3795 ((PackageSetting)p.mExtras).readUserState(userId), userId); 3796 if (ai != null) { 3797 list.add(ai); 3798 } 3799 } 3800 } 3801 } 3802 3803 return new ParceledListSlice<ApplicationInfo>(list); 3804 } 3805 } 3806 3807 public List<ApplicationInfo> getPersistentApplications(int flags) { 3808 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 3809 3810 // reader 3811 synchronized (mPackages) { 3812 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 3813 final int userId = UserHandle.getCallingUserId(); 3814 while (i.hasNext()) { 3815 final PackageParser.Package p = i.next(); 3816 if (p.applicationInfo != null 3817 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 3818 && (!mSafeMode || isSystemApp(p))) { 3819 PackageSetting ps = mSettings.mPackages.get(p.packageName); 3820 if (ps != null) { 3821 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3822 ps.readUserState(userId), userId); 3823 if (ai != null) { 3824 finalList.add(ai); 3825 } 3826 } 3827 } 3828 } 3829 } 3830 3831 return finalList; 3832 } 3833 3834 @Override 3835 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 3836 if (!sUserManager.exists(userId)) return null; 3837 // reader 3838 synchronized (mPackages) { 3839 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 3840 PackageSetting ps = provider != null 3841 ? mSettings.mPackages.get(provider.owner.packageName) 3842 : null; 3843 return ps != null 3844 && mSettings.isEnabledLPr(provider.info, flags, userId) 3845 && (!mSafeMode || (provider.info.applicationInfo.flags 3846 &ApplicationInfo.FLAG_SYSTEM) != 0) 3847 ? PackageParser.generateProviderInfo(provider, flags, 3848 ps.readUserState(userId), userId) 3849 : null; 3850 } 3851 } 3852 3853 /** 3854 * @deprecated 3855 */ 3856 @Deprecated 3857 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 3858 // reader 3859 synchronized (mPackages) { 3860 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 3861 .entrySet().iterator(); 3862 final int userId = UserHandle.getCallingUserId(); 3863 while (i.hasNext()) { 3864 Map.Entry<String, PackageParser.Provider> entry = i.next(); 3865 PackageParser.Provider p = entry.getValue(); 3866 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3867 3868 if (ps != null && p.syncable 3869 && (!mSafeMode || (p.info.applicationInfo.flags 3870 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 3871 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 3872 ps.readUserState(userId), userId); 3873 if (info != null) { 3874 outNames.add(entry.getKey()); 3875 outInfo.add(info); 3876 } 3877 } 3878 } 3879 } 3880 } 3881 3882 @Override 3883 public List<ProviderInfo> queryContentProviders(String processName, 3884 int uid, int flags) { 3885 ArrayList<ProviderInfo> finalList = null; 3886 // reader 3887 synchronized (mPackages) { 3888 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 3889 final int userId = processName != null ? 3890 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 3891 while (i.hasNext()) { 3892 final PackageParser.Provider p = i.next(); 3893 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3894 if (ps != null && p.info.authority != null 3895 && (processName == null 3896 || (p.info.processName.equals(processName) 3897 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 3898 && mSettings.isEnabledLPr(p.info, flags, userId) 3899 && (!mSafeMode 3900 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 3901 if (finalList == null) { 3902 finalList = new ArrayList<ProviderInfo>(3); 3903 } 3904 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 3905 ps.readUserState(userId), userId); 3906 if (info != null) { 3907 finalList.add(info); 3908 } 3909 } 3910 } 3911 } 3912 3913 if (finalList != null) { 3914 Collections.sort(finalList, mProviderInitOrderSorter); 3915 } 3916 3917 return finalList; 3918 } 3919 3920 @Override 3921 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 3922 int flags) { 3923 // reader 3924 synchronized (mPackages) { 3925 final PackageParser.Instrumentation i = mInstrumentation.get(name); 3926 return PackageParser.generateInstrumentationInfo(i, flags); 3927 } 3928 } 3929 3930 @Override 3931 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 3932 int flags) { 3933 ArrayList<InstrumentationInfo> finalList = 3934 new ArrayList<InstrumentationInfo>(); 3935 3936 // reader 3937 synchronized (mPackages) { 3938 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 3939 while (i.hasNext()) { 3940 final PackageParser.Instrumentation p = i.next(); 3941 if (targetPackage == null 3942 || targetPackage.equals(p.info.targetPackage)) { 3943 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 3944 flags); 3945 if (ii != null) { 3946 finalList.add(ii); 3947 } 3948 } 3949 } 3950 } 3951 3952 return finalList; 3953 } 3954 3955 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 3956 HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 3957 if (overlays == null) { 3958 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 3959 return; 3960 } 3961 for (PackageParser.Package opkg : overlays.values()) { 3962 // Not much to do if idmap fails: we already logged the error 3963 // and we certainly don't want to abort installation of pkg simply 3964 // because an overlay didn't fit properly. For these reasons, 3965 // ignore the return value of createIdmapForPackagePairLI. 3966 createIdmapForPackagePairLI(pkg, opkg); 3967 } 3968 } 3969 3970 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 3971 PackageParser.Package opkg) { 3972 if (!opkg.mTrustedOverlay) { 3973 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 3974 opkg.baseCodePath + ": overlay not trusted"); 3975 return false; 3976 } 3977 HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 3978 if (overlaySet == null) { 3979 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 3980 opkg.baseCodePath + " but target package has no known overlays"); 3981 return false; 3982 } 3983 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 3984 // TODO: generate idmap for split APKs 3985 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 3986 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 3987 + opkg.baseCodePath); 3988 return false; 3989 } 3990 PackageParser.Package[] overlayArray = 3991 overlaySet.values().toArray(new PackageParser.Package[0]); 3992 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 3993 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 3994 return p1.mOverlayPriority - p2.mOverlayPriority; 3995 } 3996 }; 3997 Arrays.sort(overlayArray, cmp); 3998 3999 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4000 int i = 0; 4001 for (PackageParser.Package p : overlayArray) { 4002 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4003 } 4004 return true; 4005 } 4006 4007 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 4008 final File[] files = dir.listFiles(); 4009 if (ArrayUtils.isEmpty(files)) { 4010 Log.d(TAG, "No files in app dir " + dir); 4011 return; 4012 } 4013 4014 if (DEBUG_PACKAGE_SCANNING) { 4015 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 4016 + " flags=0x" + Integer.toHexString(parseFlags)); 4017 } 4018 4019 for (File file : files) { 4020 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 4021 && !PackageInstallerService.isStageName(file.getName()); 4022 if (!isPackage) { 4023 // Ignore entries which are not packages 4024 continue; 4025 } 4026 try { 4027 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 4028 scanFlags, currentTime, null); 4029 } catch (PackageManagerException e) { 4030 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4031 4032 // Delete invalid userdata apps 4033 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4034 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4035 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 4036 if (file.isDirectory()) { 4037 FileUtils.deleteContents(file); 4038 } 4039 file.delete(); 4040 } 4041 } 4042 } 4043 } 4044 4045 private static File getSettingsProblemFile() { 4046 File dataDir = Environment.getDataDirectory(); 4047 File systemDir = new File(dataDir, "system"); 4048 File fname = new File(systemDir, "uiderrors.txt"); 4049 return fname; 4050 } 4051 4052 static void reportSettingsProblem(int priority, String msg) { 4053 logCriticalInfo(priority, msg); 4054 } 4055 4056 static void logCriticalInfo(int priority, String msg) { 4057 Slog.println(priority, TAG, msg); 4058 EventLogTags.writePmCriticalInfo(msg); 4059 try { 4060 File fname = getSettingsProblemFile(); 4061 FileOutputStream out = new FileOutputStream(fname, true); 4062 PrintWriter pw = new FastPrintWriter(out); 4063 SimpleDateFormat formatter = new SimpleDateFormat(); 4064 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4065 pw.println(dateString + ": " + msg); 4066 pw.close(); 4067 FileUtils.setPermissions( 4068 fname.toString(), 4069 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4070 -1, -1); 4071 } catch (java.io.IOException e) { 4072 } 4073 } 4074 4075 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 4076 PackageParser.Package pkg, File srcFile, int parseFlags) 4077 throws PackageManagerException { 4078 if (ps != null 4079 && ps.codePath.equals(srcFile) 4080 && ps.timeStamp == srcFile.lastModified() 4081 && !isCompatSignatureUpdateNeeded(pkg)) { 4082 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4083 if (ps.signatures.mSignatures != null 4084 && ps.signatures.mSignatures.length != 0 4085 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4086 // Optimization: reuse the existing cached certificates 4087 // if the package appears to be unchanged. 4088 pkg.mSignatures = ps.signatures.mSignatures; 4089 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4090 synchronized (mPackages) { 4091 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 4092 } 4093 return; 4094 } 4095 4096 Slog.w(TAG, "PackageSetting for " + ps.name 4097 + " is missing signatures. Collecting certs again to recover them."); 4098 } else { 4099 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4100 } 4101 4102 try { 4103 pp.collectCertificates(pkg, parseFlags); 4104 pp.collectManifestDigest(pkg); 4105 } catch (PackageParserException e) { 4106 throw PackageManagerException.from(e); 4107 } 4108 } 4109 4110 /* 4111 * Scan a package and return the newly parsed package. 4112 * Returns null in case of errors and the error code is stored in mLastScanError 4113 */ 4114 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 4115 long currentTime, UserHandle user) throws PackageManagerException { 4116 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4117 parseFlags |= mDefParseFlags; 4118 PackageParser pp = new PackageParser(); 4119 pp.setSeparateProcesses(mSeparateProcesses); 4120 pp.setOnlyCoreApps(mOnlyCore); 4121 pp.setDisplayMetrics(mMetrics); 4122 4123 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 4124 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4125 } 4126 4127 final PackageParser.Package pkg; 4128 try { 4129 pkg = pp.parsePackage(scanFile, parseFlags); 4130 } catch (PackageParserException e) { 4131 throw PackageManagerException.from(e); 4132 } 4133 4134 PackageSetting ps = null; 4135 PackageSetting updatedPkg; 4136 // reader 4137 synchronized (mPackages) { 4138 // Look to see if we already know about this package. 4139 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4140 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4141 // This package has been renamed to its original name. Let's 4142 // use that. 4143 ps = mSettings.peekPackageLPr(oldName); 4144 } 4145 // If there was no original package, see one for the real package name. 4146 if (ps == null) { 4147 ps = mSettings.peekPackageLPr(pkg.packageName); 4148 } 4149 // Check to see if this package could be hiding/updating a system 4150 // package. Must look for it either under the original or real 4151 // package name depending on our state. 4152 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4153 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4154 } 4155 boolean updatedPkgBetter = false; 4156 // First check if this is a system package that may involve an update 4157 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4158 if (ps != null && !ps.codePath.equals(scanFile)) { 4159 // The path has changed from what was last scanned... check the 4160 // version of the new path against what we have stored to determine 4161 // what to do. 4162 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4163 if (pkg.mVersionCode < ps.versionCode) { 4164 // The system package has been updated and the code path does not match 4165 // Ignore entry. Skip it. 4166 logCriticalInfo(Log.INFO, "Package " + ps.name + " at " + scanFile 4167 + " ignored: updated version " + ps.versionCode 4168 + " better than this " + pkg.mVersionCode); 4169 if (!updatedPkg.codePath.equals(scanFile)) { 4170 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4171 + ps.name + " changing from " + updatedPkg.codePathString 4172 + " to " + scanFile); 4173 updatedPkg.codePath = scanFile; 4174 updatedPkg.codePathString = scanFile.toString(); 4175 // This is the point at which we know that the system-disk APK 4176 // for this package has moved during a reboot (e.g. due to an OTA), 4177 // so we need to reevaluate it for privilege policy. 4178 if (locationIsPrivileged(scanFile)) { 4179 updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED; 4180 } 4181 } 4182 updatedPkg.pkg = pkg; 4183 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 4184 } else { 4185 // The current app on the system partition is better than 4186 // what we have updated to on the data partition; switch 4187 // back to the system partition version. 4188 // At this point, its safely assumed that package installation for 4189 // apps in system partition will go through. If not there won't be a working 4190 // version of the app 4191 // writer 4192 synchronized (mPackages) { 4193 // Just remove the loaded entries from package lists. 4194 mPackages.remove(ps.name); 4195 } 4196 4197 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 4198 + "reverting from " + ps.codePathString 4199 + ": new version " + pkg.mVersionCode 4200 + " better than installed " + ps.versionCode); 4201 4202 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4203 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4204 getAppDexInstructionSets(ps)); 4205 synchronized (mInstallLock) { 4206 args.cleanUpResourcesLI(); 4207 } 4208 synchronized (mPackages) { 4209 mSettings.enableSystemPackageLPw(ps.name); 4210 } 4211 updatedPkgBetter = true; 4212 } 4213 } 4214 } 4215 4216 if (updatedPkg != null) { 4217 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4218 // initially 4219 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4220 4221 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4222 // flag set initially 4223 if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) { 4224 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4225 } 4226 } 4227 4228 // Verify certificates against what was last scanned 4229 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 4230 4231 /* 4232 * A new system app appeared, but we already had a non-system one of the 4233 * same name installed earlier. 4234 */ 4235 boolean shouldHideSystemApp = false; 4236 if (updatedPkg == null && ps != null 4237 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4238 /* 4239 * Check to make sure the signatures match first. If they don't, 4240 * wipe the installed application and its data. 4241 */ 4242 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4243 != PackageManager.SIGNATURE_MATCH) { 4244 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 4245 + " signatures don't match existing userdata copy; removing"); 4246 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4247 ps = null; 4248 } else { 4249 /* 4250 * If the newly-added system app is an older version than the 4251 * already installed version, hide it. It will be scanned later 4252 * and re-added like an update. 4253 */ 4254 if (pkg.mVersionCode < ps.versionCode) { 4255 shouldHideSystemApp = true; 4256 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 4257 + " but new version " + pkg.mVersionCode + " better than installed " 4258 + ps.versionCode + "; hiding system"); 4259 } else { 4260 /* 4261 * The newly found system app is a newer version that the 4262 * one previously installed. Simply remove the 4263 * already-installed application and replace it with our own 4264 * while keeping the application data. 4265 */ 4266 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 4267 + " reverting from " + ps.codePathString + ": new version " 4268 + pkg.mVersionCode + " better than installed " + ps.versionCode); 4269 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4270 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4271 getAppDexInstructionSets(ps)); 4272 synchronized (mInstallLock) { 4273 args.cleanUpResourcesLI(); 4274 } 4275 } 4276 } 4277 } 4278 4279 // The apk is forward locked (not public) if its code and resources 4280 // are kept in different files. (except for app in either system or 4281 // vendor path). 4282 // TODO grab this value from PackageSettings 4283 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4284 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4285 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 4286 } 4287 } 4288 4289 // TODO: extend to support forward-locked splits 4290 String resourcePath = null; 4291 String baseResourcePath = null; 4292 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 4293 if (ps != null && ps.resourcePathString != null) { 4294 resourcePath = ps.resourcePathString; 4295 baseResourcePath = ps.resourcePathString; 4296 } else { 4297 // Should not happen at all. Just log an error. 4298 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 4299 } 4300 } else { 4301 resourcePath = pkg.codePath; 4302 baseResourcePath = pkg.baseCodePath; 4303 } 4304 4305 // Set application objects path explicitly. 4306 pkg.applicationInfo.setCodePath(pkg.codePath); 4307 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 4308 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 4309 pkg.applicationInfo.setResourcePath(resourcePath); 4310 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 4311 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 4312 4313 // Note that we invoke the following method only if we are about to unpack an application 4314 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 4315 | SCAN_UPDATE_SIGNATURE, currentTime, user); 4316 4317 /* 4318 * If the system app should be overridden by a previously installed 4319 * data, hide the system app now and let the /data/app scan pick it up 4320 * again. 4321 */ 4322 if (shouldHideSystemApp) { 4323 synchronized (mPackages) { 4324 /* 4325 * We have to grant systems permissions before we hide, because 4326 * grantPermissions will assume the package update is trying to 4327 * expand its permissions. 4328 */ 4329 grantPermissionsLPw(pkg, true, pkg.packageName); 4330 mSettings.disableSystemPackageLPw(pkg.packageName); 4331 } 4332 } 4333 4334 return scannedPkg; 4335 } 4336 4337 private static String fixProcessName(String defProcessName, 4338 String processName, int uid) { 4339 if (processName == null) { 4340 return defProcessName; 4341 } 4342 return processName; 4343 } 4344 4345 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 4346 throws PackageManagerException { 4347 if (pkgSetting.signatures.mSignatures != null) { 4348 // Already existing package. Make sure signatures match 4349 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 4350 == PackageManager.SIGNATURE_MATCH; 4351 if (!match) { 4352 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 4353 == PackageManager.SIGNATURE_MATCH; 4354 } 4355 if (!match) { 4356 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 4357 + pkg.packageName + " signatures do not match the " 4358 + "previously installed version; ignoring!"); 4359 } 4360 } 4361 4362 // Check for shared user signatures 4363 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 4364 // Already existing package. Make sure signatures match 4365 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4366 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 4367 if (!match) { 4368 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 4369 == PackageManager.SIGNATURE_MATCH; 4370 } 4371 if (!match) { 4372 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 4373 "Package " + pkg.packageName 4374 + " has no signatures that match those in shared user " 4375 + pkgSetting.sharedUser.name + "; ignoring!"); 4376 } 4377 } 4378 } 4379 4380 /** 4381 * Enforces that only the system UID or root's UID can call a method exposed 4382 * via Binder. 4383 * 4384 * @param message used as message if SecurityException is thrown 4385 * @throws SecurityException if the caller is not system or root 4386 */ 4387 private static final void enforceSystemOrRoot(String message) { 4388 final int uid = Binder.getCallingUid(); 4389 if (uid != Process.SYSTEM_UID && uid != 0) { 4390 throw new SecurityException(message); 4391 } 4392 } 4393 4394 @Override 4395 public void performBootDexOpt() { 4396 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4397 4398 final HashSet<PackageParser.Package> pkgs; 4399 synchronized (mPackages) { 4400 pkgs = mDeferredDexOpt; 4401 mDeferredDexOpt = null; 4402 } 4403 4404 if (pkgs != null) { 4405 // Filter out packages that aren't recently used. 4406 // 4407 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 4408 // should do a full dexopt. 4409 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 4410 // TODO: add a property to control this? 4411 long dexOptLRUThresholdInMinutes; 4412 if (mLazyDexOpt) { 4413 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 4414 } else { 4415 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 4416 } 4417 long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 4418 4419 int total = pkgs.size(); 4420 int skipped = 0; 4421 long now = System.currentTimeMillis(); 4422 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 4423 PackageParser.Package pkg = i.next(); 4424 long then = pkg.mLastPackageUsageTimeInMills; 4425 if (then + dexOptLRUThresholdInMills < now) { 4426 if (DEBUG_DEXOPT) { 4427 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 4428 ((then == 0) ? "never" : new Date(then))); 4429 } 4430 i.remove(); 4431 skipped++; 4432 } 4433 } 4434 if (DEBUG_DEXOPT) { 4435 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 4436 } 4437 } 4438 4439 int i = 0; 4440 for (PackageParser.Package pkg : pkgs) { 4441 i++; 4442 if (DEBUG_DEXOPT) { 4443 Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size() 4444 + ": " + pkg.packageName); 4445 } 4446 if (!isFirstBoot()) { 4447 try { 4448 ActivityManagerNative.getDefault().showBootMessage( 4449 mContext.getResources().getString( 4450 R.string.android_upgrading_apk, 4451 i, pkgs.size()), true); 4452 } catch (RemoteException e) { 4453 } 4454 } 4455 PackageParser.Package p = pkg; 4456 synchronized (mInstallLock) { 4457 performDexOptLI(p, null /* instruction sets */, false /* force dex */, false /* defer */, 4458 true /* include dependencies */); 4459 } 4460 } 4461 } 4462 } 4463 4464 @Override 4465 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 4466 return performDexOpt(packageName, instructionSet, false); 4467 } 4468 4469 private static String getPrimaryInstructionSet(ApplicationInfo info) { 4470 if (info.primaryCpuAbi == null) { 4471 return getPreferredInstructionSet(); 4472 } 4473 4474 return VMRuntime.getInstructionSet(info.primaryCpuAbi); 4475 } 4476 4477 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 4478 boolean dexopt = mLazyDexOpt || backgroundDexopt; 4479 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 4480 if (!dexopt && !updateUsage) { 4481 // We aren't going to dexopt or update usage, so bail early. 4482 return false; 4483 } 4484 PackageParser.Package p; 4485 final String targetInstructionSet; 4486 synchronized (mPackages) { 4487 p = mPackages.get(packageName); 4488 if (p == null) { 4489 return false; 4490 } 4491 if (updateUsage) { 4492 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 4493 } 4494 mPackageUsage.write(false); 4495 if (!dexopt) { 4496 // We aren't going to dexopt, so bail early. 4497 return false; 4498 } 4499 4500 targetInstructionSet = instructionSet != null ? instructionSet : 4501 getPrimaryInstructionSet(p.applicationInfo); 4502 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 4503 return false; 4504 } 4505 } 4506 4507 synchronized (mInstallLock) { 4508 final String[] instructionSets = new String[] { targetInstructionSet }; 4509 return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */, 4510 true /* include dependencies */) == DEX_OPT_PERFORMED; 4511 } 4512 } 4513 4514 public HashSet<String> getPackagesThatNeedDexOpt() { 4515 HashSet<String> pkgs = null; 4516 synchronized (mPackages) { 4517 for (PackageParser.Package p : mPackages.values()) { 4518 if (DEBUG_DEXOPT) { 4519 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 4520 } 4521 if (!p.mDexOptPerformed.isEmpty()) { 4522 continue; 4523 } 4524 if (pkgs == null) { 4525 pkgs = new HashSet<String>(); 4526 } 4527 pkgs.add(p.packageName); 4528 } 4529 } 4530 return pkgs; 4531 } 4532 4533 public void shutdown() { 4534 mPackageUsage.write(true); 4535 } 4536 4537 private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets, 4538 boolean forceDex, boolean defer, HashSet<String> done) { 4539 for (int i=0; i<libs.size(); i++) { 4540 PackageParser.Package libPkg; 4541 String libName; 4542 synchronized (mPackages) { 4543 libName = libs.get(i); 4544 SharedLibraryEntry lib = mSharedLibraries.get(libName); 4545 if (lib != null && lib.apk != null) { 4546 libPkg = mPackages.get(lib.apk); 4547 } else { 4548 libPkg = null; 4549 } 4550 } 4551 if (libPkg != null && !done.contains(libName)) { 4552 performDexOptLI(libPkg, instructionSets, forceDex, defer, done); 4553 } 4554 } 4555 } 4556 4557 static final int DEX_OPT_SKIPPED = 0; 4558 static final int DEX_OPT_PERFORMED = 1; 4559 static final int DEX_OPT_DEFERRED = 2; 4560 static final int DEX_OPT_FAILED = -1; 4561 4562 private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets, 4563 boolean forceDex, boolean defer, HashSet<String> done) { 4564 final String[] instructionSets = targetInstructionSets != null ? 4565 targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo); 4566 4567 if (done != null) { 4568 done.add(pkg.packageName); 4569 if (pkg.usesLibraries != null) { 4570 performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done); 4571 } 4572 if (pkg.usesOptionalLibraries != null) { 4573 performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done); 4574 } 4575 } 4576 4577 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) { 4578 return DEX_OPT_SKIPPED; 4579 } 4580 4581 final boolean vmSafeMode = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0; 4582 4583 final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly(); 4584 boolean performedDexOpt = false; 4585 // There are three basic cases here: 4586 // 1.) we need to dexopt, either because we are forced or it is needed 4587 // 2.) we are defering a needed dexopt 4588 // 3.) we are skipping an unneeded dexopt 4589 final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 4590 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 4591 if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) { 4592 continue; 4593 } 4594 4595 for (String path : paths) { 4596 try { 4597 // This will return DEXOPT_NEEDED if we either cannot find any odex file for this 4598 // patckage or the one we find does not match the image checksum (i.e. it was 4599 // compiled against an old image). It will return PATCHOAT_NEEDED if we can find a 4600 // odex file and it matches the checksum of the image but not its base address, 4601 // meaning we need to move it. 4602 final byte isDexOptNeeded = DexFile.isDexOptNeededInternal(path, 4603 pkg.packageName, dexCodeInstructionSet, defer); 4604 if (forceDex || (!defer && isDexOptNeeded == DexFile.DEXOPT_NEEDED)) { 4605 Log.i(TAG, "Running dexopt on: " + path + " pkg=" 4606 + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet 4607 + " vmSafeMode=" + vmSafeMode); 4608 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4609 final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg), 4610 pkg.packageName, dexCodeInstructionSet, vmSafeMode); 4611 4612 if (ret < 0) { 4613 // Don't bother running dexopt again if we failed, it will probably 4614 // just result in an error again. Also, don't bother dexopting for other 4615 // paths & ISAs. 4616 return DEX_OPT_FAILED; 4617 } 4618 4619 performedDexOpt = true; 4620 } else if (!defer && isDexOptNeeded == DexFile.PATCHOAT_NEEDED) { 4621 Log.i(TAG, "Running patchoat on: " + pkg.applicationInfo.packageName); 4622 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4623 final int ret = mInstaller.patchoat(path, sharedGid, !isForwardLocked(pkg), 4624 pkg.packageName, dexCodeInstructionSet); 4625 4626 if (ret < 0) { 4627 // Don't bother running patchoat again if we failed, it will probably 4628 // just result in an error again. Also, don't bother dexopting for other 4629 // paths & ISAs. 4630 return DEX_OPT_FAILED; 4631 } 4632 4633 performedDexOpt = true; 4634 } 4635 4636 // We're deciding to defer a needed dexopt. Don't bother dexopting for other 4637 // paths and instruction sets. We'll deal with them all together when we process 4638 // our list of deferred dexopts. 4639 if (defer && isDexOptNeeded != DexFile.UP_TO_DATE) { 4640 if (mDeferredDexOpt == null) { 4641 mDeferredDexOpt = new HashSet<PackageParser.Package>(); 4642 } 4643 mDeferredDexOpt.add(pkg); 4644 return DEX_OPT_DEFERRED; 4645 } 4646 } catch (FileNotFoundException e) { 4647 Slog.w(TAG, "Apk not found for dexopt: " + path); 4648 return DEX_OPT_FAILED; 4649 } catch (IOException e) { 4650 Slog.w(TAG, "IOException reading apk: " + path, e); 4651 return DEX_OPT_FAILED; 4652 } catch (StaleDexCacheError e) { 4653 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e); 4654 return DEX_OPT_FAILED; 4655 } catch (Exception e) { 4656 Slog.w(TAG, "Exception when doing dexopt : ", e); 4657 return DEX_OPT_FAILED; 4658 } 4659 } 4660 4661 // At this point we haven't failed dexopt and we haven't deferred dexopt. We must 4662 // either have either succeeded dexopt, or have had isDexOptNeededInternal tell us 4663 // it isn't required. We therefore mark that this package doesn't need dexopt unless 4664 // it's forced. performedDexOpt will tell us whether we performed dex-opt or skipped 4665 // it. 4666 pkg.mDexOptPerformed.add(dexCodeInstructionSet); 4667 } 4668 4669 // If we've gotten here, we're sure that no error occurred and that we haven't 4670 // deferred dex-opt. We've either dex-opted one more paths or instruction sets or 4671 // we've skipped all of them because they are up to date. In both cases this 4672 // package doesn't need dexopt any longer. 4673 return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED; 4674 } 4675 4676 private static String[] getAppDexInstructionSets(ApplicationInfo info) { 4677 if (info.primaryCpuAbi != null) { 4678 if (info.secondaryCpuAbi != null) { 4679 return new String[] { 4680 VMRuntime.getInstructionSet(info.primaryCpuAbi), 4681 VMRuntime.getInstructionSet(info.secondaryCpuAbi) }; 4682 } else { 4683 return new String[] { 4684 VMRuntime.getInstructionSet(info.primaryCpuAbi) }; 4685 } 4686 } 4687 4688 return new String[] { getPreferredInstructionSet() }; 4689 } 4690 4691 private static String[] getAppDexInstructionSets(PackageSetting ps) { 4692 if (ps.primaryCpuAbiString != null) { 4693 if (ps.secondaryCpuAbiString != null) { 4694 return new String[] { 4695 VMRuntime.getInstructionSet(ps.primaryCpuAbiString), 4696 VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) }; 4697 } else { 4698 return new String[] { 4699 VMRuntime.getInstructionSet(ps.primaryCpuAbiString) }; 4700 } 4701 } 4702 4703 return new String[] { getPreferredInstructionSet() }; 4704 } 4705 4706 private static String getPreferredInstructionSet() { 4707 if (sPreferredInstructionSet == null) { 4708 sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]); 4709 } 4710 4711 return sPreferredInstructionSet; 4712 } 4713 4714 private static List<String> getAllInstructionSets() { 4715 final String[] allAbis = Build.SUPPORTED_ABIS; 4716 final List<String> allInstructionSets = new ArrayList<String>(allAbis.length); 4717 4718 for (String abi : allAbis) { 4719 final String instructionSet = VMRuntime.getInstructionSet(abi); 4720 if (!allInstructionSets.contains(instructionSet)) { 4721 allInstructionSets.add(instructionSet); 4722 } 4723 } 4724 4725 return allInstructionSets; 4726 } 4727 4728 /** 4729 * Returns the instruction set that should be used to compile dex code. In the presence of 4730 * a native bridge this might be different than the one shared libraries use. 4731 */ 4732 private static String getDexCodeInstructionSet(String sharedLibraryIsa) { 4733 String dexCodeIsa = SystemProperties.get("ro.dalvik.vm.isa." + sharedLibraryIsa); 4734 return (dexCodeIsa.isEmpty() ? sharedLibraryIsa : dexCodeIsa); 4735 } 4736 4737 private static String[] getDexCodeInstructionSets(String[] instructionSets) { 4738 HashSet<String> dexCodeInstructionSets = new HashSet<String>(instructionSets.length); 4739 for (String instructionSet : instructionSets) { 4740 dexCodeInstructionSets.add(getDexCodeInstructionSet(instructionSet)); 4741 } 4742 return dexCodeInstructionSets.toArray(new String[dexCodeInstructionSets.size()]); 4743 } 4744 4745 @Override 4746 public void forceDexOpt(String packageName) { 4747 enforceSystemOrRoot("forceDexOpt"); 4748 4749 PackageParser.Package pkg; 4750 synchronized (mPackages) { 4751 pkg = mPackages.get(packageName); 4752 if (pkg == null) { 4753 throw new IllegalArgumentException("Missing package: " + packageName); 4754 } 4755 } 4756 4757 synchronized (mInstallLock) { 4758 final String[] instructionSets = new String[] { 4759 getPrimaryInstructionSet(pkg.applicationInfo) }; 4760 final int res = performDexOptLI(pkg, instructionSets, true, false, true); 4761 if (res != DEX_OPT_PERFORMED) { 4762 throw new IllegalStateException("Failed to dexopt: " + res); 4763 } 4764 } 4765 } 4766 4767 private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets, 4768 boolean forceDex, boolean defer, boolean inclDependencies) { 4769 HashSet<String> done; 4770 if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) { 4771 done = new HashSet<String>(); 4772 done.add(pkg.packageName); 4773 } else { 4774 done = null; 4775 } 4776 return performDexOptLI(pkg, instructionSets, forceDex, defer, done); 4777 } 4778 4779 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 4780 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 4781 Slog.w(TAG, "Unable to update from " + oldPkg.name 4782 + " to " + newPkg.packageName 4783 + ": old package not in system partition"); 4784 return false; 4785 } else if (mPackages.get(oldPkg.name) != null) { 4786 Slog.w(TAG, "Unable to update from " + oldPkg.name 4787 + " to " + newPkg.packageName 4788 + ": old package still exists"); 4789 return false; 4790 } 4791 return true; 4792 } 4793 4794 File getDataPathForUser(int userId) { 4795 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId); 4796 } 4797 4798 private File getDataPathForPackage(String packageName, int userId) { 4799 /* 4800 * Until we fully support multiple users, return the directory we 4801 * previously would have. The PackageManagerTests will need to be 4802 * revised when this is changed back.. 4803 */ 4804 if (userId == 0) { 4805 return new File(mAppDataDir, packageName); 4806 } else { 4807 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 4808 + File.separator + packageName); 4809 } 4810 } 4811 4812 private int createDataDirsLI(String packageName, int uid, String seinfo) { 4813 int[] users = sUserManager.getUserIds(); 4814 int res = mInstaller.install(packageName, uid, uid, seinfo); 4815 if (res < 0) { 4816 return res; 4817 } 4818 for (int user : users) { 4819 if (user != 0) { 4820 res = mInstaller.createUserData(packageName, 4821 UserHandle.getUid(user, uid), user, seinfo); 4822 if (res < 0) { 4823 return res; 4824 } 4825 } 4826 } 4827 return res; 4828 } 4829 4830 private int removeDataDirsLI(String packageName) { 4831 int[] users = sUserManager.getUserIds(); 4832 int res = 0; 4833 for (int user : users) { 4834 int resInner = mInstaller.remove(packageName, user); 4835 if (resInner < 0) { 4836 res = resInner; 4837 } 4838 } 4839 4840 return res; 4841 } 4842 4843 private int deleteCodeCacheDirsLI(String packageName) { 4844 int[] users = sUserManager.getUserIds(); 4845 int res = 0; 4846 for (int user : users) { 4847 int resInner = mInstaller.deleteCodeCacheFiles(packageName, user); 4848 if (resInner < 0) { 4849 res = resInner; 4850 } 4851 } 4852 return res; 4853 } 4854 4855 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 4856 PackageParser.Package changingLib) { 4857 if (file.path != null) { 4858 usesLibraryFiles.add(file.path); 4859 return; 4860 } 4861 PackageParser.Package p = mPackages.get(file.apk); 4862 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 4863 // If we are doing this while in the middle of updating a library apk, 4864 // then we need to make sure to use that new apk for determining the 4865 // dependencies here. (We haven't yet finished committing the new apk 4866 // to the package manager state.) 4867 if (p == null || p.packageName.equals(changingLib.packageName)) { 4868 p = changingLib; 4869 } 4870 } 4871 if (p != null) { 4872 usesLibraryFiles.addAll(p.getAllCodePaths()); 4873 } 4874 } 4875 4876 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 4877 PackageParser.Package changingLib) throws PackageManagerException { 4878 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 4879 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 4880 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 4881 for (int i=0; i<N; i++) { 4882 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 4883 if (file == null) { 4884 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 4885 "Package " + pkg.packageName + " requires unavailable shared library " 4886 + pkg.usesLibraries.get(i) + "; failing!"); 4887 } 4888 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4889 } 4890 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 4891 for (int i=0; i<N; i++) { 4892 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 4893 if (file == null) { 4894 Slog.w(TAG, "Package " + pkg.packageName 4895 + " desires unavailable shared library " 4896 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 4897 } else { 4898 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4899 } 4900 } 4901 N = usesLibraryFiles.size(); 4902 if (N > 0) { 4903 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 4904 } else { 4905 pkg.usesLibraryFiles = null; 4906 } 4907 } 4908 } 4909 4910 private static boolean hasString(List<String> list, List<String> which) { 4911 if (list == null) { 4912 return false; 4913 } 4914 for (int i=list.size()-1; i>=0; i--) { 4915 for (int j=which.size()-1; j>=0; j--) { 4916 if (which.get(j).equals(list.get(i))) { 4917 return true; 4918 } 4919 } 4920 } 4921 return false; 4922 } 4923 4924 private void updateAllSharedLibrariesLPw() { 4925 for (PackageParser.Package pkg : mPackages.values()) { 4926 try { 4927 updateSharedLibrariesLPw(pkg, null); 4928 } catch (PackageManagerException e) { 4929 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 4930 } 4931 } 4932 } 4933 4934 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 4935 PackageParser.Package changingPkg) { 4936 ArrayList<PackageParser.Package> res = null; 4937 for (PackageParser.Package pkg : mPackages.values()) { 4938 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 4939 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 4940 if (res == null) { 4941 res = new ArrayList<PackageParser.Package>(); 4942 } 4943 res.add(pkg); 4944 try { 4945 updateSharedLibrariesLPw(pkg, changingPkg); 4946 } catch (PackageManagerException e) { 4947 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 4948 } 4949 } 4950 } 4951 return res; 4952 } 4953 4954 /** 4955 * Derive the value of the {@code cpuAbiOverride} based on the provided 4956 * value and an optional stored value from the package settings. 4957 */ 4958 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 4959 String cpuAbiOverride = null; 4960 4961 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 4962 cpuAbiOverride = null; 4963 } else if (abiOverride != null) { 4964 cpuAbiOverride = abiOverride; 4965 } else if (settings != null) { 4966 cpuAbiOverride = settings.cpuAbiOverrideString; 4967 } 4968 4969 return cpuAbiOverride; 4970 } 4971 4972 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 4973 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 4974 boolean success = false; 4975 try { 4976 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 4977 currentTime, user); 4978 success = true; 4979 return res; 4980 } finally { 4981 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 4982 removeDataDirsLI(pkg.packageName); 4983 } 4984 } 4985 } 4986 4987 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 4988 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 4989 final File scanFile = new File(pkg.codePath); 4990 if (pkg.applicationInfo.getCodePath() == null || 4991 pkg.applicationInfo.getResourcePath() == null) { 4992 // Bail out. The resource and code paths haven't been set. 4993 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 4994 "Code and resource paths haven't been set correctly"); 4995 } 4996 4997 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4998 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 4999 } 5000 5001 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5002 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED; 5003 } 5004 5005 if (mCustomResolverComponentName != null && 5006 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5007 setUpCustomResolverActivity(pkg); 5008 } 5009 5010 if (pkg.packageName.equals("android")) { 5011 synchronized (mPackages) { 5012 if (mAndroidApplication != null) { 5013 Slog.w(TAG, "*************************************************"); 5014 Slog.w(TAG, "Core android package being redefined. Skipping."); 5015 Slog.w(TAG, " file=" + scanFile); 5016 Slog.w(TAG, "*************************************************"); 5017 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5018 "Core android package being redefined. Skipping."); 5019 } 5020 5021 // Set up information for our fall-back user intent resolution activity. 5022 mPlatformPackage = pkg; 5023 pkg.mVersionCode = mSdkVersion; 5024 mAndroidApplication = pkg.applicationInfo; 5025 5026 if (!mResolverReplaced) { 5027 mResolveActivity.applicationInfo = mAndroidApplication; 5028 mResolveActivity.name = ResolverActivity.class.getName(); 5029 mResolveActivity.packageName = mAndroidApplication.packageName; 5030 mResolveActivity.processName = "system:ui"; 5031 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5032 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5033 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5034 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5035 mResolveActivity.exported = true; 5036 mResolveActivity.enabled = true; 5037 mResolveInfo.activityInfo = mResolveActivity; 5038 mResolveInfo.priority = 0; 5039 mResolveInfo.preferredOrder = 0; 5040 mResolveInfo.match = 0; 5041 mResolveComponentName = new ComponentName( 5042 mAndroidApplication.packageName, mResolveActivity.name); 5043 } 5044 } 5045 } 5046 5047 if (DEBUG_PACKAGE_SCANNING) { 5048 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5049 Log.d(TAG, "Scanning package " + pkg.packageName); 5050 } 5051 5052 if (mPackages.containsKey(pkg.packageName) 5053 || mSharedLibraries.containsKey(pkg.packageName)) { 5054 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5055 "Application package " + pkg.packageName 5056 + " already installed. Skipping duplicate."); 5057 } 5058 5059 // Initialize package source and resource directories 5060 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5061 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5062 5063 SharedUserSetting suid = null; 5064 PackageSetting pkgSetting = null; 5065 5066 if (!isSystemApp(pkg)) { 5067 // Only system apps can use these features. 5068 pkg.mOriginalPackages = null; 5069 pkg.mRealPackage = null; 5070 pkg.mAdoptPermissions = null; 5071 } 5072 5073 // writer 5074 synchronized (mPackages) { 5075 if (pkg.mSharedUserId != null) { 5076 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true); 5077 if (suid == null) { 5078 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5079 "Creating application package " + pkg.packageName 5080 + " for shared user failed"); 5081 } 5082 if (DEBUG_PACKAGE_SCANNING) { 5083 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5084 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5085 + "): packages=" + suid.packages); 5086 } 5087 } 5088 5089 // Check if we are renaming from an original package name. 5090 PackageSetting origPackage = null; 5091 String realName = null; 5092 if (pkg.mOriginalPackages != null) { 5093 // This package may need to be renamed to a previously 5094 // installed name. Let's check on that... 5095 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5096 if (pkg.mOriginalPackages.contains(renamed)) { 5097 // This package had originally been installed as the 5098 // original name, and we have already taken care of 5099 // transitioning to the new one. Just update the new 5100 // one to continue using the old name. 5101 realName = pkg.mRealPackage; 5102 if (!pkg.packageName.equals(renamed)) { 5103 // Callers into this function may have already taken 5104 // care of renaming the package; only do it here if 5105 // it is not already done. 5106 pkg.setPackageName(renamed); 5107 } 5108 5109 } else { 5110 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5111 if ((origPackage = mSettings.peekPackageLPr( 5112 pkg.mOriginalPackages.get(i))) != null) { 5113 // We do have the package already installed under its 5114 // original name... should we use it? 5115 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5116 // New package is not compatible with original. 5117 origPackage = null; 5118 continue; 5119 } else if (origPackage.sharedUser != null) { 5120 // Make sure uid is compatible between packages. 5121 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5122 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5123 + " to " + pkg.packageName + ": old uid " 5124 + origPackage.sharedUser.name 5125 + " differs from " + pkg.mSharedUserId); 5126 origPackage = null; 5127 continue; 5128 } 5129 } else { 5130 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5131 + pkg.packageName + " to old name " + origPackage.name); 5132 } 5133 break; 5134 } 5135 } 5136 } 5137 } 5138 5139 if (mTransferedPackages.contains(pkg.packageName)) { 5140 Slog.w(TAG, "Package " + pkg.packageName 5141 + " was transferred to another, but its .apk remains"); 5142 } 5143 5144 // Just create the setting, don't add it yet. For already existing packages 5145 // the PkgSetting exists already and doesn't have to be created. 5146 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5147 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 5148 pkg.applicationInfo.primaryCpuAbi, 5149 pkg.applicationInfo.secondaryCpuAbi, 5150 pkg.applicationInfo.flags, user, false); 5151 if (pkgSetting == null) { 5152 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5153 "Creating application package " + pkg.packageName + " failed"); 5154 } 5155 5156 if (pkgSetting.origPackage != null) { 5157 // If we are first transitioning from an original package, 5158 // fix up the new package's name now. We need to do this after 5159 // looking up the package under its new name, so getPackageLP 5160 // can take care of fiddling things correctly. 5161 pkg.setPackageName(origPackage.name); 5162 5163 // File a report about this. 5164 String msg = "New package " + pkgSetting.realName 5165 + " renamed to replace old package " + pkgSetting.name; 5166 reportSettingsProblem(Log.WARN, msg); 5167 5168 // Make a note of it. 5169 mTransferedPackages.add(origPackage.name); 5170 5171 // No longer need to retain this. 5172 pkgSetting.origPackage = null; 5173 } 5174 5175 if (realName != null) { 5176 // Make a note of it. 5177 mTransferedPackages.add(pkg.packageName); 5178 } 5179 5180 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5181 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5182 } 5183 5184 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5185 // Check all shared libraries and map to their actual file path. 5186 // We only do this here for apps not on a system dir, because those 5187 // are the only ones that can fail an install due to this. We 5188 // will take care of the system apps by updating all of their 5189 // library paths after the scan is done. 5190 updateSharedLibrariesLPw(pkg, null); 5191 } 5192 5193 if (mFoundPolicyFile) { 5194 SELinuxMMAC.assignSeinfoValue(pkg); 5195 } 5196 5197 pkg.applicationInfo.uid = pkgSetting.appId; 5198 pkg.mExtras = pkgSetting; 5199 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5200 try { 5201 verifySignaturesLP(pkgSetting, pkg); 5202 } catch (PackageManagerException e) { 5203 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5204 throw e; 5205 } 5206 // The signature has changed, but this package is in the system 5207 // image... let's recover! 5208 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5209 // However... if this package is part of a shared user, but it 5210 // doesn't match the signature of the shared user, let's fail. 5211 // What this means is that you can't change the signatures 5212 // associated with an overall shared user, which doesn't seem all 5213 // that unreasonable. 5214 if (pkgSetting.sharedUser != null) { 5215 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5216 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5217 throw new PackageManagerException( 5218 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 5219 "Signature mismatch for shared user : " 5220 + pkgSetting.sharedUser); 5221 } 5222 } 5223 // File a report about this. 5224 String msg = "System package " + pkg.packageName 5225 + " signature changed; retaining data."; 5226 reportSettingsProblem(Log.WARN, msg); 5227 } 5228 } else { 5229 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 5230 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5231 + pkg.packageName + " upgrade keys do not match the " 5232 + "previously installed version"); 5233 } else { 5234 // signatures may have changed as result of upgrade 5235 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5236 } 5237 } 5238 // Verify that this new package doesn't have any content providers 5239 // that conflict with existing packages. Only do this if the 5240 // package isn't already installed, since we don't want to break 5241 // things that are installed. 5242 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 5243 final int N = pkg.providers.size(); 5244 int i; 5245 for (i=0; i<N; i++) { 5246 PackageParser.Provider p = pkg.providers.get(i); 5247 if (p.info.authority != null) { 5248 String names[] = p.info.authority.split(";"); 5249 for (int j = 0; j < names.length; j++) { 5250 if (mProvidersByAuthority.containsKey(names[j])) { 5251 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5252 final String otherPackageName = 5253 ((other != null && other.getComponentName() != null) ? 5254 other.getComponentName().getPackageName() : "?"); 5255 throw new PackageManagerException( 5256 INSTALL_FAILED_CONFLICTING_PROVIDER, 5257 "Can't install because provider name " + names[j] 5258 + " (in package " + pkg.applicationInfo.packageName 5259 + ") is already used by " + otherPackageName); 5260 } 5261 } 5262 } 5263 } 5264 } 5265 5266 if (pkg.mAdoptPermissions != null) { 5267 // This package wants to adopt ownership of permissions from 5268 // another package. 5269 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 5270 final String origName = pkg.mAdoptPermissions.get(i); 5271 final PackageSetting orig = mSettings.peekPackageLPr(origName); 5272 if (orig != null) { 5273 if (verifyPackageUpdateLPr(orig, pkg)) { 5274 Slog.i(TAG, "Adopting permissions from " + origName + " to " 5275 + pkg.packageName); 5276 mSettings.transferPermissionsLPw(origName, pkg.packageName); 5277 } 5278 } 5279 } 5280 } 5281 } 5282 5283 final String pkgName = pkg.packageName; 5284 5285 final long scanFileTime = scanFile.lastModified(); 5286 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 5287 pkg.applicationInfo.processName = fixProcessName( 5288 pkg.applicationInfo.packageName, 5289 pkg.applicationInfo.processName, 5290 pkg.applicationInfo.uid); 5291 5292 File dataPath; 5293 if (mPlatformPackage == pkg) { 5294 // The system package is special. 5295 dataPath = new File(Environment.getDataDirectory(), "system"); 5296 5297 pkg.applicationInfo.dataDir = dataPath.getPath(); 5298 5299 } else { 5300 // This is a normal package, need to make its data directory. 5301 dataPath = getDataPathForPackage(pkg.packageName, 0); 5302 5303 boolean uidError = false; 5304 if (dataPath.exists()) { 5305 int currentUid = 0; 5306 try { 5307 StructStat stat = Os.stat(dataPath.getPath()); 5308 currentUid = stat.st_uid; 5309 } catch (ErrnoException e) { 5310 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 5311 } 5312 5313 // If we have mismatched owners for the data path, we have a problem. 5314 if (currentUid != pkg.applicationInfo.uid) { 5315 boolean recovered = false; 5316 if (currentUid == 0) { 5317 // The directory somehow became owned by root. Wow. 5318 // This is probably because the system was stopped while 5319 // installd was in the middle of messing with its libs 5320 // directory. Ask installd to fix that. 5321 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 5322 pkg.applicationInfo.uid); 5323 if (ret >= 0) { 5324 recovered = true; 5325 String msg = "Package " + pkg.packageName 5326 + " unexpectedly changed to uid 0; recovered to " + 5327 + pkg.applicationInfo.uid; 5328 reportSettingsProblem(Log.WARN, msg); 5329 } 5330 } 5331 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5332 || (scanFlags&SCAN_BOOTING) != 0)) { 5333 // If this is a system app, we can at least delete its 5334 // current data so the application will still work. 5335 int ret = removeDataDirsLI(pkgName); 5336 if (ret >= 0) { 5337 // TODO: Kill the processes first 5338 // Old data gone! 5339 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5340 ? "System package " : "Third party package "; 5341 String msg = prefix + pkg.packageName 5342 + " has changed from uid: " 5343 + currentUid + " to " 5344 + pkg.applicationInfo.uid + "; old data erased"; 5345 reportSettingsProblem(Log.WARN, msg); 5346 recovered = true; 5347 5348 // And now re-install the app. 5349 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5350 pkg.applicationInfo.seinfo); 5351 if (ret == -1) { 5352 // Ack should not happen! 5353 msg = prefix + pkg.packageName 5354 + " could not have data directory re-created after delete."; 5355 reportSettingsProblem(Log.WARN, msg); 5356 throw new PackageManagerException( 5357 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 5358 } 5359 } 5360 if (!recovered) { 5361 mHasSystemUidErrors = true; 5362 } 5363 } else if (!recovered) { 5364 // If we allow this install to proceed, we will be broken. 5365 // Abort, abort! 5366 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 5367 "scanPackageLI"); 5368 } 5369 if (!recovered) { 5370 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 5371 + pkg.applicationInfo.uid + "/fs_" 5372 + currentUid; 5373 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 5374 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 5375 String msg = "Package " + pkg.packageName 5376 + " has mismatched uid: " 5377 + currentUid + " on disk, " 5378 + pkg.applicationInfo.uid + " in settings"; 5379 // writer 5380 synchronized (mPackages) { 5381 mSettings.mReadMessages.append(msg); 5382 mSettings.mReadMessages.append('\n'); 5383 uidError = true; 5384 if (!pkgSetting.uidError) { 5385 reportSettingsProblem(Log.ERROR, msg); 5386 } 5387 } 5388 } 5389 } 5390 pkg.applicationInfo.dataDir = dataPath.getPath(); 5391 if (mShouldRestoreconData) { 5392 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 5393 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 5394 pkg.applicationInfo.uid); 5395 } 5396 } else { 5397 if (DEBUG_PACKAGE_SCANNING) { 5398 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5399 Log.v(TAG, "Want this data dir: " + dataPath); 5400 } 5401 //invoke installer to do the actual installation 5402 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5403 pkg.applicationInfo.seinfo); 5404 if (ret < 0) { 5405 // Error from installer 5406 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5407 "Unable to create data dirs [errorCode=" + ret + "]"); 5408 } 5409 5410 if (dataPath.exists()) { 5411 pkg.applicationInfo.dataDir = dataPath.getPath(); 5412 } else { 5413 Slog.w(TAG, "Unable to create data directory: " + dataPath); 5414 pkg.applicationInfo.dataDir = null; 5415 } 5416 } 5417 5418 pkgSetting.uidError = uidError; 5419 } 5420 5421 final String path = scanFile.getPath(); 5422 final String codePath = pkg.applicationInfo.getCodePath(); 5423 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 5424 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 5425 setBundledAppAbisAndRoots(pkg, pkgSetting); 5426 5427 // If we haven't found any native libraries for the app, check if it has 5428 // renderscript code. We'll need to force the app to 32 bit if it has 5429 // renderscript bitcode. 5430 if (pkg.applicationInfo.primaryCpuAbi == null 5431 && pkg.applicationInfo.secondaryCpuAbi == null 5432 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5433 NativeLibraryHelper.Handle handle = null; 5434 try { 5435 handle = NativeLibraryHelper.Handle.create(scanFile); 5436 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5437 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 5438 } 5439 } catch (IOException ioe) { 5440 Slog.w(TAG, "Error scanning system app : " + ioe); 5441 } finally { 5442 IoUtils.closeQuietly(handle); 5443 } 5444 } 5445 5446 setNativeLibraryPaths(pkg); 5447 } else { 5448 // TODO: We can probably be smarter about this stuff. For installed apps, 5449 // we can calculate this information at install time once and for all. For 5450 // system apps, we can probably assume that this information doesn't change 5451 // after the first boot scan. As things stand, we do lots of unnecessary work. 5452 5453 // Give ourselves some initial paths; we'll come back for another 5454 // pass once we've determined ABI below. 5455 setNativeLibraryPaths(pkg); 5456 5457 final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg); 5458 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 5459 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 5460 5461 NativeLibraryHelper.Handle handle = null; 5462 try { 5463 handle = NativeLibraryHelper.Handle.create(scanFile); 5464 // TODO(multiArch): This can be null for apps that didn't go through the 5465 // usual installation process. We can calculate it again, like we 5466 // do during install time. 5467 // 5468 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 5469 // unnecessary. 5470 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 5471 5472 // Null out the abis so that they can be recalculated. 5473 pkg.applicationInfo.primaryCpuAbi = null; 5474 pkg.applicationInfo.secondaryCpuAbi = null; 5475 if (isMultiArch(pkg.applicationInfo)) { 5476 // Warn if we've set an abiOverride for multi-lib packages.. 5477 // By definition, we need to copy both 32 and 64 bit libraries for 5478 // such packages. 5479 if (pkg.cpuAbiOverride != null 5480 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 5481 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 5482 } 5483 5484 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 5485 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 5486 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 5487 if (isAsec) { 5488 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 5489 } else { 5490 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5491 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 5492 useIsaSpecificSubdirs); 5493 } 5494 } 5495 5496 maybeThrowExceptionForMultiArchCopy( 5497 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 5498 5499 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5500 if (isAsec) { 5501 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 5502 } else { 5503 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5504 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 5505 useIsaSpecificSubdirs); 5506 } 5507 } 5508 5509 maybeThrowExceptionForMultiArchCopy( 5510 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 5511 5512 if (abi64 >= 0) { 5513 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 5514 } 5515 5516 if (abi32 >= 0) { 5517 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 5518 if (abi64 >= 0) { 5519 pkg.applicationInfo.secondaryCpuAbi = abi; 5520 } else { 5521 pkg.applicationInfo.primaryCpuAbi = abi; 5522 } 5523 } 5524 } else { 5525 String[] abiList = (cpuAbiOverride != null) ? 5526 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 5527 5528 // Enable gross and lame hacks for apps that are built with old 5529 // SDK tools. We must scan their APKs for renderscript bitcode and 5530 // not launch them if it's present. Don't bother checking on devices 5531 // that don't have 64 bit support. 5532 boolean needsRenderScriptOverride = false; 5533 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 5534 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5535 abiList = Build.SUPPORTED_32_BIT_ABIS; 5536 needsRenderScriptOverride = true; 5537 } 5538 5539 final int copyRet; 5540 if (isAsec) { 5541 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 5542 } else { 5543 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5544 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 5545 } 5546 5547 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5548 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5549 "Error unpackaging native libs for app, errorCode=" + copyRet); 5550 } 5551 5552 if (copyRet >= 0) { 5553 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 5554 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 5555 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 5556 } else if (needsRenderScriptOverride) { 5557 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 5558 } 5559 } 5560 } catch (IOException ioe) { 5561 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 5562 } finally { 5563 IoUtils.closeQuietly(handle); 5564 } 5565 5566 // Now that we've calculated the ABIs and determined if it's an internal app, 5567 // we will go ahead and populate the nativeLibraryPath. 5568 setNativeLibraryPaths(pkg); 5569 5570 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 5571 final int[] userIds = sUserManager.getUserIds(); 5572 synchronized (mInstallLock) { 5573 // Create a native library symlink only if we have native libraries 5574 // and if the native libraries are 32 bit libraries. We do not provide 5575 // this symlink for 64 bit libraries. 5576 if (pkg.applicationInfo.primaryCpuAbi != null && 5577 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 5578 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 5579 for (int userId : userIds) { 5580 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 5581 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5582 "Failed linking native library dir (user=" + userId + ")"); 5583 } 5584 } 5585 } 5586 } 5587 } 5588 5589 // This is a special case for the "system" package, where the ABI is 5590 // dictated by the zygote configuration (and init.rc). We should keep track 5591 // of this ABI so that we can deal with "normal" applications that run under 5592 // the same UID correctly. 5593 if (mPlatformPackage == pkg) { 5594 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 5595 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 5596 } 5597 5598 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 5599 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 5600 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 5601 // Copy the derived override back to the parsed package, so that we can 5602 // update the package settings accordingly. 5603 pkg.cpuAbiOverride = cpuAbiOverride; 5604 5605 if (DEBUG_ABI_SELECTION) { 5606 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 5607 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 5608 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 5609 } 5610 5611 // Push the derived path down into PackageSettings so we know what to 5612 // clean up at uninstall time. 5613 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 5614 5615 if (DEBUG_ABI_SELECTION) { 5616 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 5617 " primary=" + pkg.applicationInfo.primaryCpuAbi + 5618 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 5619 } 5620 5621 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 5622 // We don't do this here during boot because we can do it all 5623 // at once after scanning all existing packages. 5624 // 5625 // We also do this *before* we perform dexopt on this package, so that 5626 // we can avoid redundant dexopts, and also to make sure we've got the 5627 // code and package path correct. 5628 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 5629 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 5630 } 5631 5632 if ((scanFlags & SCAN_NO_DEX) == 0) { 5633 if (performDexOptLI(pkg, null /* instruction sets */, forceDex, 5634 (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) { 5635 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 5636 } 5637 } 5638 5639 if (mFactoryTest && pkg.requestedPermissions.contains( 5640 android.Manifest.permission.FACTORY_TEST)) { 5641 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 5642 } 5643 5644 ArrayList<PackageParser.Package> clientLibPkgs = null; 5645 5646 // writer 5647 synchronized (mPackages) { 5648 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5649 // Only system apps can add new shared libraries. 5650 if (pkg.libraryNames != null) { 5651 for (int i=0; i<pkg.libraryNames.size(); i++) { 5652 String name = pkg.libraryNames.get(i); 5653 boolean allowed = false; 5654 if (isUpdatedSystemApp(pkg)) { 5655 // New library entries can only be added through the 5656 // system image. This is important to get rid of a lot 5657 // of nasty edge cases: for example if we allowed a non- 5658 // system update of the app to add a library, then uninstalling 5659 // the update would make the library go away, and assumptions 5660 // we made such as through app install filtering would now 5661 // have allowed apps on the device which aren't compatible 5662 // with it. Better to just have the restriction here, be 5663 // conservative, and create many fewer cases that can negatively 5664 // impact the user experience. 5665 final PackageSetting sysPs = mSettings 5666 .getDisabledSystemPkgLPr(pkg.packageName); 5667 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 5668 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 5669 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 5670 allowed = true; 5671 allowed = true; 5672 break; 5673 } 5674 } 5675 } 5676 } else { 5677 allowed = true; 5678 } 5679 if (allowed) { 5680 if (!mSharedLibraries.containsKey(name)) { 5681 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 5682 } else if (!name.equals(pkg.packageName)) { 5683 Slog.w(TAG, "Package " + pkg.packageName + " library " 5684 + name + " already exists; skipping"); 5685 } 5686 } else { 5687 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 5688 + name + " that is not declared on system image; skipping"); 5689 } 5690 } 5691 if ((scanFlags&SCAN_BOOTING) == 0) { 5692 // If we are not booting, we need to update any applications 5693 // that are clients of our shared library. If we are booting, 5694 // this will all be done once the scan is complete. 5695 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 5696 } 5697 } 5698 } 5699 } 5700 5701 // We also need to dexopt any apps that are dependent on this library. Note that 5702 // if these fail, we should abort the install since installing the library will 5703 // result in some apps being broken. 5704 if (clientLibPkgs != null) { 5705 if ((scanFlags & SCAN_NO_DEX) == 0) { 5706 for (int i = 0; i < clientLibPkgs.size(); i++) { 5707 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5708 if (performDexOptLI(clientPkg, null /* instruction sets */, forceDex, 5709 (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) { 5710 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 5711 "scanPackageLI failed to dexopt clientLibPkgs"); 5712 } 5713 } 5714 } 5715 } 5716 5717 // Request the ActivityManager to kill the process(only for existing packages) 5718 // so that we do not end up in a confused state while the user is still using the older 5719 // version of the application while the new one gets installed. 5720 if ((scanFlags & SCAN_REPLACING) != 0) { 5721 killApplication(pkg.applicationInfo.packageName, 5722 pkg.applicationInfo.uid, "update pkg"); 5723 } 5724 5725 // Also need to kill any apps that are dependent on the library. 5726 if (clientLibPkgs != null) { 5727 for (int i=0; i<clientLibPkgs.size(); i++) { 5728 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5729 killApplication(clientPkg.applicationInfo.packageName, 5730 clientPkg.applicationInfo.uid, "update lib"); 5731 } 5732 } 5733 5734 // writer 5735 synchronized (mPackages) { 5736 // We don't expect installation to fail beyond this point 5737 5738 // Add the new setting to mSettings 5739 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 5740 // Add the new setting to mPackages 5741 mPackages.put(pkg.applicationInfo.packageName, pkg); 5742 // Make sure we don't accidentally delete its data. 5743 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 5744 while (iter.hasNext()) { 5745 PackageCleanItem item = iter.next(); 5746 if (pkgName.equals(item.packageName)) { 5747 iter.remove(); 5748 } 5749 } 5750 5751 // Take care of first install / last update times. 5752 if (currentTime != 0) { 5753 if (pkgSetting.firstInstallTime == 0) { 5754 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 5755 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 5756 pkgSetting.lastUpdateTime = currentTime; 5757 } 5758 } else if (pkgSetting.firstInstallTime == 0) { 5759 // We need *something*. Take time time stamp of the file. 5760 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 5761 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 5762 if (scanFileTime != pkgSetting.timeStamp) { 5763 // A package on the system image has changed; consider this 5764 // to be an update. 5765 pkgSetting.lastUpdateTime = scanFileTime; 5766 } 5767 } 5768 5769 // Add the package's KeySets to the global KeySetManagerService 5770 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5771 try { 5772 // Old KeySetData no longer valid. 5773 ksms.removeAppKeySetDataLPw(pkg.packageName); 5774 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 5775 if (pkg.mKeySetMapping != null) { 5776 for (Map.Entry<String, ArraySet<PublicKey>> entry : 5777 pkg.mKeySetMapping.entrySet()) { 5778 if (entry.getValue() != null) { 5779 ksms.addDefinedKeySetToPackageLPw(pkg.packageName, 5780 entry.getValue(), entry.getKey()); 5781 } 5782 } 5783 if (pkg.mUpgradeKeySets != null) { 5784 for (String upgradeAlias : pkg.mUpgradeKeySets) { 5785 ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias); 5786 } 5787 } 5788 } 5789 } catch (NullPointerException e) { 5790 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 5791 } catch (IllegalArgumentException e) { 5792 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 5793 } 5794 5795 int N = pkg.providers.size(); 5796 StringBuilder r = null; 5797 int i; 5798 for (i=0; i<N; i++) { 5799 PackageParser.Provider p = pkg.providers.get(i); 5800 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 5801 p.info.processName, pkg.applicationInfo.uid); 5802 mProviders.addProvider(p); 5803 p.syncable = p.info.isSyncable; 5804 if (p.info.authority != null) { 5805 String names[] = p.info.authority.split(";"); 5806 p.info.authority = null; 5807 for (int j = 0; j < names.length; j++) { 5808 if (j == 1 && p.syncable) { 5809 // We only want the first authority for a provider to possibly be 5810 // syncable, so if we already added this provider using a different 5811 // authority clear the syncable flag. We copy the provider before 5812 // changing it because the mProviders object contains a reference 5813 // to a provider that we don't want to change. 5814 // Only do this for the second authority since the resulting provider 5815 // object can be the same for all future authorities for this provider. 5816 p = new PackageParser.Provider(p); 5817 p.syncable = false; 5818 } 5819 if (!mProvidersByAuthority.containsKey(names[j])) { 5820 mProvidersByAuthority.put(names[j], p); 5821 if (p.info.authority == null) { 5822 p.info.authority = names[j]; 5823 } else { 5824 p.info.authority = p.info.authority + ";" + names[j]; 5825 } 5826 if (DEBUG_PACKAGE_SCANNING) { 5827 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5828 Log.d(TAG, "Registered content provider: " + names[j] 5829 + ", className = " + p.info.name + ", isSyncable = " 5830 + p.info.isSyncable); 5831 } 5832 } else { 5833 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5834 Slog.w(TAG, "Skipping provider name " + names[j] + 5835 " (in package " + pkg.applicationInfo.packageName + 5836 "): name already used by " 5837 + ((other != null && other.getComponentName() != null) 5838 ? other.getComponentName().getPackageName() : "?")); 5839 } 5840 } 5841 } 5842 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5843 if (r == null) { 5844 r = new StringBuilder(256); 5845 } else { 5846 r.append(' '); 5847 } 5848 r.append(p.info.name); 5849 } 5850 } 5851 if (r != null) { 5852 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 5853 } 5854 5855 N = pkg.services.size(); 5856 r = null; 5857 for (i=0; i<N; i++) { 5858 PackageParser.Service s = pkg.services.get(i); 5859 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 5860 s.info.processName, pkg.applicationInfo.uid); 5861 mServices.addService(s); 5862 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5863 if (r == null) { 5864 r = new StringBuilder(256); 5865 } else { 5866 r.append(' '); 5867 } 5868 r.append(s.info.name); 5869 } 5870 } 5871 if (r != null) { 5872 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 5873 } 5874 5875 N = pkg.receivers.size(); 5876 r = null; 5877 for (i=0; i<N; i++) { 5878 PackageParser.Activity a = pkg.receivers.get(i); 5879 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5880 a.info.processName, pkg.applicationInfo.uid); 5881 mReceivers.addActivity(a, "receiver"); 5882 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5883 if (r == null) { 5884 r = new StringBuilder(256); 5885 } else { 5886 r.append(' '); 5887 } 5888 r.append(a.info.name); 5889 } 5890 } 5891 if (r != null) { 5892 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 5893 } 5894 5895 N = pkg.activities.size(); 5896 r = null; 5897 for (i=0; i<N; i++) { 5898 PackageParser.Activity a = pkg.activities.get(i); 5899 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5900 a.info.processName, pkg.applicationInfo.uid); 5901 mActivities.addActivity(a, "activity"); 5902 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5903 if (r == null) { 5904 r = new StringBuilder(256); 5905 } else { 5906 r.append(' '); 5907 } 5908 r.append(a.info.name); 5909 } 5910 } 5911 if (r != null) { 5912 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 5913 } 5914 5915 N = pkg.permissionGroups.size(); 5916 r = null; 5917 for (i=0; i<N; i++) { 5918 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 5919 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 5920 if (cur == null) { 5921 mPermissionGroups.put(pg.info.name, pg); 5922 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5923 if (r == null) { 5924 r = new StringBuilder(256); 5925 } else { 5926 r.append(' '); 5927 } 5928 r.append(pg.info.name); 5929 } 5930 } else { 5931 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 5932 + pg.info.packageName + " ignored: original from " 5933 + cur.info.packageName); 5934 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5935 if (r == null) { 5936 r = new StringBuilder(256); 5937 } else { 5938 r.append(' '); 5939 } 5940 r.append("DUP:"); 5941 r.append(pg.info.name); 5942 } 5943 } 5944 } 5945 if (r != null) { 5946 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 5947 } 5948 5949 N = pkg.permissions.size(); 5950 r = null; 5951 for (i=0; i<N; i++) { 5952 PackageParser.Permission p = pkg.permissions.get(i); 5953 HashMap<String, BasePermission> permissionMap = 5954 p.tree ? mSettings.mPermissionTrees 5955 : mSettings.mPermissions; 5956 p.group = mPermissionGroups.get(p.info.group); 5957 if (p.info.group == null || p.group != null) { 5958 BasePermission bp = permissionMap.get(p.info.name); 5959 5960 // Allow system apps to redefine non-system permissions 5961 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 5962 final boolean currentOwnerIsSystem = (bp.perm != null 5963 && isSystemApp(bp.perm.owner)); 5964 if (isSystemApp(p.owner) && !currentOwnerIsSystem) { 5965 String msg = "New decl " + p.owner + " of permission " 5966 + p.info.name + " is system; overriding " + bp.sourcePackage; 5967 reportSettingsProblem(Log.WARN, msg); 5968 bp = null; 5969 } 5970 } 5971 5972 if (bp == null) { 5973 bp = new BasePermission(p.info.name, p.info.packageName, 5974 BasePermission.TYPE_NORMAL); 5975 permissionMap.put(p.info.name, bp); 5976 } 5977 5978 if (bp.perm == null) { 5979 if (bp.sourcePackage == null 5980 || bp.sourcePackage.equals(p.info.packageName)) { 5981 BasePermission tree = findPermissionTreeLP(p.info.name); 5982 if (tree == null 5983 || tree.sourcePackage.equals(p.info.packageName)) { 5984 bp.packageSetting = pkgSetting; 5985 bp.perm = p; 5986 bp.uid = pkg.applicationInfo.uid; 5987 bp.sourcePackage = p.info.packageName; 5988 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5989 if (r == null) { 5990 r = new StringBuilder(256); 5991 } else { 5992 r.append(' '); 5993 } 5994 r.append(p.info.name); 5995 } 5996 } else { 5997 Slog.w(TAG, "Permission " + p.info.name + " from package " 5998 + p.info.packageName + " ignored: base tree " 5999 + tree.name + " is from package " 6000 + tree.sourcePackage); 6001 } 6002 } else { 6003 Slog.w(TAG, "Permission " + p.info.name + " from package " 6004 + p.info.packageName + " ignored: original from " 6005 + bp.sourcePackage); 6006 } 6007 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6008 if (r == null) { 6009 r = new StringBuilder(256); 6010 } else { 6011 r.append(' '); 6012 } 6013 r.append("DUP:"); 6014 r.append(p.info.name); 6015 } 6016 if (bp.perm == p) { 6017 bp.protectionLevel = p.info.protectionLevel; 6018 } 6019 } else { 6020 Slog.w(TAG, "Permission " + p.info.name + " from package " 6021 + p.info.packageName + " ignored: no group " 6022 + p.group); 6023 } 6024 } 6025 if (r != null) { 6026 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6027 } 6028 6029 N = pkg.instrumentation.size(); 6030 r = null; 6031 for (i=0; i<N; i++) { 6032 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6033 a.info.packageName = pkg.applicationInfo.packageName; 6034 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6035 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6036 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6037 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6038 a.info.dataDir = pkg.applicationInfo.dataDir; 6039 6040 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6041 // need other information about the application, like the ABI and what not ? 6042 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6043 mInstrumentation.put(a.getComponentName(), a); 6044 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6045 if (r == null) { 6046 r = new StringBuilder(256); 6047 } else { 6048 r.append(' '); 6049 } 6050 r.append(a.info.name); 6051 } 6052 } 6053 if (r != null) { 6054 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6055 } 6056 6057 if (pkg.protectedBroadcasts != null) { 6058 N = pkg.protectedBroadcasts.size(); 6059 for (i=0; i<N; i++) { 6060 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6061 } 6062 } 6063 6064 pkgSetting.setTimeStamp(scanFileTime); 6065 6066 // Create idmap files for pairs of (packages, overlay packages). 6067 // Note: "android", ie framework-res.apk, is handled by native layers. 6068 if (pkg.mOverlayTarget != null) { 6069 // This is an overlay package. 6070 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6071 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6072 mOverlays.put(pkg.mOverlayTarget, 6073 new HashMap<String, PackageParser.Package>()); 6074 } 6075 HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6076 map.put(pkg.packageName, pkg); 6077 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6078 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6079 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6080 "scanPackageLI failed to createIdmap"); 6081 } 6082 } 6083 } else if (mOverlays.containsKey(pkg.packageName) && 6084 !pkg.packageName.equals("android")) { 6085 // This is a regular package, with one or more known overlay packages. 6086 createIdmapsForPackageLI(pkg); 6087 } 6088 } 6089 6090 return pkg; 6091 } 6092 6093 /** 6094 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6095 * i.e, so that all packages can be run inside a single process if required. 6096 * 6097 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6098 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6099 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6100 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6101 * updating a package that belongs to a shared user. 6102 * 6103 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6104 * adds unnecessary complexity. 6105 */ 6106 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6107 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6108 String requiredInstructionSet = null; 6109 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6110 requiredInstructionSet = VMRuntime.getInstructionSet( 6111 scannedPackage.applicationInfo.primaryCpuAbi); 6112 } 6113 6114 PackageSetting requirer = null; 6115 for (PackageSetting ps : packagesForUser) { 6116 // If packagesForUser contains scannedPackage, we skip it. This will happen 6117 // when scannedPackage is an update of an existing package. Without this check, 6118 // we will never be able to change the ABI of any package belonging to a shared 6119 // user, even if it's compatible with other packages. 6120 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6121 if (ps.primaryCpuAbiString == null) { 6122 continue; 6123 } 6124 6125 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6126 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6127 // We have a mismatch between instruction sets (say arm vs arm64) warn about 6128 // this but there's not much we can do. 6129 String errorMessage = "Instruction set mismatch, " 6130 + ((requirer == null) ? "[caller]" : requirer) 6131 + " requires " + requiredInstructionSet + " whereas " + ps 6132 + " requires " + instructionSet; 6133 Slog.w(TAG, errorMessage); 6134 } 6135 6136 if (requiredInstructionSet == null) { 6137 requiredInstructionSet = instructionSet; 6138 requirer = ps; 6139 } 6140 } 6141 } 6142 6143 if (requiredInstructionSet != null) { 6144 String adjustedAbi; 6145 if (requirer != null) { 6146 // requirer != null implies that either scannedPackage was null or that scannedPackage 6147 // did not require an ABI, in which case we have to adjust scannedPackage to match 6148 // the ABI of the set (which is the same as requirer's ABI) 6149 adjustedAbi = requirer.primaryCpuAbiString; 6150 if (scannedPackage != null) { 6151 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6152 } 6153 } else { 6154 // requirer == null implies that we're updating all ABIs in the set to 6155 // match scannedPackage. 6156 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6157 } 6158 6159 for (PackageSetting ps : packagesForUser) { 6160 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6161 if (ps.primaryCpuAbiString != null) { 6162 continue; 6163 } 6164 6165 ps.primaryCpuAbiString = adjustedAbi; 6166 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6167 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6168 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6169 6170 if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt, 6171 deferDexOpt, true) == DEX_OPT_FAILED) { 6172 ps.primaryCpuAbiString = null; 6173 ps.pkg.applicationInfo.primaryCpuAbi = null; 6174 return; 6175 } else { 6176 mInstaller.rmdex(ps.codePathString, 6177 getDexCodeInstructionSet(getPreferredInstructionSet())); 6178 } 6179 } 6180 } 6181 } 6182 } 6183 } 6184 6185 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6186 synchronized (mPackages) { 6187 mResolverReplaced = true; 6188 // Set up information for custom user intent resolution activity. 6189 mResolveActivity.applicationInfo = pkg.applicationInfo; 6190 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6191 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6192 mResolveActivity.processName = null; 6193 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6194 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6195 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6196 mResolveActivity.theme = 0; 6197 mResolveActivity.exported = true; 6198 mResolveActivity.enabled = true; 6199 mResolveInfo.activityInfo = mResolveActivity; 6200 mResolveInfo.priority = 0; 6201 mResolveInfo.preferredOrder = 0; 6202 mResolveInfo.match = 0; 6203 mResolveComponentName = mCustomResolverComponentName; 6204 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6205 mResolveComponentName); 6206 } 6207 } 6208 6209 private static String calculateBundledApkRoot(final String codePathString) { 6210 final File codePath = new File(codePathString); 6211 final File codeRoot; 6212 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6213 codeRoot = Environment.getRootDirectory(); 6214 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6215 codeRoot = Environment.getOemDirectory(); 6216 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6217 codeRoot = Environment.getVendorDirectory(); 6218 } else { 6219 // Unrecognized code path; take its top real segment as the apk root: 6220 // e.g. /something/app/blah.apk => /something 6221 try { 6222 File f = codePath.getCanonicalFile(); 6223 File parent = f.getParentFile(); // non-null because codePath is a file 6224 File tmp; 6225 while ((tmp = parent.getParentFile()) != null) { 6226 f = parent; 6227 parent = tmp; 6228 } 6229 codeRoot = f; 6230 Slog.w(TAG, "Unrecognized code path " 6231 + codePath + " - using " + codeRoot); 6232 } catch (IOException e) { 6233 // Can't canonicalize the code path -- shenanigans? 6234 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6235 return Environment.getRootDirectory().getPath(); 6236 } 6237 } 6238 return codeRoot.getPath(); 6239 } 6240 6241 /** 6242 * Derive and set the location of native libraries for the given package, 6243 * which varies depending on where and how the package was installed. 6244 */ 6245 private void setNativeLibraryPaths(PackageParser.Package pkg) { 6246 final ApplicationInfo info = pkg.applicationInfo; 6247 final String codePath = pkg.codePath; 6248 final File codeFile = new File(codePath); 6249 final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info); 6250 final boolean asecApp = isForwardLocked(info) || isExternal(info); 6251 6252 info.nativeLibraryRootDir = null; 6253 info.nativeLibraryRootRequiresIsa = false; 6254 info.nativeLibraryDir = null; 6255 info.secondaryNativeLibraryDir = null; 6256 6257 if (isApkFile(codeFile)) { 6258 // Monolithic install 6259 if (bundledApp) { 6260 // If "/system/lib64/apkname" exists, assume that is the per-package 6261 // native library directory to use; otherwise use "/system/lib/apkname". 6262 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 6263 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 6264 getPrimaryInstructionSet(info)); 6265 6266 // This is a bundled system app so choose the path based on the ABI. 6267 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 6268 // is just the default path. 6269 final String apkName = deriveCodePathName(codePath); 6270 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 6271 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 6272 apkName).getAbsolutePath(); 6273 6274 if (info.secondaryCpuAbi != null) { 6275 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 6276 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 6277 secondaryLibDir, apkName).getAbsolutePath(); 6278 } 6279 } else if (asecApp) { 6280 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 6281 .getAbsolutePath(); 6282 } else { 6283 final String apkName = deriveCodePathName(codePath); 6284 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 6285 .getAbsolutePath(); 6286 } 6287 6288 info.nativeLibraryRootRequiresIsa = false; 6289 info.nativeLibraryDir = info.nativeLibraryRootDir; 6290 } else { 6291 // Cluster install 6292 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 6293 info.nativeLibraryRootRequiresIsa = true; 6294 6295 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 6296 getPrimaryInstructionSet(info)).getAbsolutePath(); 6297 6298 if (info.secondaryCpuAbi != null) { 6299 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 6300 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 6301 } 6302 } 6303 } 6304 6305 /** 6306 * Calculate the abis and roots for a bundled app. These can uniquely 6307 * be determined from the contents of the system partition, i.e whether 6308 * it contains 64 or 32 bit shared libraries etc. We do not validate any 6309 * of this information, and instead assume that the system was built 6310 * sensibly. 6311 */ 6312 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 6313 PackageSetting pkgSetting) { 6314 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 6315 6316 // If "/system/lib64/apkname" exists, assume that is the per-package 6317 // native library directory to use; otherwise use "/system/lib/apkname". 6318 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 6319 setBundledAppAbi(pkg, apkRoot, apkName); 6320 // pkgSetting might be null during rescan following uninstall of updates 6321 // to a bundled app, so accommodate that possibility. The settings in 6322 // that case will be established later from the parsed package. 6323 // 6324 // If the settings aren't null, sync them up with what we've just derived. 6325 // note that apkRoot isn't stored in the package settings. 6326 if (pkgSetting != null) { 6327 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6328 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6329 } 6330 } 6331 6332 /** 6333 * Deduces the ABI of a bundled app and sets the relevant fields on the 6334 * parsed pkg object. 6335 * 6336 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 6337 * under which system libraries are installed. 6338 * @param apkName the name of the installed package. 6339 */ 6340 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 6341 final File codeFile = new File(pkg.codePath); 6342 6343 final boolean has64BitLibs; 6344 final boolean has32BitLibs; 6345 if (isApkFile(codeFile)) { 6346 // Monolithic install 6347 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 6348 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 6349 } else { 6350 // Cluster install 6351 final File rootDir = new File(codeFile, LIB_DIR_NAME); 6352 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 6353 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 6354 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 6355 has64BitLibs = (new File(rootDir, isa)).exists(); 6356 } else { 6357 has64BitLibs = false; 6358 } 6359 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 6360 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 6361 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 6362 has32BitLibs = (new File(rootDir, isa)).exists(); 6363 } else { 6364 has32BitLibs = false; 6365 } 6366 } 6367 6368 if (has64BitLibs && !has32BitLibs) { 6369 // The package has 64 bit libs, but not 32 bit libs. Its primary 6370 // ABI should be 64 bit. We can safely assume here that the bundled 6371 // native libraries correspond to the most preferred ABI in the list. 6372 6373 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6374 pkg.applicationInfo.secondaryCpuAbi = null; 6375 } else if (has32BitLibs && !has64BitLibs) { 6376 // The package has 32 bit libs but not 64 bit libs. Its primary 6377 // ABI should be 32 bit. 6378 6379 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6380 pkg.applicationInfo.secondaryCpuAbi = null; 6381 } else if (has32BitLibs && has64BitLibs) { 6382 // The application has both 64 and 32 bit bundled libraries. We check 6383 // here that the app declares multiArch support, and warn if it doesn't. 6384 // 6385 // We will be lenient here and record both ABIs. The primary will be the 6386 // ABI that's higher on the list, i.e, a device that's configured to prefer 6387 // 64 bit apps will see a 64 bit primary ABI, 6388 6389 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 6390 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 6391 } 6392 6393 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 6394 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6395 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6396 } else { 6397 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6398 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6399 } 6400 } else { 6401 pkg.applicationInfo.primaryCpuAbi = null; 6402 pkg.applicationInfo.secondaryCpuAbi = null; 6403 } 6404 } 6405 6406 private void killApplication(String pkgName, int appId, String reason) { 6407 // Request the ActivityManager to kill the process(only for existing packages) 6408 // so that we do not end up in a confused state while the user is still using the older 6409 // version of the application while the new one gets installed. 6410 IActivityManager am = ActivityManagerNative.getDefault(); 6411 if (am != null) { 6412 try { 6413 am.killApplicationWithAppId(pkgName, appId, reason); 6414 } catch (RemoteException e) { 6415 } 6416 } 6417 } 6418 6419 void removePackageLI(PackageSetting ps, boolean chatty) { 6420 if (DEBUG_INSTALL) { 6421 if (chatty) 6422 Log.d(TAG, "Removing package " + ps.name); 6423 } 6424 6425 // writer 6426 synchronized (mPackages) { 6427 mPackages.remove(ps.name); 6428 final PackageParser.Package pkg = ps.pkg; 6429 if (pkg != null) { 6430 cleanPackageDataStructuresLILPw(pkg, chatty); 6431 } 6432 } 6433 } 6434 6435 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 6436 if (DEBUG_INSTALL) { 6437 if (chatty) 6438 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 6439 } 6440 6441 // writer 6442 synchronized (mPackages) { 6443 mPackages.remove(pkg.applicationInfo.packageName); 6444 cleanPackageDataStructuresLILPw(pkg, chatty); 6445 } 6446 } 6447 6448 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 6449 int N = pkg.providers.size(); 6450 StringBuilder r = null; 6451 int i; 6452 for (i=0; i<N; i++) { 6453 PackageParser.Provider p = pkg.providers.get(i); 6454 mProviders.removeProvider(p); 6455 if (p.info.authority == null) { 6456 6457 /* There was another ContentProvider with this authority when 6458 * this app was installed so this authority is null, 6459 * Ignore it as we don't have to unregister the provider. 6460 */ 6461 continue; 6462 } 6463 String names[] = p.info.authority.split(";"); 6464 for (int j = 0; j < names.length; j++) { 6465 if (mProvidersByAuthority.get(names[j]) == p) { 6466 mProvidersByAuthority.remove(names[j]); 6467 if (DEBUG_REMOVE) { 6468 if (chatty) 6469 Log.d(TAG, "Unregistered content provider: " + names[j] 6470 + ", className = " + p.info.name + ", isSyncable = " 6471 + p.info.isSyncable); 6472 } 6473 } 6474 } 6475 if (DEBUG_REMOVE && chatty) { 6476 if (r == null) { 6477 r = new StringBuilder(256); 6478 } else { 6479 r.append(' '); 6480 } 6481 r.append(p.info.name); 6482 } 6483 } 6484 if (r != null) { 6485 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 6486 } 6487 6488 N = pkg.services.size(); 6489 r = null; 6490 for (i=0; i<N; i++) { 6491 PackageParser.Service s = pkg.services.get(i); 6492 mServices.removeService(s); 6493 if (chatty) { 6494 if (r == null) { 6495 r = new StringBuilder(256); 6496 } else { 6497 r.append(' '); 6498 } 6499 r.append(s.info.name); 6500 } 6501 } 6502 if (r != null) { 6503 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 6504 } 6505 6506 N = pkg.receivers.size(); 6507 r = null; 6508 for (i=0; i<N; i++) { 6509 PackageParser.Activity a = pkg.receivers.get(i); 6510 mReceivers.removeActivity(a, "receiver"); 6511 if (DEBUG_REMOVE && chatty) { 6512 if (r == null) { 6513 r = new StringBuilder(256); 6514 } else { 6515 r.append(' '); 6516 } 6517 r.append(a.info.name); 6518 } 6519 } 6520 if (r != null) { 6521 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 6522 } 6523 6524 N = pkg.activities.size(); 6525 r = null; 6526 for (i=0; i<N; i++) { 6527 PackageParser.Activity a = pkg.activities.get(i); 6528 mActivities.removeActivity(a, "activity"); 6529 if (DEBUG_REMOVE && chatty) { 6530 if (r == null) { 6531 r = new StringBuilder(256); 6532 } else { 6533 r.append(' '); 6534 } 6535 r.append(a.info.name); 6536 } 6537 } 6538 if (r != null) { 6539 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 6540 } 6541 6542 N = pkg.permissions.size(); 6543 r = null; 6544 for (i=0; i<N; i++) { 6545 PackageParser.Permission p = pkg.permissions.get(i); 6546 BasePermission bp = mSettings.mPermissions.get(p.info.name); 6547 if (bp == null) { 6548 bp = mSettings.mPermissionTrees.get(p.info.name); 6549 } 6550 if (bp != null && bp.perm == p) { 6551 bp.perm = null; 6552 if (DEBUG_REMOVE && chatty) { 6553 if (r == null) { 6554 r = new StringBuilder(256); 6555 } else { 6556 r.append(' '); 6557 } 6558 r.append(p.info.name); 6559 } 6560 } 6561 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6562 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 6563 if (appOpPerms != null) { 6564 appOpPerms.remove(pkg.packageName); 6565 } 6566 } 6567 } 6568 if (r != null) { 6569 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6570 } 6571 6572 N = pkg.requestedPermissions.size(); 6573 r = null; 6574 for (i=0; i<N; i++) { 6575 String perm = pkg.requestedPermissions.get(i); 6576 BasePermission bp = mSettings.mPermissions.get(perm); 6577 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6578 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 6579 if (appOpPerms != null) { 6580 appOpPerms.remove(pkg.packageName); 6581 if (appOpPerms.isEmpty()) { 6582 mAppOpPermissionPackages.remove(perm); 6583 } 6584 } 6585 } 6586 } 6587 if (r != null) { 6588 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6589 } 6590 6591 N = pkg.instrumentation.size(); 6592 r = null; 6593 for (i=0; i<N; i++) { 6594 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6595 mInstrumentation.remove(a.getComponentName()); 6596 if (DEBUG_REMOVE && chatty) { 6597 if (r == null) { 6598 r = new StringBuilder(256); 6599 } else { 6600 r.append(' '); 6601 } 6602 r.append(a.info.name); 6603 } 6604 } 6605 if (r != null) { 6606 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 6607 } 6608 6609 r = null; 6610 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6611 // Only system apps can hold shared libraries. 6612 if (pkg.libraryNames != null) { 6613 for (i=0; i<pkg.libraryNames.size(); i++) { 6614 String name = pkg.libraryNames.get(i); 6615 SharedLibraryEntry cur = mSharedLibraries.get(name); 6616 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 6617 mSharedLibraries.remove(name); 6618 if (DEBUG_REMOVE && chatty) { 6619 if (r == null) { 6620 r = new StringBuilder(256); 6621 } else { 6622 r.append(' '); 6623 } 6624 r.append(name); 6625 } 6626 } 6627 } 6628 } 6629 } 6630 if (r != null) { 6631 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 6632 } 6633 } 6634 6635 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 6636 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 6637 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 6638 return true; 6639 } 6640 } 6641 return false; 6642 } 6643 6644 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 6645 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 6646 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 6647 6648 private void updatePermissionsLPw(String changingPkg, 6649 PackageParser.Package pkgInfo, int flags) { 6650 // Make sure there are no dangling permission trees. 6651 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 6652 while (it.hasNext()) { 6653 final BasePermission bp = it.next(); 6654 if (bp.packageSetting == null) { 6655 // We may not yet have parsed the package, so just see if 6656 // we still know about its settings. 6657 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6658 } 6659 if (bp.packageSetting == null) { 6660 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 6661 + " from package " + bp.sourcePackage); 6662 it.remove(); 6663 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6664 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6665 Slog.i(TAG, "Removing old permission tree: " + bp.name 6666 + " from package " + bp.sourcePackage); 6667 flags |= UPDATE_PERMISSIONS_ALL; 6668 it.remove(); 6669 } 6670 } 6671 } 6672 6673 // Make sure all dynamic permissions have been assigned to a package, 6674 // and make sure there are no dangling permissions. 6675 it = mSettings.mPermissions.values().iterator(); 6676 while (it.hasNext()) { 6677 final BasePermission bp = it.next(); 6678 if (bp.type == BasePermission.TYPE_DYNAMIC) { 6679 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 6680 + bp.name + " pkg=" + bp.sourcePackage 6681 + " info=" + bp.pendingInfo); 6682 if (bp.packageSetting == null && bp.pendingInfo != null) { 6683 final BasePermission tree = findPermissionTreeLP(bp.name); 6684 if (tree != null && tree.perm != null) { 6685 bp.packageSetting = tree.packageSetting; 6686 bp.perm = new PackageParser.Permission(tree.perm.owner, 6687 new PermissionInfo(bp.pendingInfo)); 6688 bp.perm.info.packageName = tree.perm.info.packageName; 6689 bp.perm.info.name = bp.name; 6690 bp.uid = tree.uid; 6691 } 6692 } 6693 } 6694 if (bp.packageSetting == null) { 6695 // We may not yet have parsed the package, so just see if 6696 // we still know about its settings. 6697 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6698 } 6699 if (bp.packageSetting == null) { 6700 Slog.w(TAG, "Removing dangling permission: " + bp.name 6701 + " from package " + bp.sourcePackage); 6702 it.remove(); 6703 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6704 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6705 Slog.i(TAG, "Removing old permission: " + bp.name 6706 + " from package " + bp.sourcePackage); 6707 flags |= UPDATE_PERMISSIONS_ALL; 6708 it.remove(); 6709 } 6710 } 6711 } 6712 6713 // Now update the permissions for all packages, in particular 6714 // replace the granted permissions of the system packages. 6715 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 6716 for (PackageParser.Package pkg : mPackages.values()) { 6717 if (pkg != pkgInfo) { 6718 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 6719 changingPkg); 6720 } 6721 } 6722 } 6723 6724 if (pkgInfo != null) { 6725 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 6726 } 6727 } 6728 6729 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 6730 String packageOfInterest) { 6731 final PackageSetting ps = (PackageSetting) pkg.mExtras; 6732 if (ps == null) { 6733 return; 6734 } 6735 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 6736 HashSet<String> origPermissions = gp.grantedPermissions; 6737 boolean changedPermission = false; 6738 6739 if (replace) { 6740 ps.permissionsFixed = false; 6741 if (gp == ps) { 6742 origPermissions = new HashSet<String>(gp.grantedPermissions); 6743 gp.grantedPermissions.clear(); 6744 gp.gids = mGlobalGids; 6745 } 6746 } 6747 6748 if (gp.gids == null) { 6749 gp.gids = mGlobalGids; 6750 } 6751 6752 final int N = pkg.requestedPermissions.size(); 6753 for (int i=0; i<N; i++) { 6754 final String name = pkg.requestedPermissions.get(i); 6755 final boolean required = pkg.requestedPermissionsRequired.get(i); 6756 final BasePermission bp = mSettings.mPermissions.get(name); 6757 if (DEBUG_INSTALL) { 6758 if (gp != ps) { 6759 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 6760 } 6761 } 6762 6763 if (bp == null || bp.packageSetting == null) { 6764 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 6765 Slog.w(TAG, "Unknown permission " + name 6766 + " in package " + pkg.packageName); 6767 } 6768 continue; 6769 } 6770 6771 final String perm = bp.name; 6772 boolean allowed; 6773 boolean allowedSig = false; 6774 if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6775 // Keep track of app op permissions. 6776 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 6777 if (pkgs == null) { 6778 pkgs = new ArraySet<>(); 6779 mAppOpPermissionPackages.put(bp.name, pkgs); 6780 } 6781 pkgs.add(pkg.packageName); 6782 } 6783 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 6784 if (level == PermissionInfo.PROTECTION_NORMAL 6785 || level == PermissionInfo.PROTECTION_DANGEROUS) { 6786 // We grant a normal or dangerous permission if any of the following 6787 // are true: 6788 // 1) The permission is required 6789 // 2) The permission is optional, but was granted in the past 6790 // 3) The permission is optional, but was requested by an 6791 // app in /system (not /data) 6792 // 6793 // Otherwise, reject the permission. 6794 allowed = (required || origPermissions.contains(perm) 6795 || (isSystemApp(ps) && !isUpdatedSystemApp(ps))); 6796 } else if (bp.packageSetting == null) { 6797 // This permission is invalid; skip it. 6798 allowed = false; 6799 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 6800 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions); 6801 if (allowed) { 6802 allowedSig = true; 6803 } 6804 } else { 6805 allowed = false; 6806 } 6807 if (DEBUG_INSTALL) { 6808 if (gp != ps) { 6809 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 6810 } 6811 } 6812 if (allowed) { 6813 if (!isSystemApp(ps) && ps.permissionsFixed) { 6814 // If this is an existing, non-system package, then 6815 // we can't add any new permissions to it. 6816 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 6817 // Except... if this is a permission that was added 6818 // to the platform (note: need to only do this when 6819 // updating the platform). 6820 allowed = isNewPlatformPermissionForPackage(perm, pkg); 6821 } 6822 } 6823 if (allowed) { 6824 if (!gp.grantedPermissions.contains(perm)) { 6825 changedPermission = true; 6826 gp.grantedPermissions.add(perm); 6827 gp.gids = appendInts(gp.gids, bp.gids); 6828 } else if (!ps.haveGids) { 6829 gp.gids = appendInts(gp.gids, bp.gids); 6830 } 6831 } else { 6832 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 6833 Slog.w(TAG, "Not granting permission " + perm 6834 + " to package " + pkg.packageName 6835 + " because it was previously installed without"); 6836 } 6837 } 6838 } else { 6839 if (gp.grantedPermissions.remove(perm)) { 6840 changedPermission = true; 6841 gp.gids = removeInts(gp.gids, bp.gids); 6842 Slog.i(TAG, "Un-granting permission " + perm 6843 + " from package " + pkg.packageName 6844 + " (protectionLevel=" + bp.protectionLevel 6845 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6846 + ")"); 6847 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 6848 // Don't print warning for app op permissions, since it is fine for them 6849 // not to be granted, there is a UI for the user to decide. 6850 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 6851 Slog.w(TAG, "Not granting permission " + perm 6852 + " to package " + pkg.packageName 6853 + " (protectionLevel=" + bp.protectionLevel 6854 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6855 + ")"); 6856 } 6857 } 6858 } 6859 } 6860 6861 if ((changedPermission || replace) && !ps.permissionsFixed && 6862 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 6863 // This is the first that we have heard about this package, so the 6864 // permissions we have now selected are fixed until explicitly 6865 // changed. 6866 ps.permissionsFixed = true; 6867 } 6868 ps.haveGids = true; 6869 } 6870 6871 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 6872 boolean allowed = false; 6873 final int NP = PackageParser.NEW_PERMISSIONS.length; 6874 for (int ip=0; ip<NP; ip++) { 6875 final PackageParser.NewPermissionInfo npi 6876 = PackageParser.NEW_PERMISSIONS[ip]; 6877 if (npi.name.equals(perm) 6878 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 6879 allowed = true; 6880 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 6881 + pkg.packageName); 6882 break; 6883 } 6884 } 6885 return allowed; 6886 } 6887 6888 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 6889 BasePermission bp, HashSet<String> origPermissions) { 6890 boolean allowed; 6891 allowed = (compareSignatures( 6892 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 6893 == PackageManager.SIGNATURE_MATCH) 6894 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 6895 == PackageManager.SIGNATURE_MATCH); 6896 if (!allowed && (bp.protectionLevel 6897 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 6898 if (isSystemApp(pkg)) { 6899 // For updated system applications, a system permission 6900 // is granted only if it had been defined by the original application. 6901 if (isUpdatedSystemApp(pkg)) { 6902 final PackageSetting sysPs = mSettings 6903 .getDisabledSystemPkgLPr(pkg.packageName); 6904 final GrantedPermissions origGp = sysPs.sharedUser != null 6905 ? sysPs.sharedUser : sysPs; 6906 6907 if (origGp.grantedPermissions.contains(perm)) { 6908 // If the original was granted this permission, we take 6909 // that grant decision as read and propagate it to the 6910 // update. 6911 allowed = true; 6912 } else { 6913 // The system apk may have been updated with an older 6914 // version of the one on the data partition, but which 6915 // granted a new system permission that it didn't have 6916 // before. In this case we do want to allow the app to 6917 // now get the new permission if the ancestral apk is 6918 // privileged to get it. 6919 if (sysPs.pkg != null && sysPs.isPrivileged()) { 6920 for (int j=0; 6921 j<sysPs.pkg.requestedPermissions.size(); j++) { 6922 if (perm.equals( 6923 sysPs.pkg.requestedPermissions.get(j))) { 6924 allowed = true; 6925 break; 6926 } 6927 } 6928 } 6929 } 6930 } else { 6931 allowed = isPrivilegedApp(pkg); 6932 } 6933 } 6934 } 6935 if (!allowed && (bp.protectionLevel 6936 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 6937 // For development permissions, a development permission 6938 // is granted only if it was already granted. 6939 allowed = origPermissions.contains(perm); 6940 } 6941 return allowed; 6942 } 6943 6944 final class ActivityIntentResolver 6945 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 6946 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 6947 boolean defaultOnly, int userId) { 6948 if (!sUserManager.exists(userId)) return null; 6949 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 6950 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 6951 } 6952 6953 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 6954 int userId) { 6955 if (!sUserManager.exists(userId)) return null; 6956 mFlags = flags; 6957 return super.queryIntent(intent, resolvedType, 6958 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 6959 } 6960 6961 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 6962 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 6963 if (!sUserManager.exists(userId)) return null; 6964 if (packageActivities == null) { 6965 return null; 6966 } 6967 mFlags = flags; 6968 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 6969 final int N = packageActivities.size(); 6970 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 6971 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 6972 6973 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 6974 for (int i = 0; i < N; ++i) { 6975 intentFilters = packageActivities.get(i).intents; 6976 if (intentFilters != null && intentFilters.size() > 0) { 6977 PackageParser.ActivityIntentInfo[] array = 6978 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 6979 intentFilters.toArray(array); 6980 listCut.add(array); 6981 } 6982 } 6983 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 6984 } 6985 6986 public final void addActivity(PackageParser.Activity a, String type) { 6987 final boolean systemApp = isSystemApp(a.info.applicationInfo); 6988 mActivities.put(a.getComponentName(), a); 6989 if (DEBUG_SHOW_INFO) 6990 Log.v( 6991 TAG, " " + type + " " + 6992 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 6993 if (DEBUG_SHOW_INFO) 6994 Log.v(TAG, " Class=" + a.info.name); 6995 final int NI = a.intents.size(); 6996 for (int j=0; j<NI; j++) { 6997 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 6998 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 6999 intent.setPriority(0); 7000 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 7001 + a.className + " with priority > 0, forcing to 0"); 7002 } 7003 if (DEBUG_SHOW_INFO) { 7004 Log.v(TAG, " IntentFilter:"); 7005 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7006 } 7007 if (!intent.debugCheck()) { 7008 Log.w(TAG, "==> For Activity " + a.info.name); 7009 } 7010 addFilter(intent); 7011 } 7012 } 7013 7014 public final void removeActivity(PackageParser.Activity a, String type) { 7015 mActivities.remove(a.getComponentName()); 7016 if (DEBUG_SHOW_INFO) { 7017 Log.v(TAG, " " + type + " " 7018 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 7019 : a.info.name) + ":"); 7020 Log.v(TAG, " Class=" + a.info.name); 7021 } 7022 final int NI = a.intents.size(); 7023 for (int j=0; j<NI; j++) { 7024 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7025 if (DEBUG_SHOW_INFO) { 7026 Log.v(TAG, " IntentFilter:"); 7027 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7028 } 7029 removeFilter(intent); 7030 } 7031 } 7032 7033 @Override 7034 protected boolean allowFilterResult( 7035 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 7036 ActivityInfo filterAi = filter.activity.info; 7037 for (int i=dest.size()-1; i>=0; i--) { 7038 ActivityInfo destAi = dest.get(i).activityInfo; 7039 if (destAi.name == filterAi.name 7040 && destAi.packageName == filterAi.packageName) { 7041 return false; 7042 } 7043 } 7044 return true; 7045 } 7046 7047 @Override 7048 protected ActivityIntentInfo[] newArray(int size) { 7049 return new ActivityIntentInfo[size]; 7050 } 7051 7052 @Override 7053 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 7054 if (!sUserManager.exists(userId)) return true; 7055 PackageParser.Package p = filter.activity.owner; 7056 if (p != null) { 7057 PackageSetting ps = (PackageSetting)p.mExtras; 7058 if (ps != null) { 7059 // System apps are never considered stopped for purposes of 7060 // filtering, because there may be no way for the user to 7061 // actually re-launch them. 7062 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 7063 && ps.getStopped(userId); 7064 } 7065 } 7066 return false; 7067 } 7068 7069 @Override 7070 protected boolean isPackageForFilter(String packageName, 7071 PackageParser.ActivityIntentInfo info) { 7072 return packageName.equals(info.activity.owner.packageName); 7073 } 7074 7075 @Override 7076 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7077 int match, int userId) { 7078 if (!sUserManager.exists(userId)) return null; 7079 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7080 return null; 7081 } 7082 final PackageParser.Activity activity = info.activity; 7083 if (mSafeMode && (activity.info.applicationInfo.flags 7084 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7085 return null; 7086 } 7087 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7088 if (ps == null) { 7089 return null; 7090 } 7091 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7092 ps.readUserState(userId), userId); 7093 if (ai == null) { 7094 return null; 7095 } 7096 final ResolveInfo res = new ResolveInfo(); 7097 res.activityInfo = ai; 7098 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7099 res.filter = info; 7100 } 7101 res.priority = info.getPriority(); 7102 res.preferredOrder = activity.owner.mPreferredOrder; 7103 //System.out.println("Result: " + res.activityInfo.className + 7104 // " = " + res.priority); 7105 res.match = match; 7106 res.isDefault = info.hasDefault; 7107 res.labelRes = info.labelRes; 7108 res.nonLocalizedLabel = info.nonLocalizedLabel; 7109 if (userNeedsBadging(userId)) { 7110 res.noResourceId = true; 7111 } else { 7112 res.icon = info.icon; 7113 } 7114 res.system = isSystemApp(res.activityInfo.applicationInfo); 7115 return res; 7116 } 7117 7118 @Override 7119 protected void sortResults(List<ResolveInfo> results) { 7120 Collections.sort(results, mResolvePrioritySorter); 7121 } 7122 7123 @Override 7124 protected void dumpFilter(PrintWriter out, String prefix, 7125 PackageParser.ActivityIntentInfo filter) { 7126 out.print(prefix); out.print( 7127 Integer.toHexString(System.identityHashCode(filter.activity))); 7128 out.print(' '); 7129 filter.activity.printComponentShortName(out); 7130 out.print(" filter "); 7131 out.println(Integer.toHexString(System.identityHashCode(filter))); 7132 } 7133 7134// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7135// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7136// final List<ResolveInfo> retList = Lists.newArrayList(); 7137// while (i.hasNext()) { 7138// final ResolveInfo resolveInfo = i.next(); 7139// if (isEnabledLP(resolveInfo.activityInfo)) { 7140// retList.add(resolveInfo); 7141// } 7142// } 7143// return retList; 7144// } 7145 7146 // Keys are String (activity class name), values are Activity. 7147 private final HashMap<ComponentName, PackageParser.Activity> mActivities 7148 = new HashMap<ComponentName, PackageParser.Activity>(); 7149 private int mFlags; 7150 } 7151 7152 private final class ServiceIntentResolver 7153 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 7154 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7155 boolean defaultOnly, int userId) { 7156 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7157 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7158 } 7159 7160 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7161 int userId) { 7162 if (!sUserManager.exists(userId)) return null; 7163 mFlags = flags; 7164 return super.queryIntent(intent, resolvedType, 7165 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7166 } 7167 7168 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7169 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 7170 if (!sUserManager.exists(userId)) return null; 7171 if (packageServices == null) { 7172 return null; 7173 } 7174 mFlags = flags; 7175 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7176 final int N = packageServices.size(); 7177 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 7178 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 7179 7180 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 7181 for (int i = 0; i < N; ++i) { 7182 intentFilters = packageServices.get(i).intents; 7183 if (intentFilters != null && intentFilters.size() > 0) { 7184 PackageParser.ServiceIntentInfo[] array = 7185 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 7186 intentFilters.toArray(array); 7187 listCut.add(array); 7188 } 7189 } 7190 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7191 } 7192 7193 public final void addService(PackageParser.Service s) { 7194 mServices.put(s.getComponentName(), s); 7195 if (DEBUG_SHOW_INFO) { 7196 Log.v(TAG, " " 7197 + (s.info.nonLocalizedLabel != null 7198 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7199 Log.v(TAG, " Class=" + s.info.name); 7200 } 7201 final int NI = s.intents.size(); 7202 int j; 7203 for (j=0; j<NI; j++) { 7204 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7205 if (DEBUG_SHOW_INFO) { 7206 Log.v(TAG, " IntentFilter:"); 7207 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7208 } 7209 if (!intent.debugCheck()) { 7210 Log.w(TAG, "==> For Service " + s.info.name); 7211 } 7212 addFilter(intent); 7213 } 7214 } 7215 7216 public final void removeService(PackageParser.Service s) { 7217 mServices.remove(s.getComponentName()); 7218 if (DEBUG_SHOW_INFO) { 7219 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 7220 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7221 Log.v(TAG, " Class=" + s.info.name); 7222 } 7223 final int NI = s.intents.size(); 7224 int j; 7225 for (j=0; j<NI; j++) { 7226 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7227 if (DEBUG_SHOW_INFO) { 7228 Log.v(TAG, " IntentFilter:"); 7229 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7230 } 7231 removeFilter(intent); 7232 } 7233 } 7234 7235 @Override 7236 protected boolean allowFilterResult( 7237 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 7238 ServiceInfo filterSi = filter.service.info; 7239 for (int i=dest.size()-1; i>=0; i--) { 7240 ServiceInfo destAi = dest.get(i).serviceInfo; 7241 if (destAi.name == filterSi.name 7242 && destAi.packageName == filterSi.packageName) { 7243 return false; 7244 } 7245 } 7246 return true; 7247 } 7248 7249 @Override 7250 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 7251 return new PackageParser.ServiceIntentInfo[size]; 7252 } 7253 7254 @Override 7255 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 7256 if (!sUserManager.exists(userId)) return true; 7257 PackageParser.Package p = filter.service.owner; 7258 if (p != null) { 7259 PackageSetting ps = (PackageSetting)p.mExtras; 7260 if (ps != null) { 7261 // System apps are never considered stopped for purposes of 7262 // filtering, because there may be no way for the user to 7263 // actually re-launch them. 7264 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7265 && ps.getStopped(userId); 7266 } 7267 } 7268 return false; 7269 } 7270 7271 @Override 7272 protected boolean isPackageForFilter(String packageName, 7273 PackageParser.ServiceIntentInfo info) { 7274 return packageName.equals(info.service.owner.packageName); 7275 } 7276 7277 @Override 7278 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 7279 int match, int userId) { 7280 if (!sUserManager.exists(userId)) return null; 7281 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 7282 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 7283 return null; 7284 } 7285 final PackageParser.Service service = info.service; 7286 if (mSafeMode && (service.info.applicationInfo.flags 7287 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7288 return null; 7289 } 7290 PackageSetting ps = (PackageSetting) service.owner.mExtras; 7291 if (ps == null) { 7292 return null; 7293 } 7294 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 7295 ps.readUserState(userId), userId); 7296 if (si == null) { 7297 return null; 7298 } 7299 final ResolveInfo res = new ResolveInfo(); 7300 res.serviceInfo = si; 7301 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7302 res.filter = filter; 7303 } 7304 res.priority = info.getPriority(); 7305 res.preferredOrder = service.owner.mPreferredOrder; 7306 //System.out.println("Result: " + res.activityInfo.className + 7307 // " = " + res.priority); 7308 res.match = match; 7309 res.isDefault = info.hasDefault; 7310 res.labelRes = info.labelRes; 7311 res.nonLocalizedLabel = info.nonLocalizedLabel; 7312 res.icon = info.icon; 7313 res.system = isSystemApp(res.serviceInfo.applicationInfo); 7314 return res; 7315 } 7316 7317 @Override 7318 protected void sortResults(List<ResolveInfo> results) { 7319 Collections.sort(results, mResolvePrioritySorter); 7320 } 7321 7322 @Override 7323 protected void dumpFilter(PrintWriter out, String prefix, 7324 PackageParser.ServiceIntentInfo filter) { 7325 out.print(prefix); out.print( 7326 Integer.toHexString(System.identityHashCode(filter.service))); 7327 out.print(' '); 7328 filter.service.printComponentShortName(out); 7329 out.print(" filter "); 7330 out.println(Integer.toHexString(System.identityHashCode(filter))); 7331 } 7332 7333// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7334// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7335// final List<ResolveInfo> retList = Lists.newArrayList(); 7336// while (i.hasNext()) { 7337// final ResolveInfo resolveInfo = (ResolveInfo) i; 7338// if (isEnabledLP(resolveInfo.serviceInfo)) { 7339// retList.add(resolveInfo); 7340// } 7341// } 7342// return retList; 7343// } 7344 7345 // Keys are String (activity class name), values are Activity. 7346 private final HashMap<ComponentName, PackageParser.Service> mServices 7347 = new HashMap<ComponentName, PackageParser.Service>(); 7348 private int mFlags; 7349 }; 7350 7351 private final class ProviderIntentResolver 7352 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 7353 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7354 boolean defaultOnly, int userId) { 7355 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7356 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7357 } 7358 7359 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7360 int userId) { 7361 if (!sUserManager.exists(userId)) 7362 return null; 7363 mFlags = flags; 7364 return super.queryIntent(intent, resolvedType, 7365 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7366 } 7367 7368 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7369 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 7370 if (!sUserManager.exists(userId)) 7371 return null; 7372 if (packageProviders == null) { 7373 return null; 7374 } 7375 mFlags = flags; 7376 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 7377 final int N = packageProviders.size(); 7378 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 7379 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 7380 7381 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 7382 for (int i = 0; i < N; ++i) { 7383 intentFilters = packageProviders.get(i).intents; 7384 if (intentFilters != null && intentFilters.size() > 0) { 7385 PackageParser.ProviderIntentInfo[] array = 7386 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 7387 intentFilters.toArray(array); 7388 listCut.add(array); 7389 } 7390 } 7391 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7392 } 7393 7394 public final void addProvider(PackageParser.Provider p) { 7395 if (mProviders.containsKey(p.getComponentName())) { 7396 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 7397 return; 7398 } 7399 7400 mProviders.put(p.getComponentName(), p); 7401 if (DEBUG_SHOW_INFO) { 7402 Log.v(TAG, " " 7403 + (p.info.nonLocalizedLabel != null 7404 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7405 Log.v(TAG, " Class=" + p.info.name); 7406 } 7407 final int NI = p.intents.size(); 7408 int j; 7409 for (j = 0; j < NI; j++) { 7410 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7411 if (DEBUG_SHOW_INFO) { 7412 Log.v(TAG, " IntentFilter:"); 7413 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7414 } 7415 if (!intent.debugCheck()) { 7416 Log.w(TAG, "==> For Provider " + p.info.name); 7417 } 7418 addFilter(intent); 7419 } 7420 } 7421 7422 public final void removeProvider(PackageParser.Provider p) { 7423 mProviders.remove(p.getComponentName()); 7424 if (DEBUG_SHOW_INFO) { 7425 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 7426 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7427 Log.v(TAG, " Class=" + p.info.name); 7428 } 7429 final int NI = p.intents.size(); 7430 int j; 7431 for (j = 0; j < NI; j++) { 7432 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7433 if (DEBUG_SHOW_INFO) { 7434 Log.v(TAG, " IntentFilter:"); 7435 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7436 } 7437 removeFilter(intent); 7438 } 7439 } 7440 7441 @Override 7442 protected boolean allowFilterResult( 7443 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 7444 ProviderInfo filterPi = filter.provider.info; 7445 for (int i = dest.size() - 1; i >= 0; i--) { 7446 ProviderInfo destPi = dest.get(i).providerInfo; 7447 if (destPi.name == filterPi.name 7448 && destPi.packageName == filterPi.packageName) { 7449 return false; 7450 } 7451 } 7452 return true; 7453 } 7454 7455 @Override 7456 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 7457 return new PackageParser.ProviderIntentInfo[size]; 7458 } 7459 7460 @Override 7461 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 7462 if (!sUserManager.exists(userId)) 7463 return true; 7464 PackageParser.Package p = filter.provider.owner; 7465 if (p != null) { 7466 PackageSetting ps = (PackageSetting) p.mExtras; 7467 if (ps != null) { 7468 // System apps are never considered stopped for purposes of 7469 // filtering, because there may be no way for the user to 7470 // actually re-launch them. 7471 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7472 && ps.getStopped(userId); 7473 } 7474 } 7475 return false; 7476 } 7477 7478 @Override 7479 protected boolean isPackageForFilter(String packageName, 7480 PackageParser.ProviderIntentInfo info) { 7481 return packageName.equals(info.provider.owner.packageName); 7482 } 7483 7484 @Override 7485 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 7486 int match, int userId) { 7487 if (!sUserManager.exists(userId)) 7488 return null; 7489 final PackageParser.ProviderIntentInfo info = filter; 7490 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 7491 return null; 7492 } 7493 final PackageParser.Provider provider = info.provider; 7494 if (mSafeMode && (provider.info.applicationInfo.flags 7495 & ApplicationInfo.FLAG_SYSTEM) == 0) { 7496 return null; 7497 } 7498 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 7499 if (ps == null) { 7500 return null; 7501 } 7502 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 7503 ps.readUserState(userId), userId); 7504 if (pi == null) { 7505 return null; 7506 } 7507 final ResolveInfo res = new ResolveInfo(); 7508 res.providerInfo = pi; 7509 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 7510 res.filter = filter; 7511 } 7512 res.priority = info.getPriority(); 7513 res.preferredOrder = provider.owner.mPreferredOrder; 7514 res.match = match; 7515 res.isDefault = info.hasDefault; 7516 res.labelRes = info.labelRes; 7517 res.nonLocalizedLabel = info.nonLocalizedLabel; 7518 res.icon = info.icon; 7519 res.system = isSystemApp(res.providerInfo.applicationInfo); 7520 return res; 7521 } 7522 7523 @Override 7524 protected void sortResults(List<ResolveInfo> results) { 7525 Collections.sort(results, mResolvePrioritySorter); 7526 } 7527 7528 @Override 7529 protected void dumpFilter(PrintWriter out, String prefix, 7530 PackageParser.ProviderIntentInfo filter) { 7531 out.print(prefix); 7532 out.print( 7533 Integer.toHexString(System.identityHashCode(filter.provider))); 7534 out.print(' '); 7535 filter.provider.printComponentShortName(out); 7536 out.print(" filter "); 7537 out.println(Integer.toHexString(System.identityHashCode(filter))); 7538 } 7539 7540 private final HashMap<ComponentName, PackageParser.Provider> mProviders 7541 = new HashMap<ComponentName, PackageParser.Provider>(); 7542 private int mFlags; 7543 }; 7544 7545 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 7546 new Comparator<ResolveInfo>() { 7547 public int compare(ResolveInfo r1, ResolveInfo r2) { 7548 int v1 = r1.priority; 7549 int v2 = r2.priority; 7550 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 7551 if (v1 != v2) { 7552 return (v1 > v2) ? -1 : 1; 7553 } 7554 v1 = r1.preferredOrder; 7555 v2 = r2.preferredOrder; 7556 if (v1 != v2) { 7557 return (v1 > v2) ? -1 : 1; 7558 } 7559 if (r1.isDefault != r2.isDefault) { 7560 return r1.isDefault ? -1 : 1; 7561 } 7562 v1 = r1.match; 7563 v2 = r2.match; 7564 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 7565 if (v1 != v2) { 7566 return (v1 > v2) ? -1 : 1; 7567 } 7568 if (r1.system != r2.system) { 7569 return r1.system ? -1 : 1; 7570 } 7571 return 0; 7572 } 7573 }; 7574 7575 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 7576 new Comparator<ProviderInfo>() { 7577 public int compare(ProviderInfo p1, ProviderInfo p2) { 7578 final int v1 = p1.initOrder; 7579 final int v2 = p2.initOrder; 7580 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 7581 } 7582 }; 7583 7584 static final void sendPackageBroadcast(String action, String pkg, 7585 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 7586 int[] userIds) { 7587 IActivityManager am = ActivityManagerNative.getDefault(); 7588 if (am != null) { 7589 try { 7590 if (userIds == null) { 7591 userIds = am.getRunningUserIds(); 7592 } 7593 for (int id : userIds) { 7594 final Intent intent = new Intent(action, 7595 pkg != null ? Uri.fromParts("package", pkg, null) : null); 7596 if (extras != null) { 7597 intent.putExtras(extras); 7598 } 7599 if (targetPkg != null) { 7600 intent.setPackage(targetPkg); 7601 } 7602 // Modify the UID when posting to other users 7603 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 7604 if (uid > 0 && UserHandle.getUserId(uid) != id) { 7605 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 7606 intent.putExtra(Intent.EXTRA_UID, uid); 7607 } 7608 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 7609 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 7610 if (DEBUG_BROADCASTS) { 7611 RuntimeException here = new RuntimeException("here"); 7612 here.fillInStackTrace(); 7613 Slog.d(TAG, "Sending to user " + id + ": " 7614 + intent.toShortString(false, true, false, false) 7615 + " " + intent.getExtras(), here); 7616 } 7617 am.broadcastIntent(null, intent, null, finishedReceiver, 7618 0, null, null, null, android.app.AppOpsManager.OP_NONE, 7619 finishedReceiver != null, false, id); 7620 } 7621 } catch (RemoteException ex) { 7622 } 7623 } 7624 } 7625 7626 /** 7627 * Check if the external storage media is available. This is true if there 7628 * is a mounted external storage medium or if the external storage is 7629 * emulated. 7630 */ 7631 private boolean isExternalMediaAvailable() { 7632 return mMediaMounted || Environment.isExternalStorageEmulated(); 7633 } 7634 7635 @Override 7636 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 7637 // writer 7638 synchronized (mPackages) { 7639 if (!isExternalMediaAvailable()) { 7640 // If the external storage is no longer mounted at this point, 7641 // the caller may not have been able to delete all of this 7642 // packages files and can not delete any more. Bail. 7643 return null; 7644 } 7645 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 7646 if (lastPackage != null) { 7647 pkgs.remove(lastPackage); 7648 } 7649 if (pkgs.size() > 0) { 7650 return pkgs.get(0); 7651 } 7652 } 7653 return null; 7654 } 7655 7656 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 7657 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 7658 userId, andCode ? 1 : 0, packageName); 7659 if (mSystemReady) { 7660 msg.sendToTarget(); 7661 } else { 7662 if (mPostSystemReadyMessages == null) { 7663 mPostSystemReadyMessages = new ArrayList<>(); 7664 } 7665 mPostSystemReadyMessages.add(msg); 7666 } 7667 } 7668 7669 void startCleaningPackages() { 7670 // reader 7671 synchronized (mPackages) { 7672 if (!isExternalMediaAvailable()) { 7673 return; 7674 } 7675 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 7676 return; 7677 } 7678 } 7679 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 7680 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 7681 IActivityManager am = ActivityManagerNative.getDefault(); 7682 if (am != null) { 7683 try { 7684 am.startService(null, intent, null, UserHandle.USER_OWNER); 7685 } catch (RemoteException e) { 7686 } 7687 } 7688 } 7689 7690 @Override 7691 public void installPackage(String originPath, IPackageInstallObserver2 observer, 7692 int installFlags, String installerPackageName, VerificationParams verificationParams, 7693 String packageAbiOverride) { 7694 installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams, 7695 packageAbiOverride, UserHandle.getCallingUserId()); 7696 } 7697 7698 @Override 7699 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 7700 int installFlags, String installerPackageName, VerificationParams verificationParams, 7701 String packageAbiOverride, int userId) { 7702 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 7703 7704 final int callingUid = Binder.getCallingUid(); 7705 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 7706 7707 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 7708 try { 7709 if (observer != null) { 7710 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 7711 } 7712 } catch (RemoteException re) { 7713 } 7714 return; 7715 } 7716 7717 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 7718 installFlags |= PackageManager.INSTALL_FROM_ADB; 7719 7720 } else { 7721 // Caller holds INSTALL_PACKAGES permission, so we're less strict 7722 // about installerPackageName. 7723 7724 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 7725 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 7726 } 7727 7728 UserHandle user; 7729 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 7730 user = UserHandle.ALL; 7731 } else { 7732 user = new UserHandle(userId); 7733 } 7734 7735 verificationParams.setInstallerUid(callingUid); 7736 7737 final File originFile = new File(originPath); 7738 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 7739 7740 final Message msg = mHandler.obtainMessage(INIT_COPY); 7741 msg.obj = new InstallParams(origin, observer, installFlags, 7742 installerPackageName, verificationParams, user, packageAbiOverride); 7743 mHandler.sendMessage(msg); 7744 } 7745 7746 void installStage(String packageName, File stagedDir, String stagedCid, 7747 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 7748 String installerPackageName, int installerUid, UserHandle user) { 7749 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 7750 params.referrerUri, installerUid, null); 7751 7752 final OriginInfo origin; 7753 if (stagedDir != null) { 7754 origin = OriginInfo.fromStagedFile(stagedDir); 7755 } else { 7756 origin = OriginInfo.fromStagedContainer(stagedCid); 7757 } 7758 7759 final Message msg = mHandler.obtainMessage(INIT_COPY); 7760 msg.obj = new InstallParams(origin, observer, params.installFlags, 7761 installerPackageName, verifParams, user, params.abiOverride); 7762 mHandler.sendMessage(msg); 7763 } 7764 7765 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 7766 Bundle extras = new Bundle(1); 7767 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 7768 7769 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 7770 packageName, extras, null, null, new int[] {userId}); 7771 try { 7772 IActivityManager am = ActivityManagerNative.getDefault(); 7773 final boolean isSystem = 7774 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 7775 if (isSystem && am.isUserRunning(userId, false)) { 7776 // The just-installed/enabled app is bundled on the system, so presumed 7777 // to be able to run automatically without needing an explicit launch. 7778 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 7779 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 7780 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 7781 .setPackage(packageName); 7782 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 7783 android.app.AppOpsManager.OP_NONE, false, false, userId); 7784 } 7785 } catch (RemoteException e) { 7786 // shouldn't happen 7787 Slog.w(TAG, "Unable to bootstrap installed package", e); 7788 } 7789 } 7790 7791 @Override 7792 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 7793 int userId) { 7794 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7795 PackageSetting pkgSetting; 7796 final int uid = Binder.getCallingUid(); 7797 enforceCrossUserPermission(uid, userId, true, true, 7798 "setApplicationHiddenSetting for user " + userId); 7799 7800 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 7801 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 7802 return false; 7803 } 7804 7805 long callingId = Binder.clearCallingIdentity(); 7806 try { 7807 boolean sendAdded = false; 7808 boolean sendRemoved = false; 7809 // writer 7810 synchronized (mPackages) { 7811 pkgSetting = mSettings.mPackages.get(packageName); 7812 if (pkgSetting == null) { 7813 return false; 7814 } 7815 if (pkgSetting.getHidden(userId) != hidden) { 7816 pkgSetting.setHidden(hidden, userId); 7817 mSettings.writePackageRestrictionsLPr(userId); 7818 if (hidden) { 7819 sendRemoved = true; 7820 } else { 7821 sendAdded = true; 7822 } 7823 } 7824 } 7825 if (sendAdded) { 7826 sendPackageAddedForUser(packageName, pkgSetting, userId); 7827 return true; 7828 } 7829 if (sendRemoved) { 7830 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 7831 "hiding pkg"); 7832 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 7833 } 7834 } finally { 7835 Binder.restoreCallingIdentity(callingId); 7836 } 7837 return false; 7838 } 7839 7840 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 7841 int userId) { 7842 final PackageRemovedInfo info = new PackageRemovedInfo(); 7843 info.removedPackage = packageName; 7844 info.removedUsers = new int[] {userId}; 7845 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 7846 info.sendBroadcast(false, false, false); 7847 } 7848 7849 /** 7850 * Returns true if application is not found or there was an error. Otherwise it returns 7851 * the hidden state of the package for the given user. 7852 */ 7853 @Override 7854 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 7855 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7856 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 7857 false, "getApplicationHidden for user " + userId); 7858 PackageSetting pkgSetting; 7859 long callingId = Binder.clearCallingIdentity(); 7860 try { 7861 // writer 7862 synchronized (mPackages) { 7863 pkgSetting = mSettings.mPackages.get(packageName); 7864 if (pkgSetting == null) { 7865 return true; 7866 } 7867 return pkgSetting.getHidden(userId); 7868 } 7869 } finally { 7870 Binder.restoreCallingIdentity(callingId); 7871 } 7872 } 7873 7874 /** 7875 * @hide 7876 */ 7877 @Override 7878 public int installExistingPackageAsUser(String packageName, int userId) { 7879 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7880 null); 7881 PackageSetting pkgSetting; 7882 final int uid = Binder.getCallingUid(); 7883 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 7884 + userId); 7885 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 7886 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 7887 } 7888 7889 long callingId = Binder.clearCallingIdentity(); 7890 try { 7891 boolean sendAdded = false; 7892 Bundle extras = new Bundle(1); 7893 7894 // writer 7895 synchronized (mPackages) { 7896 pkgSetting = mSettings.mPackages.get(packageName); 7897 if (pkgSetting == null) { 7898 return PackageManager.INSTALL_FAILED_INVALID_URI; 7899 } 7900 if (!pkgSetting.getInstalled(userId)) { 7901 pkgSetting.setInstalled(true, userId); 7902 pkgSetting.setHidden(false, userId); 7903 mSettings.writePackageRestrictionsLPr(userId); 7904 sendAdded = true; 7905 } 7906 } 7907 7908 if (sendAdded) { 7909 sendPackageAddedForUser(packageName, pkgSetting, userId); 7910 } 7911 } finally { 7912 Binder.restoreCallingIdentity(callingId); 7913 } 7914 7915 return PackageManager.INSTALL_SUCCEEDED; 7916 } 7917 7918 boolean isUserRestricted(int userId, String restrictionKey) { 7919 Bundle restrictions = sUserManager.getUserRestrictions(userId); 7920 if (restrictions.getBoolean(restrictionKey, false)) { 7921 Log.w(TAG, "User is restricted: " + restrictionKey); 7922 return true; 7923 } 7924 return false; 7925 } 7926 7927 @Override 7928 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 7929 mContext.enforceCallingOrSelfPermission( 7930 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7931 "Only package verification agents can verify applications"); 7932 7933 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7934 final PackageVerificationResponse response = new PackageVerificationResponse( 7935 verificationCode, Binder.getCallingUid()); 7936 msg.arg1 = id; 7937 msg.obj = response; 7938 mHandler.sendMessage(msg); 7939 } 7940 7941 @Override 7942 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 7943 long millisecondsToDelay) { 7944 mContext.enforceCallingOrSelfPermission( 7945 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7946 "Only package verification agents can extend verification timeouts"); 7947 7948 final PackageVerificationState state = mPendingVerification.get(id); 7949 final PackageVerificationResponse response = new PackageVerificationResponse( 7950 verificationCodeAtTimeout, Binder.getCallingUid()); 7951 7952 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 7953 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 7954 } 7955 if (millisecondsToDelay < 0) { 7956 millisecondsToDelay = 0; 7957 } 7958 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 7959 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 7960 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 7961 } 7962 7963 if ((state != null) && !state.timeoutExtended()) { 7964 state.extendTimeout(); 7965 7966 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7967 msg.arg1 = id; 7968 msg.obj = response; 7969 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 7970 } 7971 } 7972 7973 private void broadcastPackageVerified(int verificationId, Uri packageUri, 7974 int verificationCode, UserHandle user) { 7975 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 7976 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 7977 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 7978 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 7979 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 7980 7981 mContext.sendBroadcastAsUser(intent, user, 7982 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 7983 } 7984 7985 private ComponentName matchComponentForVerifier(String packageName, 7986 List<ResolveInfo> receivers) { 7987 ActivityInfo targetReceiver = null; 7988 7989 final int NR = receivers.size(); 7990 for (int i = 0; i < NR; i++) { 7991 final ResolveInfo info = receivers.get(i); 7992 if (info.activityInfo == null) { 7993 continue; 7994 } 7995 7996 if (packageName.equals(info.activityInfo.packageName)) { 7997 targetReceiver = info.activityInfo; 7998 break; 7999 } 8000 } 8001 8002 if (targetReceiver == null) { 8003 return null; 8004 } 8005 8006 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8007 } 8008 8009 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8010 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8011 if (pkgInfo.verifiers.length == 0) { 8012 return null; 8013 } 8014 8015 final int N = pkgInfo.verifiers.length; 8016 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8017 for (int i = 0; i < N; i++) { 8018 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8019 8020 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8021 receivers); 8022 if (comp == null) { 8023 continue; 8024 } 8025 8026 final int verifierUid = getUidForVerifier(verifierInfo); 8027 if (verifierUid == -1) { 8028 continue; 8029 } 8030 8031 if (DEBUG_VERIFY) { 8032 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8033 + " with the correct signature"); 8034 } 8035 sufficientVerifiers.add(comp); 8036 verificationState.addSufficientVerifier(verifierUid); 8037 } 8038 8039 return sufficientVerifiers; 8040 } 8041 8042 private int getUidForVerifier(VerifierInfo verifierInfo) { 8043 synchronized (mPackages) { 8044 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8045 if (pkg == null) { 8046 return -1; 8047 } else if (pkg.mSignatures.length != 1) { 8048 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8049 + " has more than one signature; ignoring"); 8050 return -1; 8051 } 8052 8053 /* 8054 * If the public key of the package's signature does not match 8055 * our expected public key, then this is a different package and 8056 * we should skip. 8057 */ 8058 8059 final byte[] expectedPublicKey; 8060 try { 8061 final Signature verifierSig = pkg.mSignatures[0]; 8062 final PublicKey publicKey = verifierSig.getPublicKey(); 8063 expectedPublicKey = publicKey.getEncoded(); 8064 } catch (CertificateException e) { 8065 return -1; 8066 } 8067 8068 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8069 8070 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8071 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8072 + " does not have the expected public key; ignoring"); 8073 return -1; 8074 } 8075 8076 return pkg.applicationInfo.uid; 8077 } 8078 } 8079 8080 @Override 8081 public void finishPackageInstall(int token) { 8082 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8083 8084 if (DEBUG_INSTALL) { 8085 Slog.v(TAG, "BM finishing package install for " + token); 8086 } 8087 8088 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8089 mHandler.sendMessage(msg); 8090 } 8091 8092 /** 8093 * Get the verification agent timeout. 8094 * 8095 * @return verification timeout in milliseconds 8096 */ 8097 private long getVerificationTimeout() { 8098 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8099 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8100 DEFAULT_VERIFICATION_TIMEOUT); 8101 } 8102 8103 /** 8104 * Get the default verification agent response code. 8105 * 8106 * @return default verification response code 8107 */ 8108 private int getDefaultVerificationResponse() { 8109 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8110 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8111 DEFAULT_VERIFICATION_RESPONSE); 8112 } 8113 8114 /** 8115 * Check whether or not package verification has been enabled. 8116 * 8117 * @return true if verification should be performed 8118 */ 8119 private boolean isVerificationEnabled(int userId, int installFlags) { 8120 if (!DEFAULT_VERIFY_ENABLE) { 8121 return false; 8122 } 8123 8124 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 8125 8126 // Check if installing from ADB 8127 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 8128 // Do not run verification in a test harness environment 8129 if (ActivityManager.isRunningInTestHarness()) { 8130 return false; 8131 } 8132 if (ensureVerifyAppsEnabled) { 8133 return true; 8134 } 8135 // Check if the developer does not want package verification for ADB installs 8136 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8137 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8138 return false; 8139 } 8140 } 8141 8142 if (ensureVerifyAppsEnabled) { 8143 return true; 8144 } 8145 8146 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8147 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8148 } 8149 8150 /** 8151 * Get the "allow unknown sources" setting. 8152 * 8153 * @return the current "allow unknown sources" setting 8154 */ 8155 private int getUnknownSourcesSettings() { 8156 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8157 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 8158 -1); 8159 } 8160 8161 @Override 8162 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 8163 final int uid = Binder.getCallingUid(); 8164 // writer 8165 synchronized (mPackages) { 8166 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 8167 if (targetPackageSetting == null) { 8168 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 8169 } 8170 8171 PackageSetting installerPackageSetting; 8172 if (installerPackageName != null) { 8173 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 8174 if (installerPackageSetting == null) { 8175 throw new IllegalArgumentException("Unknown installer package: " 8176 + installerPackageName); 8177 } 8178 } else { 8179 installerPackageSetting = null; 8180 } 8181 8182 Signature[] callerSignature; 8183 Object obj = mSettings.getUserIdLPr(uid); 8184 if (obj != null) { 8185 if (obj instanceof SharedUserSetting) { 8186 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 8187 } else if (obj instanceof PackageSetting) { 8188 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 8189 } else { 8190 throw new SecurityException("Bad object " + obj + " for uid " + uid); 8191 } 8192 } else { 8193 throw new SecurityException("Unknown calling uid " + uid); 8194 } 8195 8196 // Verify: can't set installerPackageName to a package that is 8197 // not signed with the same cert as the caller. 8198 if (installerPackageSetting != null) { 8199 if (compareSignatures(callerSignature, 8200 installerPackageSetting.signatures.mSignatures) 8201 != PackageManager.SIGNATURE_MATCH) { 8202 throw new SecurityException( 8203 "Caller does not have same cert as new installer package " 8204 + installerPackageName); 8205 } 8206 } 8207 8208 // Verify: if target already has an installer package, it must 8209 // be signed with the same cert as the caller. 8210 if (targetPackageSetting.installerPackageName != null) { 8211 PackageSetting setting = mSettings.mPackages.get( 8212 targetPackageSetting.installerPackageName); 8213 // If the currently set package isn't valid, then it's always 8214 // okay to change it. 8215 if (setting != null) { 8216 if (compareSignatures(callerSignature, 8217 setting.signatures.mSignatures) 8218 != PackageManager.SIGNATURE_MATCH) { 8219 throw new SecurityException( 8220 "Caller does not have same cert as old installer package " 8221 + targetPackageSetting.installerPackageName); 8222 } 8223 } 8224 } 8225 8226 // Okay! 8227 targetPackageSetting.installerPackageName = installerPackageName; 8228 scheduleWriteSettingsLocked(); 8229 } 8230 } 8231 8232 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 8233 // Queue up an async operation since the package installation may take a little while. 8234 mHandler.post(new Runnable() { 8235 public void run() { 8236 mHandler.removeCallbacks(this); 8237 // Result object to be returned 8238 PackageInstalledInfo res = new PackageInstalledInfo(); 8239 res.returnCode = currentStatus; 8240 res.uid = -1; 8241 res.pkg = null; 8242 res.removedInfo = new PackageRemovedInfo(); 8243 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 8244 args.doPreInstall(res.returnCode); 8245 synchronized (mInstallLock) { 8246 installPackageLI(args, res); 8247 } 8248 args.doPostInstall(res.returnCode, res.uid); 8249 } 8250 8251 // A restore should be performed at this point if (a) the install 8252 // succeeded, (b) the operation is not an update, and (c) the new 8253 // package has not opted out of backup participation. 8254 final boolean update = res.removedInfo.removedPackage != null; 8255 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 8256 boolean doRestore = !update 8257 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 8258 8259 // Set up the post-install work request bookkeeping. This will be used 8260 // and cleaned up by the post-install event handling regardless of whether 8261 // there's a restore pass performed. Token values are >= 1. 8262 int token; 8263 if (mNextInstallToken < 0) mNextInstallToken = 1; 8264 token = mNextInstallToken++; 8265 8266 PostInstallData data = new PostInstallData(args, res); 8267 mRunningInstalls.put(token, data); 8268 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 8269 8270 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 8271 // Pass responsibility to the Backup Manager. It will perform a 8272 // restore if appropriate, then pass responsibility back to the 8273 // Package Manager to run the post-install observer callbacks 8274 // and broadcasts. 8275 IBackupManager bm = IBackupManager.Stub.asInterface( 8276 ServiceManager.getService(Context.BACKUP_SERVICE)); 8277 if (bm != null) { 8278 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 8279 + " to BM for possible restore"); 8280 try { 8281 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 8282 } catch (RemoteException e) { 8283 // can't happen; the backup manager is local 8284 } catch (Exception e) { 8285 Slog.e(TAG, "Exception trying to enqueue restore", e); 8286 doRestore = false; 8287 } 8288 } else { 8289 Slog.e(TAG, "Backup Manager not found!"); 8290 doRestore = false; 8291 } 8292 } 8293 8294 if (!doRestore) { 8295 // No restore possible, or the Backup Manager was mysteriously not 8296 // available -- just fire the post-install work request directly. 8297 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 8298 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8299 mHandler.sendMessage(msg); 8300 } 8301 } 8302 }); 8303 } 8304 8305 private abstract class HandlerParams { 8306 private static final int MAX_RETRIES = 4; 8307 8308 /** 8309 * Number of times startCopy() has been attempted and had a non-fatal 8310 * error. 8311 */ 8312 private int mRetries = 0; 8313 8314 /** User handle for the user requesting the information or installation. */ 8315 private final UserHandle mUser; 8316 8317 HandlerParams(UserHandle user) { 8318 mUser = user; 8319 } 8320 8321 UserHandle getUser() { 8322 return mUser; 8323 } 8324 8325 final boolean startCopy() { 8326 boolean res; 8327 try { 8328 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 8329 8330 if (++mRetries > MAX_RETRIES) { 8331 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 8332 mHandler.sendEmptyMessage(MCS_GIVE_UP); 8333 handleServiceError(); 8334 return false; 8335 } else { 8336 handleStartCopy(); 8337 res = true; 8338 } 8339 } catch (RemoteException e) { 8340 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 8341 mHandler.sendEmptyMessage(MCS_RECONNECT); 8342 res = false; 8343 } 8344 handleReturnCode(); 8345 return res; 8346 } 8347 8348 final void serviceError() { 8349 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 8350 handleServiceError(); 8351 handleReturnCode(); 8352 } 8353 8354 abstract void handleStartCopy() throws RemoteException; 8355 abstract void handleServiceError(); 8356 abstract void handleReturnCode(); 8357 } 8358 8359 class MeasureParams extends HandlerParams { 8360 private final PackageStats mStats; 8361 private boolean mSuccess; 8362 8363 private final IPackageStatsObserver mObserver; 8364 8365 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 8366 super(new UserHandle(stats.userHandle)); 8367 mObserver = observer; 8368 mStats = stats; 8369 } 8370 8371 @Override 8372 public String toString() { 8373 return "MeasureParams{" 8374 + Integer.toHexString(System.identityHashCode(this)) 8375 + " " + mStats.packageName + "}"; 8376 } 8377 8378 @Override 8379 void handleStartCopy() throws RemoteException { 8380 synchronized (mInstallLock) { 8381 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 8382 } 8383 8384 if (mSuccess) { 8385 final boolean mounted; 8386 if (Environment.isExternalStorageEmulated()) { 8387 mounted = true; 8388 } else { 8389 final String status = Environment.getExternalStorageState(); 8390 mounted = (Environment.MEDIA_MOUNTED.equals(status) 8391 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 8392 } 8393 8394 if (mounted) { 8395 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 8396 8397 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 8398 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 8399 8400 mStats.externalDataSize = calculateDirectorySize(mContainerService, 8401 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 8402 8403 // Always subtract cache size, since it's a subdirectory 8404 mStats.externalDataSize -= mStats.externalCacheSize; 8405 8406 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 8407 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 8408 8409 mStats.externalObbSize = calculateDirectorySize(mContainerService, 8410 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 8411 } 8412 } 8413 } 8414 8415 @Override 8416 void handleReturnCode() { 8417 if (mObserver != null) { 8418 try { 8419 mObserver.onGetStatsCompleted(mStats, mSuccess); 8420 } catch (RemoteException e) { 8421 Slog.i(TAG, "Observer no longer exists."); 8422 } 8423 } 8424 } 8425 8426 @Override 8427 void handleServiceError() { 8428 Slog.e(TAG, "Could not measure application " + mStats.packageName 8429 + " external storage"); 8430 } 8431 } 8432 8433 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 8434 throws RemoteException { 8435 long result = 0; 8436 for (File path : paths) { 8437 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 8438 } 8439 return result; 8440 } 8441 8442 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 8443 for (File path : paths) { 8444 try { 8445 mcs.clearDirectory(path.getAbsolutePath()); 8446 } catch (RemoteException e) { 8447 } 8448 } 8449 } 8450 8451 static class OriginInfo { 8452 /** 8453 * Location where install is coming from, before it has been 8454 * copied/renamed into place. This could be a single monolithic APK 8455 * file, or a cluster directory. This location may be untrusted. 8456 */ 8457 final File file; 8458 final String cid; 8459 8460 /** 8461 * Flag indicating that {@link #file} or {@link #cid} has already been 8462 * staged, meaning downstream users don't need to defensively copy the 8463 * contents. 8464 */ 8465 final boolean staged; 8466 8467 /** 8468 * Flag indicating that {@link #file} or {@link #cid} is an already 8469 * installed app that is being moved. 8470 */ 8471 final boolean existing; 8472 8473 final String resolvedPath; 8474 final File resolvedFile; 8475 8476 static OriginInfo fromNothing() { 8477 return new OriginInfo(null, null, false, false); 8478 } 8479 8480 static OriginInfo fromUntrustedFile(File file) { 8481 return new OriginInfo(file, null, false, false); 8482 } 8483 8484 static OriginInfo fromExistingFile(File file) { 8485 return new OriginInfo(file, null, false, true); 8486 } 8487 8488 static OriginInfo fromStagedFile(File file) { 8489 return new OriginInfo(file, null, true, false); 8490 } 8491 8492 static OriginInfo fromStagedContainer(String cid) { 8493 return new OriginInfo(null, cid, true, false); 8494 } 8495 8496 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 8497 this.file = file; 8498 this.cid = cid; 8499 this.staged = staged; 8500 this.existing = existing; 8501 8502 if (cid != null) { 8503 resolvedPath = PackageHelper.getSdDir(cid); 8504 resolvedFile = new File(resolvedPath); 8505 } else if (file != null) { 8506 resolvedPath = file.getAbsolutePath(); 8507 resolvedFile = file; 8508 } else { 8509 resolvedPath = null; 8510 resolvedFile = null; 8511 } 8512 } 8513 } 8514 8515 class InstallParams extends HandlerParams { 8516 final OriginInfo origin; 8517 final IPackageInstallObserver2 observer; 8518 int installFlags; 8519 final String installerPackageName; 8520 final VerificationParams verificationParams; 8521 private InstallArgs mArgs; 8522 private int mRet; 8523 final String packageAbiOverride; 8524 8525 InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 8526 String installerPackageName, VerificationParams verificationParams, UserHandle user, 8527 String packageAbiOverride) { 8528 super(user); 8529 this.origin = origin; 8530 this.observer = observer; 8531 this.installFlags = installFlags; 8532 this.installerPackageName = installerPackageName; 8533 this.verificationParams = verificationParams; 8534 this.packageAbiOverride = packageAbiOverride; 8535 } 8536 8537 @Override 8538 public String toString() { 8539 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 8540 + " file=" + origin.file + " cid=" + origin.cid + "}"; 8541 } 8542 8543 public ManifestDigest getManifestDigest() { 8544 if (verificationParams == null) { 8545 return null; 8546 } 8547 return verificationParams.getManifestDigest(); 8548 } 8549 8550 private int installLocationPolicy(PackageInfoLite pkgLite) { 8551 String packageName = pkgLite.packageName; 8552 int installLocation = pkgLite.installLocation; 8553 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 8554 // reader 8555 synchronized (mPackages) { 8556 PackageParser.Package pkg = mPackages.get(packageName); 8557 if (pkg != null) { 8558 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 8559 // Check for downgrading. 8560 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 8561 if (pkgLite.versionCode < pkg.mVersionCode) { 8562 Slog.w(TAG, "Can't install update of " + packageName 8563 + " update version " + pkgLite.versionCode 8564 + " is older than installed version " 8565 + pkg.mVersionCode); 8566 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 8567 } 8568 } 8569 // Check for updated system application. 8570 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8571 if (onSd) { 8572 Slog.w(TAG, "Cannot install update to system app on sdcard"); 8573 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 8574 } 8575 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8576 } else { 8577 if (onSd) { 8578 // Install flag overrides everything. 8579 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8580 } 8581 // If current upgrade specifies particular preference 8582 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 8583 // Application explicitly specified internal. 8584 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8585 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 8586 // App explictly prefers external. Let policy decide 8587 } else { 8588 // Prefer previous location 8589 if (isExternal(pkg)) { 8590 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8591 } 8592 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8593 } 8594 } 8595 } else { 8596 // Invalid install. Return error code 8597 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 8598 } 8599 } 8600 } 8601 // All the special cases have been taken care of. 8602 // Return result based on recommended install location. 8603 if (onSd) { 8604 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8605 } 8606 return pkgLite.recommendedInstallLocation; 8607 } 8608 8609 /* 8610 * Invoke remote method to get package information and install 8611 * location values. Override install location based on default 8612 * policy if needed and then create install arguments based 8613 * on the install location. 8614 */ 8615 public void handleStartCopy() throws RemoteException { 8616 int ret = PackageManager.INSTALL_SUCCEEDED; 8617 8618 // If we're already staged, we've firmly committed to an install location 8619 if (origin.staged) { 8620 if (origin.file != null) { 8621 installFlags |= PackageManager.INSTALL_INTERNAL; 8622 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 8623 } else if (origin.cid != null) { 8624 installFlags |= PackageManager.INSTALL_EXTERNAL; 8625 installFlags &= ~PackageManager.INSTALL_INTERNAL; 8626 } else { 8627 throw new IllegalStateException("Invalid stage location"); 8628 } 8629 } 8630 8631 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 8632 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 8633 8634 PackageInfoLite pkgLite = null; 8635 8636 if (onInt && onSd) { 8637 // Check if both bits are set. 8638 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 8639 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8640 } else { 8641 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 8642 packageAbiOverride); 8643 8644 /* 8645 * If we have too little free space, try to free cache 8646 * before giving up. 8647 */ 8648 if (!origin.staged && pkgLite.recommendedInstallLocation 8649 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8650 // TODO: focus freeing disk space on the target device 8651 final StorageManager storage = StorageManager.from(mContext); 8652 final long lowThreshold = storage.getStorageLowBytes( 8653 Environment.getDataDirectory()); 8654 8655 final long sizeBytes = mContainerService.calculateInstalledSize( 8656 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 8657 8658 if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) { 8659 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 8660 installFlags, packageAbiOverride); 8661 } 8662 8663 /* 8664 * The cache free must have deleted the file we 8665 * downloaded to install. 8666 * 8667 * TODO: fix the "freeCache" call to not delete 8668 * the file we care about. 8669 */ 8670 if (pkgLite.recommendedInstallLocation 8671 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8672 pkgLite.recommendedInstallLocation 8673 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 8674 } 8675 } 8676 } 8677 8678 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8679 int loc = pkgLite.recommendedInstallLocation; 8680 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 8681 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8682 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 8683 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 8684 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8685 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8686 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 8687 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 8688 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8689 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 8690 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 8691 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 8692 } else { 8693 // Override with defaults if needed. 8694 loc = installLocationPolicy(pkgLite); 8695 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 8696 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 8697 } else if (!onSd && !onInt) { 8698 // Override install location with flags 8699 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 8700 // Set the flag to install on external media. 8701 installFlags |= PackageManager.INSTALL_EXTERNAL; 8702 installFlags &= ~PackageManager.INSTALL_INTERNAL; 8703 } else { 8704 // Make sure the flag for installing on external 8705 // media is unset 8706 installFlags |= PackageManager.INSTALL_INTERNAL; 8707 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 8708 } 8709 } 8710 } 8711 } 8712 8713 final InstallArgs args = createInstallArgs(this); 8714 mArgs = args; 8715 8716 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8717 /* 8718 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 8719 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 8720 */ 8721 int userIdentifier = getUser().getIdentifier(); 8722 if (userIdentifier == UserHandle.USER_ALL 8723 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 8724 userIdentifier = UserHandle.USER_OWNER; 8725 } 8726 8727 /* 8728 * Determine if we have any installed package verifiers. If we 8729 * do, then we'll defer to them to verify the packages. 8730 */ 8731 final int requiredUid = mRequiredVerifierPackage == null ? -1 8732 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 8733 if (!origin.existing && requiredUid != -1 8734 && isVerificationEnabled(userIdentifier, installFlags)) { 8735 final Intent verification = new Intent( 8736 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 8737 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 8738 PACKAGE_MIME_TYPE); 8739 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8740 8741 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 8742 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 8743 0 /* TODO: Which userId? */); 8744 8745 if (DEBUG_VERIFY) { 8746 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 8747 + verification.toString() + " with " + pkgLite.verifiers.length 8748 + " optional verifiers"); 8749 } 8750 8751 final int verificationId = mPendingVerificationToken++; 8752 8753 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8754 8755 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 8756 installerPackageName); 8757 8758 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 8759 installFlags); 8760 8761 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 8762 pkgLite.packageName); 8763 8764 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 8765 pkgLite.versionCode); 8766 8767 if (verificationParams != null) { 8768 if (verificationParams.getVerificationURI() != null) { 8769 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 8770 verificationParams.getVerificationURI()); 8771 } 8772 if (verificationParams.getOriginatingURI() != null) { 8773 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 8774 verificationParams.getOriginatingURI()); 8775 } 8776 if (verificationParams.getReferrer() != null) { 8777 verification.putExtra(Intent.EXTRA_REFERRER, 8778 verificationParams.getReferrer()); 8779 } 8780 if (verificationParams.getOriginatingUid() >= 0) { 8781 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 8782 verificationParams.getOriginatingUid()); 8783 } 8784 if (verificationParams.getInstallerUid() >= 0) { 8785 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 8786 verificationParams.getInstallerUid()); 8787 } 8788 } 8789 8790 final PackageVerificationState verificationState = new PackageVerificationState( 8791 requiredUid, args); 8792 8793 mPendingVerification.append(verificationId, verificationState); 8794 8795 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 8796 receivers, verificationState); 8797 8798 /* 8799 * If any sufficient verifiers were listed in the package 8800 * manifest, attempt to ask them. 8801 */ 8802 if (sufficientVerifiers != null) { 8803 final int N = sufficientVerifiers.size(); 8804 if (N == 0) { 8805 Slog.i(TAG, "Additional verifiers required, but none installed."); 8806 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 8807 } else { 8808 for (int i = 0; i < N; i++) { 8809 final ComponentName verifierComponent = sufficientVerifiers.get(i); 8810 8811 final Intent sufficientIntent = new Intent(verification); 8812 sufficientIntent.setComponent(verifierComponent); 8813 8814 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 8815 } 8816 } 8817 } 8818 8819 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 8820 mRequiredVerifierPackage, receivers); 8821 if (ret == PackageManager.INSTALL_SUCCEEDED 8822 && mRequiredVerifierPackage != null) { 8823 /* 8824 * Send the intent to the required verification agent, 8825 * but only start the verification timeout after the 8826 * target BroadcastReceivers have run. 8827 */ 8828 verification.setComponent(requiredVerifierComponent); 8829 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 8830 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8831 new BroadcastReceiver() { 8832 @Override 8833 public void onReceive(Context context, Intent intent) { 8834 final Message msg = mHandler 8835 .obtainMessage(CHECK_PENDING_VERIFICATION); 8836 msg.arg1 = verificationId; 8837 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 8838 } 8839 }, null, 0, null, null); 8840 8841 /* 8842 * We don't want the copy to proceed until verification 8843 * succeeds, so null out this field. 8844 */ 8845 mArgs = null; 8846 } 8847 } else { 8848 /* 8849 * No package verification is enabled, so immediately start 8850 * the remote call to initiate copy using temporary file. 8851 */ 8852 ret = args.copyApk(mContainerService, true); 8853 } 8854 } 8855 8856 mRet = ret; 8857 } 8858 8859 @Override 8860 void handleReturnCode() { 8861 // If mArgs is null, then MCS couldn't be reached. When it 8862 // reconnects, it will try again to install. At that point, this 8863 // will succeed. 8864 if (mArgs != null) { 8865 processPendingInstall(mArgs, mRet); 8866 } 8867 } 8868 8869 @Override 8870 void handleServiceError() { 8871 mArgs = createInstallArgs(this); 8872 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8873 } 8874 8875 public boolean isForwardLocked() { 8876 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8877 } 8878 } 8879 8880 /** 8881 * Used during creation of InstallArgs 8882 * 8883 * @param installFlags package installation flags 8884 * @return true if should be installed on external storage 8885 */ 8886 private static boolean installOnSd(int installFlags) { 8887 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 8888 return false; 8889 } 8890 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 8891 return true; 8892 } 8893 return false; 8894 } 8895 8896 /** 8897 * Used during creation of InstallArgs 8898 * 8899 * @param installFlags package installation flags 8900 * @return true if should be installed as forward locked 8901 */ 8902 private static boolean installForwardLocked(int installFlags) { 8903 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8904 } 8905 8906 private InstallArgs createInstallArgs(InstallParams params) { 8907 if (installOnSd(params.installFlags) || params.isForwardLocked()) { 8908 return new AsecInstallArgs(params); 8909 } else { 8910 return new FileInstallArgs(params); 8911 } 8912 } 8913 8914 /** 8915 * Create args that describe an existing installed package. Typically used 8916 * when cleaning up old installs, or used as a move source. 8917 */ 8918 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 8919 String resourcePath, String nativeLibraryRoot, String[] instructionSets) { 8920 final boolean isInAsec; 8921 if (installOnSd(installFlags)) { 8922 /* Apps on SD card are always in ASEC containers. */ 8923 isInAsec = true; 8924 } else if (installForwardLocked(installFlags) 8925 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 8926 /* 8927 * Forward-locked apps are only in ASEC containers if they're the 8928 * new style 8929 */ 8930 isInAsec = true; 8931 } else { 8932 isInAsec = false; 8933 } 8934 8935 if (isInAsec) { 8936 return new AsecInstallArgs(codePath, instructionSets, 8937 installOnSd(installFlags), installForwardLocked(installFlags)); 8938 } else { 8939 return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot, 8940 instructionSets); 8941 } 8942 } 8943 8944 static abstract class InstallArgs { 8945 /** @see InstallParams#origin */ 8946 final OriginInfo origin; 8947 8948 final IPackageInstallObserver2 observer; 8949 // Always refers to PackageManager flags only 8950 final int installFlags; 8951 final String installerPackageName; 8952 final ManifestDigest manifestDigest; 8953 final UserHandle user; 8954 final String abiOverride; 8955 8956 // The list of instruction sets supported by this app. This is currently 8957 // only used during the rmdex() phase to clean up resources. We can get rid of this 8958 // if we move dex files under the common app path. 8959 /* nullable */ String[] instructionSets; 8960 8961 InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 8962 String installerPackageName, ManifestDigest manifestDigest, UserHandle user, 8963 String[] instructionSets, String abiOverride) { 8964 this.origin = origin; 8965 this.installFlags = installFlags; 8966 this.observer = observer; 8967 this.installerPackageName = installerPackageName; 8968 this.manifestDigest = manifestDigest; 8969 this.user = user; 8970 this.instructionSets = instructionSets; 8971 this.abiOverride = abiOverride; 8972 } 8973 8974 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 8975 abstract int doPreInstall(int status); 8976 8977 /** 8978 * Rename package into final resting place. All paths on the given 8979 * scanned package should be updated to reflect the rename. 8980 */ 8981 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 8982 abstract int doPostInstall(int status, int uid); 8983 8984 /** @see PackageSettingBase#codePathString */ 8985 abstract String getCodePath(); 8986 /** @see PackageSettingBase#resourcePathString */ 8987 abstract String getResourcePath(); 8988 abstract String getLegacyNativeLibraryPath(); 8989 8990 // Need installer lock especially for dex file removal. 8991 abstract void cleanUpResourcesLI(); 8992 abstract boolean doPostDeleteLI(boolean delete); 8993 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 8994 8995 /** 8996 * Called before the source arguments are copied. This is used mostly 8997 * for MoveParams when it needs to read the source file to put it in the 8998 * destination. 8999 */ 9000 int doPreCopy() { 9001 return PackageManager.INSTALL_SUCCEEDED; 9002 } 9003 9004 /** 9005 * Called after the source arguments are copied. This is used mostly for 9006 * MoveParams when it needs to read the source file to put it in the 9007 * destination. 9008 * 9009 * @return 9010 */ 9011 int doPostCopy(int uid) { 9012 return PackageManager.INSTALL_SUCCEEDED; 9013 } 9014 9015 protected boolean isFwdLocked() { 9016 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9017 } 9018 9019 protected boolean isExternal() { 9020 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9021 } 9022 9023 UserHandle getUser() { 9024 return user; 9025 } 9026 } 9027 9028 /** 9029 * Logic to handle installation of non-ASEC applications, including copying 9030 * and renaming logic. 9031 */ 9032 class FileInstallArgs extends InstallArgs { 9033 private File codeFile; 9034 private File resourceFile; 9035 private File legacyNativeLibraryPath; 9036 9037 // Example topology: 9038 // /data/app/com.example/base.apk 9039 // /data/app/com.example/split_foo.apk 9040 // /data/app/com.example/lib/arm/libfoo.so 9041 // /data/app/com.example/lib/arm64/libfoo.so 9042 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 9043 9044 /** New install */ 9045 FileInstallArgs(InstallParams params) { 9046 super(params.origin, params.observer, params.installFlags, 9047 params.installerPackageName, params.getManifestDigest(), params.getUser(), 9048 null /* instruction sets */, params.packageAbiOverride); 9049 if (isFwdLocked()) { 9050 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 9051 } 9052 } 9053 9054 /** Existing install */ 9055 FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath, 9056 String[] instructionSets) { 9057 super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null); 9058 this.codeFile = (codePath != null) ? new File(codePath) : null; 9059 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 9060 this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ? 9061 new File(legacyNativeLibraryPath) : null; 9062 } 9063 9064 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9065 final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(), 9066 isFwdLocked(), abiOverride); 9067 9068 final StorageManager storage = StorageManager.from(mContext); 9069 return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory())); 9070 } 9071 9072 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9073 if (origin.staged) { 9074 Slog.d(TAG, origin.file + " already staged; skipping copy"); 9075 codeFile = origin.file; 9076 resourceFile = origin.file; 9077 return PackageManager.INSTALL_SUCCEEDED; 9078 } 9079 9080 try { 9081 final File tempDir = mInstallerService.allocateInternalStageDirLegacy(); 9082 codeFile = tempDir; 9083 resourceFile = tempDir; 9084 } catch (IOException e) { 9085 Slog.w(TAG, "Failed to create copy file: " + e); 9086 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9087 } 9088 9089 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 9090 @Override 9091 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 9092 if (!FileUtils.isValidExtFilename(name)) { 9093 throw new IllegalArgumentException("Invalid filename: " + name); 9094 } 9095 try { 9096 final File file = new File(codeFile, name); 9097 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 9098 O_RDWR | O_CREAT, 0644); 9099 Os.chmod(file.getAbsolutePath(), 0644); 9100 return new ParcelFileDescriptor(fd); 9101 } catch (ErrnoException e) { 9102 throw new RemoteException("Failed to open: " + e.getMessage()); 9103 } 9104 } 9105 }; 9106 9107 int ret = PackageManager.INSTALL_SUCCEEDED; 9108 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 9109 if (ret != PackageManager.INSTALL_SUCCEEDED) { 9110 Slog.e(TAG, "Failed to copy package"); 9111 return ret; 9112 } 9113 9114 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 9115 NativeLibraryHelper.Handle handle = null; 9116 try { 9117 handle = NativeLibraryHelper.Handle.create(codeFile); 9118 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 9119 abiOverride); 9120 } catch (IOException e) { 9121 Slog.e(TAG, "Copying native libraries failed", e); 9122 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9123 } finally { 9124 IoUtils.closeQuietly(handle); 9125 } 9126 9127 return ret; 9128 } 9129 9130 int doPreInstall(int status) { 9131 if (status != PackageManager.INSTALL_SUCCEEDED) { 9132 cleanUp(); 9133 } 9134 return status; 9135 } 9136 9137 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9138 if (status != PackageManager.INSTALL_SUCCEEDED) { 9139 cleanUp(); 9140 return false; 9141 } else { 9142 final File beforeCodeFile = codeFile; 9143 final File afterCodeFile = getNextCodePath(pkg.packageName); 9144 9145 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 9146 try { 9147 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 9148 } catch (ErrnoException e) { 9149 Slog.d(TAG, "Failed to rename", e); 9150 return false; 9151 } 9152 9153 if (!SELinux.restoreconRecursive(afterCodeFile)) { 9154 Slog.d(TAG, "Failed to restorecon"); 9155 return false; 9156 } 9157 9158 // Reflect the rename internally 9159 codeFile = afterCodeFile; 9160 resourceFile = afterCodeFile; 9161 9162 // Reflect the rename in scanned details 9163 pkg.codePath = afterCodeFile.getAbsolutePath(); 9164 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9165 pkg.baseCodePath); 9166 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9167 pkg.splitCodePaths); 9168 9169 // Reflect the rename in app info 9170 pkg.applicationInfo.setCodePath(pkg.codePath); 9171 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9172 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9173 pkg.applicationInfo.setResourcePath(pkg.codePath); 9174 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9175 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9176 9177 return true; 9178 } 9179 } 9180 9181 int doPostInstall(int status, int uid) { 9182 if (status != PackageManager.INSTALL_SUCCEEDED) { 9183 cleanUp(); 9184 } 9185 return status; 9186 } 9187 9188 @Override 9189 String getCodePath() { 9190 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 9191 } 9192 9193 @Override 9194 String getResourcePath() { 9195 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 9196 } 9197 9198 @Override 9199 String getLegacyNativeLibraryPath() { 9200 return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null; 9201 } 9202 9203 private boolean cleanUp() { 9204 if (codeFile == null || !codeFile.exists()) { 9205 return false; 9206 } 9207 9208 if (codeFile.isDirectory()) { 9209 FileUtils.deleteContents(codeFile); 9210 } 9211 codeFile.delete(); 9212 9213 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 9214 resourceFile.delete(); 9215 } 9216 9217 if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) { 9218 if (!FileUtils.deleteContents(legacyNativeLibraryPath)) { 9219 Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath); 9220 } 9221 legacyNativeLibraryPath.delete(); 9222 } 9223 9224 return true; 9225 } 9226 9227 void cleanUpResourcesLI() { 9228 // Try enumerating all code paths before deleting 9229 List<String> allCodePaths = Collections.EMPTY_LIST; 9230 if (codeFile != null && codeFile.exists()) { 9231 try { 9232 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9233 allCodePaths = pkg.getAllCodePaths(); 9234 } catch (PackageParserException e) { 9235 // Ignored; we tried our best 9236 } 9237 } 9238 9239 cleanUp(); 9240 9241 if (!allCodePaths.isEmpty()) { 9242 if (instructionSets == null) { 9243 throw new IllegalStateException("instructionSet == null"); 9244 } 9245 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9246 for (String codePath : allCodePaths) { 9247 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9248 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9249 if (retCode < 0) { 9250 Slog.w(TAG, "Couldn't remove dex file for package: " 9251 + " at location " + codePath + ", retcode=" + retCode); 9252 // we don't consider this to be a failure of the core package deletion 9253 } 9254 } 9255 } 9256 } 9257 } 9258 9259 boolean doPostDeleteLI(boolean delete) { 9260 // XXX err, shouldn't we respect the delete flag? 9261 cleanUpResourcesLI(); 9262 return true; 9263 } 9264 } 9265 9266 private boolean isAsecExternal(String cid) { 9267 final String asecPath = PackageHelper.getSdFilesystem(cid); 9268 return !asecPath.startsWith(mAsecInternalPath); 9269 } 9270 9271 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 9272 PackageManagerException { 9273 if (copyRet < 0) { 9274 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 9275 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 9276 throw new PackageManagerException(copyRet, message); 9277 } 9278 } 9279 } 9280 9281 /** 9282 * Extract the MountService "container ID" from the full code path of an 9283 * .apk. 9284 */ 9285 static String cidFromCodePath(String fullCodePath) { 9286 int eidx = fullCodePath.lastIndexOf("/"); 9287 String subStr1 = fullCodePath.substring(0, eidx); 9288 int sidx = subStr1.lastIndexOf("/"); 9289 return subStr1.substring(sidx+1, eidx); 9290 } 9291 9292 /** 9293 * Logic to handle installation of ASEC applications, including copying and 9294 * renaming logic. 9295 */ 9296 class AsecInstallArgs extends InstallArgs { 9297 static final String RES_FILE_NAME = "pkg.apk"; 9298 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 9299 9300 String cid; 9301 String packagePath; 9302 String resourcePath; 9303 String legacyNativeLibraryDir; 9304 9305 /** New install */ 9306 AsecInstallArgs(InstallParams params) { 9307 super(params.origin, params.observer, params.installFlags, 9308 params.installerPackageName, params.getManifestDigest(), 9309 params.getUser(), null /* instruction sets */, 9310 params.packageAbiOverride); 9311 } 9312 9313 /** Existing install */ 9314 AsecInstallArgs(String fullCodePath, String[] instructionSets, 9315 boolean isExternal, boolean isForwardLocked) { 9316 super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0) 9317 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9318 instructionSets, null); 9319 // Hackily pretend we're still looking at a full code path 9320 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 9321 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 9322 } 9323 9324 // Extract cid from fullCodePath 9325 int eidx = fullCodePath.lastIndexOf("/"); 9326 String subStr1 = fullCodePath.substring(0, eidx); 9327 int sidx = subStr1.lastIndexOf("/"); 9328 cid = subStr1.substring(sidx+1, eidx); 9329 setMountPath(subStr1); 9330 } 9331 9332 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 9333 super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 9334 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9335 instructionSets, null); 9336 this.cid = cid; 9337 setMountPath(PackageHelper.getSdDir(cid)); 9338 } 9339 9340 void createCopyFile() { 9341 cid = mInstallerService.allocateExternalStageCidLegacy(); 9342 } 9343 9344 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9345 final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(), 9346 abiOverride); 9347 9348 final File target; 9349 if (isExternal()) { 9350 target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory(); 9351 } else { 9352 target = Environment.getDataDirectory(); 9353 } 9354 9355 final StorageManager storage = StorageManager.from(mContext); 9356 return (sizeBytes <= storage.getStorageBytesUntilLow(target)); 9357 } 9358 9359 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9360 if (origin.staged) { 9361 Slog.d(TAG, origin.cid + " already staged; skipping copy"); 9362 cid = origin.cid; 9363 setMountPath(PackageHelper.getSdDir(cid)); 9364 return PackageManager.INSTALL_SUCCEEDED; 9365 } 9366 9367 if (temp) { 9368 createCopyFile(); 9369 } else { 9370 /* 9371 * Pre-emptively destroy the container since it's destroyed if 9372 * copying fails due to it existing anyway. 9373 */ 9374 PackageHelper.destroySdDir(cid); 9375 } 9376 9377 final String newMountPath = imcs.copyPackageToContainer( 9378 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(), 9379 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 9380 9381 if (newMountPath != null) { 9382 setMountPath(newMountPath); 9383 return PackageManager.INSTALL_SUCCEEDED; 9384 } else { 9385 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9386 } 9387 } 9388 9389 @Override 9390 String getCodePath() { 9391 return packagePath; 9392 } 9393 9394 @Override 9395 String getResourcePath() { 9396 return resourcePath; 9397 } 9398 9399 @Override 9400 String getLegacyNativeLibraryPath() { 9401 return legacyNativeLibraryDir; 9402 } 9403 9404 int doPreInstall(int status) { 9405 if (status != PackageManager.INSTALL_SUCCEEDED) { 9406 // Destroy container 9407 PackageHelper.destroySdDir(cid); 9408 } else { 9409 boolean mounted = PackageHelper.isContainerMounted(cid); 9410 if (!mounted) { 9411 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 9412 Process.SYSTEM_UID); 9413 if (newMountPath != null) { 9414 setMountPath(newMountPath); 9415 } else { 9416 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9417 } 9418 } 9419 } 9420 return status; 9421 } 9422 9423 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9424 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 9425 String newMountPath = null; 9426 if (PackageHelper.isContainerMounted(cid)) { 9427 // Unmount the container 9428 if (!PackageHelper.unMountSdDir(cid)) { 9429 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9430 return false; 9431 } 9432 } 9433 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9434 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9435 " which might be stale. Will try to clean up."); 9436 // Clean up the stale container and proceed to recreate. 9437 if (!PackageHelper.destroySdDir(newCacheId)) { 9438 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9439 return false; 9440 } 9441 // Successfully cleaned up stale container. Try to rename again. 9442 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9443 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9444 + " inspite of cleaning it up."); 9445 return false; 9446 } 9447 } 9448 if (!PackageHelper.isContainerMounted(newCacheId)) { 9449 Slog.w(TAG, "Mounting container " + newCacheId); 9450 newMountPath = PackageHelper.mountSdDir(newCacheId, 9451 getEncryptKey(), Process.SYSTEM_UID); 9452 } else { 9453 newMountPath = PackageHelper.getSdDir(newCacheId); 9454 } 9455 if (newMountPath == null) { 9456 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9457 return false; 9458 } 9459 Log.i(TAG, "Succesfully renamed " + cid + 9460 " to " + newCacheId + 9461 " at new path: " + newMountPath); 9462 cid = newCacheId; 9463 9464 final File beforeCodeFile = new File(packagePath); 9465 setMountPath(newMountPath); 9466 final File afterCodeFile = new File(packagePath); 9467 9468 // Reflect the rename in scanned details 9469 pkg.codePath = afterCodeFile.getAbsolutePath(); 9470 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9471 pkg.baseCodePath); 9472 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9473 pkg.splitCodePaths); 9474 9475 // Reflect the rename in app info 9476 pkg.applicationInfo.setCodePath(pkg.codePath); 9477 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9478 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9479 pkg.applicationInfo.setResourcePath(pkg.codePath); 9480 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9481 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9482 9483 return true; 9484 } 9485 9486 private void setMountPath(String mountPath) { 9487 final File mountFile = new File(mountPath); 9488 9489 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 9490 if (monolithicFile.exists()) { 9491 packagePath = monolithicFile.getAbsolutePath(); 9492 if (isFwdLocked()) { 9493 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 9494 } else { 9495 resourcePath = packagePath; 9496 } 9497 } else { 9498 packagePath = mountFile.getAbsolutePath(); 9499 resourcePath = packagePath; 9500 } 9501 9502 legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath(); 9503 } 9504 9505 int doPostInstall(int status, int uid) { 9506 if (status != PackageManager.INSTALL_SUCCEEDED) { 9507 cleanUp(); 9508 } else { 9509 final int groupOwner; 9510 final String protectedFile; 9511 if (isFwdLocked()) { 9512 groupOwner = UserHandle.getSharedAppGid(uid); 9513 protectedFile = RES_FILE_NAME; 9514 } else { 9515 groupOwner = -1; 9516 protectedFile = null; 9517 } 9518 9519 if (uid < Process.FIRST_APPLICATION_UID 9520 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9521 Slog.e(TAG, "Failed to finalize " + cid); 9522 PackageHelper.destroySdDir(cid); 9523 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9524 } 9525 9526 boolean mounted = PackageHelper.isContainerMounted(cid); 9527 if (!mounted) { 9528 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9529 } 9530 } 9531 return status; 9532 } 9533 9534 private void cleanUp() { 9535 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9536 9537 // Destroy secure container 9538 PackageHelper.destroySdDir(cid); 9539 } 9540 9541 private List<String> getAllCodePaths() { 9542 final File codeFile = new File(getCodePath()); 9543 if (codeFile != null && codeFile.exists()) { 9544 try { 9545 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9546 return pkg.getAllCodePaths(); 9547 } catch (PackageParserException e) { 9548 // Ignored; we tried our best 9549 } 9550 } 9551 return Collections.EMPTY_LIST; 9552 } 9553 9554 void cleanUpResourcesLI() { 9555 // Enumerate all code paths before deleting 9556 cleanUpResourcesLI(getAllCodePaths()); 9557 } 9558 9559 private void cleanUpResourcesLI(List<String> allCodePaths) { 9560 cleanUp(); 9561 9562 if (!allCodePaths.isEmpty()) { 9563 if (instructionSets == null) { 9564 throw new IllegalStateException("instructionSet == null"); 9565 } 9566 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9567 for (String codePath : allCodePaths) { 9568 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9569 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9570 if (retCode < 0) { 9571 Slog.w(TAG, "Couldn't remove dex file for package: " 9572 + " at location " + codePath + ", retcode=" + retCode); 9573 // we don't consider this to be a failure of the core package deletion 9574 } 9575 } 9576 } 9577 } 9578 } 9579 9580 boolean matchContainer(String app) { 9581 if (cid.startsWith(app)) { 9582 return true; 9583 } 9584 return false; 9585 } 9586 9587 String getPackageName() { 9588 return getAsecPackageName(cid); 9589 } 9590 9591 boolean doPostDeleteLI(boolean delete) { 9592 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 9593 final List<String> allCodePaths = getAllCodePaths(); 9594 boolean mounted = PackageHelper.isContainerMounted(cid); 9595 if (mounted) { 9596 // Unmount first 9597 if (PackageHelper.unMountSdDir(cid)) { 9598 mounted = false; 9599 } 9600 } 9601 if (!mounted && delete) { 9602 cleanUpResourcesLI(allCodePaths); 9603 } 9604 return !mounted; 9605 } 9606 9607 @Override 9608 int doPreCopy() { 9609 if (isFwdLocked()) { 9610 if (!PackageHelper.fixSdPermissions(cid, 9611 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 9612 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9613 } 9614 } 9615 9616 return PackageManager.INSTALL_SUCCEEDED; 9617 } 9618 9619 @Override 9620 int doPostCopy(int uid) { 9621 if (isFwdLocked()) { 9622 if (uid < Process.FIRST_APPLICATION_UID 9623 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 9624 RES_FILE_NAME)) { 9625 Slog.e(TAG, "Failed to finalize " + cid); 9626 PackageHelper.destroySdDir(cid); 9627 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9628 } 9629 } 9630 9631 return PackageManager.INSTALL_SUCCEEDED; 9632 } 9633 } 9634 9635 static String getAsecPackageName(String packageCid) { 9636 int idx = packageCid.lastIndexOf("-"); 9637 if (idx == -1) { 9638 return packageCid; 9639 } 9640 return packageCid.substring(0, idx); 9641 } 9642 9643 // Utility method used to create code paths based on package name and available index. 9644 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 9645 String idxStr = ""; 9646 int idx = 1; 9647 // Fall back to default value of idx=1 if prefix is not 9648 // part of oldCodePath 9649 if (oldCodePath != null) { 9650 String subStr = oldCodePath; 9651 // Drop the suffix right away 9652 if (suffix != null && subStr.endsWith(suffix)) { 9653 subStr = subStr.substring(0, subStr.length() - suffix.length()); 9654 } 9655 // If oldCodePath already contains prefix find out the 9656 // ending index to either increment or decrement. 9657 int sidx = subStr.lastIndexOf(prefix); 9658 if (sidx != -1) { 9659 subStr = subStr.substring(sidx + prefix.length()); 9660 if (subStr != null) { 9661 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 9662 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 9663 } 9664 try { 9665 idx = Integer.parseInt(subStr); 9666 if (idx <= 1) { 9667 idx++; 9668 } else { 9669 idx--; 9670 } 9671 } catch(NumberFormatException e) { 9672 } 9673 } 9674 } 9675 } 9676 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 9677 return prefix + idxStr; 9678 } 9679 9680 private File getNextCodePath(String packageName) { 9681 int suffix = 1; 9682 File result; 9683 do { 9684 result = new File(mAppInstallDir, packageName + "-" + suffix); 9685 suffix++; 9686 } while (result.exists()); 9687 return result; 9688 } 9689 9690 // Utility method used to ignore ADD/REMOVE events 9691 // by directory observer. 9692 private static boolean ignoreCodePath(String fullPathStr) { 9693 String apkName = deriveCodePathName(fullPathStr); 9694 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 9695 if (idx != -1 && ((idx+1) < apkName.length())) { 9696 // Make sure the package ends with a numeral 9697 String version = apkName.substring(idx+1); 9698 try { 9699 Integer.parseInt(version); 9700 return true; 9701 } catch (NumberFormatException e) {} 9702 } 9703 return false; 9704 } 9705 9706 // Utility method that returns the relative package path with respect 9707 // to the installation directory. Like say for /data/data/com.test-1.apk 9708 // string com.test-1 is returned. 9709 static String deriveCodePathName(String codePath) { 9710 if (codePath == null) { 9711 return null; 9712 } 9713 final File codeFile = new File(codePath); 9714 final String name = codeFile.getName(); 9715 if (codeFile.isDirectory()) { 9716 return name; 9717 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 9718 final int lastDot = name.lastIndexOf('.'); 9719 return name.substring(0, lastDot); 9720 } else { 9721 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 9722 return null; 9723 } 9724 } 9725 9726 class PackageInstalledInfo { 9727 String name; 9728 int uid; 9729 // The set of users that originally had this package installed. 9730 int[] origUsers; 9731 // The set of users that now have this package installed. 9732 int[] newUsers; 9733 PackageParser.Package pkg; 9734 int returnCode; 9735 String returnMsg; 9736 PackageRemovedInfo removedInfo; 9737 9738 public void setError(int code, String msg) { 9739 returnCode = code; 9740 returnMsg = msg; 9741 Slog.w(TAG, msg); 9742 } 9743 9744 public void setError(String msg, PackageParserException e) { 9745 returnCode = e.error; 9746 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9747 Slog.w(TAG, msg, e); 9748 } 9749 9750 public void setError(String msg, PackageManagerException e) { 9751 returnCode = e.error; 9752 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9753 Slog.w(TAG, msg, e); 9754 } 9755 9756 // In some error cases we want to convey more info back to the observer 9757 String origPackage; 9758 String origPermission; 9759 } 9760 9761 /* 9762 * Install a non-existing package. 9763 */ 9764 private void installNewPackageLI(PackageParser.Package pkg, 9765 int parseFlags, int scanFlags, UserHandle user, 9766 String installerPackageName, PackageInstalledInfo res) { 9767 // Remember this for later, in case we need to rollback this install 9768 String pkgName = pkg.packageName; 9769 9770 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 9771 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 9772 synchronized(mPackages) { 9773 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 9774 // A package with the same name is already installed, though 9775 // it has been renamed to an older name. The package we 9776 // are trying to install should be installed as an update to 9777 // the existing one, but that has not been requested, so bail. 9778 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9779 + " without first uninstalling package running as " 9780 + mSettings.mRenamedPackages.get(pkgName)); 9781 return; 9782 } 9783 if (mPackages.containsKey(pkgName)) { 9784 // Don't allow installation over an existing package with the same name. 9785 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9786 + " without first uninstalling."); 9787 return; 9788 } 9789 } 9790 9791 try { 9792 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 9793 System.currentTimeMillis(), user); 9794 9795 updateSettingsLI(newPackage, installerPackageName, null, null, res); 9796 // delete the partially installed application. the data directory will have to be 9797 // restored if it was already existing 9798 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9799 // remove package from internal structures. Note that we want deletePackageX to 9800 // delete the package data and cache directories that it created in 9801 // scanPackageLocked, unless those directories existed before we even tried to 9802 // install. 9803 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 9804 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 9805 res.removedInfo, true); 9806 } 9807 9808 } catch (PackageManagerException e) { 9809 res.setError("Package couldn't be installed in " + pkg.codePath, e); 9810 } 9811 } 9812 9813 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 9814 // Upgrade keysets are being used. Determine if new package has a superset of the 9815 // required keys. 9816 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 9817 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9818 for (int i = 0; i < upgradeKeySets.length; i++) { 9819 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 9820 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 9821 return true; 9822 } 9823 } 9824 return false; 9825 } 9826 9827 private void replacePackageLI(PackageParser.Package pkg, 9828 int parseFlags, int scanFlags, UserHandle user, 9829 String installerPackageName, PackageInstalledInfo res) { 9830 PackageParser.Package oldPackage; 9831 String pkgName = pkg.packageName; 9832 int[] allUsers; 9833 boolean[] perUserInstalled; 9834 9835 // First find the old package info and check signatures 9836 synchronized(mPackages) { 9837 oldPackage = mPackages.get(pkgName); 9838 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 9839 PackageSetting ps = mSettings.mPackages.get(pkgName); 9840 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 9841 // default to original signature matching 9842 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 9843 != PackageManager.SIGNATURE_MATCH) { 9844 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9845 "New package has a different signature: " + pkgName); 9846 return; 9847 } 9848 } else { 9849 if(!checkUpgradeKeySetLP(ps, pkg)) { 9850 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9851 "New package not signed by keys specified by upgrade-keysets: " 9852 + pkgName); 9853 return; 9854 } 9855 } 9856 9857 // In case of rollback, remember per-user/profile install state 9858 allUsers = sUserManager.getUserIds(); 9859 perUserInstalled = new boolean[allUsers.length]; 9860 for (int i = 0; i < allUsers.length; i++) { 9861 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 9862 } 9863 } 9864 9865 boolean sysPkg = (isSystemApp(oldPackage)); 9866 if (sysPkg) { 9867 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 9868 user, allUsers, perUserInstalled, installerPackageName, res); 9869 } else { 9870 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 9871 user, allUsers, perUserInstalled, installerPackageName, res); 9872 } 9873 } 9874 9875 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 9876 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 9877 int[] allUsers, boolean[] perUserInstalled, 9878 String installerPackageName, PackageInstalledInfo res) { 9879 String pkgName = deletedPackage.packageName; 9880 boolean deletedPkg = true; 9881 boolean updatedSettings = false; 9882 9883 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 9884 + deletedPackage); 9885 long origUpdateTime; 9886 if (pkg.mExtras != null) { 9887 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 9888 } else { 9889 origUpdateTime = 0; 9890 } 9891 9892 // First delete the existing package while retaining the data directory 9893 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 9894 res.removedInfo, true)) { 9895 // If the existing package wasn't successfully deleted 9896 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 9897 deletedPkg = false; 9898 } else { 9899 // Successfully deleted the old package; proceed with replace. 9900 9901 // If deleted package lived in a container, give users a chance to 9902 // relinquish resources before killing. 9903 if (isForwardLocked(deletedPackage) || isExternal(deletedPackage)) { 9904 if (DEBUG_INSTALL) { 9905 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 9906 } 9907 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 9908 final ArrayList<String> pkgList = new ArrayList<String>(1); 9909 pkgList.add(deletedPackage.applicationInfo.packageName); 9910 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 9911 } 9912 9913 deleteCodeCacheDirsLI(pkgName); 9914 try { 9915 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 9916 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 9917 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 9918 updatedSettings = true; 9919 } catch (PackageManagerException e) { 9920 res.setError("Package couldn't be installed in " + pkg.codePath, e); 9921 } 9922 } 9923 9924 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9925 // remove package from internal structures. Note that we want deletePackageX to 9926 // delete the package data and cache directories that it created in 9927 // scanPackageLocked, unless those directories existed before we even tried to 9928 // install. 9929 if(updatedSettings) { 9930 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 9931 deletePackageLI( 9932 pkgName, null, true, allUsers, perUserInstalled, 9933 PackageManager.DELETE_KEEP_DATA, 9934 res.removedInfo, true); 9935 } 9936 // Since we failed to install the new package we need to restore the old 9937 // package that we deleted. 9938 if (deletedPkg) { 9939 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 9940 File restoreFile = new File(deletedPackage.codePath); 9941 // Parse old package 9942 boolean oldOnSd = isExternal(deletedPackage); 9943 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 9944 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) | 9945 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 9946 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 9947 try { 9948 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 9949 } catch (PackageManagerException e) { 9950 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 9951 + e.getMessage()); 9952 return; 9953 } 9954 // Restore of old package succeeded. Update permissions. 9955 // writer 9956 synchronized (mPackages) { 9957 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 9958 UPDATE_PERMISSIONS_ALL); 9959 // can downgrade to reader 9960 mSettings.writeLPr(); 9961 } 9962 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 9963 } 9964 } 9965 } 9966 9967 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 9968 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 9969 int[] allUsers, boolean[] perUserInstalled, 9970 String installerPackageName, PackageInstalledInfo res) { 9971 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 9972 + ", old=" + deletedPackage); 9973 boolean updatedSettings = false; 9974 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 9975 if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) { 9976 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 9977 } 9978 String packageName = deletedPackage.packageName; 9979 if (packageName == null) { 9980 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 9981 "Attempt to delete null packageName."); 9982 return; 9983 } 9984 PackageParser.Package oldPkg; 9985 PackageSetting oldPkgSetting; 9986 // reader 9987 synchronized (mPackages) { 9988 oldPkg = mPackages.get(packageName); 9989 oldPkgSetting = mSettings.mPackages.get(packageName); 9990 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 9991 (oldPkgSetting == null)) { 9992 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 9993 "Couldn't find package:" + packageName + " information"); 9994 return; 9995 } 9996 } 9997 9998 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 9999 10000 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10001 res.removedInfo.removedPackage = packageName; 10002 // Remove existing system package 10003 removePackageLI(oldPkgSetting, true); 10004 // writer 10005 synchronized (mPackages) { 10006 if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) { 10007 // We didn't need to disable the .apk as a current system package, 10008 // which means we are replacing another update that is already 10009 // installed. We need to make sure to delete the older one's .apk. 10010 res.removedInfo.args = createInstallArgsForExisting(0, 10011 deletedPackage.applicationInfo.getCodePath(), 10012 deletedPackage.applicationInfo.getResourcePath(), 10013 deletedPackage.applicationInfo.nativeLibraryRootDir, 10014 getAppDexInstructionSets(deletedPackage.applicationInfo)); 10015 } else { 10016 res.removedInfo.args = null; 10017 } 10018 } 10019 10020 // Successfully disabled the old package. Now proceed with re-installation 10021 deleteCodeCacheDirsLI(packageName); 10022 10023 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10024 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10025 10026 PackageParser.Package newPackage = null; 10027 try { 10028 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 10029 if (newPackage.mExtras != null) { 10030 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 10031 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10032 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10033 10034 // is the update attempting to change shared user? that isn't going to work... 10035 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10036 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 10037 "Forbidding shared user change from " + oldPkgSetting.sharedUser 10038 + " to " + newPkgSetting.sharedUser); 10039 updatedSettings = true; 10040 } 10041 } 10042 10043 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10044 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10045 updatedSettings = true; 10046 } 10047 10048 } catch (PackageManagerException e) { 10049 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10050 } 10051 10052 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10053 // Re installation failed. Restore old information 10054 // Remove new pkg information 10055 if (newPackage != null) { 10056 removeInstalledPackageLI(newPackage, true); 10057 } 10058 // Add back the old system package 10059 try { 10060 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 10061 } catch (PackageManagerException e) { 10062 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 10063 } 10064 // Restore the old system information in Settings 10065 synchronized(mPackages) { 10066 if (updatedSettings) { 10067 mSettings.enableSystemPackageLPw(packageName); 10068 mSettings.setInstallerPackageName(packageName, 10069 oldPkgSetting.installerPackageName); 10070 } 10071 mSettings.writeLPr(); 10072 } 10073 } 10074 } 10075 10076 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10077 int[] allUsers, boolean[] perUserInstalled, 10078 PackageInstalledInfo res) { 10079 String pkgName = newPackage.packageName; 10080 synchronized (mPackages) { 10081 //write settings. the installStatus will be incomplete at this stage. 10082 //note that the new package setting would have already been 10083 //added to mPackages. It hasn't been persisted yet. 10084 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10085 mSettings.writeLPr(); 10086 } 10087 10088 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10089 10090 synchronized (mPackages) { 10091 updatePermissionsLPw(newPackage.packageName, newPackage, 10092 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10093 ? UPDATE_PERMISSIONS_ALL : 0)); 10094 // For system-bundled packages, we assume that installing an upgraded version 10095 // of the package implies that the user actually wants to run that new code, 10096 // so we enable the package. 10097 if (isSystemApp(newPackage)) { 10098 // NB: implicit assumption that system package upgrades apply to all users 10099 if (DEBUG_INSTALL) { 10100 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10101 } 10102 PackageSetting ps = mSettings.mPackages.get(pkgName); 10103 if (ps != null) { 10104 if (res.origUsers != null) { 10105 for (int userHandle : res.origUsers) { 10106 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10107 userHandle, installerPackageName); 10108 } 10109 } 10110 // Also convey the prior install/uninstall state 10111 if (allUsers != null && perUserInstalled != null) { 10112 for (int i = 0; i < allUsers.length; i++) { 10113 if (DEBUG_INSTALL) { 10114 Slog.d(TAG, " user " + allUsers[i] 10115 + " => " + perUserInstalled[i]); 10116 } 10117 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10118 } 10119 // these install state changes will be persisted in the 10120 // upcoming call to mSettings.writeLPr(). 10121 } 10122 } 10123 } 10124 res.name = pkgName; 10125 res.uid = newPackage.applicationInfo.uid; 10126 res.pkg = newPackage; 10127 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10128 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10129 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10130 //to update install status 10131 mSettings.writeLPr(); 10132 } 10133 } 10134 10135 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 10136 final int installFlags = args.installFlags; 10137 String installerPackageName = args.installerPackageName; 10138 File tmpPackageFile = new File(args.getCodePath()); 10139 boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10140 boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0); 10141 boolean replace = false; 10142 final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE; 10143 // Result object to be returned 10144 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10145 10146 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10147 // Retrieve PackageSettings and parse package 10148 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10149 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10150 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 10151 PackageParser pp = new PackageParser(); 10152 pp.setSeparateProcesses(mSeparateProcesses); 10153 pp.setDisplayMetrics(mMetrics); 10154 10155 final PackageParser.Package pkg; 10156 try { 10157 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 10158 } catch (PackageParserException e) { 10159 res.setError("Failed parse during installPackageLI", e); 10160 return; 10161 } 10162 10163 // Mark that we have an install time CPU ABI override. 10164 pkg.cpuAbiOverride = args.abiOverride; 10165 10166 String pkgName = res.name = pkg.packageName; 10167 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 10168 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 10169 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 10170 return; 10171 } 10172 } 10173 10174 try { 10175 pp.collectCertificates(pkg, parseFlags); 10176 pp.collectManifestDigest(pkg); 10177 } catch (PackageParserException e) { 10178 res.setError("Failed collect during installPackageLI", e); 10179 return; 10180 } 10181 10182 /* If the installer passed in a manifest digest, compare it now. */ 10183 if (args.manifestDigest != null) { 10184 if (DEBUG_INSTALL) { 10185 final String parsedManifest = pkg.manifestDigest == null ? "null" 10186 : pkg.manifestDigest.toString(); 10187 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 10188 + parsedManifest); 10189 } 10190 10191 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 10192 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 10193 return; 10194 } 10195 } else if (DEBUG_INSTALL) { 10196 final String parsedManifest = pkg.manifestDigest == null 10197 ? "null" : pkg.manifestDigest.toString(); 10198 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 10199 } 10200 10201 // Get rid of all references to package scan path via parser. 10202 pp = null; 10203 String oldCodePath = null; 10204 boolean systemApp = false; 10205 synchronized (mPackages) { 10206 // Check whether the newly-scanned package wants to define an already-defined perm 10207 int N = pkg.permissions.size(); 10208 for (int i = N-1; i >= 0; i--) { 10209 PackageParser.Permission perm = pkg.permissions.get(i); 10210 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 10211 if (bp != null) { 10212 // If the defining package is signed with our cert, it's okay. This 10213 // also includes the "updating the same package" case, of course. 10214 // "updating same package" could also involve key-rotation. 10215 final boolean sigsOk; 10216 if (!bp.sourcePackage.equals(pkg.packageName) 10217 || !(bp.packageSetting instanceof PackageSetting) 10218 || !bp.packageSetting.keySetData.isUsingUpgradeKeySets() 10219 || ((PackageSetting) bp.packageSetting).sharedUser != null) { 10220 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 10221 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 10222 } else { 10223 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 10224 } 10225 if (!sigsOk) { 10226 // If the owning package is the system itself, we log but allow 10227 // install to proceed; we fail the install on all other permission 10228 // redefinitions. 10229 if (!bp.sourcePackage.equals("android")) { 10230 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 10231 + pkg.packageName + " attempting to redeclare permission " 10232 + perm.info.name + " already owned by " + bp.sourcePackage); 10233 res.origPermission = perm.info.name; 10234 res.origPackage = bp.sourcePackage; 10235 return; 10236 } else { 10237 Slog.w(TAG, "Package " + pkg.packageName 10238 + " attempting to redeclare system permission " 10239 + perm.info.name + "; ignoring new declaration"); 10240 pkg.permissions.remove(i); 10241 } 10242 } 10243 } 10244 } 10245 10246 // Check if installing already existing package 10247 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10248 String oldName = mSettings.mRenamedPackages.get(pkgName); 10249 if (pkg.mOriginalPackages != null 10250 && pkg.mOriginalPackages.contains(oldName) 10251 && mPackages.containsKey(oldName)) { 10252 // This package is derived from an original package, 10253 // and this device has been updating from that original 10254 // name. We must continue using the original name, so 10255 // rename the new package here. 10256 pkg.setPackageName(oldName); 10257 pkgName = pkg.packageName; 10258 replace = true; 10259 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 10260 + oldName + " pkgName=" + pkgName); 10261 } else if (mPackages.containsKey(pkgName)) { 10262 // This package, under its official name, already exists 10263 // on the device; we should replace it. 10264 replace = true; 10265 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 10266 } 10267 } 10268 PackageSetting ps = mSettings.mPackages.get(pkgName); 10269 if (ps != null) { 10270 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 10271 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 10272 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 10273 systemApp = (ps.pkg.applicationInfo.flags & 10274 ApplicationInfo.FLAG_SYSTEM) != 0; 10275 } 10276 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10277 } 10278 } 10279 10280 if (systemApp && onSd) { 10281 // Disable updates to system apps on sdcard 10282 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 10283 "Cannot install updates to system apps on sdcard"); 10284 return; 10285 } 10286 10287 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 10288 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 10289 return; 10290 } 10291 10292 if (replace) { 10293 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 10294 installerPackageName, res); 10295 } else { 10296 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 10297 args.user, installerPackageName, res); 10298 } 10299 synchronized (mPackages) { 10300 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10301 if (ps != null) { 10302 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10303 } 10304 } 10305 } 10306 10307 private static boolean isForwardLocked(PackageParser.Package pkg) { 10308 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10309 } 10310 10311 private static boolean isForwardLocked(ApplicationInfo info) { 10312 return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10313 } 10314 10315 private boolean isForwardLocked(PackageSetting ps) { 10316 return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10317 } 10318 10319 private static boolean isMultiArch(PackageSetting ps) { 10320 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10321 } 10322 10323 private static boolean isMultiArch(ApplicationInfo info) { 10324 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10325 } 10326 10327 private static boolean isExternal(PackageParser.Package pkg) { 10328 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10329 } 10330 10331 private static boolean isExternal(PackageSetting ps) { 10332 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10333 } 10334 10335 private static boolean isExternal(ApplicationInfo info) { 10336 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10337 } 10338 10339 private static boolean isSystemApp(PackageParser.Package pkg) { 10340 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10341 } 10342 10343 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 10344 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0; 10345 } 10346 10347 private static boolean isSystemApp(ApplicationInfo info) { 10348 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10349 } 10350 10351 private static boolean isSystemApp(PackageSetting ps) { 10352 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 10353 } 10354 10355 private static boolean isUpdatedSystemApp(PackageSetting ps) { 10356 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10357 } 10358 10359 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 10360 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10361 } 10362 10363 private static boolean isUpdatedSystemApp(ApplicationInfo info) { 10364 return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10365 } 10366 10367 private int packageFlagsToInstallFlags(PackageSetting ps) { 10368 int installFlags = 0; 10369 if (isExternal(ps)) { 10370 installFlags |= PackageManager.INSTALL_EXTERNAL; 10371 } 10372 if (isForwardLocked(ps)) { 10373 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 10374 } 10375 return installFlags; 10376 } 10377 10378 private void deleteTempPackageFiles() { 10379 final FilenameFilter filter = new FilenameFilter() { 10380 public boolean accept(File dir, String name) { 10381 return name.startsWith("vmdl") && name.endsWith(".tmp"); 10382 } 10383 }; 10384 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 10385 file.delete(); 10386 } 10387 } 10388 10389 @Override 10390 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 10391 int flags) { 10392 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 10393 flags); 10394 } 10395 10396 @Override 10397 public void deletePackage(final String packageName, 10398 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 10399 mContext.enforceCallingOrSelfPermission( 10400 android.Manifest.permission.DELETE_PACKAGES, null); 10401 final int uid = Binder.getCallingUid(); 10402 if (UserHandle.getUserId(uid) != userId) { 10403 mContext.enforceCallingPermission( 10404 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 10405 "deletePackage for user " + userId); 10406 } 10407 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 10408 try { 10409 observer.onPackageDeleted(packageName, 10410 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 10411 } catch (RemoteException re) { 10412 } 10413 return; 10414 } 10415 10416 boolean uninstallBlocked = false; 10417 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 10418 int[] users = sUserManager.getUserIds(); 10419 for (int i = 0; i < users.length; ++i) { 10420 if (getBlockUninstallForUser(packageName, users[i])) { 10421 uninstallBlocked = true; 10422 break; 10423 } 10424 } 10425 } else { 10426 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 10427 } 10428 if (uninstallBlocked) { 10429 try { 10430 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 10431 null); 10432 } catch (RemoteException re) { 10433 } 10434 return; 10435 } 10436 10437 if (DEBUG_REMOVE) { 10438 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 10439 } 10440 // Queue up an async operation since the package deletion may take a little while. 10441 mHandler.post(new Runnable() { 10442 public void run() { 10443 mHandler.removeCallbacks(this); 10444 final int returnCode = deletePackageX(packageName, userId, flags); 10445 if (observer != null) { 10446 try { 10447 observer.onPackageDeleted(packageName, returnCode, null); 10448 } catch (RemoteException e) { 10449 Log.i(TAG, "Observer no longer exists."); 10450 } //end catch 10451 } //end if 10452 } //end run 10453 }); 10454 } 10455 10456 private boolean isPackageDeviceAdmin(String packageName, int userId) { 10457 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 10458 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 10459 try { 10460 if (dpm != null) { 10461 if (dpm.isDeviceOwner(packageName)) { 10462 return true; 10463 } 10464 int[] users; 10465 if (userId == UserHandle.USER_ALL) { 10466 users = sUserManager.getUserIds(); 10467 } else { 10468 users = new int[]{userId}; 10469 } 10470 for (int i = 0; i < users.length; ++i) { 10471 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 10472 return true; 10473 } 10474 } 10475 } 10476 } catch (RemoteException e) { 10477 } 10478 return false; 10479 } 10480 10481 /** 10482 * This method is an internal method that could be get invoked either 10483 * to delete an installed package or to clean up a failed installation. 10484 * After deleting an installed package, a broadcast is sent to notify any 10485 * listeners that the package has been installed. For cleaning up a failed 10486 * installation, the broadcast is not necessary since the package's 10487 * installation wouldn't have sent the initial broadcast either 10488 * The key steps in deleting a package are 10489 * deleting the package information in internal structures like mPackages, 10490 * deleting the packages base directories through installd 10491 * updating mSettings to reflect current status 10492 * persisting settings for later use 10493 * sending a broadcast if necessary 10494 */ 10495 private int deletePackageX(String packageName, int userId, int flags) { 10496 final PackageRemovedInfo info = new PackageRemovedInfo(); 10497 final boolean res; 10498 10499 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 10500 ? UserHandle.ALL : new UserHandle(userId); 10501 10502 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 10503 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 10504 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 10505 } 10506 10507 boolean removedForAllUsers = false; 10508 boolean systemUpdate = false; 10509 10510 // for the uninstall-updates case and restricted profiles, remember the per- 10511 // userhandle installed state 10512 int[] allUsers; 10513 boolean[] perUserInstalled; 10514 synchronized (mPackages) { 10515 PackageSetting ps = mSettings.mPackages.get(packageName); 10516 allUsers = sUserManager.getUserIds(); 10517 perUserInstalled = new boolean[allUsers.length]; 10518 for (int i = 0; i < allUsers.length; i++) { 10519 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10520 } 10521 } 10522 10523 synchronized (mInstallLock) { 10524 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 10525 res = deletePackageLI(packageName, removeForUser, 10526 true, allUsers, perUserInstalled, 10527 flags | REMOVE_CHATTY, info, true); 10528 systemUpdate = info.isRemovedPackageSystemUpdate; 10529 if (res && !systemUpdate && mPackages.get(packageName) == null) { 10530 removedForAllUsers = true; 10531 } 10532 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 10533 + " removedForAllUsers=" + removedForAllUsers); 10534 } 10535 10536 if (res) { 10537 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 10538 10539 // If the removed package was a system update, the old system package 10540 // was re-enabled; we need to broadcast this information 10541 if (systemUpdate) { 10542 Bundle extras = new Bundle(1); 10543 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 10544 ? info.removedAppId : info.uid); 10545 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10546 10547 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 10548 extras, null, null, null); 10549 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 10550 extras, null, null, null); 10551 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 10552 null, packageName, null, null); 10553 } 10554 } 10555 // Force a gc here. 10556 Runtime.getRuntime().gc(); 10557 // Delete the resources here after sending the broadcast to let 10558 // other processes clean up before deleting resources. 10559 if (info.args != null) { 10560 synchronized (mInstallLock) { 10561 info.args.doPostDeleteLI(true); 10562 } 10563 } 10564 10565 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10566 } 10567 10568 static class PackageRemovedInfo { 10569 String removedPackage; 10570 int uid = -1; 10571 int removedAppId = -1; 10572 int[] removedUsers = null; 10573 boolean isRemovedPackageSystemUpdate = false; 10574 // Clean up resources deleted packages. 10575 InstallArgs args = null; 10576 10577 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 10578 Bundle extras = new Bundle(1); 10579 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 10580 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 10581 if (replacing) { 10582 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10583 } 10584 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 10585 if (removedPackage != null) { 10586 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 10587 extras, null, null, removedUsers); 10588 if (fullRemove && !replacing) { 10589 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 10590 extras, null, null, removedUsers); 10591 } 10592 } 10593 if (removedAppId >= 0) { 10594 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 10595 removedUsers); 10596 } 10597 } 10598 } 10599 10600 /* 10601 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 10602 * flag is not set, the data directory is removed as well. 10603 * make sure this flag is set for partially installed apps. If not its meaningless to 10604 * delete a partially installed application. 10605 */ 10606 private void removePackageDataLI(PackageSetting ps, 10607 int[] allUserHandles, boolean[] perUserInstalled, 10608 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 10609 String packageName = ps.name; 10610 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 10611 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 10612 // Retrieve object to delete permissions for shared user later on 10613 final PackageSetting deletedPs; 10614 // reader 10615 synchronized (mPackages) { 10616 deletedPs = mSettings.mPackages.get(packageName); 10617 if (outInfo != null) { 10618 outInfo.removedPackage = packageName; 10619 outInfo.removedUsers = deletedPs != null 10620 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 10621 : null; 10622 } 10623 } 10624 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10625 removeDataDirsLI(packageName); 10626 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 10627 } 10628 // writer 10629 synchronized (mPackages) { 10630 if (deletedPs != null) { 10631 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10632 if (outInfo != null) { 10633 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 10634 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 10635 } 10636 if (deletedPs != null) { 10637 updatePermissionsLPw(deletedPs.name, null, 0); 10638 if (deletedPs.sharedUser != null) { 10639 // remove permissions associated with package 10640 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 10641 } 10642 } 10643 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 10644 } 10645 // make sure to preserve per-user disabled state if this removal was just 10646 // a downgrade of a system app to the factory package 10647 if (allUserHandles != null && perUserInstalled != null) { 10648 if (DEBUG_REMOVE) { 10649 Slog.d(TAG, "Propagating install state across downgrade"); 10650 } 10651 for (int i = 0; i < allUserHandles.length; i++) { 10652 if (DEBUG_REMOVE) { 10653 Slog.d(TAG, " user " + allUserHandles[i] 10654 + " => " + perUserInstalled[i]); 10655 } 10656 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10657 } 10658 } 10659 } 10660 // can downgrade to reader 10661 if (writeSettings) { 10662 // Save settings now 10663 mSettings.writeLPr(); 10664 } 10665 } 10666 if (outInfo != null) { 10667 // A user ID was deleted here. Go through all users and remove it 10668 // from KeyStore. 10669 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 10670 } 10671 } 10672 10673 static boolean locationIsPrivileged(File path) { 10674 try { 10675 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 10676 .getCanonicalPath(); 10677 return path.getCanonicalPath().startsWith(privilegedAppDir); 10678 } catch (IOException e) { 10679 Slog.e(TAG, "Unable to access code path " + path); 10680 } 10681 return false; 10682 } 10683 10684 /* 10685 * Tries to delete system package. 10686 */ 10687 private boolean deleteSystemPackageLI(PackageSetting newPs, 10688 int[] allUserHandles, boolean[] perUserInstalled, 10689 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 10690 final boolean applyUserRestrictions 10691 = (allUserHandles != null) && (perUserInstalled != null); 10692 PackageSetting disabledPs = null; 10693 // Confirm if the system package has been updated 10694 // An updated system app can be deleted. This will also have to restore 10695 // the system pkg from system partition 10696 // reader 10697 synchronized (mPackages) { 10698 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 10699 } 10700 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 10701 + " disabledPs=" + disabledPs); 10702 if (disabledPs == null) { 10703 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 10704 return false; 10705 } else if (DEBUG_REMOVE) { 10706 Slog.d(TAG, "Deleting system pkg from data partition"); 10707 } 10708 if (DEBUG_REMOVE) { 10709 if (applyUserRestrictions) { 10710 Slog.d(TAG, "Remembering install states:"); 10711 for (int i = 0; i < allUserHandles.length; i++) { 10712 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 10713 } 10714 } 10715 } 10716 // Delete the updated package 10717 outInfo.isRemovedPackageSystemUpdate = true; 10718 if (disabledPs.versionCode < newPs.versionCode) { 10719 // Delete data for downgrades 10720 flags &= ~PackageManager.DELETE_KEEP_DATA; 10721 } else { 10722 // Preserve data by setting flag 10723 flags |= PackageManager.DELETE_KEEP_DATA; 10724 } 10725 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 10726 allUserHandles, perUserInstalled, outInfo, writeSettings); 10727 if (!ret) { 10728 return false; 10729 } 10730 // writer 10731 synchronized (mPackages) { 10732 // Reinstate the old system package 10733 mSettings.enableSystemPackageLPw(newPs.name); 10734 // Remove any native libraries from the upgraded package. 10735 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 10736 } 10737 // Install the system package 10738 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 10739 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 10740 if (locationIsPrivileged(disabledPs.codePath)) { 10741 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10742 } 10743 10744 final PackageParser.Package newPkg; 10745 try { 10746 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 10747 } catch (PackageManagerException e) { 10748 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 10749 return false; 10750 } 10751 10752 // writer 10753 synchronized (mPackages) { 10754 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 10755 updatePermissionsLPw(newPkg.packageName, newPkg, 10756 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 10757 if (applyUserRestrictions) { 10758 if (DEBUG_REMOVE) { 10759 Slog.d(TAG, "Propagating install state across reinstall"); 10760 } 10761 for (int i = 0; i < allUserHandles.length; i++) { 10762 if (DEBUG_REMOVE) { 10763 Slog.d(TAG, " user " + allUserHandles[i] 10764 + " => " + perUserInstalled[i]); 10765 } 10766 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10767 } 10768 // Regardless of writeSettings we need to ensure that this restriction 10769 // state propagation is persisted 10770 mSettings.writeAllUsersPackageRestrictionsLPr(); 10771 } 10772 // can downgrade to reader here 10773 if (writeSettings) { 10774 mSettings.writeLPr(); 10775 } 10776 } 10777 return true; 10778 } 10779 10780 private boolean deleteInstalledPackageLI(PackageSetting ps, 10781 boolean deleteCodeAndResources, int flags, 10782 int[] allUserHandles, boolean[] perUserInstalled, 10783 PackageRemovedInfo outInfo, boolean writeSettings) { 10784 if (outInfo != null) { 10785 outInfo.uid = ps.appId; 10786 } 10787 10788 // Delete package data from internal structures and also remove data if flag is set 10789 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 10790 10791 // Delete application code and resources 10792 if (deleteCodeAndResources && (outInfo != null)) { 10793 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 10794 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 10795 getAppDexInstructionSets(ps)); 10796 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 10797 } 10798 return true; 10799 } 10800 10801 @Override 10802 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 10803 int userId) { 10804 mContext.enforceCallingOrSelfPermission( 10805 android.Manifest.permission.DELETE_PACKAGES, null); 10806 synchronized (mPackages) { 10807 PackageSetting ps = mSettings.mPackages.get(packageName); 10808 if (ps == null) { 10809 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 10810 return false; 10811 } 10812 if (!ps.getInstalled(userId)) { 10813 // Can't block uninstall for an app that is not installed or enabled. 10814 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 10815 return false; 10816 } 10817 ps.setBlockUninstall(blockUninstall, userId); 10818 mSettings.writePackageRestrictionsLPr(userId); 10819 } 10820 return true; 10821 } 10822 10823 @Override 10824 public boolean getBlockUninstallForUser(String packageName, int userId) { 10825 synchronized (mPackages) { 10826 PackageSetting ps = mSettings.mPackages.get(packageName); 10827 if (ps == null) { 10828 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 10829 return false; 10830 } 10831 return ps.getBlockUninstall(userId); 10832 } 10833 } 10834 10835 /* 10836 * This method handles package deletion in general 10837 */ 10838 private boolean deletePackageLI(String packageName, UserHandle user, 10839 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 10840 int flags, PackageRemovedInfo outInfo, 10841 boolean writeSettings) { 10842 if (packageName == null) { 10843 Slog.w(TAG, "Attempt to delete null packageName."); 10844 return false; 10845 } 10846 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 10847 PackageSetting ps; 10848 boolean dataOnly = false; 10849 int removeUser = -1; 10850 int appId = -1; 10851 synchronized (mPackages) { 10852 ps = mSettings.mPackages.get(packageName); 10853 if (ps == null) { 10854 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 10855 return false; 10856 } 10857 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 10858 && user.getIdentifier() != UserHandle.USER_ALL) { 10859 // The caller is asking that the package only be deleted for a single 10860 // user. To do this, we just mark its uninstalled state and delete 10861 // its data. If this is a system app, we only allow this to happen if 10862 // they have set the special DELETE_SYSTEM_APP which requests different 10863 // semantics than normal for uninstalling system apps. 10864 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 10865 ps.setUserState(user.getIdentifier(), 10866 COMPONENT_ENABLED_STATE_DEFAULT, 10867 false, //installed 10868 true, //stopped 10869 true, //notLaunched 10870 false, //hidden 10871 null, null, null, 10872 false // blockUninstall 10873 ); 10874 if (!isSystemApp(ps)) { 10875 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 10876 // Other user still have this package installed, so all 10877 // we need to do is clear this user's data and save that 10878 // it is uninstalled. 10879 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 10880 removeUser = user.getIdentifier(); 10881 appId = ps.appId; 10882 mSettings.writePackageRestrictionsLPr(removeUser); 10883 } else { 10884 // We need to set it back to 'installed' so the uninstall 10885 // broadcasts will be sent correctly. 10886 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 10887 ps.setInstalled(true, user.getIdentifier()); 10888 } 10889 } else { 10890 // This is a system app, so we assume that the 10891 // other users still have this package installed, so all 10892 // we need to do is clear this user's data and save that 10893 // it is uninstalled. 10894 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 10895 removeUser = user.getIdentifier(); 10896 appId = ps.appId; 10897 mSettings.writePackageRestrictionsLPr(removeUser); 10898 } 10899 } 10900 } 10901 10902 if (removeUser >= 0) { 10903 // From above, we determined that we are deleting this only 10904 // for a single user. Continue the work here. 10905 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 10906 if (outInfo != null) { 10907 outInfo.removedPackage = packageName; 10908 outInfo.removedAppId = appId; 10909 outInfo.removedUsers = new int[] {removeUser}; 10910 } 10911 mInstaller.clearUserData(packageName, removeUser); 10912 removeKeystoreDataIfNeeded(removeUser, appId); 10913 schedulePackageCleaning(packageName, removeUser, false); 10914 return true; 10915 } 10916 10917 if (dataOnly) { 10918 // Delete application data first 10919 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 10920 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 10921 return true; 10922 } 10923 10924 boolean ret = false; 10925 if (isSystemApp(ps)) { 10926 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 10927 // When an updated system application is deleted we delete the existing resources as well and 10928 // fall back to existing code in system partition 10929 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 10930 flags, outInfo, writeSettings); 10931 } else { 10932 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 10933 // Kill application pre-emptively especially for apps on sd. 10934 killApplication(packageName, ps.appId, "uninstall pkg"); 10935 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 10936 allUserHandles, perUserInstalled, 10937 outInfo, writeSettings); 10938 } 10939 10940 return ret; 10941 } 10942 10943 private final class ClearStorageConnection implements ServiceConnection { 10944 IMediaContainerService mContainerService; 10945 10946 @Override 10947 public void onServiceConnected(ComponentName name, IBinder service) { 10948 synchronized (this) { 10949 mContainerService = IMediaContainerService.Stub.asInterface(service); 10950 notifyAll(); 10951 } 10952 } 10953 10954 @Override 10955 public void onServiceDisconnected(ComponentName name) { 10956 } 10957 } 10958 10959 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 10960 final boolean mounted; 10961 if (Environment.isExternalStorageEmulated()) { 10962 mounted = true; 10963 } else { 10964 final String status = Environment.getExternalStorageState(); 10965 10966 mounted = status.equals(Environment.MEDIA_MOUNTED) 10967 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 10968 } 10969 10970 if (!mounted) { 10971 return; 10972 } 10973 10974 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 10975 int[] users; 10976 if (userId == UserHandle.USER_ALL) { 10977 users = sUserManager.getUserIds(); 10978 } else { 10979 users = new int[] { userId }; 10980 } 10981 final ClearStorageConnection conn = new ClearStorageConnection(); 10982 if (mContext.bindServiceAsUser( 10983 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 10984 try { 10985 for (int curUser : users) { 10986 long timeout = SystemClock.uptimeMillis() + 5000; 10987 synchronized (conn) { 10988 long now = SystemClock.uptimeMillis(); 10989 while (conn.mContainerService == null && now < timeout) { 10990 try { 10991 conn.wait(timeout - now); 10992 } catch (InterruptedException e) { 10993 } 10994 } 10995 } 10996 if (conn.mContainerService == null) { 10997 return; 10998 } 10999 11000 final UserEnvironment userEnv = new UserEnvironment(curUser); 11001 clearDirectory(conn.mContainerService, 11002 userEnv.buildExternalStorageAppCacheDirs(packageName)); 11003 if (allData) { 11004 clearDirectory(conn.mContainerService, 11005 userEnv.buildExternalStorageAppDataDirs(packageName)); 11006 clearDirectory(conn.mContainerService, 11007 userEnv.buildExternalStorageAppMediaDirs(packageName)); 11008 } 11009 } 11010 } finally { 11011 mContext.unbindService(conn); 11012 } 11013 } 11014 } 11015 11016 @Override 11017 public void clearApplicationUserData(final String packageName, 11018 final IPackageDataObserver observer, final int userId) { 11019 mContext.enforceCallingOrSelfPermission( 11020 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 11021 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 11022 // Queue up an async operation since the package deletion may take a little while. 11023 mHandler.post(new Runnable() { 11024 public void run() { 11025 mHandler.removeCallbacks(this); 11026 final boolean succeeded; 11027 synchronized (mInstallLock) { 11028 succeeded = clearApplicationUserDataLI(packageName, userId); 11029 } 11030 clearExternalStorageDataSync(packageName, userId, true); 11031 if (succeeded) { 11032 // invoke DeviceStorageMonitor's update method to clear any notifications 11033 DeviceStorageMonitorInternal 11034 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 11035 if (dsm != null) { 11036 dsm.checkMemory(); 11037 } 11038 } 11039 if(observer != null) { 11040 try { 11041 observer.onRemoveCompleted(packageName, succeeded); 11042 } catch (RemoteException e) { 11043 Log.i(TAG, "Observer no longer exists."); 11044 } 11045 } //end if observer 11046 } //end run 11047 }); 11048 } 11049 11050 private boolean clearApplicationUserDataLI(String packageName, int userId) { 11051 if (packageName == null) { 11052 Slog.w(TAG, "Attempt to delete null packageName."); 11053 return false; 11054 } 11055 11056 // Try finding details about the requested package 11057 PackageParser.Package pkg; 11058 synchronized (mPackages) { 11059 pkg = mPackages.get(packageName); 11060 if (pkg == null) { 11061 final PackageSetting ps = mSettings.mPackages.get(packageName); 11062 if (ps != null) { 11063 pkg = ps.pkg; 11064 } 11065 } 11066 } 11067 11068 if (pkg == null) { 11069 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11070 } 11071 11072 // Always delete data directories for package, even if we found no other 11073 // record of app. This helps users recover from UID mismatches without 11074 // resorting to a full data wipe. 11075 int retCode = mInstaller.clearUserData(packageName, userId); 11076 if (retCode < 0) { 11077 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 11078 return false; 11079 } 11080 11081 if (pkg == null) { 11082 return false; 11083 } 11084 11085 if (pkg != null && pkg.applicationInfo != null) { 11086 final int appId = pkg.applicationInfo.uid; 11087 removeKeystoreDataIfNeeded(userId, appId); 11088 } 11089 11090 // Create a native library symlink only if we have native libraries 11091 // and if the native libraries are 32 bit libraries. We do not provide 11092 // this symlink for 64 bit libraries. 11093 if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null && 11094 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 11095 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 11096 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 11097 Slog.w(TAG, "Failed linking native library dir"); 11098 return false; 11099 } 11100 } 11101 11102 return true; 11103 } 11104 11105 /** 11106 * Remove entries from the keystore daemon. Will only remove it if the 11107 * {@code appId} is valid. 11108 */ 11109 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 11110 if (appId < 0) { 11111 return; 11112 } 11113 11114 final KeyStore keyStore = KeyStore.getInstance(); 11115 if (keyStore != null) { 11116 if (userId == UserHandle.USER_ALL) { 11117 for (final int individual : sUserManager.getUserIds()) { 11118 keyStore.clearUid(UserHandle.getUid(individual, appId)); 11119 } 11120 } else { 11121 keyStore.clearUid(UserHandle.getUid(userId, appId)); 11122 } 11123 } else { 11124 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 11125 } 11126 } 11127 11128 @Override 11129 public void deleteApplicationCacheFiles(final String packageName, 11130 final IPackageDataObserver observer) { 11131 mContext.enforceCallingOrSelfPermission( 11132 android.Manifest.permission.DELETE_CACHE_FILES, null); 11133 // Queue up an async operation since the package deletion may take a little while. 11134 final int userId = UserHandle.getCallingUserId(); 11135 mHandler.post(new Runnable() { 11136 public void run() { 11137 mHandler.removeCallbacks(this); 11138 final boolean succeded; 11139 synchronized (mInstallLock) { 11140 succeded = deleteApplicationCacheFilesLI(packageName, userId); 11141 } 11142 clearExternalStorageDataSync(packageName, userId, false); 11143 if(observer != null) { 11144 try { 11145 observer.onRemoveCompleted(packageName, succeded); 11146 } catch (RemoteException e) { 11147 Log.i(TAG, "Observer no longer exists."); 11148 } 11149 } //end if observer 11150 } //end run 11151 }); 11152 } 11153 11154 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 11155 if (packageName == null) { 11156 Slog.w(TAG, "Attempt to delete null packageName."); 11157 return false; 11158 } 11159 PackageParser.Package p; 11160 synchronized (mPackages) { 11161 p = mPackages.get(packageName); 11162 } 11163 if (p == null) { 11164 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11165 return false; 11166 } 11167 final ApplicationInfo applicationInfo = p.applicationInfo; 11168 if (applicationInfo == null) { 11169 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11170 return false; 11171 } 11172 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 11173 if (retCode < 0) { 11174 Slog.w(TAG, "Couldn't remove cache files for package: " 11175 + packageName + " u" + userId); 11176 return false; 11177 } 11178 return true; 11179 } 11180 11181 @Override 11182 public void getPackageSizeInfo(final String packageName, int userHandle, 11183 final IPackageStatsObserver observer) { 11184 mContext.enforceCallingOrSelfPermission( 11185 android.Manifest.permission.GET_PACKAGE_SIZE, null); 11186 if (packageName == null) { 11187 throw new IllegalArgumentException("Attempt to get size of null packageName"); 11188 } 11189 11190 PackageStats stats = new PackageStats(packageName, userHandle); 11191 11192 /* 11193 * Queue up an async operation since the package measurement may take a 11194 * little while. 11195 */ 11196 Message msg = mHandler.obtainMessage(INIT_COPY); 11197 msg.obj = new MeasureParams(stats, observer); 11198 mHandler.sendMessage(msg); 11199 } 11200 11201 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 11202 PackageStats pStats) { 11203 if (packageName == null) { 11204 Slog.w(TAG, "Attempt to get size of null packageName."); 11205 return false; 11206 } 11207 PackageParser.Package p; 11208 boolean dataOnly = false; 11209 String libDirRoot = null; 11210 String asecPath = null; 11211 PackageSetting ps = null; 11212 synchronized (mPackages) { 11213 p = mPackages.get(packageName); 11214 ps = mSettings.mPackages.get(packageName); 11215 if(p == null) { 11216 dataOnly = true; 11217 if((ps == null) || (ps.pkg == null)) { 11218 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11219 return false; 11220 } 11221 p = ps.pkg; 11222 } 11223 if (ps != null) { 11224 libDirRoot = ps.legacyNativeLibraryPathString; 11225 } 11226 if (p != null && (isExternal(p) || isForwardLocked(p))) { 11227 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 11228 if (secureContainerId != null) { 11229 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 11230 } 11231 } 11232 } 11233 String publicSrcDir = null; 11234 if(!dataOnly) { 11235 final ApplicationInfo applicationInfo = p.applicationInfo; 11236 if (applicationInfo == null) { 11237 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11238 return false; 11239 } 11240 if (isForwardLocked(p)) { 11241 publicSrcDir = applicationInfo.getBaseResourcePath(); 11242 } 11243 } 11244 // TODO: extend to measure size of split APKs 11245 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 11246 // not just the first level. 11247 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 11248 // just the primary. 11249 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 11250 int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot, 11251 publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 11252 if (res < 0) { 11253 return false; 11254 } 11255 11256 // Fix-up for forward-locked applications in ASEC containers. 11257 if (!isExternal(p)) { 11258 pStats.codeSize += pStats.externalCodeSize; 11259 pStats.externalCodeSize = 0L; 11260 } 11261 11262 return true; 11263 } 11264 11265 11266 @Override 11267 public void addPackageToPreferred(String packageName) { 11268 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 11269 } 11270 11271 @Override 11272 public void removePackageFromPreferred(String packageName) { 11273 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 11274 } 11275 11276 @Override 11277 public List<PackageInfo> getPreferredPackages(int flags) { 11278 return new ArrayList<PackageInfo>(); 11279 } 11280 11281 private int getUidTargetSdkVersionLockedLPr(int uid) { 11282 Object obj = mSettings.getUserIdLPr(uid); 11283 if (obj instanceof SharedUserSetting) { 11284 final SharedUserSetting sus = (SharedUserSetting) obj; 11285 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 11286 final Iterator<PackageSetting> it = sus.packages.iterator(); 11287 while (it.hasNext()) { 11288 final PackageSetting ps = it.next(); 11289 if (ps.pkg != null) { 11290 int v = ps.pkg.applicationInfo.targetSdkVersion; 11291 if (v < vers) vers = v; 11292 } 11293 } 11294 return vers; 11295 } else if (obj instanceof PackageSetting) { 11296 final PackageSetting ps = (PackageSetting) obj; 11297 if (ps.pkg != null) { 11298 return ps.pkg.applicationInfo.targetSdkVersion; 11299 } 11300 } 11301 return Build.VERSION_CODES.CUR_DEVELOPMENT; 11302 } 11303 11304 @Override 11305 public void addPreferredActivity(IntentFilter filter, int match, 11306 ComponentName[] set, ComponentName activity, int userId) { 11307 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11308 "Adding preferred"); 11309 } 11310 11311 private void addPreferredActivityInternal(IntentFilter filter, int match, 11312 ComponentName[] set, ComponentName activity, boolean always, int userId, 11313 String opname) { 11314 // writer 11315 int callingUid = Binder.getCallingUid(); 11316 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 11317 if (filter.countActions() == 0) { 11318 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11319 return; 11320 } 11321 synchronized (mPackages) { 11322 if (mContext.checkCallingOrSelfPermission( 11323 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11324 != PackageManager.PERMISSION_GRANTED) { 11325 if (getUidTargetSdkVersionLockedLPr(callingUid) 11326 < Build.VERSION_CODES.FROYO) { 11327 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 11328 + callingUid); 11329 return; 11330 } 11331 mContext.enforceCallingOrSelfPermission( 11332 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11333 } 11334 11335 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 11336 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 11337 + userId + ":"); 11338 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11339 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 11340 mSettings.writePackageRestrictionsLPr(userId); 11341 } 11342 } 11343 11344 @Override 11345 public void replacePreferredActivity(IntentFilter filter, int match, 11346 ComponentName[] set, ComponentName activity, int userId) { 11347 if (filter.countActions() != 1) { 11348 throw new IllegalArgumentException( 11349 "replacePreferredActivity expects filter to have only 1 action."); 11350 } 11351 if (filter.countDataAuthorities() != 0 11352 || filter.countDataPaths() != 0 11353 || filter.countDataSchemes() > 1 11354 || filter.countDataTypes() != 0) { 11355 throw new IllegalArgumentException( 11356 "replacePreferredActivity expects filter to have no data authorities, " + 11357 "paths, or types; and at most one scheme."); 11358 } 11359 11360 final int callingUid = Binder.getCallingUid(); 11361 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 11362 synchronized (mPackages) { 11363 if (mContext.checkCallingOrSelfPermission( 11364 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11365 != PackageManager.PERMISSION_GRANTED) { 11366 if (getUidTargetSdkVersionLockedLPr(callingUid) 11367 < Build.VERSION_CODES.FROYO) { 11368 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 11369 + Binder.getCallingUid()); 11370 return; 11371 } 11372 mContext.enforceCallingOrSelfPermission( 11373 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11374 } 11375 11376 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11377 if (pir != null) { 11378 // Get all of the existing entries that exactly match this filter. 11379 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 11380 if (existing != null && existing.size() == 1) { 11381 PreferredActivity cur = existing.get(0); 11382 if (DEBUG_PREFERRED) { 11383 Slog.i(TAG, "Checking replace of preferred:"); 11384 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11385 if (!cur.mPref.mAlways) { 11386 Slog.i(TAG, " -- CUR; not mAlways!"); 11387 } else { 11388 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 11389 Slog.i(TAG, " -- CUR: mSet=" 11390 + Arrays.toString(cur.mPref.mSetComponents)); 11391 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 11392 Slog.i(TAG, " -- NEW: mMatch=" 11393 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 11394 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 11395 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 11396 } 11397 } 11398 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 11399 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 11400 && cur.mPref.sameSet(set)) { 11401 // Setting the preferred activity to what it happens to be already 11402 if (DEBUG_PREFERRED) { 11403 Slog.i(TAG, "Replacing with same preferred activity " 11404 + cur.mPref.mShortComponent + " for user " 11405 + userId + ":"); 11406 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11407 } 11408 return; 11409 } 11410 } 11411 11412 if (existing != null) { 11413 if (DEBUG_PREFERRED) { 11414 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 11415 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11416 } 11417 for (int i = 0; i < existing.size(); i++) { 11418 PreferredActivity pa = existing.get(i); 11419 if (DEBUG_PREFERRED) { 11420 Slog.i(TAG, "Removing existing preferred activity " 11421 + pa.mPref.mComponent + ":"); 11422 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 11423 } 11424 pir.removeFilter(pa); 11425 } 11426 } 11427 } 11428 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11429 "Replacing preferred"); 11430 } 11431 } 11432 11433 @Override 11434 public void clearPackagePreferredActivities(String packageName) { 11435 final int uid = Binder.getCallingUid(); 11436 // writer 11437 synchronized (mPackages) { 11438 PackageParser.Package pkg = mPackages.get(packageName); 11439 if (pkg == null || pkg.applicationInfo.uid != uid) { 11440 if (mContext.checkCallingOrSelfPermission( 11441 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11442 != PackageManager.PERMISSION_GRANTED) { 11443 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11444 < Build.VERSION_CODES.FROYO) { 11445 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 11446 + Binder.getCallingUid()); 11447 return; 11448 } 11449 mContext.enforceCallingOrSelfPermission( 11450 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11451 } 11452 } 11453 11454 int user = UserHandle.getCallingUserId(); 11455 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 11456 mSettings.writePackageRestrictionsLPr(user); 11457 scheduleWriteSettingsLocked(); 11458 } 11459 } 11460 } 11461 11462 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 11463 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 11464 ArrayList<PreferredActivity> removed = null; 11465 boolean changed = false; 11466 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11467 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 11468 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11469 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 11470 continue; 11471 } 11472 Iterator<PreferredActivity> it = pir.filterIterator(); 11473 while (it.hasNext()) { 11474 PreferredActivity pa = it.next(); 11475 // Mark entry for removal only if it matches the package name 11476 // and the entry is of type "always". 11477 if (packageName == null || 11478 (pa.mPref.mComponent.getPackageName().equals(packageName) 11479 && pa.mPref.mAlways)) { 11480 if (removed == null) { 11481 removed = new ArrayList<PreferredActivity>(); 11482 } 11483 removed.add(pa); 11484 } 11485 } 11486 if (removed != null) { 11487 for (int j=0; j<removed.size(); j++) { 11488 PreferredActivity pa = removed.get(j); 11489 pir.removeFilter(pa); 11490 } 11491 changed = true; 11492 } 11493 } 11494 return changed; 11495 } 11496 11497 @Override 11498 public void resetPreferredActivities(int userId) { 11499 /* TODO: Actually use userId. Why is it being passed in? */ 11500 mContext.enforceCallingOrSelfPermission( 11501 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11502 // writer 11503 synchronized (mPackages) { 11504 int user = UserHandle.getCallingUserId(); 11505 clearPackagePreferredActivitiesLPw(null, user); 11506 mSettings.readDefaultPreferredAppsLPw(this, user); 11507 mSettings.writePackageRestrictionsLPr(user); 11508 scheduleWriteSettingsLocked(); 11509 } 11510 } 11511 11512 @Override 11513 public int getPreferredActivities(List<IntentFilter> outFilters, 11514 List<ComponentName> outActivities, String packageName) { 11515 11516 int num = 0; 11517 final int userId = UserHandle.getCallingUserId(); 11518 // reader 11519 synchronized (mPackages) { 11520 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11521 if (pir != null) { 11522 final Iterator<PreferredActivity> it = pir.filterIterator(); 11523 while (it.hasNext()) { 11524 final PreferredActivity pa = it.next(); 11525 if (packageName == null 11526 || (pa.mPref.mComponent.getPackageName().equals(packageName) 11527 && pa.mPref.mAlways)) { 11528 if (outFilters != null) { 11529 outFilters.add(new IntentFilter(pa)); 11530 } 11531 if (outActivities != null) { 11532 outActivities.add(pa.mPref.mComponent); 11533 } 11534 } 11535 } 11536 } 11537 } 11538 11539 return num; 11540 } 11541 11542 @Override 11543 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 11544 int userId) { 11545 int callingUid = Binder.getCallingUid(); 11546 if (callingUid != Process.SYSTEM_UID) { 11547 throw new SecurityException( 11548 "addPersistentPreferredActivity can only be run by the system"); 11549 } 11550 if (filter.countActions() == 0) { 11551 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11552 return; 11553 } 11554 synchronized (mPackages) { 11555 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 11556 " :"); 11557 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11558 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 11559 new PersistentPreferredActivity(filter, activity)); 11560 mSettings.writePackageRestrictionsLPr(userId); 11561 } 11562 } 11563 11564 @Override 11565 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 11566 int callingUid = Binder.getCallingUid(); 11567 if (callingUid != Process.SYSTEM_UID) { 11568 throw new SecurityException( 11569 "clearPackagePersistentPreferredActivities can only be run by the system"); 11570 } 11571 ArrayList<PersistentPreferredActivity> removed = null; 11572 boolean changed = false; 11573 synchronized (mPackages) { 11574 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 11575 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 11576 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 11577 .valueAt(i); 11578 if (userId != thisUserId) { 11579 continue; 11580 } 11581 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 11582 while (it.hasNext()) { 11583 PersistentPreferredActivity ppa = it.next(); 11584 // Mark entry for removal only if it matches the package name. 11585 if (ppa.mComponent.getPackageName().equals(packageName)) { 11586 if (removed == null) { 11587 removed = new ArrayList<PersistentPreferredActivity>(); 11588 } 11589 removed.add(ppa); 11590 } 11591 } 11592 if (removed != null) { 11593 for (int j=0; j<removed.size(); j++) { 11594 PersistentPreferredActivity ppa = removed.get(j); 11595 ppir.removeFilter(ppa); 11596 } 11597 changed = true; 11598 } 11599 } 11600 11601 if (changed) { 11602 mSettings.writePackageRestrictionsLPr(userId); 11603 } 11604 } 11605 } 11606 11607 @Override 11608 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 11609 int ownerUserId, int sourceUserId, int targetUserId, int flags) { 11610 mContext.enforceCallingOrSelfPermission( 11611 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11612 int callingUid = Binder.getCallingUid(); 11613 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11614 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 11615 if (intentFilter.countActions() == 0) { 11616 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 11617 return; 11618 } 11619 synchronized (mPackages) { 11620 CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter, 11621 ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags); 11622 mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter); 11623 mSettings.writePackageRestrictionsLPr(sourceUserId); 11624 } 11625 } 11626 11627 @Override 11628 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage, 11629 int ownerUserId) { 11630 mContext.enforceCallingOrSelfPermission( 11631 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11632 int callingUid = Binder.getCallingUid(); 11633 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11634 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 11635 int callingUserId = UserHandle.getUserId(callingUid); 11636 synchronized (mPackages) { 11637 CrossProfileIntentResolver resolver = 11638 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11639 HashSet<CrossProfileIntentFilter> set = 11640 new HashSet<CrossProfileIntentFilter>(resolver.filterSet()); 11641 for (CrossProfileIntentFilter filter : set) { 11642 if (filter.getOwnerPackage().equals(ownerPackage) 11643 && filter.getOwnerUserId() == callingUserId) { 11644 resolver.removeFilter(filter); 11645 } 11646 } 11647 mSettings.writePackageRestrictionsLPr(sourceUserId); 11648 } 11649 } 11650 11651 // Enforcing that callingUid is owning pkg on userId 11652 private void enforceOwnerRights(String pkg, int userId, int callingUid) { 11653 // The system owns everything. 11654 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 11655 return; 11656 } 11657 int callingUserId = UserHandle.getUserId(callingUid); 11658 if (callingUserId != userId) { 11659 throw new SecurityException("calling uid " + callingUid 11660 + " pretends to own " + pkg + " on user " + userId + " but belongs to user " 11661 + callingUserId); 11662 } 11663 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 11664 if (pi == null) { 11665 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 11666 + callingUserId); 11667 } 11668 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 11669 throw new SecurityException("Calling uid " + callingUid 11670 + " does not own package " + pkg); 11671 } 11672 } 11673 11674 @Override 11675 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 11676 Intent intent = new Intent(Intent.ACTION_MAIN); 11677 intent.addCategory(Intent.CATEGORY_HOME); 11678 11679 final int callingUserId = UserHandle.getCallingUserId(); 11680 List<ResolveInfo> list = queryIntentActivities(intent, null, 11681 PackageManager.GET_META_DATA, callingUserId); 11682 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 11683 true, false, false, callingUserId); 11684 11685 allHomeCandidates.clear(); 11686 if (list != null) { 11687 for (ResolveInfo ri : list) { 11688 allHomeCandidates.add(ri); 11689 } 11690 } 11691 return (preferred == null || preferred.activityInfo == null) 11692 ? null 11693 : new ComponentName(preferred.activityInfo.packageName, 11694 preferred.activityInfo.name); 11695 } 11696 11697 @Override 11698 public void setApplicationEnabledSetting(String appPackageName, 11699 int newState, int flags, int userId, String callingPackage) { 11700 if (!sUserManager.exists(userId)) return; 11701 if (callingPackage == null) { 11702 callingPackage = Integer.toString(Binder.getCallingUid()); 11703 } 11704 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 11705 } 11706 11707 @Override 11708 public void setComponentEnabledSetting(ComponentName componentName, 11709 int newState, int flags, int userId) { 11710 if (!sUserManager.exists(userId)) return; 11711 setEnabledSetting(componentName.getPackageName(), 11712 componentName.getClassName(), newState, flags, userId, null); 11713 } 11714 11715 private void setEnabledSetting(final String packageName, String className, int newState, 11716 final int flags, int userId, String callingPackage) { 11717 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 11718 || newState == COMPONENT_ENABLED_STATE_ENABLED 11719 || newState == COMPONENT_ENABLED_STATE_DISABLED 11720 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 11721 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 11722 throw new IllegalArgumentException("Invalid new component state: " 11723 + newState); 11724 } 11725 PackageSetting pkgSetting; 11726 final int uid = Binder.getCallingUid(); 11727 final int permission = mContext.checkCallingOrSelfPermission( 11728 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11729 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 11730 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11731 boolean sendNow = false; 11732 boolean isApp = (className == null); 11733 String componentName = isApp ? packageName : className; 11734 int packageUid = -1; 11735 ArrayList<String> components; 11736 11737 // writer 11738 synchronized (mPackages) { 11739 pkgSetting = mSettings.mPackages.get(packageName); 11740 if (pkgSetting == null) { 11741 if (className == null) { 11742 throw new IllegalArgumentException( 11743 "Unknown package: " + packageName); 11744 } 11745 throw new IllegalArgumentException( 11746 "Unknown component: " + packageName 11747 + "/" + className); 11748 } 11749 // Allow root and verify that userId is not being specified by a different user 11750 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 11751 throw new SecurityException( 11752 "Permission Denial: attempt to change component state from pid=" 11753 + Binder.getCallingPid() 11754 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 11755 } 11756 if (className == null) { 11757 // We're dealing with an application/package level state change 11758 if (pkgSetting.getEnabled(userId) == newState) { 11759 // Nothing to do 11760 return; 11761 } 11762 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 11763 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 11764 // Don't care about who enables an app. 11765 callingPackage = null; 11766 } 11767 pkgSetting.setEnabled(newState, userId, callingPackage); 11768 // pkgSetting.pkg.mSetEnabled = newState; 11769 } else { 11770 // We're dealing with a component level state change 11771 // First, verify that this is a valid class name. 11772 PackageParser.Package pkg = pkgSetting.pkg; 11773 if (pkg == null || !pkg.hasComponentClassName(className)) { 11774 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 11775 throw new IllegalArgumentException("Component class " + className 11776 + " does not exist in " + packageName); 11777 } else { 11778 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 11779 + className + " does not exist in " + packageName); 11780 } 11781 } 11782 switch (newState) { 11783 case COMPONENT_ENABLED_STATE_ENABLED: 11784 if (!pkgSetting.enableComponentLPw(className, userId)) { 11785 return; 11786 } 11787 break; 11788 case COMPONENT_ENABLED_STATE_DISABLED: 11789 if (!pkgSetting.disableComponentLPw(className, userId)) { 11790 return; 11791 } 11792 break; 11793 case COMPONENT_ENABLED_STATE_DEFAULT: 11794 if (!pkgSetting.restoreComponentLPw(className, userId)) { 11795 return; 11796 } 11797 break; 11798 default: 11799 Slog.e(TAG, "Invalid new component state: " + newState); 11800 return; 11801 } 11802 } 11803 mSettings.writePackageRestrictionsLPr(userId); 11804 components = mPendingBroadcasts.get(userId, packageName); 11805 final boolean newPackage = components == null; 11806 if (newPackage) { 11807 components = new ArrayList<String>(); 11808 } 11809 if (!components.contains(componentName)) { 11810 components.add(componentName); 11811 } 11812 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 11813 sendNow = true; 11814 // Purge entry from pending broadcast list if another one exists already 11815 // since we are sending one right away. 11816 mPendingBroadcasts.remove(userId, packageName); 11817 } else { 11818 if (newPackage) { 11819 mPendingBroadcasts.put(userId, packageName, components); 11820 } 11821 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 11822 // Schedule a message 11823 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 11824 } 11825 } 11826 } 11827 11828 long callingId = Binder.clearCallingIdentity(); 11829 try { 11830 if (sendNow) { 11831 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 11832 sendPackageChangedBroadcast(packageName, 11833 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 11834 } 11835 } finally { 11836 Binder.restoreCallingIdentity(callingId); 11837 } 11838 } 11839 11840 private void sendPackageChangedBroadcast(String packageName, 11841 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 11842 if (DEBUG_INSTALL) 11843 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 11844 + componentNames); 11845 Bundle extras = new Bundle(4); 11846 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 11847 String nameList[] = new String[componentNames.size()]; 11848 componentNames.toArray(nameList); 11849 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 11850 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 11851 extras.putInt(Intent.EXTRA_UID, packageUid); 11852 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 11853 new int[] {UserHandle.getUserId(packageUid)}); 11854 } 11855 11856 @Override 11857 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 11858 if (!sUserManager.exists(userId)) return; 11859 final int uid = Binder.getCallingUid(); 11860 final int permission = mContext.checkCallingOrSelfPermission( 11861 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11862 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11863 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 11864 // writer 11865 synchronized (mPackages) { 11866 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 11867 uid, userId)) { 11868 scheduleWritePackageRestrictionsLocked(userId); 11869 } 11870 } 11871 } 11872 11873 @Override 11874 public String getInstallerPackageName(String packageName) { 11875 // reader 11876 synchronized (mPackages) { 11877 return mSettings.getInstallerPackageNameLPr(packageName); 11878 } 11879 } 11880 11881 @Override 11882 public int getApplicationEnabledSetting(String packageName, int userId) { 11883 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11884 int uid = Binder.getCallingUid(); 11885 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 11886 // reader 11887 synchronized (mPackages) { 11888 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 11889 } 11890 } 11891 11892 @Override 11893 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 11894 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11895 int uid = Binder.getCallingUid(); 11896 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 11897 // reader 11898 synchronized (mPackages) { 11899 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 11900 } 11901 } 11902 11903 @Override 11904 public void enterSafeMode() { 11905 enforceSystemOrRoot("Only the system can request entering safe mode"); 11906 11907 if (!mSystemReady) { 11908 mSafeMode = true; 11909 } 11910 } 11911 11912 @Override 11913 public void systemReady() { 11914 mSystemReady = true; 11915 11916 // Read the compatibilty setting when the system is ready. 11917 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 11918 mContext.getContentResolver(), 11919 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 11920 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 11921 if (DEBUG_SETTINGS) { 11922 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 11923 } 11924 11925 synchronized (mPackages) { 11926 // Verify that all of the preferred activity components actually 11927 // exist. It is possible for applications to be updated and at 11928 // that point remove a previously declared activity component that 11929 // had been set as a preferred activity. We try to clean this up 11930 // the next time we encounter that preferred activity, but it is 11931 // possible for the user flow to never be able to return to that 11932 // situation so here we do a sanity check to make sure we haven't 11933 // left any junk around. 11934 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 11935 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11936 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11937 removed.clear(); 11938 for (PreferredActivity pa : pir.filterSet()) { 11939 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 11940 removed.add(pa); 11941 } 11942 } 11943 if (removed.size() > 0) { 11944 for (int r=0; r<removed.size(); r++) { 11945 PreferredActivity pa = removed.get(r); 11946 Slog.w(TAG, "Removing dangling preferred activity: " 11947 + pa.mPref.mComponent); 11948 pir.removeFilter(pa); 11949 } 11950 mSettings.writePackageRestrictionsLPr( 11951 mSettings.mPreferredActivities.keyAt(i)); 11952 } 11953 } 11954 } 11955 sUserManager.systemReady(); 11956 11957 // Kick off any messages waiting for system ready 11958 if (mPostSystemReadyMessages != null) { 11959 for (Message msg : mPostSystemReadyMessages) { 11960 msg.sendToTarget(); 11961 } 11962 mPostSystemReadyMessages = null; 11963 } 11964 } 11965 11966 @Override 11967 public boolean isSafeMode() { 11968 return mSafeMode; 11969 } 11970 11971 @Override 11972 public boolean hasSystemUidErrors() { 11973 return mHasSystemUidErrors; 11974 } 11975 11976 static String arrayToString(int[] array) { 11977 StringBuffer buf = new StringBuffer(128); 11978 buf.append('['); 11979 if (array != null) { 11980 for (int i=0; i<array.length; i++) { 11981 if (i > 0) buf.append(", "); 11982 buf.append(array[i]); 11983 } 11984 } 11985 buf.append(']'); 11986 return buf.toString(); 11987 } 11988 11989 static class DumpState { 11990 public static final int DUMP_LIBS = 1 << 0; 11991 public static final int DUMP_FEATURES = 1 << 1; 11992 public static final int DUMP_RESOLVERS = 1 << 2; 11993 public static final int DUMP_PERMISSIONS = 1 << 3; 11994 public static final int DUMP_PACKAGES = 1 << 4; 11995 public static final int DUMP_SHARED_USERS = 1 << 5; 11996 public static final int DUMP_MESSAGES = 1 << 6; 11997 public static final int DUMP_PROVIDERS = 1 << 7; 11998 public static final int DUMP_VERIFIERS = 1 << 8; 11999 public static final int DUMP_PREFERRED = 1 << 9; 12000 public static final int DUMP_PREFERRED_XML = 1 << 10; 12001 public static final int DUMP_KEYSETS = 1 << 11; 12002 public static final int DUMP_VERSION = 1 << 12; 12003 public static final int DUMP_INSTALLS = 1 << 13; 12004 12005 public static final int OPTION_SHOW_FILTERS = 1 << 0; 12006 12007 private int mTypes; 12008 12009 private int mOptions; 12010 12011 private boolean mTitlePrinted; 12012 12013 private SharedUserSetting mSharedUser; 12014 12015 public boolean isDumping(int type) { 12016 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 12017 return true; 12018 } 12019 12020 return (mTypes & type) != 0; 12021 } 12022 12023 public void setDump(int type) { 12024 mTypes |= type; 12025 } 12026 12027 public boolean isOptionEnabled(int option) { 12028 return (mOptions & option) != 0; 12029 } 12030 12031 public void setOptionEnabled(int option) { 12032 mOptions |= option; 12033 } 12034 12035 public boolean onTitlePrinted() { 12036 final boolean printed = mTitlePrinted; 12037 mTitlePrinted = true; 12038 return printed; 12039 } 12040 12041 public boolean getTitlePrinted() { 12042 return mTitlePrinted; 12043 } 12044 12045 public void setTitlePrinted(boolean enabled) { 12046 mTitlePrinted = enabled; 12047 } 12048 12049 public SharedUserSetting getSharedUser() { 12050 return mSharedUser; 12051 } 12052 12053 public void setSharedUser(SharedUserSetting user) { 12054 mSharedUser = user; 12055 } 12056 } 12057 12058 @Override 12059 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 12060 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 12061 != PackageManager.PERMISSION_GRANTED) { 12062 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 12063 + Binder.getCallingPid() 12064 + ", uid=" + Binder.getCallingUid() 12065 + " without permission " 12066 + android.Manifest.permission.DUMP); 12067 return; 12068 } 12069 12070 DumpState dumpState = new DumpState(); 12071 boolean fullPreferred = false; 12072 boolean checkin = false; 12073 12074 String packageName = null; 12075 12076 int opti = 0; 12077 while (opti < args.length) { 12078 String opt = args[opti]; 12079 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 12080 break; 12081 } 12082 opti++; 12083 if ("-a".equals(opt)) { 12084 // Right now we only know how to print all. 12085 } else if ("-h".equals(opt)) { 12086 pw.println("Package manager dump options:"); 12087 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 12088 pw.println(" --checkin: dump for a checkin"); 12089 pw.println(" -f: print details of intent filters"); 12090 pw.println(" -h: print this help"); 12091 pw.println(" cmd may be one of:"); 12092 pw.println(" l[ibraries]: list known shared libraries"); 12093 pw.println(" f[ibraries]: list device features"); 12094 pw.println(" k[eysets]: print known keysets"); 12095 pw.println(" r[esolvers]: dump intent resolvers"); 12096 pw.println(" perm[issions]: dump permissions"); 12097 pw.println(" pref[erred]: print preferred package settings"); 12098 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 12099 pw.println(" prov[iders]: dump content providers"); 12100 pw.println(" p[ackages]: dump installed packages"); 12101 pw.println(" s[hared-users]: dump shared user IDs"); 12102 pw.println(" m[essages]: print collected runtime messages"); 12103 pw.println(" v[erifiers]: print package verifier info"); 12104 pw.println(" version: print database version info"); 12105 pw.println(" write: write current settings now"); 12106 pw.println(" <package.name>: info about given package"); 12107 pw.println(" installs: details about install sessions"); 12108 return; 12109 } else if ("--checkin".equals(opt)) { 12110 checkin = true; 12111 } else if ("-f".equals(opt)) { 12112 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12113 } else { 12114 pw.println("Unknown argument: " + opt + "; use -h for help"); 12115 } 12116 } 12117 12118 // Is the caller requesting to dump a particular piece of data? 12119 if (opti < args.length) { 12120 String cmd = args[opti]; 12121 opti++; 12122 // Is this a package name? 12123 if ("android".equals(cmd) || cmd.contains(".")) { 12124 packageName = cmd; 12125 // When dumping a single package, we always dump all of its 12126 // filter information since the amount of data will be reasonable. 12127 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12128 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 12129 dumpState.setDump(DumpState.DUMP_LIBS); 12130 } else if ("f".equals(cmd) || "features".equals(cmd)) { 12131 dumpState.setDump(DumpState.DUMP_FEATURES); 12132 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 12133 dumpState.setDump(DumpState.DUMP_RESOLVERS); 12134 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 12135 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 12136 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 12137 dumpState.setDump(DumpState.DUMP_PREFERRED); 12138 } else if ("preferred-xml".equals(cmd)) { 12139 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 12140 if (opti < args.length && "--full".equals(args[opti])) { 12141 fullPreferred = true; 12142 opti++; 12143 } 12144 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 12145 dumpState.setDump(DumpState.DUMP_PACKAGES); 12146 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 12147 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 12148 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 12149 dumpState.setDump(DumpState.DUMP_PROVIDERS); 12150 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 12151 dumpState.setDump(DumpState.DUMP_MESSAGES); 12152 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 12153 dumpState.setDump(DumpState.DUMP_VERIFIERS); 12154 } else if ("version".equals(cmd)) { 12155 dumpState.setDump(DumpState.DUMP_VERSION); 12156 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 12157 dumpState.setDump(DumpState.DUMP_KEYSETS); 12158 } else if ("installs".equals(cmd)) { 12159 dumpState.setDump(DumpState.DUMP_INSTALLS); 12160 } else if ("write".equals(cmd)) { 12161 synchronized (mPackages) { 12162 mSettings.writeLPr(); 12163 pw.println("Settings written."); 12164 return; 12165 } 12166 } 12167 } 12168 12169 if (checkin) { 12170 pw.println("vers,1"); 12171 } 12172 12173 // reader 12174 synchronized (mPackages) { 12175 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 12176 if (!checkin) { 12177 if (dumpState.onTitlePrinted()) 12178 pw.println(); 12179 pw.println("Database versions:"); 12180 pw.print(" SDK Version:"); 12181 pw.print(" internal="); 12182 pw.print(mSettings.mInternalSdkPlatform); 12183 pw.print(" external="); 12184 pw.println(mSettings.mExternalSdkPlatform); 12185 pw.print(" DB Version:"); 12186 pw.print(" internal="); 12187 pw.print(mSettings.mInternalDatabaseVersion); 12188 pw.print(" external="); 12189 pw.println(mSettings.mExternalDatabaseVersion); 12190 } 12191 } 12192 12193 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 12194 if (!checkin) { 12195 if (dumpState.onTitlePrinted()) 12196 pw.println(); 12197 pw.println("Verifiers:"); 12198 pw.print(" Required: "); 12199 pw.print(mRequiredVerifierPackage); 12200 pw.print(" (uid="); 12201 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 12202 pw.println(")"); 12203 } else if (mRequiredVerifierPackage != null) { 12204 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 12205 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 12206 } 12207 } 12208 12209 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 12210 boolean printedHeader = false; 12211 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 12212 while (it.hasNext()) { 12213 String name = it.next(); 12214 SharedLibraryEntry ent = mSharedLibraries.get(name); 12215 if (!checkin) { 12216 if (!printedHeader) { 12217 if (dumpState.onTitlePrinted()) 12218 pw.println(); 12219 pw.println("Libraries:"); 12220 printedHeader = true; 12221 } 12222 pw.print(" "); 12223 } else { 12224 pw.print("lib,"); 12225 } 12226 pw.print(name); 12227 if (!checkin) { 12228 pw.print(" -> "); 12229 } 12230 if (ent.path != null) { 12231 if (!checkin) { 12232 pw.print("(jar) "); 12233 pw.print(ent.path); 12234 } else { 12235 pw.print(",jar,"); 12236 pw.print(ent.path); 12237 } 12238 } else { 12239 if (!checkin) { 12240 pw.print("(apk) "); 12241 pw.print(ent.apk); 12242 } else { 12243 pw.print(",apk,"); 12244 pw.print(ent.apk); 12245 } 12246 } 12247 pw.println(); 12248 } 12249 } 12250 12251 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 12252 if (dumpState.onTitlePrinted()) 12253 pw.println(); 12254 if (!checkin) { 12255 pw.println("Features:"); 12256 } 12257 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 12258 while (it.hasNext()) { 12259 String name = it.next(); 12260 if (!checkin) { 12261 pw.print(" "); 12262 } else { 12263 pw.print("feat,"); 12264 } 12265 pw.println(name); 12266 } 12267 } 12268 12269 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 12270 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 12271 : "Activity Resolver Table:", " ", packageName, 12272 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12273 dumpState.setTitlePrinted(true); 12274 } 12275 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 12276 : "Receiver Resolver Table:", " ", packageName, 12277 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12278 dumpState.setTitlePrinted(true); 12279 } 12280 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 12281 : "Service Resolver Table:", " ", packageName, 12282 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12283 dumpState.setTitlePrinted(true); 12284 } 12285 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 12286 : "Provider Resolver Table:", " ", packageName, 12287 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12288 dumpState.setTitlePrinted(true); 12289 } 12290 } 12291 12292 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 12293 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12294 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12295 int user = mSettings.mPreferredActivities.keyAt(i); 12296 if (pir.dump(pw, 12297 dumpState.getTitlePrinted() 12298 ? "\nPreferred Activities User " + user + ":" 12299 : "Preferred Activities User " + user + ":", " ", 12300 packageName, true)) { 12301 dumpState.setTitlePrinted(true); 12302 } 12303 } 12304 } 12305 12306 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 12307 pw.flush(); 12308 FileOutputStream fout = new FileOutputStream(fd); 12309 BufferedOutputStream str = new BufferedOutputStream(fout); 12310 XmlSerializer serializer = new FastXmlSerializer(); 12311 try { 12312 serializer.setOutput(str, "utf-8"); 12313 serializer.startDocument(null, true); 12314 serializer.setFeature( 12315 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 12316 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 12317 serializer.endDocument(); 12318 serializer.flush(); 12319 } catch (IllegalArgumentException e) { 12320 pw.println("Failed writing: " + e); 12321 } catch (IllegalStateException e) { 12322 pw.println("Failed writing: " + e); 12323 } catch (IOException e) { 12324 pw.println("Failed writing: " + e); 12325 } 12326 } 12327 12328 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 12329 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 12330 if (packageName == null) { 12331 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 12332 if (iperm == 0) { 12333 if (dumpState.onTitlePrinted()) 12334 pw.println(); 12335 pw.println("AppOp Permissions:"); 12336 } 12337 pw.print(" AppOp Permission "); 12338 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 12339 pw.println(":"); 12340 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 12341 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 12342 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 12343 } 12344 } 12345 } 12346 } 12347 12348 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 12349 boolean printedSomething = false; 12350 for (PackageParser.Provider p : mProviders.mProviders.values()) { 12351 if (packageName != null && !packageName.equals(p.info.packageName)) { 12352 continue; 12353 } 12354 if (!printedSomething) { 12355 if (dumpState.onTitlePrinted()) 12356 pw.println(); 12357 pw.println("Registered ContentProviders:"); 12358 printedSomething = true; 12359 } 12360 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 12361 pw.print(" "); pw.println(p.toString()); 12362 } 12363 printedSomething = false; 12364 for (Map.Entry<String, PackageParser.Provider> entry : 12365 mProvidersByAuthority.entrySet()) { 12366 PackageParser.Provider p = entry.getValue(); 12367 if (packageName != null && !packageName.equals(p.info.packageName)) { 12368 continue; 12369 } 12370 if (!printedSomething) { 12371 if (dumpState.onTitlePrinted()) 12372 pw.println(); 12373 pw.println("ContentProvider Authorities:"); 12374 printedSomething = true; 12375 } 12376 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 12377 pw.print(" "); pw.println(p.toString()); 12378 if (p.info != null && p.info.applicationInfo != null) { 12379 final String appInfo = p.info.applicationInfo.toString(); 12380 pw.print(" applicationInfo="); pw.println(appInfo); 12381 } 12382 } 12383 } 12384 12385 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 12386 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 12387 } 12388 12389 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 12390 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 12391 } 12392 12393 if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 12394 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState); 12395 } 12396 12397 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 12398 // XXX should handle packageName != null by dumping only install data that 12399 // the given package is involved with. 12400 if (dumpState.onTitlePrinted()) pw.println(); 12401 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 12402 } 12403 12404 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 12405 if (dumpState.onTitlePrinted()) pw.println(); 12406 mSettings.dumpReadMessagesLPr(pw, dumpState); 12407 12408 pw.println(); 12409 pw.println("Package warning messages:"); 12410 final File fname = getSettingsProblemFile(); 12411 FileInputStream in = null; 12412 try { 12413 in = new FileInputStream(fname); 12414 final int avail = in.available(); 12415 final byte[] data = new byte[avail]; 12416 in.read(data); 12417 pw.print(new String(data)); 12418 } catch (FileNotFoundException e) { 12419 } catch (IOException e) { 12420 } finally { 12421 if (in != null) { 12422 try { 12423 in.close(); 12424 } catch (IOException e) { 12425 } 12426 } 12427 } 12428 } 12429 } 12430 } 12431 12432 // ------- apps on sdcard specific code ------- 12433 static final boolean DEBUG_SD_INSTALL = false; 12434 12435 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 12436 12437 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 12438 12439 private boolean mMediaMounted = false; 12440 12441 static String getEncryptKey() { 12442 try { 12443 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 12444 SD_ENCRYPTION_KEYSTORE_NAME); 12445 if (sdEncKey == null) { 12446 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 12447 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 12448 if (sdEncKey == null) { 12449 Slog.e(TAG, "Failed to create encryption keys"); 12450 return null; 12451 } 12452 } 12453 return sdEncKey; 12454 } catch (NoSuchAlgorithmException nsae) { 12455 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 12456 return null; 12457 } catch (IOException ioe) { 12458 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 12459 return null; 12460 } 12461 } 12462 12463 /* 12464 * Update media status on PackageManager. 12465 */ 12466 @Override 12467 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 12468 int callingUid = Binder.getCallingUid(); 12469 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 12470 throw new SecurityException("Media status can only be updated by the system"); 12471 } 12472 // reader; this apparently protects mMediaMounted, but should probably 12473 // be a different lock in that case. 12474 synchronized (mPackages) { 12475 Log.i(TAG, "Updating external media status from " 12476 + (mMediaMounted ? "mounted" : "unmounted") + " to " 12477 + (mediaStatus ? "mounted" : "unmounted")); 12478 if (DEBUG_SD_INSTALL) 12479 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 12480 + ", mMediaMounted=" + mMediaMounted); 12481 if (mediaStatus == mMediaMounted) { 12482 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 12483 : 0, -1); 12484 mHandler.sendMessage(msg); 12485 return; 12486 } 12487 mMediaMounted = mediaStatus; 12488 } 12489 // Queue up an async operation since the package installation may take a 12490 // little while. 12491 mHandler.post(new Runnable() { 12492 public void run() { 12493 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 12494 } 12495 }); 12496 } 12497 12498 /** 12499 * Called by MountService when the initial ASECs to scan are available. 12500 * Should block until all the ASEC containers are finished being scanned. 12501 */ 12502 public void scanAvailableAsecs() { 12503 updateExternalMediaStatusInner(true, false, false); 12504 if (mShouldRestoreconData) { 12505 SELinuxMMAC.setRestoreconDone(); 12506 mShouldRestoreconData = false; 12507 } 12508 } 12509 12510 /* 12511 * Collect information of applications on external media, map them against 12512 * existing containers and update information based on current mount status. 12513 * Please note that we always have to report status if reportStatus has been 12514 * set to true especially when unloading packages. 12515 */ 12516 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 12517 boolean externalStorage) { 12518 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 12519 int[] uidArr = EmptyArray.INT; 12520 12521 final String[] list = PackageHelper.getSecureContainerList(); 12522 if (ArrayUtils.isEmpty(list)) { 12523 Log.i(TAG, "No secure containers found"); 12524 } else { 12525 // Process list of secure containers and categorize them 12526 // as active or stale based on their package internal state. 12527 12528 // reader 12529 synchronized (mPackages) { 12530 for (String cid : list) { 12531 // Leave stages untouched for now; installer service owns them 12532 if (PackageInstallerService.isStageName(cid)) continue; 12533 12534 if (DEBUG_SD_INSTALL) 12535 Log.i(TAG, "Processing container " + cid); 12536 String pkgName = getAsecPackageName(cid); 12537 if (pkgName == null) { 12538 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 12539 continue; 12540 } 12541 if (DEBUG_SD_INSTALL) 12542 Log.i(TAG, "Looking for pkg : " + pkgName); 12543 12544 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12545 if (ps == null) { 12546 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 12547 continue; 12548 } 12549 12550 /* 12551 * Skip packages that are not external if we're unmounting 12552 * external storage. 12553 */ 12554 if (externalStorage && !isMounted && !isExternal(ps)) { 12555 continue; 12556 } 12557 12558 final AsecInstallArgs args = new AsecInstallArgs(cid, 12559 getAppDexInstructionSets(ps), isForwardLocked(ps)); 12560 // The package status is changed only if the code path 12561 // matches between settings and the container id. 12562 if (ps.codePathString != null 12563 && ps.codePathString.startsWith(args.getCodePath())) { 12564 if (DEBUG_SD_INSTALL) { 12565 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 12566 + " at code path: " + ps.codePathString); 12567 } 12568 12569 // We do have a valid package installed on sdcard 12570 processCids.put(args, ps.codePathString); 12571 final int uid = ps.appId; 12572 if (uid != -1) { 12573 uidArr = ArrayUtils.appendInt(uidArr, uid); 12574 } 12575 } else { 12576 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 12577 + ps.codePathString); 12578 } 12579 } 12580 } 12581 12582 Arrays.sort(uidArr); 12583 } 12584 12585 // Process packages with valid entries. 12586 if (isMounted) { 12587 if (DEBUG_SD_INSTALL) 12588 Log.i(TAG, "Loading packages"); 12589 loadMediaPackages(processCids, uidArr); 12590 startCleaningPackages(); 12591 mInstallerService.onSecureContainersAvailable(); 12592 } else { 12593 if (DEBUG_SD_INSTALL) 12594 Log.i(TAG, "Unloading packages"); 12595 unloadMediaPackages(processCids, uidArr, reportStatus); 12596 } 12597 } 12598 12599 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 12600 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 12601 int size = pkgList.size(); 12602 if (size > 0) { 12603 // Send broadcasts here 12604 Bundle extras = new Bundle(); 12605 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 12606 .toArray(new String[size])); 12607 if (uidArr != null) { 12608 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 12609 } 12610 if (replacing) { 12611 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 12612 } 12613 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 12614 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 12615 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 12616 } 12617 } 12618 12619 /* 12620 * Look at potentially valid container ids from processCids If package 12621 * information doesn't match the one on record or package scanning fails, 12622 * the cid is added to list of removeCids. We currently don't delete stale 12623 * containers. 12624 */ 12625 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 12626 ArrayList<String> pkgList = new ArrayList<String>(); 12627 Set<AsecInstallArgs> keys = processCids.keySet(); 12628 12629 for (AsecInstallArgs args : keys) { 12630 String codePath = processCids.get(args); 12631 if (DEBUG_SD_INSTALL) 12632 Log.i(TAG, "Loading container : " + args.cid); 12633 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12634 try { 12635 // Make sure there are no container errors first. 12636 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 12637 Slog.e(TAG, "Failed to mount cid : " + args.cid 12638 + " when installing from sdcard"); 12639 continue; 12640 } 12641 // Check code path here. 12642 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 12643 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 12644 + " does not match one in settings " + codePath); 12645 continue; 12646 } 12647 // Parse package 12648 int parseFlags = mDefParseFlags; 12649 if (args.isExternal()) { 12650 parseFlags |= PackageParser.PARSE_ON_SDCARD; 12651 } 12652 if (args.isFwdLocked()) { 12653 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 12654 } 12655 12656 synchronized (mInstallLock) { 12657 PackageParser.Package pkg = null; 12658 try { 12659 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 12660 } catch (PackageManagerException e) { 12661 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 12662 } 12663 // Scan the package 12664 if (pkg != null) { 12665 /* 12666 * TODO why is the lock being held? doPostInstall is 12667 * called in other places without the lock. This needs 12668 * to be straightened out. 12669 */ 12670 // writer 12671 synchronized (mPackages) { 12672 retCode = PackageManager.INSTALL_SUCCEEDED; 12673 pkgList.add(pkg.packageName); 12674 // Post process args 12675 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 12676 pkg.applicationInfo.uid); 12677 } 12678 } else { 12679 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 12680 } 12681 } 12682 12683 } finally { 12684 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 12685 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 12686 } 12687 } 12688 } 12689 // writer 12690 synchronized (mPackages) { 12691 // If the platform SDK has changed since the last time we booted, 12692 // we need to re-grant app permission to catch any new ones that 12693 // appear. This is really a hack, and means that apps can in some 12694 // cases get permissions that the user didn't initially explicitly 12695 // allow... it would be nice to have some better way to handle 12696 // this situation. 12697 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 12698 if (regrantPermissions) 12699 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 12700 + mSdkVersion + "; regranting permissions for external storage"); 12701 mSettings.mExternalSdkPlatform = mSdkVersion; 12702 12703 // Make sure group IDs have been assigned, and any permission 12704 // changes in other apps are accounted for 12705 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 12706 | (regrantPermissions 12707 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 12708 : 0)); 12709 12710 mSettings.updateExternalDatabaseVersion(); 12711 12712 // can downgrade to reader 12713 // Persist settings 12714 mSettings.writeLPr(); 12715 } 12716 // Send a broadcast to let everyone know we are done processing 12717 if (pkgList.size() > 0) { 12718 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12719 } 12720 } 12721 12722 /* 12723 * Utility method to unload a list of specified containers 12724 */ 12725 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 12726 // Just unmount all valid containers. 12727 for (AsecInstallArgs arg : cidArgs) { 12728 synchronized (mInstallLock) { 12729 arg.doPostDeleteLI(false); 12730 } 12731 } 12732 } 12733 12734 /* 12735 * Unload packages mounted on external media. This involves deleting package 12736 * data from internal structures, sending broadcasts about diabled packages, 12737 * gc'ing to free up references, unmounting all secure containers 12738 * corresponding to packages on external media, and posting a 12739 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 12740 * that we always have to post this message if status has been requested no 12741 * matter what. 12742 */ 12743 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 12744 final boolean reportStatus) { 12745 if (DEBUG_SD_INSTALL) 12746 Log.i(TAG, "unloading media packages"); 12747 ArrayList<String> pkgList = new ArrayList<String>(); 12748 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 12749 final Set<AsecInstallArgs> keys = processCids.keySet(); 12750 for (AsecInstallArgs args : keys) { 12751 String pkgName = args.getPackageName(); 12752 if (DEBUG_SD_INSTALL) 12753 Log.i(TAG, "Trying to unload pkg : " + pkgName); 12754 // Delete package internally 12755 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 12756 synchronized (mInstallLock) { 12757 boolean res = deletePackageLI(pkgName, null, false, null, null, 12758 PackageManager.DELETE_KEEP_DATA, outInfo, false); 12759 if (res) { 12760 pkgList.add(pkgName); 12761 } else { 12762 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 12763 failedList.add(args); 12764 } 12765 } 12766 } 12767 12768 // reader 12769 synchronized (mPackages) { 12770 // We didn't update the settings after removing each package; 12771 // write them now for all packages. 12772 mSettings.writeLPr(); 12773 } 12774 12775 // We have to absolutely send UPDATED_MEDIA_STATUS only 12776 // after confirming that all the receivers processed the ordered 12777 // broadcast when packages get disabled, force a gc to clean things up. 12778 // and unload all the containers. 12779 if (pkgList.size() > 0) { 12780 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 12781 new IIntentReceiver.Stub() { 12782 public void performReceive(Intent intent, int resultCode, String data, 12783 Bundle extras, boolean ordered, boolean sticky, 12784 int sendingUser) throws RemoteException { 12785 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 12786 reportStatus ? 1 : 0, 1, keys); 12787 mHandler.sendMessage(msg); 12788 } 12789 }); 12790 } else { 12791 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 12792 keys); 12793 mHandler.sendMessage(msg); 12794 } 12795 } 12796 12797 /** Binder call */ 12798 @Override 12799 public void movePackage(final String packageName, final IPackageMoveObserver observer, 12800 final int flags) { 12801 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 12802 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 12803 int returnCode = PackageManager.MOVE_SUCCEEDED; 12804 int currInstallFlags = 0; 12805 int newInstallFlags = 0; 12806 12807 File codeFile = null; 12808 String installerPackageName = null; 12809 String packageAbiOverride = null; 12810 12811 // reader 12812 synchronized (mPackages) { 12813 final PackageParser.Package pkg = mPackages.get(packageName); 12814 final PackageSetting ps = mSettings.mPackages.get(packageName); 12815 if (pkg == null || ps == null) { 12816 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12817 } else { 12818 // Disable moving fwd locked apps and system packages 12819 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 12820 Slog.w(TAG, "Cannot move system application"); 12821 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 12822 } else if (pkg.mOperationPending) { 12823 Slog.w(TAG, "Attempt to move package which has pending operations"); 12824 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 12825 } else { 12826 // Find install location first 12827 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 12828 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 12829 Slog.w(TAG, "Ambigous flags specified for move location."); 12830 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12831 } else { 12832 newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 12833 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 12834 currInstallFlags = isExternal(pkg) 12835 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 12836 12837 if (newInstallFlags == currInstallFlags) { 12838 Slog.w(TAG, "No move required. Trying to move to same location"); 12839 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12840 } else { 12841 if (isForwardLocked(pkg)) { 12842 currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12843 newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12844 } 12845 } 12846 } 12847 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12848 pkg.mOperationPending = true; 12849 } 12850 } 12851 12852 codeFile = new File(pkg.codePath); 12853 installerPackageName = ps.installerPackageName; 12854 packageAbiOverride = ps.cpuAbiOverrideString; 12855 } 12856 } 12857 12858 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 12859 try { 12860 observer.packageMoved(packageName, returnCode); 12861 } catch (RemoteException ignored) { 12862 } 12863 return; 12864 } 12865 12866 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 12867 @Override 12868 public void onUserActionRequired(Intent intent) throws RemoteException { 12869 throw new IllegalStateException(); 12870 } 12871 12872 @Override 12873 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 12874 Bundle extras) throws RemoteException { 12875 Slog.d(TAG, "Install result for move: " 12876 + PackageManager.installStatusToString(returnCode, msg)); 12877 12878 // We usually have a new package now after the install, but if 12879 // we failed we need to clear the pending flag on the original 12880 // package object. 12881 synchronized (mPackages) { 12882 final PackageParser.Package pkg = mPackages.get(packageName); 12883 if (pkg != null) { 12884 pkg.mOperationPending = false; 12885 } 12886 } 12887 12888 final int status = PackageManager.installStatusToPublicStatus(returnCode); 12889 switch (status) { 12890 case PackageInstaller.STATUS_SUCCESS: 12891 observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED); 12892 break; 12893 case PackageInstaller.STATUS_FAILURE_STORAGE: 12894 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 12895 break; 12896 default: 12897 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR); 12898 break; 12899 } 12900 } 12901 }; 12902 12903 // Treat a move like reinstalling an existing app, which ensures that we 12904 // process everythign uniformly, like unpacking native libraries. 12905 newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 12906 12907 final Message msg = mHandler.obtainMessage(INIT_COPY); 12908 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 12909 msg.obj = new InstallParams(origin, installObserver, newInstallFlags, 12910 installerPackageName, null, user, packageAbiOverride); 12911 mHandler.sendMessage(msg); 12912 } 12913 12914 @Override 12915 public boolean setInstallLocation(int loc) { 12916 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 12917 null); 12918 if (getInstallLocation() == loc) { 12919 return true; 12920 } 12921 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 12922 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 12923 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 12924 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 12925 return true; 12926 } 12927 return false; 12928 } 12929 12930 @Override 12931 public int getInstallLocation() { 12932 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12933 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 12934 PackageHelper.APP_INSTALL_AUTO); 12935 } 12936 12937 /** Called by UserManagerService */ 12938 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 12939 mDirtyUsers.remove(userHandle); 12940 mSettings.removeUserLPw(userHandle); 12941 mPendingBroadcasts.remove(userHandle); 12942 if (mInstaller != null) { 12943 // Technically, we shouldn't be doing this with the package lock 12944 // held. However, this is very rare, and there is already so much 12945 // other disk I/O going on, that we'll let it slide for now. 12946 mInstaller.removeUserDataDirs(userHandle); 12947 } 12948 mUserNeedsBadging.delete(userHandle); 12949 removeUnusedPackagesLILPw(userManager, userHandle); 12950 } 12951 12952 /** 12953 * We're removing userHandle and would like to remove any downloaded packages 12954 * that are no longer in use by any other user. 12955 * @param userHandle the user being removed 12956 */ 12957 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 12958 final boolean DEBUG_CLEAN_APKS = false; 12959 int [] users = userManager.getUserIdsLPr(); 12960 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 12961 while (psit.hasNext()) { 12962 PackageSetting ps = psit.next(); 12963 if (ps.pkg == null) { 12964 continue; 12965 } 12966 final String packageName = ps.pkg.packageName; 12967 // Skip over if system app 12968 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12969 continue; 12970 } 12971 if (DEBUG_CLEAN_APKS) { 12972 Slog.i(TAG, "Checking package " + packageName); 12973 } 12974 boolean keep = false; 12975 for (int i = 0; i < users.length; i++) { 12976 if (users[i] != userHandle && ps.getInstalled(users[i])) { 12977 keep = true; 12978 if (DEBUG_CLEAN_APKS) { 12979 Slog.i(TAG, " Keeping package " + packageName + " for user " 12980 + users[i]); 12981 } 12982 break; 12983 } 12984 } 12985 if (!keep) { 12986 if (DEBUG_CLEAN_APKS) { 12987 Slog.i(TAG, " Removing package " + packageName); 12988 } 12989 mHandler.post(new Runnable() { 12990 public void run() { 12991 deletePackageX(packageName, userHandle, 0); 12992 } //end run 12993 }); 12994 } 12995 } 12996 } 12997 12998 /** Called by UserManagerService */ 12999 void createNewUserLILPw(int userHandle, File path) { 13000 if (mInstaller != null) { 13001 mInstaller.createUserConfig(userHandle); 13002 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 13003 } 13004 } 13005 13006 @Override 13007 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 13008 mContext.enforceCallingOrSelfPermission( 13009 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13010 "Only package verification agents can read the verifier device identity"); 13011 13012 synchronized (mPackages) { 13013 return mSettings.getVerifierDeviceIdentityLPw(); 13014 } 13015 } 13016 13017 @Override 13018 public void setPermissionEnforced(String permission, boolean enforced) { 13019 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 13020 if (READ_EXTERNAL_STORAGE.equals(permission)) { 13021 synchronized (mPackages) { 13022 if (mSettings.mReadExternalStorageEnforced == null 13023 || mSettings.mReadExternalStorageEnforced != enforced) { 13024 mSettings.mReadExternalStorageEnforced = enforced; 13025 mSettings.writeLPr(); 13026 } 13027 } 13028 // kill any non-foreground processes so we restart them and 13029 // grant/revoke the GID. 13030 final IActivityManager am = ActivityManagerNative.getDefault(); 13031 if (am != null) { 13032 final long token = Binder.clearCallingIdentity(); 13033 try { 13034 am.killProcessesBelowForeground("setPermissionEnforcement"); 13035 } catch (RemoteException e) { 13036 } finally { 13037 Binder.restoreCallingIdentity(token); 13038 } 13039 } 13040 } else { 13041 throw new IllegalArgumentException("No selective enforcement for " + permission); 13042 } 13043 } 13044 13045 @Override 13046 @Deprecated 13047 public boolean isPermissionEnforced(String permission) { 13048 return true; 13049 } 13050 13051 @Override 13052 public boolean isStorageLow() { 13053 final long token = Binder.clearCallingIdentity(); 13054 try { 13055 final DeviceStorageMonitorInternal 13056 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13057 if (dsm != null) { 13058 return dsm.isMemoryLow(); 13059 } else { 13060 return false; 13061 } 13062 } finally { 13063 Binder.restoreCallingIdentity(token); 13064 } 13065 } 13066 13067 @Override 13068 public IPackageInstaller getPackageInstaller() { 13069 return mInstallerService; 13070 } 13071 13072 private boolean userNeedsBadging(int userId) { 13073 int index = mUserNeedsBadging.indexOfKey(userId); 13074 if (index < 0) { 13075 final UserInfo userInfo; 13076 final long token = Binder.clearCallingIdentity(); 13077 try { 13078 userInfo = sUserManager.getUserInfo(userId); 13079 } finally { 13080 Binder.restoreCallingIdentity(token); 13081 } 13082 final boolean b; 13083 if (userInfo != null && userInfo.isManagedProfile()) { 13084 b = true; 13085 } else { 13086 b = false; 13087 } 13088 mUserNeedsBadging.put(userId, b); 13089 return b; 13090 } 13091 return mUserNeedsBadging.valueAt(index); 13092 } 13093 13094 @Override 13095 public KeySet getKeySetByAlias(String packageName, String alias) { 13096 if (packageName == null || alias == null) { 13097 return null; 13098 } 13099 synchronized(mPackages) { 13100 final PackageParser.Package pkg = mPackages.get(packageName); 13101 if (pkg == null) { 13102 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13103 throw new IllegalArgumentException("Unknown package: " + packageName); 13104 } 13105 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13106 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 13107 } 13108 } 13109 13110 @Override 13111 public KeySet getSigningKeySet(String packageName) { 13112 if (packageName == null) { 13113 return null; 13114 } 13115 synchronized(mPackages) { 13116 final PackageParser.Package pkg = mPackages.get(packageName); 13117 if (pkg == null) { 13118 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13119 throw new IllegalArgumentException("Unknown package: " + packageName); 13120 } 13121 if (pkg.applicationInfo.uid != Binder.getCallingUid() 13122 && Process.SYSTEM_UID != Binder.getCallingUid()) { 13123 throw new SecurityException("May not access signing KeySet of other apps."); 13124 } 13125 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13126 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 13127 } 13128 } 13129 13130 @Override 13131 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 13132 if (packageName == null || ks == null) { 13133 return false; 13134 } 13135 synchronized(mPackages) { 13136 final PackageParser.Package pkg = mPackages.get(packageName); 13137 if (pkg == null) { 13138 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13139 throw new IllegalArgumentException("Unknown package: " + packageName); 13140 } 13141 IBinder ksh = ks.getToken(); 13142 if (ksh instanceof KeySetHandle) { 13143 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13144 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 13145 } 13146 return false; 13147 } 13148 } 13149 13150 @Override 13151 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 13152 if (packageName == null || ks == null) { 13153 return false; 13154 } 13155 synchronized(mPackages) { 13156 final PackageParser.Package pkg = mPackages.get(packageName); 13157 if (pkg == null) { 13158 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13159 throw new IllegalArgumentException("Unknown package: " + packageName); 13160 } 13161 IBinder ksh = ks.getToken(); 13162 if (ksh instanceof KeySetHandle) { 13163 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13164 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 13165 } 13166 return false; 13167 } 13168 } 13169} 13170