PackageManagerService.java revision 30f349d2ef3f2220c1d478b0faff4c38eaadf12c
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.FileUtils; 142import android.os.Handler; 143import android.os.IBinder; 144import android.os.Looper; 145import android.os.Message; 146import android.os.Parcel; 147import android.os.ParcelFileDescriptor; 148import android.os.Process; 149import android.os.RemoteException; 150import android.os.SELinux; 151import android.os.ServiceManager; 152import android.os.SystemClock; 153import android.os.SystemProperties; 154import android.os.UserHandle; 155import android.os.UserManager; 156import android.security.KeyStore; 157import android.security.SystemKeyStore; 158import android.system.ErrnoException; 159import android.system.Os; 160import android.system.StructStat; 161import android.text.TextUtils; 162import android.util.ArraySet; 163import android.util.AtomicFile; 164import android.util.DisplayMetrics; 165import android.util.EventLog; 166import android.util.ExceptionUtils; 167import android.util.Log; 168import android.util.LogPrinter; 169import android.util.PrintStreamPrinter; 170import android.util.Slog; 171import android.util.SparseArray; 172import android.util.SparseBooleanArray; 173import android.view.Display; 174 175import java.io.BufferedInputStream; 176import java.io.BufferedOutputStream; 177import java.io.File; 178import java.io.FileDescriptor; 179import java.io.FileInputStream; 180import java.io.FileNotFoundException; 181import java.io.FileOutputStream; 182import java.io.FilenameFilter; 183import java.io.IOException; 184import java.io.InputStream; 185import java.io.PrintWriter; 186import java.nio.charset.StandardCharsets; 187import java.security.NoSuchAlgorithmException; 188import java.security.PublicKey; 189import java.security.cert.CertificateEncodingException; 190import java.security.cert.CertificateException; 191import java.text.SimpleDateFormat; 192import java.util.ArrayList; 193import java.util.Arrays; 194import java.util.Collection; 195import java.util.Collections; 196import java.util.Comparator; 197import java.util.Date; 198import java.util.HashMap; 199import java.util.HashSet; 200import java.util.Iterator; 201import java.util.List; 202import java.util.Map; 203import java.util.Set; 204import java.util.concurrent.atomic.AtomicBoolean; 205import java.util.concurrent.atomic.AtomicLong; 206 207import dalvik.system.DexFile; 208import dalvik.system.StaleDexCacheError; 209import dalvik.system.VMRuntime; 210 211import libcore.io.IoUtils; 212import libcore.util.EmptyArray; 213 214/** 215 * Keep track of all those .apks everywhere. 216 * 217 * This is very central to the platform's security; please run the unit 218 * tests whenever making modifications here: 219 * 220mmm frameworks/base/tests/AndroidTests 221adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 222adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 223 * 224 * {@hide} 225 */ 226public class PackageManagerService extends IPackageManager.Stub { 227 static final String TAG = "PackageManager"; 228 static final boolean DEBUG_SETTINGS = false; 229 static final boolean DEBUG_PREFERRED = false; 230 static final boolean DEBUG_UPGRADE = false; 231 private static final boolean DEBUG_INSTALL = false; 232 private static final boolean DEBUG_REMOVE = false; 233 private static final boolean DEBUG_BROADCASTS = false; 234 private static final boolean DEBUG_SHOW_INFO = false; 235 private static final boolean DEBUG_PACKAGE_INFO = false; 236 private static final boolean DEBUG_INTENT_MATCHING = false; 237 private static final boolean DEBUG_PACKAGE_SCANNING = false; 238 private static final boolean DEBUG_VERIFY = false; 239 private static final boolean DEBUG_DEXOPT = false; 240 private static final boolean DEBUG_ABI_SELECTION = false; 241 242 private static final int RADIO_UID = Process.PHONE_UID; 243 private static final int LOG_UID = Process.LOG_UID; 244 private static final int NFC_UID = Process.NFC_UID; 245 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 246 private static final int SHELL_UID = Process.SHELL_UID; 247 248 // Cap the size of permission trees that 3rd party apps can define 249 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 250 251 // Suffix used during package installation when copying/moving 252 // package apks to install directory. 253 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 254 255 static final int SCAN_NO_DEX = 1<<1; 256 static final int SCAN_FORCE_DEX = 1<<2; 257 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 258 static final int SCAN_NEW_INSTALL = 1<<4; 259 static final int SCAN_NO_PATHS = 1<<5; 260 static final int SCAN_UPDATE_TIME = 1<<6; 261 static final int SCAN_DEFER_DEX = 1<<7; 262 static final int SCAN_BOOTING = 1<<8; 263 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 264 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 265 static final int SCAN_REPLACING = 1<<11; 266 267 static final int REMOVE_CHATTY = 1<<16; 268 269 /** 270 * Timeout (in milliseconds) after which the watchdog should declare that 271 * our handler thread is wedged. The usual default for such things is one 272 * minute but we sometimes do very lengthy I/O operations on this thread, 273 * such as installing multi-gigabyte applications, so ours needs to be longer. 274 */ 275 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 276 277 /** 278 * Whether verification is enabled by default. 279 */ 280 private static final boolean DEFAULT_VERIFY_ENABLE = true; 281 282 /** 283 * The default maximum time to wait for the verification agent to return in 284 * milliseconds. 285 */ 286 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 287 288 /** 289 * The default response for package verification timeout. 290 * 291 * This can be either PackageManager.VERIFICATION_ALLOW or 292 * PackageManager.VERIFICATION_REJECT. 293 */ 294 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 295 296 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 297 298 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 299 DEFAULT_CONTAINER_PACKAGE, 300 "com.android.defcontainer.DefaultContainerService"); 301 302 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 303 304 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 305 306 private static String sPreferredInstructionSet; 307 308 final ServiceThread mHandlerThread; 309 310 private static final String IDMAP_PREFIX = "/data/resource-cache/"; 311 private static final String IDMAP_SUFFIX = "@idmap"; 312 313 final PackageHandler mHandler; 314 315 /** 316 * Messages for {@link #mHandler} that need to wait for system ready before 317 * being dispatched. 318 */ 319 private ArrayList<Message> mPostSystemReadyMessages; 320 321 final int mSdkVersion = Build.VERSION.SDK_INT; 322 323 final Context mContext; 324 final boolean mFactoryTest; 325 final boolean mOnlyCore; 326 final boolean mLazyDexOpt; 327 final DisplayMetrics mMetrics; 328 final int mDefParseFlags; 329 final String[] mSeparateProcesses; 330 331 // This is where all application persistent data goes. 332 final File mAppDataDir; 333 334 // This is where all application persistent data goes for secondary users. 335 final File mUserAppDataDir; 336 337 /** The location for ASEC container files on internal storage. */ 338 final String mAsecInternalPath; 339 340 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 341 // LOCK HELD. Can be called with mInstallLock held. 342 final Installer mInstaller; 343 344 /** Directory where installed third-party apps stored */ 345 final File mAppInstallDir; 346 347 /** 348 * Directory to which applications installed internally have their 349 * 32 bit native libraries copied. 350 */ 351 private File mAppLib32InstallDir; 352 353 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 354 // apps. 355 final File mDrmAppPrivateInstallDir; 356 357 // ---------------------------------------------------------------- 358 359 // Lock for state used when installing and doing other long running 360 // operations. Methods that must be called with this lock held have 361 // the suffix "LI". 362 final Object mInstallLock = new Object(); 363 364 // ---------------------------------------------------------------- 365 366 // Keys are String (package name), values are Package. This also serves 367 // as the lock for the global state. Methods that must be called with 368 // this lock held have the prefix "LP". 369 final HashMap<String, PackageParser.Package> mPackages = 370 new HashMap<String, PackageParser.Package>(); 371 372 // Tracks available target package names -> overlay package paths. 373 final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays = 374 new HashMap<String, HashMap<String, PackageParser.Package>>(); 375 376 final Settings mSettings; 377 boolean mRestoredSettings; 378 379 // System configuration read by SystemConfig. 380 final int[] mGlobalGids; 381 final SparseArray<HashSet<String>> mSystemPermissions; 382 final HashMap<String, FeatureInfo> mAvailableFeatures; 383 384 // If mac_permissions.xml was found for seinfo labeling. 385 boolean mFoundPolicyFile; 386 387 // If a recursive restorecon of /data/data/<pkg> is needed. 388 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 389 390 public static final class SharedLibraryEntry { 391 public final String path; 392 public final String apk; 393 394 SharedLibraryEntry(String _path, String _apk) { 395 path = _path; 396 apk = _apk; 397 } 398 } 399 400 // Currently known shared libraries. 401 final HashMap<String, SharedLibraryEntry> mSharedLibraries = 402 new HashMap<String, SharedLibraryEntry>(); 403 404 // All available activities, for your resolving pleasure. 405 final ActivityIntentResolver mActivities = 406 new ActivityIntentResolver(); 407 408 // All available receivers, for your resolving pleasure. 409 final ActivityIntentResolver mReceivers = 410 new ActivityIntentResolver(); 411 412 // All available services, for your resolving pleasure. 413 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 414 415 // All available providers, for your resolving pleasure. 416 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 417 418 // Mapping from provider base names (first directory in content URI codePath) 419 // to the provider information. 420 final HashMap<String, PackageParser.Provider> mProvidersByAuthority = 421 new HashMap<String, PackageParser.Provider>(); 422 423 // Mapping from instrumentation class names to info about them. 424 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 425 new HashMap<ComponentName, PackageParser.Instrumentation>(); 426 427 // Mapping from permission names to info about them. 428 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups = 429 new HashMap<String, PackageParser.PermissionGroup>(); 430 431 // Packages whose data we have transfered into another package, thus 432 // should no longer exist. 433 final HashSet<String> mTransferedPackages = new HashSet<String>(); 434 435 // Broadcast actions that are only available to the system. 436 final HashSet<String> mProtectedBroadcasts = new HashSet<String>(); 437 438 /** List of packages waiting for verification. */ 439 final SparseArray<PackageVerificationState> mPendingVerification 440 = new SparseArray<PackageVerificationState>(); 441 442 /** Set of packages associated with each app op permission. */ 443 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 444 445 final PackageInstallerService mInstallerService; 446 447 HashSet<PackageParser.Package> mDeferredDexOpt = null; 448 449 // Cache of users who need badging. 450 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 451 452 /** Token for keys in mPendingVerification. */ 453 private int mPendingVerificationToken = 0; 454 455 volatile boolean mSystemReady; 456 volatile boolean mSafeMode; 457 volatile boolean mHasSystemUidErrors; 458 459 ApplicationInfo mAndroidApplication; 460 final ActivityInfo mResolveActivity = new ActivityInfo(); 461 final ResolveInfo mResolveInfo = new ResolveInfo(); 462 ComponentName mResolveComponentName; 463 PackageParser.Package mPlatformPackage; 464 ComponentName mCustomResolverComponentName; 465 466 boolean mResolverReplaced = false; 467 468 // Set of pending broadcasts for aggregating enable/disable of components. 469 static class PendingPackageBroadcasts { 470 // for each user id, a map of <package name -> components within that package> 471 final SparseArray<HashMap<String, ArrayList<String>>> mUidMap; 472 473 public PendingPackageBroadcasts() { 474 mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2); 475 } 476 477 public ArrayList<String> get(int userId, String packageName) { 478 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 479 return packages.get(packageName); 480 } 481 482 public void put(int userId, String packageName, ArrayList<String> components) { 483 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 484 packages.put(packageName, components); 485 } 486 487 public void remove(int userId, String packageName) { 488 HashMap<String, ArrayList<String>> packages = mUidMap.get(userId); 489 if (packages != null) { 490 packages.remove(packageName); 491 } 492 } 493 494 public void remove(int userId) { 495 mUidMap.remove(userId); 496 } 497 498 public int userIdCount() { 499 return mUidMap.size(); 500 } 501 502 public int userIdAt(int n) { 503 return mUidMap.keyAt(n); 504 } 505 506 public HashMap<String, ArrayList<String>> packagesForUserId(int userId) { 507 return mUidMap.get(userId); 508 } 509 510 public int size() { 511 // total number of pending broadcast entries across all userIds 512 int num = 0; 513 for (int i = 0; i< mUidMap.size(); i++) { 514 num += mUidMap.valueAt(i).size(); 515 } 516 return num; 517 } 518 519 public void clear() { 520 mUidMap.clear(); 521 } 522 523 private HashMap<String, ArrayList<String>> getOrAllocate(int userId) { 524 HashMap<String, ArrayList<String>> map = mUidMap.get(userId); 525 if (map == null) { 526 map = new HashMap<String, ArrayList<String>>(); 527 mUidMap.put(userId, map); 528 } 529 return map; 530 } 531 } 532 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 533 534 // Service Connection to remote media container service to copy 535 // package uri's from external media onto secure containers 536 // or internal storage. 537 private IMediaContainerService mContainerService = null; 538 539 static final int SEND_PENDING_BROADCAST = 1; 540 static final int MCS_BOUND = 3; 541 static final int END_COPY = 4; 542 static final int INIT_COPY = 5; 543 static final int MCS_UNBIND = 6; 544 static final int START_CLEANING_PACKAGE = 7; 545 static final int FIND_INSTALL_LOC = 8; 546 static final int POST_INSTALL = 9; 547 static final int MCS_RECONNECT = 10; 548 static final int MCS_GIVE_UP = 11; 549 static final int UPDATED_MEDIA_STATUS = 12; 550 static final int WRITE_SETTINGS = 13; 551 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 552 static final int PACKAGE_VERIFIED = 15; 553 static final int CHECK_PENDING_VERIFICATION = 16; 554 555 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 556 557 // Delay time in millisecs 558 static final int BROADCAST_DELAY = 10 * 1000; 559 560 static UserManagerService sUserManager; 561 562 // Stores a list of users whose package restrictions file needs to be updated 563 private HashSet<Integer> mDirtyUsers = new HashSet<Integer>(); 564 565 final private DefaultContainerConnection mDefContainerConn = 566 new DefaultContainerConnection(); 567 class DefaultContainerConnection implements ServiceConnection { 568 public void onServiceConnected(ComponentName name, IBinder service) { 569 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 570 IMediaContainerService imcs = 571 IMediaContainerService.Stub.asInterface(service); 572 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 573 } 574 575 public void onServiceDisconnected(ComponentName name) { 576 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 577 } 578 }; 579 580 // Recordkeeping of restore-after-install operations that are currently in flight 581 // between the Package Manager and the Backup Manager 582 class PostInstallData { 583 public InstallArgs args; 584 public PackageInstalledInfo res; 585 586 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 587 args = _a; 588 res = _r; 589 } 590 }; 591 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 592 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 593 594 private final String mRequiredVerifierPackage; 595 596 private final PackageUsage mPackageUsage = new PackageUsage(); 597 598 private class PackageUsage { 599 private static final int WRITE_INTERVAL 600 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 601 602 private final Object mFileLock = new Object(); 603 private final AtomicLong mLastWritten = new AtomicLong(0); 604 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 605 606 private boolean mIsHistoricalPackageUsageAvailable = true; 607 608 boolean isHistoricalPackageUsageAvailable() { 609 return mIsHistoricalPackageUsageAvailable; 610 } 611 612 void write(boolean force) { 613 if (force) { 614 writeInternal(); 615 return; 616 } 617 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 618 && !DEBUG_DEXOPT) { 619 return; 620 } 621 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 622 new Thread("PackageUsage_DiskWriter") { 623 @Override 624 public void run() { 625 try { 626 writeInternal(); 627 } finally { 628 mBackgroundWriteRunning.set(false); 629 } 630 } 631 }.start(); 632 } 633 } 634 635 private void writeInternal() { 636 synchronized (mPackages) { 637 synchronized (mFileLock) { 638 AtomicFile file = getFile(); 639 FileOutputStream f = null; 640 try { 641 f = file.startWrite(); 642 BufferedOutputStream out = new BufferedOutputStream(f); 643 FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID); 644 StringBuilder sb = new StringBuilder(); 645 for (PackageParser.Package pkg : mPackages.values()) { 646 if (pkg.mLastPackageUsageTimeInMills == 0) { 647 continue; 648 } 649 sb.setLength(0); 650 sb.append(pkg.packageName); 651 sb.append(' '); 652 sb.append((long)pkg.mLastPackageUsageTimeInMills); 653 sb.append('\n'); 654 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 655 } 656 out.flush(); 657 file.finishWrite(f); 658 } catch (IOException e) { 659 if (f != null) { 660 file.failWrite(f); 661 } 662 Log.e(TAG, "Failed to write package usage times", e); 663 } 664 } 665 } 666 mLastWritten.set(SystemClock.elapsedRealtime()); 667 } 668 669 void readLP() { 670 synchronized (mFileLock) { 671 AtomicFile file = getFile(); 672 BufferedInputStream in = null; 673 try { 674 in = new BufferedInputStream(file.openRead()); 675 StringBuffer sb = new StringBuffer(); 676 while (true) { 677 String packageName = readToken(in, sb, ' '); 678 if (packageName == null) { 679 break; 680 } 681 String timeInMillisString = readToken(in, sb, '\n'); 682 if (timeInMillisString == null) { 683 throw new IOException("Failed to find last usage time for package " 684 + packageName); 685 } 686 PackageParser.Package pkg = mPackages.get(packageName); 687 if (pkg == null) { 688 continue; 689 } 690 long timeInMillis; 691 try { 692 timeInMillis = Long.parseLong(timeInMillisString.toString()); 693 } catch (NumberFormatException e) { 694 throw new IOException("Failed to parse " + timeInMillisString 695 + " as a long.", e); 696 } 697 pkg.mLastPackageUsageTimeInMills = timeInMillis; 698 } 699 } catch (FileNotFoundException expected) { 700 mIsHistoricalPackageUsageAvailable = false; 701 } catch (IOException e) { 702 Log.w(TAG, "Failed to read package usage times", e); 703 } finally { 704 IoUtils.closeQuietly(in); 705 } 706 } 707 mLastWritten.set(SystemClock.elapsedRealtime()); 708 } 709 710 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 711 throws IOException { 712 sb.setLength(0); 713 while (true) { 714 int ch = in.read(); 715 if (ch == -1) { 716 if (sb.length() == 0) { 717 return null; 718 } 719 throw new IOException("Unexpected EOF"); 720 } 721 if (ch == endOfToken) { 722 return sb.toString(); 723 } 724 sb.append((char)ch); 725 } 726 } 727 728 private AtomicFile getFile() { 729 File dataDir = Environment.getDataDirectory(); 730 File systemDir = new File(dataDir, "system"); 731 File fname = new File(systemDir, "package-usage.list"); 732 return new AtomicFile(fname); 733 } 734 } 735 736 class PackageHandler extends Handler { 737 private boolean mBound = false; 738 final ArrayList<HandlerParams> mPendingInstalls = 739 new ArrayList<HandlerParams>(); 740 741 private boolean connectToService() { 742 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 743 " DefaultContainerService"); 744 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 745 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 746 if (mContext.bindServiceAsUser(service, mDefContainerConn, 747 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 748 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 749 mBound = true; 750 return true; 751 } 752 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 753 return false; 754 } 755 756 private void disconnectService() { 757 mContainerService = null; 758 mBound = false; 759 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 760 mContext.unbindService(mDefContainerConn); 761 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 762 } 763 764 PackageHandler(Looper looper) { 765 super(looper); 766 } 767 768 public void handleMessage(Message msg) { 769 try { 770 doHandleMessage(msg); 771 } finally { 772 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 773 } 774 } 775 776 void doHandleMessage(Message msg) { 777 switch (msg.what) { 778 case INIT_COPY: { 779 HandlerParams params = (HandlerParams) msg.obj; 780 int idx = mPendingInstalls.size(); 781 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 782 // If a bind was already initiated we dont really 783 // need to do anything. The pending install 784 // will be processed later on. 785 if (!mBound) { 786 // If this is the only one pending we might 787 // have to bind to the service again. 788 if (!connectToService()) { 789 Slog.e(TAG, "Failed to bind to media container service"); 790 params.serviceError(); 791 return; 792 } else { 793 // Once we bind to the service, the first 794 // pending request will be processed. 795 mPendingInstalls.add(idx, params); 796 } 797 } else { 798 mPendingInstalls.add(idx, params); 799 // Already bound to the service. Just make 800 // sure we trigger off processing the first request. 801 if (idx == 0) { 802 mHandler.sendEmptyMessage(MCS_BOUND); 803 } 804 } 805 break; 806 } 807 case MCS_BOUND: { 808 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 809 if (msg.obj != null) { 810 mContainerService = (IMediaContainerService) msg.obj; 811 } 812 if (mContainerService == null) { 813 // Something seriously wrong. Bail out 814 Slog.e(TAG, "Cannot bind to media container service"); 815 for (HandlerParams params : mPendingInstalls) { 816 // Indicate service bind error 817 params.serviceError(); 818 } 819 mPendingInstalls.clear(); 820 } else if (mPendingInstalls.size() > 0) { 821 HandlerParams params = mPendingInstalls.get(0); 822 if (params != null) { 823 if (params.startCopy()) { 824 // We are done... look for more work or to 825 // go idle. 826 if (DEBUG_SD_INSTALL) Log.i(TAG, 827 "Checking for more work or unbind..."); 828 // Delete pending install 829 if (mPendingInstalls.size() > 0) { 830 mPendingInstalls.remove(0); 831 } 832 if (mPendingInstalls.size() == 0) { 833 if (mBound) { 834 if (DEBUG_SD_INSTALL) Log.i(TAG, 835 "Posting delayed MCS_UNBIND"); 836 removeMessages(MCS_UNBIND); 837 Message ubmsg = obtainMessage(MCS_UNBIND); 838 // Unbind after a little delay, to avoid 839 // continual thrashing. 840 sendMessageDelayed(ubmsg, 10000); 841 } 842 } else { 843 // There are more pending requests in queue. 844 // Just post MCS_BOUND message to trigger processing 845 // of next pending install. 846 if (DEBUG_SD_INSTALL) Log.i(TAG, 847 "Posting MCS_BOUND for next work"); 848 mHandler.sendEmptyMessage(MCS_BOUND); 849 } 850 } 851 } 852 } else { 853 // Should never happen ideally. 854 Slog.w(TAG, "Empty queue"); 855 } 856 break; 857 } 858 case MCS_RECONNECT: { 859 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 860 if (mPendingInstalls.size() > 0) { 861 if (mBound) { 862 disconnectService(); 863 } 864 if (!connectToService()) { 865 Slog.e(TAG, "Failed to bind to media container service"); 866 for (HandlerParams params : mPendingInstalls) { 867 // Indicate service bind error 868 params.serviceError(); 869 } 870 mPendingInstalls.clear(); 871 } 872 } 873 break; 874 } 875 case MCS_UNBIND: { 876 // If there is no actual work left, then time to unbind. 877 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 878 879 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 880 if (mBound) { 881 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 882 883 disconnectService(); 884 } 885 } else if (mPendingInstalls.size() > 0) { 886 // There are more pending requests in queue. 887 // Just post MCS_BOUND message to trigger processing 888 // of next pending install. 889 mHandler.sendEmptyMessage(MCS_BOUND); 890 } 891 892 break; 893 } 894 case MCS_GIVE_UP: { 895 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 896 mPendingInstalls.remove(0); 897 break; 898 } 899 case SEND_PENDING_BROADCAST: { 900 String packages[]; 901 ArrayList<String> components[]; 902 int size = 0; 903 int uids[]; 904 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 905 synchronized (mPackages) { 906 if (mPendingBroadcasts == null) { 907 return; 908 } 909 size = mPendingBroadcasts.size(); 910 if (size <= 0) { 911 // Nothing to be done. Just return 912 return; 913 } 914 packages = new String[size]; 915 components = new ArrayList[size]; 916 uids = new int[size]; 917 int i = 0; // filling out the above arrays 918 919 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 920 int packageUserId = mPendingBroadcasts.userIdAt(n); 921 Iterator<Map.Entry<String, ArrayList<String>>> it 922 = mPendingBroadcasts.packagesForUserId(packageUserId) 923 .entrySet().iterator(); 924 while (it.hasNext() && i < size) { 925 Map.Entry<String, ArrayList<String>> ent = it.next(); 926 packages[i] = ent.getKey(); 927 components[i] = ent.getValue(); 928 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 929 uids[i] = (ps != null) 930 ? UserHandle.getUid(packageUserId, ps.appId) 931 : -1; 932 i++; 933 } 934 } 935 size = i; 936 mPendingBroadcasts.clear(); 937 } 938 // Send broadcasts 939 for (int i = 0; i < size; i++) { 940 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 941 } 942 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 943 break; 944 } 945 case START_CLEANING_PACKAGE: { 946 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 947 final String packageName = (String)msg.obj; 948 final int userId = msg.arg1; 949 final boolean andCode = msg.arg2 != 0; 950 synchronized (mPackages) { 951 if (userId == UserHandle.USER_ALL) { 952 int[] users = sUserManager.getUserIds(); 953 for (int user : users) { 954 mSettings.addPackageToCleanLPw( 955 new PackageCleanItem(user, packageName, andCode)); 956 } 957 } else { 958 mSettings.addPackageToCleanLPw( 959 new PackageCleanItem(userId, packageName, andCode)); 960 } 961 } 962 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 963 startCleaningPackages(); 964 } break; 965 case POST_INSTALL: { 966 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 967 PostInstallData data = mRunningInstalls.get(msg.arg1); 968 mRunningInstalls.delete(msg.arg1); 969 boolean deleteOld = false; 970 971 if (data != null) { 972 InstallArgs args = data.args; 973 PackageInstalledInfo res = data.res; 974 975 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 976 res.removedInfo.sendBroadcast(false, true, false); 977 Bundle extras = new Bundle(1); 978 extras.putInt(Intent.EXTRA_UID, res.uid); 979 // Determine the set of users who are adding this 980 // package for the first time vs. those who are seeing 981 // an update. 982 int[] firstUsers; 983 int[] updateUsers = new int[0]; 984 if (res.origUsers == null || res.origUsers.length == 0) { 985 firstUsers = res.newUsers; 986 } else { 987 firstUsers = new int[0]; 988 for (int i=0; i<res.newUsers.length; i++) { 989 int user = res.newUsers[i]; 990 boolean isNew = true; 991 for (int j=0; j<res.origUsers.length; j++) { 992 if (res.origUsers[j] == user) { 993 isNew = false; 994 break; 995 } 996 } 997 if (isNew) { 998 int[] newFirst = new int[firstUsers.length+1]; 999 System.arraycopy(firstUsers, 0, newFirst, 0, 1000 firstUsers.length); 1001 newFirst[firstUsers.length] = user; 1002 firstUsers = newFirst; 1003 } else { 1004 int[] newUpdate = new int[updateUsers.length+1]; 1005 System.arraycopy(updateUsers, 0, newUpdate, 0, 1006 updateUsers.length); 1007 newUpdate[updateUsers.length] = user; 1008 updateUsers = newUpdate; 1009 } 1010 } 1011 } 1012 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1013 res.pkg.applicationInfo.packageName, 1014 extras, null, null, firstUsers); 1015 final boolean update = res.removedInfo.removedPackage != null; 1016 if (update) { 1017 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1018 } 1019 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1020 res.pkg.applicationInfo.packageName, 1021 extras, null, null, updateUsers); 1022 if (update) { 1023 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1024 res.pkg.applicationInfo.packageName, 1025 extras, null, null, updateUsers); 1026 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1027 null, null, 1028 res.pkg.applicationInfo.packageName, null, updateUsers); 1029 1030 // treat asec-hosted packages like removable media on upgrade 1031 if (isForwardLocked(res.pkg) || isExternal(res.pkg)) { 1032 if (DEBUG_INSTALL) { 1033 Slog.i(TAG, "upgrading pkg " + res.pkg 1034 + " is ASEC-hosted -> AVAILABLE"); 1035 } 1036 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1037 ArrayList<String> pkgList = new ArrayList<String>(1); 1038 pkgList.add(res.pkg.applicationInfo.packageName); 1039 sendResourcesChangedBroadcast(true, true, 1040 pkgList,uidArray, null); 1041 } 1042 } 1043 if (res.removedInfo.args != null) { 1044 // Remove the replaced package's older resources safely now 1045 deleteOld = true; 1046 } 1047 1048 // Log current value of "unknown sources" setting 1049 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1050 getUnknownSourcesSettings()); 1051 } 1052 // Force a gc to clear up things 1053 Runtime.getRuntime().gc(); 1054 // We delete after a gc for applications on sdcard. 1055 if (deleteOld) { 1056 synchronized (mInstallLock) { 1057 res.removedInfo.args.doPostDeleteLI(true); 1058 } 1059 } 1060 if (args.observer != null) { 1061 try { 1062 Bundle extras = extrasForInstallResult(res); 1063 args.observer.onPackageInstalled(res.name, res.returnCode, 1064 res.returnMsg, extras); 1065 } catch (RemoteException e) { 1066 Slog.i(TAG, "Observer no longer exists."); 1067 } 1068 } 1069 } else { 1070 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1071 } 1072 } break; 1073 case UPDATED_MEDIA_STATUS: { 1074 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1075 boolean reportStatus = msg.arg1 == 1; 1076 boolean doGc = msg.arg2 == 1; 1077 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1078 if (doGc) { 1079 // Force a gc to clear up stale containers. 1080 Runtime.getRuntime().gc(); 1081 } 1082 if (msg.obj != null) { 1083 @SuppressWarnings("unchecked") 1084 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1085 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1086 // Unload containers 1087 unloadAllContainers(args); 1088 } 1089 if (reportStatus) { 1090 try { 1091 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1092 PackageHelper.getMountService().finishMediaUpdate(); 1093 } catch (RemoteException e) { 1094 Log.e(TAG, "MountService not running?"); 1095 } 1096 } 1097 } break; 1098 case WRITE_SETTINGS: { 1099 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1100 synchronized (mPackages) { 1101 removeMessages(WRITE_SETTINGS); 1102 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1103 mSettings.writeLPr(); 1104 mDirtyUsers.clear(); 1105 } 1106 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1107 } break; 1108 case WRITE_PACKAGE_RESTRICTIONS: { 1109 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1110 synchronized (mPackages) { 1111 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1112 for (int userId : mDirtyUsers) { 1113 mSettings.writePackageRestrictionsLPr(userId); 1114 } 1115 mDirtyUsers.clear(); 1116 } 1117 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1118 } break; 1119 case CHECK_PENDING_VERIFICATION: { 1120 final int verificationId = msg.arg1; 1121 final PackageVerificationState state = mPendingVerification.get(verificationId); 1122 1123 if ((state != null) && !state.timeoutExtended()) { 1124 final InstallArgs args = state.getInstallArgs(); 1125 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1126 1127 Slog.i(TAG, "Verification timed out for " + originUri); 1128 mPendingVerification.remove(verificationId); 1129 1130 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1131 1132 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1133 Slog.i(TAG, "Continuing with installation of " + originUri); 1134 state.setVerifierResponse(Binder.getCallingUid(), 1135 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1136 broadcastPackageVerified(verificationId, originUri, 1137 PackageManager.VERIFICATION_ALLOW, 1138 state.getInstallArgs().getUser()); 1139 try { 1140 ret = args.copyApk(mContainerService, true); 1141 } catch (RemoteException e) { 1142 Slog.e(TAG, "Could not contact the ContainerService"); 1143 } 1144 } else { 1145 broadcastPackageVerified(verificationId, originUri, 1146 PackageManager.VERIFICATION_REJECT, 1147 state.getInstallArgs().getUser()); 1148 } 1149 1150 processPendingInstall(args, ret); 1151 mHandler.sendEmptyMessage(MCS_UNBIND); 1152 } 1153 break; 1154 } 1155 case PACKAGE_VERIFIED: { 1156 final int verificationId = msg.arg1; 1157 1158 final PackageVerificationState state = mPendingVerification.get(verificationId); 1159 if (state == null) { 1160 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1161 break; 1162 } 1163 1164 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1165 1166 state.setVerifierResponse(response.callerUid, response.code); 1167 1168 if (state.isVerificationComplete()) { 1169 mPendingVerification.remove(verificationId); 1170 1171 final InstallArgs args = state.getInstallArgs(); 1172 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1173 1174 int ret; 1175 if (state.isInstallAllowed()) { 1176 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1177 broadcastPackageVerified(verificationId, originUri, 1178 response.code, state.getInstallArgs().getUser()); 1179 try { 1180 ret = args.copyApk(mContainerService, true); 1181 } catch (RemoteException e) { 1182 Slog.e(TAG, "Could not contact the ContainerService"); 1183 } 1184 } else { 1185 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1186 } 1187 1188 processPendingInstall(args, ret); 1189 1190 mHandler.sendEmptyMessage(MCS_UNBIND); 1191 } 1192 1193 break; 1194 } 1195 } 1196 } 1197 } 1198 1199 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1200 Bundle extras = null; 1201 switch (res.returnCode) { 1202 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1203 extras = new Bundle(); 1204 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1205 res.origPermission); 1206 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1207 res.origPackage); 1208 break; 1209 } 1210 } 1211 return extras; 1212 } 1213 1214 void scheduleWriteSettingsLocked() { 1215 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1216 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1217 } 1218 } 1219 1220 void scheduleWritePackageRestrictionsLocked(int userId) { 1221 if (!sUserManager.exists(userId)) return; 1222 mDirtyUsers.add(userId); 1223 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1224 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1225 } 1226 } 1227 1228 public static final PackageManagerService main(Context context, Installer installer, 1229 boolean factoryTest, boolean onlyCore) { 1230 PackageManagerService m = new PackageManagerService(context, installer, 1231 factoryTest, onlyCore); 1232 ServiceManager.addService("package", m); 1233 return m; 1234 } 1235 1236 static String[] splitString(String str, char sep) { 1237 int count = 1; 1238 int i = 0; 1239 while ((i=str.indexOf(sep, i)) >= 0) { 1240 count++; 1241 i++; 1242 } 1243 1244 String[] res = new String[count]; 1245 i=0; 1246 count = 0; 1247 int lastI=0; 1248 while ((i=str.indexOf(sep, i)) >= 0) { 1249 res[count] = str.substring(lastI, i); 1250 count++; 1251 i++; 1252 lastI = i; 1253 } 1254 res[count] = str.substring(lastI, str.length()); 1255 return res; 1256 } 1257 1258 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1259 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1260 Context.DISPLAY_SERVICE); 1261 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1262 } 1263 1264 public PackageManagerService(Context context, Installer installer, 1265 boolean factoryTest, boolean onlyCore) { 1266 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1267 SystemClock.uptimeMillis()); 1268 1269 if (mSdkVersion <= 0) { 1270 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1271 } 1272 1273 mContext = context; 1274 mFactoryTest = factoryTest; 1275 mOnlyCore = onlyCore; 1276 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1277 mMetrics = new DisplayMetrics(); 1278 mSettings = new Settings(context); 1279 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1280 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1281 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1282 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1283 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1284 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1285 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1286 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1287 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1288 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1289 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1290 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1291 1292 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1293 if (separateProcesses != null && separateProcesses.length() > 0) { 1294 if ("*".equals(separateProcesses)) { 1295 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1296 mSeparateProcesses = null; 1297 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1298 } else { 1299 mDefParseFlags = 0; 1300 mSeparateProcesses = separateProcesses.split(","); 1301 Slog.w(TAG, "Running with debug.separate_processes: " 1302 + separateProcesses); 1303 } 1304 } else { 1305 mDefParseFlags = 0; 1306 mSeparateProcesses = null; 1307 } 1308 1309 mInstaller = installer; 1310 1311 getDefaultDisplayMetrics(context, mMetrics); 1312 1313 SystemConfig systemConfig = SystemConfig.getInstance(); 1314 mGlobalGids = systemConfig.getGlobalGids(); 1315 mSystemPermissions = systemConfig.getSystemPermissions(); 1316 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1317 1318 synchronized (mInstallLock) { 1319 // writer 1320 synchronized (mPackages) { 1321 mHandlerThread = new ServiceThread(TAG, 1322 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1323 mHandlerThread.start(); 1324 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1325 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1326 1327 File dataDir = Environment.getDataDirectory(); 1328 mAppDataDir = new File(dataDir, "data"); 1329 mAppInstallDir = new File(dataDir, "app"); 1330 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1331 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1332 mUserAppDataDir = new File(dataDir, "user"); 1333 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1334 1335 sUserManager = new UserManagerService(context, this, 1336 mInstallLock, mPackages); 1337 1338 // Propagate permission configuration in to package manager. 1339 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1340 = systemConfig.getPermissions(); 1341 for (int i=0; i<permConfig.size(); i++) { 1342 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1343 BasePermission bp = mSettings.mPermissions.get(perm.name); 1344 if (bp == null) { 1345 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1346 mSettings.mPermissions.put(perm.name, bp); 1347 } 1348 if (perm.gids != null) { 1349 bp.gids = appendInts(bp.gids, perm.gids); 1350 } 1351 } 1352 1353 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1354 for (int i=0; i<libConfig.size(); i++) { 1355 mSharedLibraries.put(libConfig.keyAt(i), 1356 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1357 } 1358 1359 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1360 1361 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1362 mSdkVersion, mOnlyCore); 1363 1364 String customResolverActivity = Resources.getSystem().getString( 1365 R.string.config_customResolverActivity); 1366 if (TextUtils.isEmpty(customResolverActivity)) { 1367 customResolverActivity = null; 1368 } else { 1369 mCustomResolverComponentName = ComponentName.unflattenFromString( 1370 customResolverActivity); 1371 } 1372 1373 long startTime = SystemClock.uptimeMillis(); 1374 1375 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1376 startTime); 1377 1378 // Set flag to monitor and not change apk file paths when 1379 // scanning install directories. 1380 int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1381 1382 final HashSet<String> alreadyDexOpted = new HashSet<String>(); 1383 1384 /** 1385 * Add everything in the in the boot class path to the 1386 * list of process files because dexopt will have been run 1387 * if necessary during zygote startup. 1388 */ 1389 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1390 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1391 1392 if (bootClassPath != null) { 1393 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1394 for (String element : bootClassPathElements) { 1395 alreadyDexOpted.add(element); 1396 } 1397 } else { 1398 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1399 } 1400 1401 if (systemServerClassPath != null) { 1402 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1403 for (String element : systemServerClassPathElements) { 1404 alreadyDexOpted.add(element); 1405 } 1406 } else { 1407 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1408 } 1409 1410 boolean didDexOptLibraryOrTool = false; 1411 1412 final List<String> allInstructionSets = getAllInstructionSets(); 1413 final String[] dexCodeInstructionSets = 1414 getDexCodeInstructionSets(allInstructionSets.toArray(new String[allInstructionSets.size()])); 1415 1416 /** 1417 * Ensure all external libraries have had dexopt run on them. 1418 */ 1419 if (mSharedLibraries.size() > 0) { 1420 // NOTE: For now, we're compiling these system "shared libraries" 1421 // (and framework jars) into all available architectures. It's possible 1422 // to compile them only when we come across an app that uses them (there's 1423 // already logic for that in scanPackageLI) but that adds some complexity. 1424 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1425 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1426 final String lib = libEntry.path; 1427 if (lib == null) { 1428 continue; 1429 } 1430 1431 try { 1432 byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null, 1433 dexCodeInstructionSet, 1434 false); 1435 if (dexoptRequired != DexFile.UP_TO_DATE) { 1436 alreadyDexOpted.add(lib); 1437 1438 // The list of "shared libraries" we have at this point is 1439 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1440 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1441 } else { 1442 mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1443 } 1444 didDexOptLibraryOrTool = true; 1445 } 1446 } catch (FileNotFoundException e) { 1447 Slog.w(TAG, "Library not found: " + lib); 1448 } catch (IOException e) { 1449 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1450 + e.getMessage()); 1451 } 1452 } 1453 } 1454 } 1455 1456 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1457 1458 // Gross hack for now: we know this file doesn't contain any 1459 // code, so don't dexopt it to avoid the resulting log spew. 1460 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1461 1462 // Gross hack for now: we know this file is only part of 1463 // the boot class path for art, so don't dexopt it to 1464 // avoid the resulting log spew. 1465 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1466 1467 /** 1468 * And there are a number of commands implemented in Java, which 1469 * we currently need to do the dexopt on so that they can be 1470 * run from a non-root shell. 1471 */ 1472 String[] frameworkFiles = frameworkDir.list(); 1473 if (frameworkFiles != null) { 1474 // TODO: We could compile these only for the most preferred ABI. We should 1475 // first double check that the dex files for these commands are not referenced 1476 // by other system apps. 1477 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1478 for (int i=0; i<frameworkFiles.length; i++) { 1479 File libPath = new File(frameworkDir, frameworkFiles[i]); 1480 String path = libPath.getPath(); 1481 // Skip the file if we already did it. 1482 if (alreadyDexOpted.contains(path)) { 1483 continue; 1484 } 1485 // Skip the file if it is not a type we want to dexopt. 1486 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1487 continue; 1488 } 1489 try { 1490 byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null, 1491 dexCodeInstructionSet, 1492 false); 1493 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1494 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1495 didDexOptLibraryOrTool = true; 1496 } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) { 1497 mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1498 didDexOptLibraryOrTool = true; 1499 } 1500 } catch (FileNotFoundException e) { 1501 Slog.w(TAG, "Jar not found: " + path); 1502 } catch (IOException e) { 1503 Slog.w(TAG, "Exception reading jar: " + path, e); 1504 } 1505 } 1506 } 1507 } 1508 1509 // Collect vendor overlay packages. 1510 // (Do this before scanning any apps.) 1511 // For security and version matching reason, only consider 1512 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1513 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1514 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1515 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1516 1517 // Find base frameworks (resource packages without code). 1518 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1519 | PackageParser.PARSE_IS_SYSTEM_DIR 1520 | PackageParser.PARSE_IS_PRIVILEGED, 1521 scanFlags | SCAN_NO_DEX, 0); 1522 1523 // Collected privileged system packages. 1524 File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1525 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1526 | PackageParser.PARSE_IS_SYSTEM_DIR 1527 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1528 1529 // Collect ordinary system packages. 1530 File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1531 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1532 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1533 1534 // Collect all vendor packages. 1535 File vendorAppDir = new File("/vendor/app"); 1536 try { 1537 vendorAppDir = vendorAppDir.getCanonicalFile(); 1538 } catch (IOException e) { 1539 // failed to look up canonical path, continue with original one 1540 } 1541 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1542 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1543 1544 // Collect all OEM packages. 1545 File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1546 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1547 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1548 1549 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1550 mInstaller.moveFiles(); 1551 1552 // Prune any system packages that no longer exist. 1553 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1554 if (!mOnlyCore) { 1555 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1556 while (psit.hasNext()) { 1557 PackageSetting ps = psit.next(); 1558 1559 /* 1560 * If this is not a system app, it can't be a 1561 * disable system app. 1562 */ 1563 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1564 continue; 1565 } 1566 1567 /* 1568 * If the package is scanned, it's not erased. 1569 */ 1570 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1571 if (scannedPkg != null) { 1572 /* 1573 * If the system app is both scanned and in the 1574 * disabled packages list, then it must have been 1575 * added via OTA. Remove it from the currently 1576 * scanned package so the previously user-installed 1577 * application can be scanned. 1578 */ 1579 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1580 Slog.i(TAG, "Expecting better updatd system app for " + ps.name 1581 + "; removing system app"); 1582 removePackageLI(ps, true); 1583 } 1584 1585 continue; 1586 } 1587 1588 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1589 psit.remove(); 1590 String msg = "System package " + ps.name 1591 + " no longer exists; wiping its data"; 1592 reportSettingsProblem(Log.WARN, msg); 1593 removeDataDirsLI(ps.name); 1594 } else { 1595 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1596 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1597 possiblyDeletedUpdatedSystemApps.add(ps.name); 1598 } 1599 } 1600 } 1601 } 1602 1603 //look for any incomplete package installations 1604 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1605 //clean up list 1606 for(int i = 0; i < deletePkgsList.size(); i++) { 1607 //clean up here 1608 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1609 } 1610 //delete tmp files 1611 deleteTempPackageFiles(); 1612 1613 // Remove any shared userIDs that have no associated packages 1614 mSettings.pruneSharedUsersLPw(); 1615 1616 if (!mOnlyCore) { 1617 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 1618 SystemClock.uptimeMillis()); 1619 scanDirLI(mAppInstallDir, 0, scanFlags, 0); 1620 1621 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 1622 scanFlags, 0); 1623 1624 /** 1625 * Remove disable package settings for any updated system 1626 * apps that were removed via an OTA. If they're not a 1627 * previously-updated app, remove them completely. 1628 * Otherwise, just revoke their system-level permissions. 1629 */ 1630 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 1631 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 1632 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 1633 1634 String msg; 1635 if (deletedPkg == null) { 1636 msg = "Updated system package " + deletedAppName 1637 + " no longer exists; wiping its data"; 1638 removeDataDirsLI(deletedAppName); 1639 } else { 1640 msg = "Updated system app + " + deletedAppName 1641 + " no longer present; removing system privileges for " 1642 + deletedAppName; 1643 1644 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 1645 1646 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 1647 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 1648 } 1649 reportSettingsProblem(Log.WARN, msg); 1650 } 1651 } 1652 1653 // Now that we know all of the shared libraries, update all clients to have 1654 // the correct library paths. 1655 updateAllSharedLibrariesLPw(); 1656 1657 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 1658 // NOTE: We ignore potential failures here during a system scan (like 1659 // the rest of the commands above) because there's precious little we 1660 // can do about it. A settings error is reported, though. 1661 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 1662 false /* force dexopt */, false /* defer dexopt */); 1663 } 1664 1665 // Now that we know all the packages we are keeping, 1666 // read and update their last usage times. 1667 mPackageUsage.readLP(); 1668 1669 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 1670 SystemClock.uptimeMillis()); 1671 Slog.i(TAG, "Time to scan packages: " 1672 + ((SystemClock.uptimeMillis()-startTime)/1000f) 1673 + " seconds"); 1674 1675 // If the platform SDK has changed since the last time we booted, 1676 // we need to re-grant app permission to catch any new ones that 1677 // appear. This is really a hack, and means that apps can in some 1678 // cases get permissions that the user didn't initially explicitly 1679 // allow... it would be nice to have some better way to handle 1680 // this situation. 1681 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 1682 != mSdkVersion; 1683 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 1684 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 1685 + "; regranting permissions for internal storage"); 1686 mSettings.mInternalSdkPlatform = mSdkVersion; 1687 1688 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 1689 | (regrantPermissions 1690 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 1691 : 0)); 1692 1693 // If this is the first boot, and it is a normal boot, then 1694 // we need to initialize the default preferred apps. 1695 if (!mRestoredSettings && !onlyCore) { 1696 mSettings.readDefaultPreferredAppsLPw(this, 0); 1697 } 1698 1699 // If this is first boot after an OTA, and a normal boot, then 1700 // we need to clear code cache directories. 1701 if (!Build.FINGERPRINT.equals(mSettings.mFingerprint) && !onlyCore) { 1702 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 1703 for (String pkgName : mSettings.mPackages.keySet()) { 1704 deleteCodeCacheDirsLI(pkgName); 1705 } 1706 mSettings.mFingerprint = Build.FINGERPRINT; 1707 } 1708 1709 // All the changes are done during package scanning. 1710 mSettings.updateInternalDatabaseVersion(); 1711 1712 // can downgrade to reader 1713 mSettings.writeLPr(); 1714 1715 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 1716 SystemClock.uptimeMillis()); 1717 1718 1719 mRequiredVerifierPackage = getRequiredVerifierLPr(); 1720 } // synchronized (mPackages) 1721 } // synchronized (mInstallLock) 1722 1723 mInstallerService = new PackageInstallerService(context, this, mAppInstallDir); 1724 1725 // Now after opening every single application zip, make sure they 1726 // are all flushed. Not really needed, but keeps things nice and 1727 // tidy. 1728 Runtime.getRuntime().gc(); 1729 } 1730 1731 @Override 1732 public boolean isFirstBoot() { 1733 return !mRestoredSettings; 1734 } 1735 1736 @Override 1737 public boolean isOnlyCoreApps() { 1738 return mOnlyCore; 1739 } 1740 1741 private String getRequiredVerifierLPr() { 1742 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 1743 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 1744 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 1745 1746 String requiredVerifier = null; 1747 1748 final int N = receivers.size(); 1749 for (int i = 0; i < N; i++) { 1750 final ResolveInfo info = receivers.get(i); 1751 1752 if (info.activityInfo == null) { 1753 continue; 1754 } 1755 1756 final String packageName = info.activityInfo.packageName; 1757 1758 final PackageSetting ps = mSettings.mPackages.get(packageName); 1759 if (ps == null) { 1760 continue; 1761 } 1762 1763 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1764 if (!gp.grantedPermissions 1765 .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) { 1766 continue; 1767 } 1768 1769 if (requiredVerifier != null) { 1770 throw new RuntimeException("There can be only one required verifier"); 1771 } 1772 1773 requiredVerifier = packageName; 1774 } 1775 1776 return requiredVerifier; 1777 } 1778 1779 @Override 1780 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 1781 throws RemoteException { 1782 try { 1783 return super.onTransact(code, data, reply, flags); 1784 } catch (RuntimeException e) { 1785 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 1786 Slog.wtf(TAG, "Package Manager Crash", e); 1787 } 1788 throw e; 1789 } 1790 } 1791 1792 void cleanupInstallFailedPackage(PackageSetting ps) { 1793 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name); 1794 removeDataDirsLI(ps.name); 1795 1796 // TODO: try cleaning up codePath directory contents first, since it 1797 // might be a cluster 1798 1799 if (ps.codePath != null) { 1800 if (!ps.codePath.delete()) { 1801 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath); 1802 } 1803 } 1804 if (ps.resourcePath != null) { 1805 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) { 1806 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath); 1807 } 1808 } 1809 mSettings.removePackageLPw(ps.name); 1810 } 1811 1812 static int[] appendInts(int[] cur, int[] add) { 1813 if (add == null) return cur; 1814 if (cur == null) return add; 1815 final int N = add.length; 1816 for (int i=0; i<N; i++) { 1817 cur = appendInt(cur, add[i]); 1818 } 1819 return cur; 1820 } 1821 1822 static int[] removeInts(int[] cur, int[] rem) { 1823 if (rem == null) return cur; 1824 if (cur == null) return cur; 1825 final int N = rem.length; 1826 for (int i=0; i<N; i++) { 1827 cur = removeInt(cur, rem[i]); 1828 } 1829 return cur; 1830 } 1831 1832 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 1833 if (!sUserManager.exists(userId)) return null; 1834 final PackageSetting ps = (PackageSetting) p.mExtras; 1835 if (ps == null) { 1836 return null; 1837 } 1838 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1839 final PackageUserState state = ps.readUserState(userId); 1840 return PackageParser.generatePackageInfo(p, gp.gids, flags, 1841 ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions, 1842 state, userId); 1843 } 1844 1845 @Override 1846 public boolean isPackageAvailable(String packageName, int userId) { 1847 if (!sUserManager.exists(userId)) return false; 1848 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available"); 1849 synchronized (mPackages) { 1850 PackageParser.Package p = mPackages.get(packageName); 1851 if (p != null) { 1852 final PackageSetting ps = (PackageSetting) p.mExtras; 1853 if (ps != null) { 1854 final PackageUserState state = ps.readUserState(userId); 1855 if (state != null) { 1856 return PackageParser.isAvailable(state); 1857 } 1858 } 1859 } 1860 } 1861 return false; 1862 } 1863 1864 @Override 1865 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 1866 if (!sUserManager.exists(userId)) return null; 1867 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info"); 1868 // reader 1869 synchronized (mPackages) { 1870 PackageParser.Package p = mPackages.get(packageName); 1871 if (DEBUG_PACKAGE_INFO) 1872 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 1873 if (p != null) { 1874 return generatePackageInfo(p, flags, userId); 1875 } 1876 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 1877 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 1878 } 1879 } 1880 return null; 1881 } 1882 1883 @Override 1884 public String[] currentToCanonicalPackageNames(String[] names) { 1885 String[] out = new String[names.length]; 1886 // reader 1887 synchronized (mPackages) { 1888 for (int i=names.length-1; i>=0; i--) { 1889 PackageSetting ps = mSettings.mPackages.get(names[i]); 1890 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 1891 } 1892 } 1893 return out; 1894 } 1895 1896 @Override 1897 public String[] canonicalToCurrentPackageNames(String[] names) { 1898 String[] out = new String[names.length]; 1899 // reader 1900 synchronized (mPackages) { 1901 for (int i=names.length-1; i>=0; i--) { 1902 String cur = mSettings.mRenamedPackages.get(names[i]); 1903 out[i] = cur != null ? cur : names[i]; 1904 } 1905 } 1906 return out; 1907 } 1908 1909 @Override 1910 public int getPackageUid(String packageName, int userId) { 1911 if (!sUserManager.exists(userId)) return -1; 1912 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid"); 1913 // reader 1914 synchronized (mPackages) { 1915 PackageParser.Package p = mPackages.get(packageName); 1916 if(p != null) { 1917 return UserHandle.getUid(userId, p.applicationInfo.uid); 1918 } 1919 PackageSetting ps = mSettings.mPackages.get(packageName); 1920 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 1921 return -1; 1922 } 1923 p = ps.pkg; 1924 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 1925 } 1926 } 1927 1928 @Override 1929 public int[] getPackageGids(String packageName) { 1930 // reader 1931 synchronized (mPackages) { 1932 PackageParser.Package p = mPackages.get(packageName); 1933 if (DEBUG_PACKAGE_INFO) 1934 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 1935 if (p != null) { 1936 final PackageSetting ps = (PackageSetting)p.mExtras; 1937 return ps.getGids(); 1938 } 1939 } 1940 // stupid thing to indicate an error. 1941 return new int[0]; 1942 } 1943 1944 static final PermissionInfo generatePermissionInfo( 1945 BasePermission bp, int flags) { 1946 if (bp.perm != null) { 1947 return PackageParser.generatePermissionInfo(bp.perm, flags); 1948 } 1949 PermissionInfo pi = new PermissionInfo(); 1950 pi.name = bp.name; 1951 pi.packageName = bp.sourcePackage; 1952 pi.nonLocalizedLabel = bp.name; 1953 pi.protectionLevel = bp.protectionLevel; 1954 return pi; 1955 } 1956 1957 @Override 1958 public PermissionInfo getPermissionInfo(String name, int flags) { 1959 // reader 1960 synchronized (mPackages) { 1961 final BasePermission p = mSettings.mPermissions.get(name); 1962 if (p != null) { 1963 return generatePermissionInfo(p, flags); 1964 } 1965 return null; 1966 } 1967 } 1968 1969 @Override 1970 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 1971 // reader 1972 synchronized (mPackages) { 1973 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 1974 for (BasePermission p : mSettings.mPermissions.values()) { 1975 if (group == null) { 1976 if (p.perm == null || p.perm.info.group == null) { 1977 out.add(generatePermissionInfo(p, flags)); 1978 } 1979 } else { 1980 if (p.perm != null && group.equals(p.perm.info.group)) { 1981 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 1982 } 1983 } 1984 } 1985 1986 if (out.size() > 0) { 1987 return out; 1988 } 1989 return mPermissionGroups.containsKey(group) ? out : null; 1990 } 1991 } 1992 1993 @Override 1994 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 1995 // reader 1996 synchronized (mPackages) { 1997 return PackageParser.generatePermissionGroupInfo( 1998 mPermissionGroups.get(name), flags); 1999 } 2000 } 2001 2002 @Override 2003 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2004 // reader 2005 synchronized (mPackages) { 2006 final int N = mPermissionGroups.size(); 2007 ArrayList<PermissionGroupInfo> out 2008 = new ArrayList<PermissionGroupInfo>(N); 2009 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2010 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2011 } 2012 return out; 2013 } 2014 } 2015 2016 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2017 int userId) { 2018 if (!sUserManager.exists(userId)) return null; 2019 PackageSetting ps = mSettings.mPackages.get(packageName); 2020 if (ps != null) { 2021 if (ps.pkg == null) { 2022 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2023 flags, userId); 2024 if (pInfo != null) { 2025 return pInfo.applicationInfo; 2026 } 2027 return null; 2028 } 2029 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2030 ps.readUserState(userId), userId); 2031 } 2032 return null; 2033 } 2034 2035 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2036 int userId) { 2037 if (!sUserManager.exists(userId)) return null; 2038 PackageSetting ps = mSettings.mPackages.get(packageName); 2039 if (ps != null) { 2040 PackageParser.Package pkg = ps.pkg; 2041 if (pkg == null) { 2042 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2043 return null; 2044 } 2045 // Only data remains, so we aren't worried about code paths 2046 pkg = new PackageParser.Package(packageName); 2047 pkg.applicationInfo.packageName = packageName; 2048 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2049 pkg.applicationInfo.dataDir = 2050 getDataPathForPackage(packageName, 0).getPath(); 2051 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2052 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2053 } 2054 return generatePackageInfo(pkg, flags, userId); 2055 } 2056 return null; 2057 } 2058 2059 @Override 2060 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2061 if (!sUserManager.exists(userId)) return null; 2062 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info"); 2063 // writer 2064 synchronized (mPackages) { 2065 PackageParser.Package p = mPackages.get(packageName); 2066 if (DEBUG_PACKAGE_INFO) Log.v( 2067 TAG, "getApplicationInfo " + packageName 2068 + ": " + p); 2069 if (p != null) { 2070 PackageSetting ps = mSettings.mPackages.get(packageName); 2071 if (ps == null) return null; 2072 // Note: isEnabledLP() does not apply here - always return info 2073 return PackageParser.generateApplicationInfo( 2074 p, flags, ps.readUserState(userId), userId); 2075 } 2076 if ("android".equals(packageName)||"system".equals(packageName)) { 2077 return mAndroidApplication; 2078 } 2079 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2080 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2081 } 2082 } 2083 return null; 2084 } 2085 2086 2087 @Override 2088 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2089 mContext.enforceCallingOrSelfPermission( 2090 android.Manifest.permission.CLEAR_APP_CACHE, null); 2091 // Queue up an async operation since clearing cache may take a little while. 2092 mHandler.post(new Runnable() { 2093 public void run() { 2094 mHandler.removeCallbacks(this); 2095 int retCode = -1; 2096 synchronized (mInstallLock) { 2097 retCode = mInstaller.freeCache(freeStorageSize); 2098 if (retCode < 0) { 2099 Slog.w(TAG, "Couldn't clear application caches"); 2100 } 2101 } 2102 if (observer != null) { 2103 try { 2104 observer.onRemoveCompleted(null, (retCode >= 0)); 2105 } catch (RemoteException e) { 2106 Slog.w(TAG, "RemoveException when invoking call back"); 2107 } 2108 } 2109 } 2110 }); 2111 } 2112 2113 @Override 2114 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2115 mContext.enforceCallingOrSelfPermission( 2116 android.Manifest.permission.CLEAR_APP_CACHE, null); 2117 // Queue up an async operation since clearing cache may take a little while. 2118 mHandler.post(new Runnable() { 2119 public void run() { 2120 mHandler.removeCallbacks(this); 2121 int retCode = -1; 2122 synchronized (mInstallLock) { 2123 retCode = mInstaller.freeCache(freeStorageSize); 2124 if (retCode < 0) { 2125 Slog.w(TAG, "Couldn't clear application caches"); 2126 } 2127 } 2128 if(pi != null) { 2129 try { 2130 // Callback via pending intent 2131 int code = (retCode >= 0) ? 1 : 0; 2132 pi.sendIntent(null, code, null, 2133 null, null); 2134 } catch (SendIntentException e1) { 2135 Slog.i(TAG, "Failed to send pending intent"); 2136 } 2137 } 2138 } 2139 }); 2140 } 2141 2142 void freeStorage(long freeStorageSize) throws IOException { 2143 synchronized (mInstallLock) { 2144 if (mInstaller.freeCache(freeStorageSize) < 0) { 2145 throw new IOException("Failed to free enough space"); 2146 } 2147 } 2148 } 2149 2150 @Override 2151 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2152 if (!sUserManager.exists(userId)) return null; 2153 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info"); 2154 synchronized (mPackages) { 2155 PackageParser.Activity a = mActivities.mActivities.get(component); 2156 2157 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2158 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2159 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2160 if (ps == null) return null; 2161 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2162 userId); 2163 } 2164 if (mResolveComponentName.equals(component)) { 2165 return mResolveActivity; 2166 } 2167 } 2168 return null; 2169 } 2170 2171 @Override 2172 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2173 String resolvedType) { 2174 synchronized (mPackages) { 2175 PackageParser.Activity a = mActivities.mActivities.get(component); 2176 if (a == null) { 2177 return false; 2178 } 2179 for (int i=0; i<a.intents.size(); i++) { 2180 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2181 intent.getData(), intent.getCategories(), TAG) >= 0) { 2182 return true; 2183 } 2184 } 2185 return false; 2186 } 2187 } 2188 2189 @Override 2190 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2191 if (!sUserManager.exists(userId)) return null; 2192 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info"); 2193 synchronized (mPackages) { 2194 PackageParser.Activity a = mReceivers.mActivities.get(component); 2195 if (DEBUG_PACKAGE_INFO) Log.v( 2196 TAG, "getReceiverInfo " + component + ": " + a); 2197 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2198 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2199 if (ps == null) return null; 2200 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2201 userId); 2202 } 2203 } 2204 return null; 2205 } 2206 2207 @Override 2208 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2209 if (!sUserManager.exists(userId)) return null; 2210 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info"); 2211 synchronized (mPackages) { 2212 PackageParser.Service s = mServices.mServices.get(component); 2213 if (DEBUG_PACKAGE_INFO) Log.v( 2214 TAG, "getServiceInfo " + component + ": " + s); 2215 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2216 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2217 if (ps == null) return null; 2218 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2219 userId); 2220 } 2221 } 2222 return null; 2223 } 2224 2225 @Override 2226 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2227 if (!sUserManager.exists(userId)) return null; 2228 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info"); 2229 synchronized (mPackages) { 2230 PackageParser.Provider p = mProviders.mProviders.get(component); 2231 if (DEBUG_PACKAGE_INFO) Log.v( 2232 TAG, "getProviderInfo " + component + ": " + p); 2233 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2234 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2235 if (ps == null) return null; 2236 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2237 userId); 2238 } 2239 } 2240 return null; 2241 } 2242 2243 @Override 2244 public String[] getSystemSharedLibraryNames() { 2245 Set<String> libSet; 2246 synchronized (mPackages) { 2247 libSet = mSharedLibraries.keySet(); 2248 int size = libSet.size(); 2249 if (size > 0) { 2250 String[] libs = new String[size]; 2251 libSet.toArray(libs); 2252 return libs; 2253 } 2254 } 2255 return null; 2256 } 2257 2258 @Override 2259 public FeatureInfo[] getSystemAvailableFeatures() { 2260 Collection<FeatureInfo> featSet; 2261 synchronized (mPackages) { 2262 featSet = mAvailableFeatures.values(); 2263 int size = featSet.size(); 2264 if (size > 0) { 2265 FeatureInfo[] features = new FeatureInfo[size+1]; 2266 featSet.toArray(features); 2267 FeatureInfo fi = new FeatureInfo(); 2268 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2269 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2270 features[size] = fi; 2271 return features; 2272 } 2273 } 2274 return null; 2275 } 2276 2277 @Override 2278 public boolean hasSystemFeature(String name) { 2279 synchronized (mPackages) { 2280 return mAvailableFeatures.containsKey(name); 2281 } 2282 } 2283 2284 private void checkValidCaller(int uid, int userId) { 2285 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2286 return; 2287 2288 throw new SecurityException("Caller uid=" + uid 2289 + " is not privileged to communicate with user=" + userId); 2290 } 2291 2292 @Override 2293 public int checkPermission(String permName, String pkgName) { 2294 synchronized (mPackages) { 2295 PackageParser.Package p = mPackages.get(pkgName); 2296 if (p != null && p.mExtras != null) { 2297 PackageSetting ps = (PackageSetting)p.mExtras; 2298 if (ps.sharedUser != null) { 2299 if (ps.sharedUser.grantedPermissions.contains(permName)) { 2300 return PackageManager.PERMISSION_GRANTED; 2301 } 2302 } else if (ps.grantedPermissions.contains(permName)) { 2303 return PackageManager.PERMISSION_GRANTED; 2304 } 2305 } 2306 } 2307 return PackageManager.PERMISSION_DENIED; 2308 } 2309 2310 @Override 2311 public int checkUidPermission(String permName, int uid) { 2312 synchronized (mPackages) { 2313 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2314 if (obj != null) { 2315 GrantedPermissions gp = (GrantedPermissions)obj; 2316 if (gp.grantedPermissions.contains(permName)) { 2317 return PackageManager.PERMISSION_GRANTED; 2318 } 2319 } else { 2320 HashSet<String> perms = mSystemPermissions.get(uid); 2321 if (perms != null && perms.contains(permName)) { 2322 return PackageManager.PERMISSION_GRANTED; 2323 } 2324 } 2325 } 2326 return PackageManager.PERMISSION_DENIED; 2327 } 2328 2329 /** 2330 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2331 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2332 * @param message the message to log on security exception 2333 */ 2334 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2335 String message) { 2336 if (userId < 0) { 2337 throw new IllegalArgumentException("Invalid userId " + userId); 2338 } 2339 if (userId == UserHandle.getUserId(callingUid)) return; 2340 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2341 if (requireFullPermission) { 2342 mContext.enforceCallingOrSelfPermission( 2343 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2344 } else { 2345 try { 2346 mContext.enforceCallingOrSelfPermission( 2347 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2348 } catch (SecurityException se) { 2349 mContext.enforceCallingOrSelfPermission( 2350 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2351 } 2352 } 2353 } 2354 } 2355 2356 private BasePermission findPermissionTreeLP(String permName) { 2357 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2358 if (permName.startsWith(bp.name) && 2359 permName.length() > bp.name.length() && 2360 permName.charAt(bp.name.length()) == '.') { 2361 return bp; 2362 } 2363 } 2364 return null; 2365 } 2366 2367 private BasePermission checkPermissionTreeLP(String permName) { 2368 if (permName != null) { 2369 BasePermission bp = findPermissionTreeLP(permName); 2370 if (bp != null) { 2371 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2372 return bp; 2373 } 2374 throw new SecurityException("Calling uid " 2375 + Binder.getCallingUid() 2376 + " is not allowed to add to permission tree " 2377 + bp.name + " owned by uid " + bp.uid); 2378 } 2379 } 2380 throw new SecurityException("No permission tree found for " + permName); 2381 } 2382 2383 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2384 if (s1 == null) { 2385 return s2 == null; 2386 } 2387 if (s2 == null) { 2388 return false; 2389 } 2390 if (s1.getClass() != s2.getClass()) { 2391 return false; 2392 } 2393 return s1.equals(s2); 2394 } 2395 2396 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2397 if (pi1.icon != pi2.icon) return false; 2398 if (pi1.logo != pi2.logo) return false; 2399 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2400 if (!compareStrings(pi1.name, pi2.name)) return false; 2401 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2402 // We'll take care of setting this one. 2403 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2404 // These are not currently stored in settings. 2405 //if (!compareStrings(pi1.group, pi2.group)) return false; 2406 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2407 //if (pi1.labelRes != pi2.labelRes) return false; 2408 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2409 return true; 2410 } 2411 2412 int permissionInfoFootprint(PermissionInfo info) { 2413 int size = info.name.length(); 2414 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2415 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2416 return size; 2417 } 2418 2419 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2420 int size = 0; 2421 for (BasePermission perm : mSettings.mPermissions.values()) { 2422 if (perm.uid == tree.uid) { 2423 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2424 } 2425 } 2426 return size; 2427 } 2428 2429 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2430 // We calculate the max size of permissions defined by this uid and throw 2431 // if that plus the size of 'info' would exceed our stated maximum. 2432 if (tree.uid != Process.SYSTEM_UID) { 2433 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2434 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2435 throw new SecurityException("Permission tree size cap exceeded"); 2436 } 2437 } 2438 } 2439 2440 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2441 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2442 throw new SecurityException("Label must be specified in permission"); 2443 } 2444 BasePermission tree = checkPermissionTreeLP(info.name); 2445 BasePermission bp = mSettings.mPermissions.get(info.name); 2446 boolean added = bp == null; 2447 boolean changed = true; 2448 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2449 if (added) { 2450 enforcePermissionCapLocked(info, tree); 2451 bp = new BasePermission(info.name, tree.sourcePackage, 2452 BasePermission.TYPE_DYNAMIC); 2453 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2454 throw new SecurityException( 2455 "Not allowed to modify non-dynamic permission " 2456 + info.name); 2457 } else { 2458 if (bp.protectionLevel == fixedLevel 2459 && bp.perm.owner.equals(tree.perm.owner) 2460 && bp.uid == tree.uid 2461 && comparePermissionInfos(bp.perm.info, info)) { 2462 changed = false; 2463 } 2464 } 2465 bp.protectionLevel = fixedLevel; 2466 info = new PermissionInfo(info); 2467 info.protectionLevel = fixedLevel; 2468 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 2469 bp.perm.info.packageName = tree.perm.info.packageName; 2470 bp.uid = tree.uid; 2471 if (added) { 2472 mSettings.mPermissions.put(info.name, bp); 2473 } 2474 if (changed) { 2475 if (!async) { 2476 mSettings.writeLPr(); 2477 } else { 2478 scheduleWriteSettingsLocked(); 2479 } 2480 } 2481 return added; 2482 } 2483 2484 @Override 2485 public boolean addPermission(PermissionInfo info) { 2486 synchronized (mPackages) { 2487 return addPermissionLocked(info, false); 2488 } 2489 } 2490 2491 @Override 2492 public boolean addPermissionAsync(PermissionInfo info) { 2493 synchronized (mPackages) { 2494 return addPermissionLocked(info, true); 2495 } 2496 } 2497 2498 @Override 2499 public void removePermission(String name) { 2500 synchronized (mPackages) { 2501 checkPermissionTreeLP(name); 2502 BasePermission bp = mSettings.mPermissions.get(name); 2503 if (bp != null) { 2504 if (bp.type != BasePermission.TYPE_DYNAMIC) { 2505 throw new SecurityException( 2506 "Not allowed to modify non-dynamic permission " 2507 + name); 2508 } 2509 mSettings.mPermissions.remove(name); 2510 mSettings.writeLPr(); 2511 } 2512 } 2513 } 2514 2515 private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) { 2516 int index = pkg.requestedPermissions.indexOf(bp.name); 2517 if (index == -1) { 2518 throw new SecurityException("Package " + pkg.packageName 2519 + " has not requested permission " + bp.name); 2520 } 2521 boolean isNormal = 2522 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2523 == PermissionInfo.PROTECTION_NORMAL); 2524 boolean isDangerous = 2525 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2526 == PermissionInfo.PROTECTION_DANGEROUS); 2527 boolean isDevelopment = 2528 ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0); 2529 2530 if (!isNormal && !isDangerous && !isDevelopment) { 2531 throw new SecurityException("Permission " + bp.name 2532 + " is not a changeable permission type"); 2533 } 2534 2535 if (isNormal || isDangerous) { 2536 if (pkg.requestedPermissionsRequired.get(index)) { 2537 throw new SecurityException("Can't change " + bp.name 2538 + ". It is required by the application"); 2539 } 2540 } 2541 } 2542 2543 @Override 2544 public void grantPermission(String packageName, String permissionName) { 2545 mContext.enforceCallingOrSelfPermission( 2546 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2547 synchronized (mPackages) { 2548 final PackageParser.Package pkg = mPackages.get(packageName); 2549 if (pkg == null) { 2550 throw new IllegalArgumentException("Unknown package: " + packageName); 2551 } 2552 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2553 if (bp == null) { 2554 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2555 } 2556 2557 checkGrantRevokePermissions(pkg, bp); 2558 2559 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2560 if (ps == null) { 2561 return; 2562 } 2563 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2564 if (gp.grantedPermissions.add(permissionName)) { 2565 if (ps.haveGids) { 2566 gp.gids = appendInts(gp.gids, bp.gids); 2567 } 2568 mSettings.writeLPr(); 2569 } 2570 } 2571 } 2572 2573 @Override 2574 public void revokePermission(String packageName, String permissionName) { 2575 int changedAppId = -1; 2576 2577 synchronized (mPackages) { 2578 final PackageParser.Package pkg = mPackages.get(packageName); 2579 if (pkg == null) { 2580 throw new IllegalArgumentException("Unknown package: " + packageName); 2581 } 2582 if (pkg.applicationInfo.uid != Binder.getCallingUid()) { 2583 mContext.enforceCallingOrSelfPermission( 2584 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2585 } 2586 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2587 if (bp == null) { 2588 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2589 } 2590 2591 checkGrantRevokePermissions(pkg, bp); 2592 2593 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2594 if (ps == null) { 2595 return; 2596 } 2597 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2598 if (gp.grantedPermissions.remove(permissionName)) { 2599 gp.grantedPermissions.remove(permissionName); 2600 if (ps.haveGids) { 2601 gp.gids = removeInts(gp.gids, bp.gids); 2602 } 2603 mSettings.writeLPr(); 2604 changedAppId = ps.appId; 2605 } 2606 } 2607 2608 if (changedAppId >= 0) { 2609 // We changed the perm on someone, kill its processes. 2610 IActivityManager am = ActivityManagerNative.getDefault(); 2611 if (am != null) { 2612 final int callingUserId = UserHandle.getCallingUserId(); 2613 final long ident = Binder.clearCallingIdentity(); 2614 try { 2615 //XXX we should only revoke for the calling user's app permissions, 2616 // but for now we impact all users. 2617 //am.killUid(UserHandle.getUid(callingUserId, changedAppId), 2618 // "revoke " + permissionName); 2619 int[] users = sUserManager.getUserIds(); 2620 for (int user : users) { 2621 am.killUid(UserHandle.getUid(user, changedAppId), 2622 "revoke " + permissionName); 2623 } 2624 } catch (RemoteException e) { 2625 } finally { 2626 Binder.restoreCallingIdentity(ident); 2627 } 2628 } 2629 } 2630 } 2631 2632 @Override 2633 public boolean isProtectedBroadcast(String actionName) { 2634 synchronized (mPackages) { 2635 return mProtectedBroadcasts.contains(actionName); 2636 } 2637 } 2638 2639 @Override 2640 public int checkSignatures(String pkg1, String pkg2) { 2641 synchronized (mPackages) { 2642 final PackageParser.Package p1 = mPackages.get(pkg1); 2643 final PackageParser.Package p2 = mPackages.get(pkg2); 2644 if (p1 == null || p1.mExtras == null 2645 || p2 == null || p2.mExtras == null) { 2646 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2647 } 2648 return compareSignatures(p1.mSignatures, p2.mSignatures); 2649 } 2650 } 2651 2652 @Override 2653 public int checkUidSignatures(int uid1, int uid2) { 2654 // Map to base uids. 2655 uid1 = UserHandle.getAppId(uid1); 2656 uid2 = UserHandle.getAppId(uid2); 2657 // reader 2658 synchronized (mPackages) { 2659 Signature[] s1; 2660 Signature[] s2; 2661 Object obj = mSettings.getUserIdLPr(uid1); 2662 if (obj != null) { 2663 if (obj instanceof SharedUserSetting) { 2664 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 2665 } else if (obj instanceof PackageSetting) { 2666 s1 = ((PackageSetting)obj).signatures.mSignatures; 2667 } else { 2668 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2669 } 2670 } else { 2671 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2672 } 2673 obj = mSettings.getUserIdLPr(uid2); 2674 if (obj != null) { 2675 if (obj instanceof SharedUserSetting) { 2676 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 2677 } else if (obj instanceof PackageSetting) { 2678 s2 = ((PackageSetting)obj).signatures.mSignatures; 2679 } else { 2680 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2681 } 2682 } else { 2683 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2684 } 2685 return compareSignatures(s1, s2); 2686 } 2687 } 2688 2689 /** 2690 * Compares two sets of signatures. Returns: 2691 * <br /> 2692 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 2693 * <br /> 2694 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 2695 * <br /> 2696 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 2697 * <br /> 2698 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 2699 * <br /> 2700 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 2701 */ 2702 static int compareSignatures(Signature[] s1, Signature[] s2) { 2703 if (s1 == null) { 2704 return s2 == null 2705 ? PackageManager.SIGNATURE_NEITHER_SIGNED 2706 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 2707 } 2708 2709 if (s2 == null) { 2710 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 2711 } 2712 2713 if (s1.length != s2.length) { 2714 return PackageManager.SIGNATURE_NO_MATCH; 2715 } 2716 2717 // Since both signature sets are of size 1, we can compare without HashSets. 2718 if (s1.length == 1) { 2719 return s1[0].equals(s2[0]) ? 2720 PackageManager.SIGNATURE_MATCH : 2721 PackageManager.SIGNATURE_NO_MATCH; 2722 } 2723 2724 HashSet<Signature> set1 = new HashSet<Signature>(); 2725 for (Signature sig : s1) { 2726 set1.add(sig); 2727 } 2728 HashSet<Signature> set2 = new HashSet<Signature>(); 2729 for (Signature sig : s2) { 2730 set2.add(sig); 2731 } 2732 // Make sure s2 contains all signatures in s1. 2733 if (set1.equals(set2)) { 2734 return PackageManager.SIGNATURE_MATCH; 2735 } 2736 return PackageManager.SIGNATURE_NO_MATCH; 2737 } 2738 2739 /** 2740 * If the database version for this type of package (internal storage or 2741 * external storage) is less than the version where package signatures 2742 * were updated, return true. 2743 */ 2744 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2745 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 2746 DatabaseVersion.SIGNATURE_END_ENTITY)) 2747 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 2748 DatabaseVersion.SIGNATURE_END_ENTITY)); 2749 } 2750 2751 /** 2752 * Used for backward compatibility to make sure any packages with 2753 * certificate chains get upgraded to the new style. {@code existingSigs} 2754 * will be in the old format (since they were stored on disk from before the 2755 * system upgrade) and {@code scannedSigs} will be in the newer format. 2756 */ 2757 private int compareSignaturesCompat(PackageSignatures existingSigs, 2758 PackageParser.Package scannedPkg) { 2759 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 2760 return PackageManager.SIGNATURE_NO_MATCH; 2761 } 2762 2763 HashSet<Signature> existingSet = new HashSet<Signature>(); 2764 for (Signature sig : existingSigs.mSignatures) { 2765 existingSet.add(sig); 2766 } 2767 HashSet<Signature> scannedCompatSet = new HashSet<Signature>(); 2768 for (Signature sig : scannedPkg.mSignatures) { 2769 try { 2770 Signature[] chainSignatures = sig.getChainSignatures(); 2771 for (Signature chainSig : chainSignatures) { 2772 scannedCompatSet.add(chainSig); 2773 } 2774 } catch (CertificateEncodingException e) { 2775 scannedCompatSet.add(sig); 2776 } 2777 } 2778 /* 2779 * Make sure the expanded scanned set contains all signatures in the 2780 * existing one. 2781 */ 2782 if (scannedCompatSet.equals(existingSet)) { 2783 // Migrate the old signatures to the new scheme. 2784 existingSigs.assignSignatures(scannedPkg.mSignatures); 2785 // The new KeySets will be re-added later in the scanning process. 2786 synchronized (mPackages) { 2787 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 2788 } 2789 return PackageManager.SIGNATURE_MATCH; 2790 } 2791 return PackageManager.SIGNATURE_NO_MATCH; 2792 } 2793 2794 @Override 2795 public String[] getPackagesForUid(int uid) { 2796 uid = UserHandle.getAppId(uid); 2797 // reader 2798 synchronized (mPackages) { 2799 Object obj = mSettings.getUserIdLPr(uid); 2800 if (obj instanceof SharedUserSetting) { 2801 final SharedUserSetting sus = (SharedUserSetting) obj; 2802 final int N = sus.packages.size(); 2803 final String[] res = new String[N]; 2804 final Iterator<PackageSetting> it = sus.packages.iterator(); 2805 int i = 0; 2806 while (it.hasNext()) { 2807 res[i++] = it.next().name; 2808 } 2809 return res; 2810 } else if (obj instanceof PackageSetting) { 2811 final PackageSetting ps = (PackageSetting) obj; 2812 return new String[] { ps.name }; 2813 } 2814 } 2815 return null; 2816 } 2817 2818 @Override 2819 public String getNameForUid(int uid) { 2820 // reader 2821 synchronized (mPackages) { 2822 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2823 if (obj instanceof SharedUserSetting) { 2824 final SharedUserSetting sus = (SharedUserSetting) obj; 2825 return sus.name + ":" + sus.userId; 2826 } else if (obj instanceof PackageSetting) { 2827 final PackageSetting ps = (PackageSetting) obj; 2828 return ps.name; 2829 } 2830 } 2831 return null; 2832 } 2833 2834 @Override 2835 public int getUidForSharedUser(String sharedUserName) { 2836 if(sharedUserName == null) { 2837 return -1; 2838 } 2839 // reader 2840 synchronized (mPackages) { 2841 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false); 2842 if (suid == null) { 2843 return -1; 2844 } 2845 return suid.userId; 2846 } 2847 } 2848 2849 @Override 2850 public int getFlagsForUid(int uid) { 2851 synchronized (mPackages) { 2852 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2853 if (obj instanceof SharedUserSetting) { 2854 final SharedUserSetting sus = (SharedUserSetting) obj; 2855 return sus.pkgFlags; 2856 } else if (obj instanceof PackageSetting) { 2857 final PackageSetting ps = (PackageSetting) obj; 2858 return ps.pkgFlags; 2859 } 2860 } 2861 return 0; 2862 } 2863 2864 @Override 2865 public String[] getAppOpPermissionPackages(String permissionName) { 2866 synchronized (mPackages) { 2867 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 2868 if (pkgs == null) { 2869 return null; 2870 } 2871 return pkgs.toArray(new String[pkgs.size()]); 2872 } 2873 } 2874 2875 @Override 2876 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 2877 int flags, int userId) { 2878 if (!sUserManager.exists(userId)) return null; 2879 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent"); 2880 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2881 return chooseBestActivity(intent, resolvedType, flags, query, userId); 2882 } 2883 2884 @Override 2885 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 2886 IntentFilter filter, int match, ComponentName activity) { 2887 final int userId = UserHandle.getCallingUserId(); 2888 if (DEBUG_PREFERRED) { 2889 Log.v(TAG, "setLastChosenActivity intent=" + intent 2890 + " resolvedType=" + resolvedType 2891 + " flags=" + flags 2892 + " filter=" + filter 2893 + " match=" + match 2894 + " activity=" + activity); 2895 filter.dump(new PrintStreamPrinter(System.out), " "); 2896 } 2897 intent.setComponent(null); 2898 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2899 // Find any earlier preferred or last chosen entries and nuke them 2900 findPreferredActivity(intent, resolvedType, 2901 flags, query, 0, false, true, false, userId); 2902 // Add the new activity as the last chosen for this filter 2903 addPreferredActivityInternal(filter, match, null, activity, false, userId, 2904 "Setting last chosen"); 2905 } 2906 2907 @Override 2908 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 2909 final int userId = UserHandle.getCallingUserId(); 2910 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 2911 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2912 return findPreferredActivity(intent, resolvedType, flags, query, 0, 2913 false, false, false, userId); 2914 } 2915 2916 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 2917 int flags, List<ResolveInfo> query, int userId) { 2918 if (query != null) { 2919 final int N = query.size(); 2920 if (N == 1) { 2921 return query.get(0); 2922 } else if (N > 1) { 2923 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 2924 // If there is more than one activity with the same priority, 2925 // then let the user decide between them. 2926 ResolveInfo r0 = query.get(0); 2927 ResolveInfo r1 = query.get(1); 2928 if (DEBUG_INTENT_MATCHING || debug) { 2929 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 2930 + r1.activityInfo.name + "=" + r1.priority); 2931 } 2932 // If the first activity has a higher priority, or a different 2933 // default, then it is always desireable to pick it. 2934 if (r0.priority != r1.priority 2935 || r0.preferredOrder != r1.preferredOrder 2936 || r0.isDefault != r1.isDefault) { 2937 return query.get(0); 2938 } 2939 // If we have saved a preference for a preferred activity for 2940 // this Intent, use that. 2941 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 2942 flags, query, r0.priority, true, false, debug, userId); 2943 if (ri != null) { 2944 return ri; 2945 } 2946 if (userId != 0) { 2947 ri = new ResolveInfo(mResolveInfo); 2948 ri.activityInfo = new ActivityInfo(ri.activityInfo); 2949 ri.activityInfo.applicationInfo = new ApplicationInfo( 2950 ri.activityInfo.applicationInfo); 2951 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 2952 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 2953 return ri; 2954 } 2955 return mResolveInfo; 2956 } 2957 } 2958 return null; 2959 } 2960 2961 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 2962 int flags, List<ResolveInfo> query, boolean debug, int userId) { 2963 final int N = query.size(); 2964 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 2965 .get(userId); 2966 // Get the list of persistent preferred activities that handle the intent 2967 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 2968 List<PersistentPreferredActivity> pprefs = ppir != null 2969 ? ppir.queryIntent(intent, resolvedType, 2970 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 2971 : null; 2972 if (pprefs != null && pprefs.size() > 0) { 2973 final int M = pprefs.size(); 2974 for (int i=0; i<M; i++) { 2975 final PersistentPreferredActivity ppa = pprefs.get(i); 2976 if (DEBUG_PREFERRED || debug) { 2977 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 2978 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 2979 + "\n component=" + ppa.mComponent); 2980 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 2981 } 2982 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 2983 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 2984 if (DEBUG_PREFERRED || debug) { 2985 Slog.v(TAG, "Found persistent preferred activity:"); 2986 if (ai != null) { 2987 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 2988 } else { 2989 Slog.v(TAG, " null"); 2990 } 2991 } 2992 if (ai == null) { 2993 // This previously registered persistent preferred activity 2994 // component is no longer known. Ignore it and do NOT remove it. 2995 continue; 2996 } 2997 for (int j=0; j<N; j++) { 2998 final ResolveInfo ri = query.get(j); 2999 if (!ri.activityInfo.applicationInfo.packageName 3000 .equals(ai.applicationInfo.packageName)) { 3001 continue; 3002 } 3003 if (!ri.activityInfo.name.equals(ai.name)) { 3004 continue; 3005 } 3006 // Found a persistent preference that can handle the intent. 3007 if (DEBUG_PREFERRED || debug) { 3008 Slog.v(TAG, "Returning persistent preferred activity: " + 3009 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3010 } 3011 return ri; 3012 } 3013 } 3014 } 3015 return null; 3016 } 3017 3018 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3019 List<ResolveInfo> query, int priority, boolean always, 3020 boolean removeMatches, boolean debug, int userId) { 3021 if (!sUserManager.exists(userId)) return null; 3022 // writer 3023 synchronized (mPackages) { 3024 if (intent.getSelector() != null) { 3025 intent = intent.getSelector(); 3026 } 3027 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3028 3029 // Try to find a matching persistent preferred activity. 3030 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3031 debug, userId); 3032 3033 // If a persistent preferred activity matched, use it. 3034 if (pri != null) { 3035 return pri; 3036 } 3037 3038 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3039 // Get the list of preferred activities that handle the intent 3040 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3041 List<PreferredActivity> prefs = pir != null 3042 ? pir.queryIntent(intent, resolvedType, 3043 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3044 : null; 3045 if (prefs != null && prefs.size() > 0) { 3046 boolean changed = false; 3047 try { 3048 // First figure out how good the original match set is. 3049 // We will only allow preferred activities that came 3050 // from the same match quality. 3051 int match = 0; 3052 3053 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3054 3055 final int N = query.size(); 3056 for (int j=0; j<N; j++) { 3057 final ResolveInfo ri = query.get(j); 3058 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3059 + ": 0x" + Integer.toHexString(match)); 3060 if (ri.match > match) { 3061 match = ri.match; 3062 } 3063 } 3064 3065 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3066 + Integer.toHexString(match)); 3067 3068 match &= IntentFilter.MATCH_CATEGORY_MASK; 3069 final int M = prefs.size(); 3070 for (int i=0; i<M; i++) { 3071 final PreferredActivity pa = prefs.get(i); 3072 if (DEBUG_PREFERRED || debug) { 3073 Slog.v(TAG, "Checking PreferredActivity ds=" 3074 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3075 + "\n component=" + pa.mPref.mComponent); 3076 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3077 } 3078 if (pa.mPref.mMatch != match) { 3079 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3080 + Integer.toHexString(pa.mPref.mMatch)); 3081 continue; 3082 } 3083 // If it's not an "always" type preferred activity and that's what we're 3084 // looking for, skip it. 3085 if (always && !pa.mPref.mAlways) { 3086 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3087 continue; 3088 } 3089 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3090 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3091 if (DEBUG_PREFERRED || debug) { 3092 Slog.v(TAG, "Found preferred activity:"); 3093 if (ai != null) { 3094 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3095 } else { 3096 Slog.v(TAG, " null"); 3097 } 3098 } 3099 if (ai == null) { 3100 // This previously registered preferred activity 3101 // component is no longer known. Most likely an update 3102 // to the app was installed and in the new version this 3103 // component no longer exists. Clean it up by removing 3104 // it from the preferred activities list, and skip it. 3105 Slog.w(TAG, "Removing dangling preferred activity: " 3106 + pa.mPref.mComponent); 3107 pir.removeFilter(pa); 3108 changed = true; 3109 continue; 3110 } 3111 for (int j=0; j<N; j++) { 3112 final ResolveInfo ri = query.get(j); 3113 if (!ri.activityInfo.applicationInfo.packageName 3114 .equals(ai.applicationInfo.packageName)) { 3115 continue; 3116 } 3117 if (!ri.activityInfo.name.equals(ai.name)) { 3118 continue; 3119 } 3120 3121 if (removeMatches) { 3122 pir.removeFilter(pa); 3123 changed = true; 3124 if (DEBUG_PREFERRED) { 3125 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3126 } 3127 break; 3128 } 3129 3130 // Okay we found a previously set preferred or last chosen app. 3131 // If the result set is different from when this 3132 // was created, we need to clear it and re-ask the 3133 // user their preference, if we're looking for an "always" type entry. 3134 if (always && !pa.mPref.sameSet(query, priority)) { 3135 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3136 + intent + " type " + resolvedType); 3137 if (DEBUG_PREFERRED) { 3138 Slog.v(TAG, "Removing preferred activity since set changed " 3139 + pa.mPref.mComponent); 3140 } 3141 pir.removeFilter(pa); 3142 // Re-add the filter as a "last chosen" entry (!always) 3143 PreferredActivity lastChosen = new PreferredActivity( 3144 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3145 pir.addFilter(lastChosen); 3146 changed = true; 3147 return null; 3148 } 3149 3150 // Yay! Either the set matched or we're looking for the last chosen 3151 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3152 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3153 return ri; 3154 } 3155 } 3156 } finally { 3157 if (changed) { 3158 if (DEBUG_PREFERRED) { 3159 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 3160 } 3161 mSettings.writePackageRestrictionsLPr(userId); 3162 } 3163 } 3164 } 3165 } 3166 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3167 return null; 3168 } 3169 3170 /* 3171 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3172 */ 3173 @Override 3174 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3175 int targetUserId) { 3176 mContext.enforceCallingOrSelfPermission( 3177 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3178 List<CrossProfileIntentFilter> matches = 3179 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3180 if (matches != null) { 3181 int size = matches.size(); 3182 for (int i = 0; i < size; i++) { 3183 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3184 } 3185 } 3186 ArrayList<String> packageNames = null; 3187 SparseArray<ArrayList<String>> fromSource = 3188 mSettings.mCrossProfilePackageInfo.get(sourceUserId); 3189 if (fromSource != null) { 3190 packageNames = fromSource.get(targetUserId); 3191 if (packageNames != null) { 3192 // We need the package name, so we try to resolve with the loosest flags possible 3193 List<ResolveInfo> resolveInfos = mActivities.queryIntent(intent, resolvedType, 3194 PackageManager.GET_UNINSTALLED_PACKAGES, targetUserId); 3195 int count = resolveInfos.size(); 3196 for (int i = 0; i < count; i++) { 3197 ResolveInfo resolveInfo = resolveInfos.get(i); 3198 if (packageNames.contains(resolveInfo.activityInfo.packageName)) { 3199 return true; 3200 } 3201 } 3202 } 3203 } 3204 return false; 3205 } 3206 3207 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3208 String resolvedType, int userId) { 3209 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3210 if (resolver != null) { 3211 return resolver.queryIntent(intent, resolvedType, false, userId); 3212 } 3213 return null; 3214 } 3215 3216 @Override 3217 public List<ResolveInfo> queryIntentActivities(Intent intent, 3218 String resolvedType, int flags, int userId) { 3219 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3220 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities"); 3221 ComponentName comp = intent.getComponent(); 3222 if (comp == null) { 3223 if (intent.getSelector() != null) { 3224 intent = intent.getSelector(); 3225 comp = intent.getComponent(); 3226 } 3227 } 3228 3229 if (comp != null) { 3230 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3231 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3232 if (ai != null) { 3233 final ResolveInfo ri = new ResolveInfo(); 3234 ri.activityInfo = ai; 3235 list.add(ri); 3236 } 3237 return list; 3238 } 3239 3240 // reader 3241 synchronized (mPackages) { 3242 final String pkgName = intent.getPackage(); 3243 boolean queryCrossProfile = (flags & PackageManager.NO_CROSS_PROFILE) == 0; 3244 if (pkgName == null) { 3245 ResolveInfo resolveInfo = null; 3246 if (queryCrossProfile) { 3247 // Check if the intent needs to be forwarded to another user for this package 3248 ArrayList<ResolveInfo> crossProfileResult = 3249 queryIntentActivitiesCrossProfilePackage( 3250 intent, resolvedType, flags, userId); 3251 if (!crossProfileResult.isEmpty()) { 3252 // Skip the current profile 3253 return crossProfileResult; 3254 } 3255 List<CrossProfileIntentFilter> matchingFilters = 3256 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3257 // Check for results that need to skip the current profile. 3258 resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3259 resolvedType, flags, userId); 3260 if (resolveInfo != null) { 3261 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3262 result.add(resolveInfo); 3263 return result; 3264 } 3265 // Check for cross profile results. 3266 resolveInfo = queryCrossProfileIntents( 3267 matchingFilters, intent, resolvedType, flags, userId); 3268 } 3269 // Check for results in the current profile. 3270 List<ResolveInfo> result = mActivities.queryIntent( 3271 intent, resolvedType, flags, userId); 3272 if (resolveInfo != null) { 3273 result.add(resolveInfo); 3274 Collections.sort(result, mResolvePrioritySorter); 3275 } 3276 return result; 3277 } 3278 final PackageParser.Package pkg = mPackages.get(pkgName); 3279 if (pkg != null) { 3280 if (queryCrossProfile) { 3281 ArrayList<ResolveInfo> crossProfileResult = 3282 queryIntentActivitiesCrossProfilePackage( 3283 intent, resolvedType, flags, userId, pkg, pkgName); 3284 if (!crossProfileResult.isEmpty()) { 3285 // Skip the current profile 3286 return crossProfileResult; 3287 } 3288 } 3289 return mActivities.queryIntentForPackage(intent, resolvedType, flags, 3290 pkg.activities, userId); 3291 } 3292 return new ArrayList<ResolveInfo>(); 3293 } 3294 } 3295 3296 private ResolveInfo querySkipCurrentProfileIntents( 3297 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3298 int flags, int sourceUserId) { 3299 if (matchingFilters != null) { 3300 int size = matchingFilters.size(); 3301 for (int i = 0; i < size; i ++) { 3302 CrossProfileIntentFilter filter = matchingFilters.get(i); 3303 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 3304 // Checking if there are activities in the target user that can handle the 3305 // intent. 3306 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3307 flags, sourceUserId); 3308 if (resolveInfo != null) { 3309 return resolveInfo; 3310 } 3311 } 3312 } 3313 } 3314 return null; 3315 } 3316 3317 private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage( 3318 Intent intent, String resolvedType, int flags, int userId) { 3319 ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>(); 3320 SparseArray<ArrayList<String>> sourceForwardingInfo = 3321 mSettings.mCrossProfilePackageInfo.get(userId); 3322 if (sourceForwardingInfo != null) { 3323 int NI = sourceForwardingInfo.size(); 3324 for (int i = 0; i < NI; i++) { 3325 int targetUserId = sourceForwardingInfo.keyAt(i); 3326 ArrayList<String> packageNames = sourceForwardingInfo.valueAt(i); 3327 List<ResolveInfo> resolveInfos = mActivities.queryIntent( 3328 intent, resolvedType, flags, targetUserId); 3329 int NJ = resolveInfos.size(); 3330 for (int j = 0; j < NJ; j++) { 3331 ResolveInfo resolveInfo = resolveInfos.get(j); 3332 if (packageNames.contains(resolveInfo.activityInfo.packageName)) { 3333 matchingResolveInfos.add(createForwardingResolveInfo( 3334 resolveInfo.filter, userId, targetUserId)); 3335 } 3336 } 3337 } 3338 } 3339 return matchingResolveInfos; 3340 } 3341 3342 private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage( 3343 Intent intent, String resolvedType, int flags, int userId, PackageParser.Package pkg, 3344 String packageName) { 3345 ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>(); 3346 SparseArray<ArrayList<String>> sourceForwardingInfo = 3347 mSettings.mCrossProfilePackageInfo.get(userId); 3348 if (sourceForwardingInfo != null) { 3349 int NI = sourceForwardingInfo.size(); 3350 for (int i = 0; i < NI; i++) { 3351 int targetUserId = sourceForwardingInfo.keyAt(i); 3352 if (sourceForwardingInfo.valueAt(i).contains(packageName)) { 3353 List<ResolveInfo> resolveInfos = mActivities.queryIntentForPackage( 3354 intent, resolvedType, flags, pkg.activities, targetUserId); 3355 int NJ = resolveInfos.size(); 3356 for (int j = 0; j < NJ; j++) { 3357 ResolveInfo resolveInfo = resolveInfos.get(j); 3358 matchingResolveInfos.add(createForwardingResolveInfo( 3359 resolveInfo.filter, userId, targetUserId)); 3360 } 3361 } 3362 } 3363 } 3364 return matchingResolveInfos; 3365 } 3366 3367 // Return matching ResolveInfo if any for skip current profile intent filters. 3368 private ResolveInfo queryCrossProfileIntents( 3369 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3370 int flags, int sourceUserId) { 3371 if (matchingFilters != null) { 3372 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 3373 // match the same intent. For performance reasons, it is better not to 3374 // run queryIntent twice for the same userId 3375 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 3376 int size = matchingFilters.size(); 3377 for (int i = 0; i < size; i++) { 3378 CrossProfileIntentFilter filter = matchingFilters.get(i); 3379 int targetUserId = filter.getTargetUserId(); 3380 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 3381 && !alreadyTriedUserIds.get(targetUserId)) { 3382 // Checking if there are activities in the target user that can handle the 3383 // intent. 3384 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3385 flags, sourceUserId); 3386 if (resolveInfo != null) return resolveInfo; 3387 alreadyTriedUserIds.put(targetUserId, true); 3388 } 3389 } 3390 } 3391 return null; 3392 } 3393 3394 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 3395 String resolvedType, int flags, int sourceUserId) { 3396 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 3397 resolvedType, flags, filter.getTargetUserId()); 3398 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 3399 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 3400 } 3401 return null; 3402 } 3403 3404 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 3405 int sourceUserId, int targetUserId) { 3406 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 3407 String className; 3408 if (targetUserId == UserHandle.USER_OWNER) { 3409 className = FORWARD_INTENT_TO_USER_OWNER; 3410 } else { 3411 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 3412 } 3413 ComponentName forwardingActivityComponentName = new ComponentName( 3414 mAndroidApplication.packageName, className); 3415 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 3416 sourceUserId); 3417 if (targetUserId == UserHandle.USER_OWNER) { 3418 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 3419 forwardingResolveInfo.noResourceId = true; 3420 } 3421 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 3422 forwardingResolveInfo.priority = 0; 3423 forwardingResolveInfo.preferredOrder = 0; 3424 forwardingResolveInfo.match = 0; 3425 forwardingResolveInfo.isDefault = true; 3426 forwardingResolveInfo.filter = filter; 3427 forwardingResolveInfo.targetUserId = targetUserId; 3428 return forwardingResolveInfo; 3429 } 3430 3431 @Override 3432 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 3433 Intent[] specifics, String[] specificTypes, Intent intent, 3434 String resolvedType, int flags, int userId) { 3435 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3436 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 3437 "query intent activity options"); 3438 final String resultsAction = intent.getAction(); 3439 3440 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 3441 | PackageManager.GET_RESOLVED_FILTER, userId); 3442 3443 if (DEBUG_INTENT_MATCHING) { 3444 Log.v(TAG, "Query " + intent + ": " + results); 3445 } 3446 3447 int specificsPos = 0; 3448 int N; 3449 3450 // todo: note that the algorithm used here is O(N^2). This 3451 // isn't a problem in our current environment, but if we start running 3452 // into situations where we have more than 5 or 10 matches then this 3453 // should probably be changed to something smarter... 3454 3455 // First we go through and resolve each of the specific items 3456 // that were supplied, taking care of removing any corresponding 3457 // duplicate items in the generic resolve list. 3458 if (specifics != null) { 3459 for (int i=0; i<specifics.length; i++) { 3460 final Intent sintent = specifics[i]; 3461 if (sintent == null) { 3462 continue; 3463 } 3464 3465 if (DEBUG_INTENT_MATCHING) { 3466 Log.v(TAG, "Specific #" + i + ": " + sintent); 3467 } 3468 3469 String action = sintent.getAction(); 3470 if (resultsAction != null && resultsAction.equals(action)) { 3471 // If this action was explicitly requested, then don't 3472 // remove things that have it. 3473 action = null; 3474 } 3475 3476 ResolveInfo ri = null; 3477 ActivityInfo ai = null; 3478 3479 ComponentName comp = sintent.getComponent(); 3480 if (comp == null) { 3481 ri = resolveIntent( 3482 sintent, 3483 specificTypes != null ? specificTypes[i] : null, 3484 flags, userId); 3485 if (ri == null) { 3486 continue; 3487 } 3488 if (ri == mResolveInfo) { 3489 // ACK! Must do something better with this. 3490 } 3491 ai = ri.activityInfo; 3492 comp = new ComponentName(ai.applicationInfo.packageName, 3493 ai.name); 3494 } else { 3495 ai = getActivityInfo(comp, flags, userId); 3496 if (ai == null) { 3497 continue; 3498 } 3499 } 3500 3501 // Look for any generic query activities that are duplicates 3502 // of this specific one, and remove them from the results. 3503 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 3504 N = results.size(); 3505 int j; 3506 for (j=specificsPos; j<N; j++) { 3507 ResolveInfo sri = results.get(j); 3508 if ((sri.activityInfo.name.equals(comp.getClassName()) 3509 && sri.activityInfo.applicationInfo.packageName.equals( 3510 comp.getPackageName())) 3511 || (action != null && sri.filter.matchAction(action))) { 3512 results.remove(j); 3513 if (DEBUG_INTENT_MATCHING) Log.v( 3514 TAG, "Removing duplicate item from " + j 3515 + " due to specific " + specificsPos); 3516 if (ri == null) { 3517 ri = sri; 3518 } 3519 j--; 3520 N--; 3521 } 3522 } 3523 3524 // Add this specific item to its proper place. 3525 if (ri == null) { 3526 ri = new ResolveInfo(); 3527 ri.activityInfo = ai; 3528 } 3529 results.add(specificsPos, ri); 3530 ri.specificIndex = i; 3531 specificsPos++; 3532 } 3533 } 3534 3535 // Now we go through the remaining generic results and remove any 3536 // duplicate actions that are found here. 3537 N = results.size(); 3538 for (int i=specificsPos; i<N-1; i++) { 3539 final ResolveInfo rii = results.get(i); 3540 if (rii.filter == null) { 3541 continue; 3542 } 3543 3544 // Iterate over all of the actions of this result's intent 3545 // filter... typically this should be just one. 3546 final Iterator<String> it = rii.filter.actionsIterator(); 3547 if (it == null) { 3548 continue; 3549 } 3550 while (it.hasNext()) { 3551 final String action = it.next(); 3552 if (resultsAction != null && resultsAction.equals(action)) { 3553 // If this action was explicitly requested, then don't 3554 // remove things that have it. 3555 continue; 3556 } 3557 for (int j=i+1; j<N; j++) { 3558 final ResolveInfo rij = results.get(j); 3559 if (rij.filter != null && rij.filter.hasAction(action)) { 3560 results.remove(j); 3561 if (DEBUG_INTENT_MATCHING) Log.v( 3562 TAG, "Removing duplicate item from " + j 3563 + " due to action " + action + " at " + i); 3564 j--; 3565 N--; 3566 } 3567 } 3568 } 3569 3570 // If the caller didn't request filter information, drop it now 3571 // so we don't have to marshall/unmarshall it. 3572 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3573 rii.filter = null; 3574 } 3575 } 3576 3577 // Filter out the caller activity if so requested. 3578 if (caller != null) { 3579 N = results.size(); 3580 for (int i=0; i<N; i++) { 3581 ActivityInfo ainfo = results.get(i).activityInfo; 3582 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 3583 && caller.getClassName().equals(ainfo.name)) { 3584 results.remove(i); 3585 break; 3586 } 3587 } 3588 } 3589 3590 // If the caller didn't request filter information, 3591 // drop them now so we don't have to 3592 // marshall/unmarshall it. 3593 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3594 N = results.size(); 3595 for (int i=0; i<N; i++) { 3596 results.get(i).filter = null; 3597 } 3598 } 3599 3600 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 3601 return results; 3602 } 3603 3604 @Override 3605 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 3606 int userId) { 3607 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3608 ComponentName comp = intent.getComponent(); 3609 if (comp == null) { 3610 if (intent.getSelector() != null) { 3611 intent = intent.getSelector(); 3612 comp = intent.getComponent(); 3613 } 3614 } 3615 if (comp != null) { 3616 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3617 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 3618 if (ai != null) { 3619 ResolveInfo ri = new ResolveInfo(); 3620 ri.activityInfo = ai; 3621 list.add(ri); 3622 } 3623 return list; 3624 } 3625 3626 // reader 3627 synchronized (mPackages) { 3628 String pkgName = intent.getPackage(); 3629 if (pkgName == null) { 3630 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 3631 } 3632 final PackageParser.Package pkg = mPackages.get(pkgName); 3633 if (pkg != null) { 3634 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 3635 userId); 3636 } 3637 return null; 3638 } 3639 } 3640 3641 @Override 3642 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 3643 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 3644 if (!sUserManager.exists(userId)) return null; 3645 if (query != null) { 3646 if (query.size() >= 1) { 3647 // If there is more than one service with the same priority, 3648 // just arbitrarily pick the first one. 3649 return query.get(0); 3650 } 3651 } 3652 return null; 3653 } 3654 3655 @Override 3656 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 3657 int userId) { 3658 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3659 ComponentName comp = intent.getComponent(); 3660 if (comp == null) { 3661 if (intent.getSelector() != null) { 3662 intent = intent.getSelector(); 3663 comp = intent.getComponent(); 3664 } 3665 } 3666 if (comp != null) { 3667 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3668 final ServiceInfo si = getServiceInfo(comp, flags, userId); 3669 if (si != null) { 3670 final ResolveInfo ri = new ResolveInfo(); 3671 ri.serviceInfo = si; 3672 list.add(ri); 3673 } 3674 return list; 3675 } 3676 3677 // reader 3678 synchronized (mPackages) { 3679 String pkgName = intent.getPackage(); 3680 if (pkgName == null) { 3681 return mServices.queryIntent(intent, resolvedType, flags, userId); 3682 } 3683 final PackageParser.Package pkg = mPackages.get(pkgName); 3684 if (pkg != null) { 3685 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 3686 userId); 3687 } 3688 return null; 3689 } 3690 } 3691 3692 @Override 3693 public List<ResolveInfo> queryIntentContentProviders( 3694 Intent intent, String resolvedType, int flags, int userId) { 3695 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3696 ComponentName comp = intent.getComponent(); 3697 if (comp == null) { 3698 if (intent.getSelector() != null) { 3699 intent = intent.getSelector(); 3700 comp = intent.getComponent(); 3701 } 3702 } 3703 if (comp != null) { 3704 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3705 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 3706 if (pi != null) { 3707 final ResolveInfo ri = new ResolveInfo(); 3708 ri.providerInfo = pi; 3709 list.add(ri); 3710 } 3711 return list; 3712 } 3713 3714 // reader 3715 synchronized (mPackages) { 3716 String pkgName = intent.getPackage(); 3717 if (pkgName == null) { 3718 return mProviders.queryIntent(intent, resolvedType, flags, userId); 3719 } 3720 final PackageParser.Package pkg = mPackages.get(pkgName); 3721 if (pkg != null) { 3722 return mProviders.queryIntentForPackage( 3723 intent, resolvedType, flags, pkg.providers, userId); 3724 } 3725 return null; 3726 } 3727 } 3728 3729 @Override 3730 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 3731 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3732 3733 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages"); 3734 3735 // writer 3736 synchronized (mPackages) { 3737 ArrayList<PackageInfo> list; 3738 if (listUninstalled) { 3739 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 3740 for (PackageSetting ps : mSettings.mPackages.values()) { 3741 PackageInfo pi; 3742 if (ps.pkg != null) { 3743 pi = generatePackageInfo(ps.pkg, flags, userId); 3744 } else { 3745 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3746 } 3747 if (pi != null) { 3748 list.add(pi); 3749 } 3750 } 3751 } else { 3752 list = new ArrayList<PackageInfo>(mPackages.size()); 3753 for (PackageParser.Package p : mPackages.values()) { 3754 PackageInfo pi = generatePackageInfo(p, flags, userId); 3755 if (pi != null) { 3756 list.add(pi); 3757 } 3758 } 3759 } 3760 3761 return new ParceledListSlice<PackageInfo>(list); 3762 } 3763 } 3764 3765 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 3766 String[] permissions, boolean[] tmp, int flags, int userId) { 3767 int numMatch = 0; 3768 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 3769 for (int i=0; i<permissions.length; i++) { 3770 if (gp.grantedPermissions.contains(permissions[i])) { 3771 tmp[i] = true; 3772 numMatch++; 3773 } else { 3774 tmp[i] = false; 3775 } 3776 } 3777 if (numMatch == 0) { 3778 return; 3779 } 3780 PackageInfo pi; 3781 if (ps.pkg != null) { 3782 pi = generatePackageInfo(ps.pkg, flags, userId); 3783 } else { 3784 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3785 } 3786 // The above might return null in cases of uninstalled apps or install-state 3787 // skew across users/profiles. 3788 if (pi != null) { 3789 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 3790 if (numMatch == permissions.length) { 3791 pi.requestedPermissions = permissions; 3792 } else { 3793 pi.requestedPermissions = new String[numMatch]; 3794 numMatch = 0; 3795 for (int i=0; i<permissions.length; i++) { 3796 if (tmp[i]) { 3797 pi.requestedPermissions[numMatch] = permissions[i]; 3798 numMatch++; 3799 } 3800 } 3801 } 3802 } 3803 list.add(pi); 3804 } 3805 } 3806 3807 @Override 3808 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 3809 String[] permissions, int flags, int userId) { 3810 if (!sUserManager.exists(userId)) return null; 3811 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3812 3813 // writer 3814 synchronized (mPackages) { 3815 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 3816 boolean[] tmpBools = new boolean[permissions.length]; 3817 if (listUninstalled) { 3818 for (PackageSetting ps : mSettings.mPackages.values()) { 3819 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 3820 } 3821 } else { 3822 for (PackageParser.Package pkg : mPackages.values()) { 3823 PackageSetting ps = (PackageSetting)pkg.mExtras; 3824 if (ps != null) { 3825 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 3826 userId); 3827 } 3828 } 3829 } 3830 3831 return new ParceledListSlice<PackageInfo>(list); 3832 } 3833 } 3834 3835 @Override 3836 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 3837 if (!sUserManager.exists(userId)) return null; 3838 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3839 3840 // writer 3841 synchronized (mPackages) { 3842 ArrayList<ApplicationInfo> list; 3843 if (listUninstalled) { 3844 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 3845 for (PackageSetting ps : mSettings.mPackages.values()) { 3846 ApplicationInfo ai; 3847 if (ps.pkg != null) { 3848 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3849 ps.readUserState(userId), userId); 3850 } else { 3851 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 3852 } 3853 if (ai != null) { 3854 list.add(ai); 3855 } 3856 } 3857 } else { 3858 list = new ArrayList<ApplicationInfo>(mPackages.size()); 3859 for (PackageParser.Package p : mPackages.values()) { 3860 if (p.mExtras != null) { 3861 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3862 ((PackageSetting)p.mExtras).readUserState(userId), userId); 3863 if (ai != null) { 3864 list.add(ai); 3865 } 3866 } 3867 } 3868 } 3869 3870 return new ParceledListSlice<ApplicationInfo>(list); 3871 } 3872 } 3873 3874 public List<ApplicationInfo> getPersistentApplications(int flags) { 3875 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 3876 3877 // reader 3878 synchronized (mPackages) { 3879 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 3880 final int userId = UserHandle.getCallingUserId(); 3881 while (i.hasNext()) { 3882 final PackageParser.Package p = i.next(); 3883 if (p.applicationInfo != null 3884 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 3885 && (!mSafeMode || isSystemApp(p))) { 3886 PackageSetting ps = mSettings.mPackages.get(p.packageName); 3887 if (ps != null) { 3888 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3889 ps.readUserState(userId), userId); 3890 if (ai != null) { 3891 finalList.add(ai); 3892 } 3893 } 3894 } 3895 } 3896 } 3897 3898 return finalList; 3899 } 3900 3901 @Override 3902 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 3903 if (!sUserManager.exists(userId)) return null; 3904 // reader 3905 synchronized (mPackages) { 3906 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 3907 PackageSetting ps = provider != null 3908 ? mSettings.mPackages.get(provider.owner.packageName) 3909 : null; 3910 return ps != null 3911 && mSettings.isEnabledLPr(provider.info, flags, userId) 3912 && (!mSafeMode || (provider.info.applicationInfo.flags 3913 &ApplicationInfo.FLAG_SYSTEM) != 0) 3914 ? PackageParser.generateProviderInfo(provider, flags, 3915 ps.readUserState(userId), userId) 3916 : null; 3917 } 3918 } 3919 3920 /** 3921 * @deprecated 3922 */ 3923 @Deprecated 3924 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 3925 // reader 3926 synchronized (mPackages) { 3927 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 3928 .entrySet().iterator(); 3929 final int userId = UserHandle.getCallingUserId(); 3930 while (i.hasNext()) { 3931 Map.Entry<String, PackageParser.Provider> entry = i.next(); 3932 PackageParser.Provider p = entry.getValue(); 3933 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3934 3935 if (ps != null && p.syncable 3936 && (!mSafeMode || (p.info.applicationInfo.flags 3937 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 3938 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 3939 ps.readUserState(userId), userId); 3940 if (info != null) { 3941 outNames.add(entry.getKey()); 3942 outInfo.add(info); 3943 } 3944 } 3945 } 3946 } 3947 } 3948 3949 @Override 3950 public List<ProviderInfo> queryContentProviders(String processName, 3951 int uid, int flags) { 3952 ArrayList<ProviderInfo> finalList = null; 3953 // reader 3954 synchronized (mPackages) { 3955 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 3956 final int userId = processName != null ? 3957 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 3958 while (i.hasNext()) { 3959 final PackageParser.Provider p = i.next(); 3960 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3961 if (ps != null && p.info.authority != null 3962 && (processName == null 3963 || (p.info.processName.equals(processName) 3964 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 3965 && mSettings.isEnabledLPr(p.info, flags, userId) 3966 && (!mSafeMode 3967 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 3968 if (finalList == null) { 3969 finalList = new ArrayList<ProviderInfo>(3); 3970 } 3971 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 3972 ps.readUserState(userId), userId); 3973 if (info != null) { 3974 finalList.add(info); 3975 } 3976 } 3977 } 3978 } 3979 3980 if (finalList != null) { 3981 Collections.sort(finalList, mProviderInitOrderSorter); 3982 } 3983 3984 return finalList; 3985 } 3986 3987 @Override 3988 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 3989 int flags) { 3990 // reader 3991 synchronized (mPackages) { 3992 final PackageParser.Instrumentation i = mInstrumentation.get(name); 3993 return PackageParser.generateInstrumentationInfo(i, flags); 3994 } 3995 } 3996 3997 @Override 3998 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 3999 int flags) { 4000 ArrayList<InstrumentationInfo> finalList = 4001 new ArrayList<InstrumentationInfo>(); 4002 4003 // reader 4004 synchronized (mPackages) { 4005 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4006 while (i.hasNext()) { 4007 final PackageParser.Instrumentation p = i.next(); 4008 if (targetPackage == null 4009 || targetPackage.equals(p.info.targetPackage)) { 4010 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4011 flags); 4012 if (ii != null) { 4013 finalList.add(ii); 4014 } 4015 } 4016 } 4017 } 4018 4019 return finalList; 4020 } 4021 4022 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4023 HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4024 if (overlays == null) { 4025 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4026 return; 4027 } 4028 for (PackageParser.Package opkg : overlays.values()) { 4029 // Not much to do if idmap fails: we already logged the error 4030 // and we certainly don't want to abort installation of pkg simply 4031 // because an overlay didn't fit properly. For these reasons, 4032 // ignore the return value of createIdmapForPackagePairLI. 4033 createIdmapForPackagePairLI(pkg, opkg); 4034 } 4035 } 4036 4037 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4038 PackageParser.Package opkg) { 4039 if (!opkg.mTrustedOverlay) { 4040 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4041 opkg.baseCodePath + ": overlay not trusted"); 4042 return false; 4043 } 4044 HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4045 if (overlaySet == null) { 4046 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4047 opkg.baseCodePath + " but target package has no known overlays"); 4048 return false; 4049 } 4050 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4051 // TODO: generate idmap for split APKs 4052 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4053 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4054 + opkg.baseCodePath); 4055 return false; 4056 } 4057 PackageParser.Package[] overlayArray = 4058 overlaySet.values().toArray(new PackageParser.Package[0]); 4059 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4060 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4061 return p1.mOverlayPriority - p2.mOverlayPriority; 4062 } 4063 }; 4064 Arrays.sort(overlayArray, cmp); 4065 4066 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4067 int i = 0; 4068 for (PackageParser.Package p : overlayArray) { 4069 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4070 } 4071 return true; 4072 } 4073 4074 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 4075 final File[] files = dir.listFiles(); 4076 if (ArrayUtils.isEmpty(files)) { 4077 Log.d(TAG, "No files in app dir " + dir); 4078 return; 4079 } 4080 4081 if (DEBUG_PACKAGE_SCANNING) { 4082 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 4083 + " flags=0x" + Integer.toHexString(parseFlags)); 4084 } 4085 4086 for (File file : files) { 4087 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 4088 && !PackageInstallerService.isStageName(file.getName()); 4089 if (!isPackage) { 4090 // Ignore entries which are not packages 4091 continue; 4092 } 4093 try { 4094 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 4095 scanFlags, currentTime, null); 4096 } catch (PackageManagerException e) { 4097 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4098 4099 // Delete invalid userdata apps 4100 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4101 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4102 Slog.w(TAG, "Deleting invalid package at " + file); 4103 if (file.isDirectory()) { 4104 FileUtils.deleteContents(file); 4105 } 4106 file.delete(); 4107 } 4108 } 4109 } 4110 } 4111 4112 private static File getSettingsProblemFile() { 4113 File dataDir = Environment.getDataDirectory(); 4114 File systemDir = new File(dataDir, "system"); 4115 File fname = new File(systemDir, "uiderrors.txt"); 4116 return fname; 4117 } 4118 4119 static void reportSettingsProblem(int priority, String msg) { 4120 try { 4121 File fname = getSettingsProblemFile(); 4122 FileOutputStream out = new FileOutputStream(fname, true); 4123 PrintWriter pw = new FastPrintWriter(out); 4124 SimpleDateFormat formatter = new SimpleDateFormat(); 4125 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4126 pw.println(dateString + ": " + msg); 4127 pw.close(); 4128 FileUtils.setPermissions( 4129 fname.toString(), 4130 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4131 -1, -1); 4132 } catch (java.io.IOException e) { 4133 } 4134 Slog.println(priority, TAG, msg); 4135 } 4136 4137 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 4138 PackageParser.Package pkg, File srcFile, int parseFlags) 4139 throws PackageManagerException { 4140 if (ps != null 4141 && ps.codePath.equals(srcFile) 4142 && ps.timeStamp == srcFile.lastModified() 4143 && !isCompatSignatureUpdateNeeded(pkg)) { 4144 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4145 if (ps.signatures.mSignatures != null 4146 && ps.signatures.mSignatures.length != 0 4147 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4148 // Optimization: reuse the existing cached certificates 4149 // if the package appears to be unchanged. 4150 pkg.mSignatures = ps.signatures.mSignatures; 4151 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4152 synchronized (mPackages) { 4153 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 4154 } 4155 return; 4156 } 4157 4158 Slog.w(TAG, "PackageSetting for " + ps.name 4159 + " is missing signatures. Collecting certs again to recover them."); 4160 } else { 4161 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4162 } 4163 4164 try { 4165 pp.collectCertificates(pkg, parseFlags); 4166 pp.collectManifestDigest(pkg); 4167 } catch (PackageParserException e) { 4168 throw new PackageManagerException(e.error, "Failed to collect certificates for " 4169 + pkg.packageName + ": " + e.getMessage()); 4170 } 4171 } 4172 4173 /* 4174 * Scan a package and return the newly parsed package. 4175 * Returns null in case of errors and the error code is stored in mLastScanError 4176 */ 4177 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 4178 long currentTime, UserHandle user) throws PackageManagerException { 4179 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4180 parseFlags |= mDefParseFlags; 4181 PackageParser pp = new PackageParser(); 4182 pp.setSeparateProcesses(mSeparateProcesses); 4183 pp.setOnlyCoreApps(mOnlyCore); 4184 pp.setDisplayMetrics(mMetrics); 4185 4186 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 4187 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4188 } 4189 4190 final PackageParser.Package pkg; 4191 try { 4192 pkg = pp.parsePackage(scanFile, parseFlags); 4193 } catch (PackageParserException e) { 4194 throw new PackageManagerException(e.error, 4195 "Failed to scan " + scanFile + ": " + e.getMessage()); 4196 } 4197 4198 PackageSetting ps = null; 4199 PackageSetting updatedPkg; 4200 // reader 4201 synchronized (mPackages) { 4202 // Look to see if we already know about this package. 4203 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4204 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4205 // This package has been renamed to its original name. Let's 4206 // use that. 4207 ps = mSettings.peekPackageLPr(oldName); 4208 } 4209 // If there was no original package, see one for the real package name. 4210 if (ps == null) { 4211 ps = mSettings.peekPackageLPr(pkg.packageName); 4212 } 4213 // Check to see if this package could be hiding/updating a system 4214 // package. Must look for it either under the original or real 4215 // package name depending on our state. 4216 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4217 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4218 } 4219 boolean updatedPkgBetter = false; 4220 // First check if this is a system package that may involve an update 4221 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4222 if (ps != null && !ps.codePath.equals(scanFile)) { 4223 // The path has changed from what was last scanned... check the 4224 // version of the new path against what we have stored to determine 4225 // what to do. 4226 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4227 if (pkg.mVersionCode < ps.versionCode) { 4228 // The system package has been updated and the code path does not match 4229 // Ignore entry. Skip it. 4230 Log.i(TAG, "Package " + ps.name + " at " + scanFile 4231 + " ignored: updated version " + ps.versionCode 4232 + " better than this " + pkg.mVersionCode); 4233 if (!updatedPkg.codePath.equals(scanFile)) { 4234 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4235 + ps.name + " changing from " + updatedPkg.codePathString 4236 + " to " + scanFile); 4237 updatedPkg.codePath = scanFile; 4238 updatedPkg.codePathString = scanFile.toString(); 4239 // This is the point at which we know that the system-disk APK 4240 // for this package has moved during a reboot (e.g. due to an OTA), 4241 // so we need to reevaluate it for privilege policy. 4242 if (locationIsPrivileged(scanFile)) { 4243 updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED; 4244 } 4245 } 4246 updatedPkg.pkg = pkg; 4247 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 4248 } else { 4249 // The current app on the system partition is better than 4250 // what we have updated to on the data partition; switch 4251 // back to the system partition version. 4252 // At this point, its safely assumed that package installation for 4253 // apps in system partition will go through. If not there won't be a working 4254 // version of the app 4255 // writer 4256 synchronized (mPackages) { 4257 // Just remove the loaded entries from package lists. 4258 mPackages.remove(ps.name); 4259 } 4260 Slog.w(TAG, "Package " + ps.name + " at " + scanFile 4261 + "reverting from " + ps.codePathString 4262 + ": new version " + pkg.mVersionCode 4263 + " better than installed " + ps.versionCode); 4264 4265 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4266 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4267 getAppDexInstructionSets(ps)); 4268 synchronized (mInstallLock) { 4269 args.cleanUpResourcesLI(); 4270 } 4271 synchronized (mPackages) { 4272 mSettings.enableSystemPackageLPw(ps.name); 4273 } 4274 updatedPkgBetter = true; 4275 } 4276 } 4277 } 4278 4279 if (updatedPkg != null) { 4280 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4281 // initially 4282 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4283 4284 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4285 // flag set initially 4286 if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) { 4287 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4288 } 4289 } 4290 4291 // Verify certificates against what was last scanned 4292 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 4293 4294 /* 4295 * A new system app appeared, but we already had a non-system one of the 4296 * same name installed earlier. 4297 */ 4298 boolean shouldHideSystemApp = false; 4299 if (updatedPkg == null && ps != null 4300 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4301 /* 4302 * Check to make sure the signatures match first. If they don't, 4303 * wipe the installed application and its data. 4304 */ 4305 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4306 != PackageManager.SIGNATURE_MATCH) { 4307 if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!"); 4308 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4309 ps = null; 4310 } else { 4311 /* 4312 * If the newly-added system app is an older version than the 4313 * already installed version, hide it. It will be scanned later 4314 * and re-added like an update. 4315 */ 4316 if (pkg.mVersionCode < ps.versionCode) { 4317 shouldHideSystemApp = true; 4318 } else { 4319 /* 4320 * The newly found system app is a newer version that the 4321 * one previously installed. Simply remove the 4322 * already-installed application and replace it with our own 4323 * while keeping the application data. 4324 */ 4325 Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from " 4326 + ps.codePathString + ": new version " + pkg.mVersionCode 4327 + " better than installed " + ps.versionCode); 4328 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4329 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4330 getAppDexInstructionSets(ps)); 4331 synchronized (mInstallLock) { 4332 args.cleanUpResourcesLI(); 4333 } 4334 } 4335 } 4336 } 4337 4338 // The apk is forward locked (not public) if its code and resources 4339 // are kept in different files. (except for app in either system or 4340 // vendor path). 4341 // TODO grab this value from PackageSettings 4342 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4343 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4344 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 4345 } 4346 } 4347 4348 // TODO: extend to support forward-locked splits 4349 String resourcePath = null; 4350 String baseResourcePath = null; 4351 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 4352 if (ps != null && ps.resourcePathString != null) { 4353 resourcePath = ps.resourcePathString; 4354 baseResourcePath = ps.resourcePathString; 4355 } else { 4356 // Should not happen at all. Just log an error. 4357 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 4358 } 4359 } else { 4360 resourcePath = pkg.codePath; 4361 baseResourcePath = pkg.baseCodePath; 4362 } 4363 4364 // Set application objects path explicitly. 4365 pkg.applicationInfo.setCodePath(pkg.codePath); 4366 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 4367 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 4368 pkg.applicationInfo.setResourcePath(resourcePath); 4369 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 4370 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 4371 4372 // Note that we invoke the following method only if we are about to unpack an application 4373 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 4374 | SCAN_UPDATE_SIGNATURE, currentTime, user); 4375 4376 /* 4377 * If the system app should be overridden by a previously installed 4378 * data, hide the system app now and let the /data/app scan pick it up 4379 * again. 4380 */ 4381 if (shouldHideSystemApp) { 4382 synchronized (mPackages) { 4383 /* 4384 * We have to grant systems permissions before we hide, because 4385 * grantPermissions will assume the package update is trying to 4386 * expand its permissions. 4387 */ 4388 grantPermissionsLPw(pkg, true); 4389 mSettings.disableSystemPackageLPw(pkg.packageName); 4390 } 4391 } 4392 4393 return scannedPkg; 4394 } 4395 4396 private static String fixProcessName(String defProcessName, 4397 String processName, int uid) { 4398 if (processName == null) { 4399 return defProcessName; 4400 } 4401 return processName; 4402 } 4403 4404 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 4405 throws PackageManagerException { 4406 if (pkgSetting.signatures.mSignatures != null) { 4407 // Already existing package. Make sure signatures match 4408 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 4409 == PackageManager.SIGNATURE_MATCH; 4410 if (!match) { 4411 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 4412 == PackageManager.SIGNATURE_MATCH; 4413 } 4414 if (!match) { 4415 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 4416 + pkg.packageName + " signatures do not match the " 4417 + "previously installed version; ignoring!"); 4418 } 4419 } 4420 4421 // Check for shared user signatures 4422 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 4423 // Already existing package. Make sure signatures match 4424 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4425 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 4426 if (!match) { 4427 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 4428 == PackageManager.SIGNATURE_MATCH; 4429 } 4430 if (!match) { 4431 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 4432 "Package " + pkg.packageName 4433 + " has no signatures that match those in shared user " 4434 + pkgSetting.sharedUser.name + "; ignoring!"); 4435 } 4436 } 4437 } 4438 4439 /** 4440 * Enforces that only the system UID or root's UID can call a method exposed 4441 * via Binder. 4442 * 4443 * @param message used as message if SecurityException is thrown 4444 * @throws SecurityException if the caller is not system or root 4445 */ 4446 private static final void enforceSystemOrRoot(String message) { 4447 final int uid = Binder.getCallingUid(); 4448 if (uid != Process.SYSTEM_UID && uid != 0) { 4449 throw new SecurityException(message); 4450 } 4451 } 4452 4453 @Override 4454 public void performBootDexOpt() { 4455 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4456 4457 final HashSet<PackageParser.Package> pkgs; 4458 synchronized (mPackages) { 4459 pkgs = mDeferredDexOpt; 4460 mDeferredDexOpt = null; 4461 } 4462 4463 if (pkgs != null) { 4464 // Filter out packages that aren't recently used. 4465 // 4466 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 4467 // should do a full dexopt. 4468 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 4469 // TODO: add a property to control this? 4470 long dexOptLRUThresholdInMinutes; 4471 if (mLazyDexOpt) { 4472 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 4473 } else { 4474 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 4475 } 4476 long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 4477 4478 int total = pkgs.size(); 4479 int skipped = 0; 4480 long now = System.currentTimeMillis(); 4481 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 4482 PackageParser.Package pkg = i.next(); 4483 long then = pkg.mLastPackageUsageTimeInMills; 4484 if (then + dexOptLRUThresholdInMills < now) { 4485 if (DEBUG_DEXOPT) { 4486 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 4487 ((then == 0) ? "never" : new Date(then))); 4488 } 4489 i.remove(); 4490 skipped++; 4491 } 4492 } 4493 if (DEBUG_DEXOPT) { 4494 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 4495 } 4496 } 4497 4498 int i = 0; 4499 for (PackageParser.Package pkg : pkgs) { 4500 i++; 4501 if (DEBUG_DEXOPT) { 4502 Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size() 4503 + ": " + pkg.packageName); 4504 } 4505 if (!isFirstBoot()) { 4506 try { 4507 ActivityManagerNative.getDefault().showBootMessage( 4508 mContext.getResources().getString( 4509 R.string.android_upgrading_apk, 4510 i, pkgs.size()), true); 4511 } catch (RemoteException e) { 4512 } 4513 } 4514 PackageParser.Package p = pkg; 4515 synchronized (mInstallLock) { 4516 performDexOptLI(p, null /* instruction sets */, false /* force dex */, false /* defer */, 4517 true /* include dependencies */); 4518 } 4519 } 4520 } 4521 } 4522 4523 @Override 4524 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 4525 return performDexOpt(packageName, instructionSet, false); 4526 } 4527 4528 private static String getPrimaryInstructionSet(ApplicationInfo info) { 4529 if (info.primaryCpuAbi == null) { 4530 return getPreferredInstructionSet(); 4531 } 4532 4533 return VMRuntime.getInstructionSet(info.primaryCpuAbi); 4534 } 4535 4536 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 4537 boolean dexopt = mLazyDexOpt || backgroundDexopt; 4538 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 4539 if (!dexopt && !updateUsage) { 4540 // We aren't going to dexopt or update usage, so bail early. 4541 return false; 4542 } 4543 PackageParser.Package p; 4544 final String targetInstructionSet; 4545 synchronized (mPackages) { 4546 p = mPackages.get(packageName); 4547 if (p == null) { 4548 return false; 4549 } 4550 if (updateUsage) { 4551 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 4552 } 4553 mPackageUsage.write(false); 4554 if (!dexopt) { 4555 // We aren't going to dexopt, so bail early. 4556 return false; 4557 } 4558 4559 targetInstructionSet = instructionSet != null ? instructionSet : 4560 getPrimaryInstructionSet(p.applicationInfo); 4561 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 4562 return false; 4563 } 4564 } 4565 4566 synchronized (mInstallLock) { 4567 final String[] instructionSets = new String[] { targetInstructionSet }; 4568 return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */, 4569 true /* include dependencies */) == DEX_OPT_PERFORMED; 4570 } 4571 } 4572 4573 public HashSet<String> getPackagesThatNeedDexOpt() { 4574 HashSet<String> pkgs = null; 4575 synchronized (mPackages) { 4576 for (PackageParser.Package p : mPackages.values()) { 4577 if (DEBUG_DEXOPT) { 4578 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 4579 } 4580 if (!p.mDexOptPerformed.isEmpty()) { 4581 continue; 4582 } 4583 if (pkgs == null) { 4584 pkgs = new HashSet<String>(); 4585 } 4586 pkgs.add(p.packageName); 4587 } 4588 } 4589 return pkgs; 4590 } 4591 4592 public void shutdown() { 4593 mPackageUsage.write(true); 4594 } 4595 4596 private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets, 4597 boolean forceDex, boolean defer, HashSet<String> done) { 4598 for (int i=0; i<libs.size(); i++) { 4599 PackageParser.Package libPkg; 4600 String libName; 4601 synchronized (mPackages) { 4602 libName = libs.get(i); 4603 SharedLibraryEntry lib = mSharedLibraries.get(libName); 4604 if (lib != null && lib.apk != null) { 4605 libPkg = mPackages.get(lib.apk); 4606 } else { 4607 libPkg = null; 4608 } 4609 } 4610 if (libPkg != null && !done.contains(libName)) { 4611 performDexOptLI(libPkg, instructionSets, forceDex, defer, done); 4612 } 4613 } 4614 } 4615 4616 static final int DEX_OPT_SKIPPED = 0; 4617 static final int DEX_OPT_PERFORMED = 1; 4618 static final int DEX_OPT_DEFERRED = 2; 4619 static final int DEX_OPT_FAILED = -1; 4620 4621 private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets, 4622 boolean forceDex, boolean defer, HashSet<String> done) { 4623 final String[] instructionSets = targetInstructionSets != null ? 4624 targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo); 4625 4626 if (done != null) { 4627 done.add(pkg.packageName); 4628 if (pkg.usesLibraries != null) { 4629 performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done); 4630 } 4631 if (pkg.usesOptionalLibraries != null) { 4632 performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done); 4633 } 4634 } 4635 4636 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) { 4637 return DEX_OPT_SKIPPED; 4638 } 4639 4640 final boolean vmSafeMode = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0; 4641 4642 final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly(); 4643 boolean performedDexOpt = false; 4644 // There are three basic cases here: 4645 // 1.) we need to dexopt, either because we are forced or it is needed 4646 // 2.) we are defering a needed dexopt 4647 // 3.) we are skipping an unneeded dexopt 4648 final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 4649 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 4650 if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) { 4651 continue; 4652 } 4653 4654 for (String path : paths) { 4655 try { 4656 // This will return DEXOPT_NEEDED if we either cannot find any odex file for this 4657 // patckage or the one we find does not match the image checksum (i.e. it was 4658 // compiled against an old image). It will return PATCHOAT_NEEDED if we can find a 4659 // odex file and it matches the checksum of the image but not its base address, 4660 // meaning we need to move it. 4661 final byte isDexOptNeeded = DexFile.isDexOptNeededInternal(path, 4662 pkg.packageName, dexCodeInstructionSet, defer); 4663 if (forceDex || (!defer && isDexOptNeeded == DexFile.DEXOPT_NEEDED)) { 4664 Log.i(TAG, "Running dexopt on: " + path + " pkg=" 4665 + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet 4666 + " vmSafeMode=" + vmSafeMode); 4667 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4668 final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg), 4669 pkg.packageName, dexCodeInstructionSet, vmSafeMode); 4670 4671 if (ret < 0) { 4672 // Don't bother running dexopt again if we failed, it will probably 4673 // just result in an error again. Also, don't bother dexopting for other 4674 // paths & ISAs. 4675 return DEX_OPT_FAILED; 4676 } 4677 4678 performedDexOpt = true; 4679 } else if (!defer && isDexOptNeeded == DexFile.PATCHOAT_NEEDED) { 4680 Log.i(TAG, "Running patchoat on: " + pkg.applicationInfo.packageName); 4681 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4682 final int ret = mInstaller.patchoat(path, sharedGid, !isForwardLocked(pkg), 4683 pkg.packageName, dexCodeInstructionSet); 4684 4685 if (ret < 0) { 4686 // Don't bother running patchoat again if we failed, it will probably 4687 // just result in an error again. Also, don't bother dexopting for other 4688 // paths & ISAs. 4689 return DEX_OPT_FAILED; 4690 } 4691 4692 performedDexOpt = true; 4693 } 4694 4695 // We're deciding to defer a needed dexopt. Don't bother dexopting for other 4696 // paths and instruction sets. We'll deal with them all together when we process 4697 // our list of deferred dexopts. 4698 if (defer && isDexOptNeeded != DexFile.UP_TO_DATE) { 4699 if (mDeferredDexOpt == null) { 4700 mDeferredDexOpt = new HashSet<PackageParser.Package>(); 4701 } 4702 mDeferredDexOpt.add(pkg); 4703 return DEX_OPT_DEFERRED; 4704 } 4705 } catch (FileNotFoundException e) { 4706 Slog.w(TAG, "Apk not found for dexopt: " + path); 4707 return DEX_OPT_FAILED; 4708 } catch (IOException e) { 4709 Slog.w(TAG, "IOException reading apk: " + path, e); 4710 return DEX_OPT_FAILED; 4711 } catch (StaleDexCacheError e) { 4712 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e); 4713 return DEX_OPT_FAILED; 4714 } catch (Exception e) { 4715 Slog.w(TAG, "Exception when doing dexopt : ", e); 4716 return DEX_OPT_FAILED; 4717 } 4718 } 4719 4720 // At this point we haven't failed dexopt and we haven't deferred dexopt. We must 4721 // either have either succeeded dexopt, or have had isDexOptNeededInternal tell us 4722 // it isn't required. We therefore mark that this package doesn't need dexopt unless 4723 // it's forced. performedDexOpt will tell us whether we performed dex-opt or skipped 4724 // it. 4725 pkg.mDexOptPerformed.add(dexCodeInstructionSet); 4726 } 4727 4728 // If we've gotten here, we're sure that no error occurred and that we haven't 4729 // deferred dex-opt. We've either dex-opted one more paths or instruction sets or 4730 // we've skipped all of them because they are up to date. In both cases this 4731 // package doesn't need dexopt any longer. 4732 return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED; 4733 } 4734 4735 private static String[] getAppDexInstructionSets(ApplicationInfo info) { 4736 if (info.primaryCpuAbi != null) { 4737 if (info.secondaryCpuAbi != null) { 4738 return new String[] { 4739 VMRuntime.getInstructionSet(info.primaryCpuAbi), 4740 VMRuntime.getInstructionSet(info.secondaryCpuAbi) }; 4741 } else { 4742 return new String[] { 4743 VMRuntime.getInstructionSet(info.primaryCpuAbi) }; 4744 } 4745 } 4746 4747 return new String[] { getPreferredInstructionSet() }; 4748 } 4749 4750 private static String[] getAppDexInstructionSets(PackageSetting ps) { 4751 if (ps.primaryCpuAbiString != null) { 4752 if (ps.secondaryCpuAbiString != null) { 4753 return new String[] { 4754 VMRuntime.getInstructionSet(ps.primaryCpuAbiString), 4755 VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) }; 4756 } else { 4757 return new String[] { 4758 VMRuntime.getInstructionSet(ps.primaryCpuAbiString) }; 4759 } 4760 } 4761 4762 return new String[] { getPreferredInstructionSet() }; 4763 } 4764 4765 private static String getPreferredInstructionSet() { 4766 if (sPreferredInstructionSet == null) { 4767 sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]); 4768 } 4769 4770 return sPreferredInstructionSet; 4771 } 4772 4773 private static List<String> getAllInstructionSets() { 4774 final String[] allAbis = Build.SUPPORTED_ABIS; 4775 final List<String> allInstructionSets = new ArrayList<String>(allAbis.length); 4776 4777 for (String abi : allAbis) { 4778 final String instructionSet = VMRuntime.getInstructionSet(abi); 4779 if (!allInstructionSets.contains(instructionSet)) { 4780 allInstructionSets.add(instructionSet); 4781 } 4782 } 4783 4784 return allInstructionSets; 4785 } 4786 4787 /** 4788 * Returns the instruction set that should be used to compile dex code. In the presence of 4789 * a native bridge this might be different than the one shared libraries use. 4790 */ 4791 private static String getDexCodeInstructionSet(String sharedLibraryIsa) { 4792 String dexCodeIsa = SystemProperties.get("ro.dalvik.vm.isa." + sharedLibraryIsa); 4793 return (dexCodeIsa.isEmpty() ? sharedLibraryIsa : dexCodeIsa); 4794 } 4795 4796 private static String[] getDexCodeInstructionSets(String[] instructionSets) { 4797 HashSet<String> dexCodeInstructionSets = new HashSet<String>(instructionSets.length); 4798 for (String instructionSet : instructionSets) { 4799 dexCodeInstructionSets.add(getDexCodeInstructionSet(instructionSet)); 4800 } 4801 return dexCodeInstructionSets.toArray(new String[dexCodeInstructionSets.size()]); 4802 } 4803 4804 @Override 4805 public void forceDexOpt(String packageName) { 4806 enforceSystemOrRoot("forceDexOpt"); 4807 4808 PackageParser.Package pkg; 4809 synchronized (mPackages) { 4810 pkg = mPackages.get(packageName); 4811 if (pkg == null) { 4812 throw new IllegalArgumentException("Missing package: " + packageName); 4813 } 4814 } 4815 4816 synchronized (mInstallLock) { 4817 final String[] instructionSets = new String[] { 4818 getPrimaryInstructionSet(pkg.applicationInfo) }; 4819 final int res = performDexOptLI(pkg, instructionSets, true, false, true); 4820 if (res != DEX_OPT_PERFORMED) { 4821 throw new IllegalStateException("Failed to dexopt: " + res); 4822 } 4823 } 4824 } 4825 4826 private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets, 4827 boolean forceDex, boolean defer, boolean inclDependencies) { 4828 HashSet<String> done; 4829 if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) { 4830 done = new HashSet<String>(); 4831 done.add(pkg.packageName); 4832 } else { 4833 done = null; 4834 } 4835 return performDexOptLI(pkg, instructionSets, forceDex, defer, done); 4836 } 4837 4838 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 4839 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 4840 Slog.w(TAG, "Unable to update from " + oldPkg.name 4841 + " to " + newPkg.packageName 4842 + ": old package not in system partition"); 4843 return false; 4844 } else if (mPackages.get(oldPkg.name) != null) { 4845 Slog.w(TAG, "Unable to update from " + oldPkg.name 4846 + " to " + newPkg.packageName 4847 + ": old package still exists"); 4848 return false; 4849 } 4850 return true; 4851 } 4852 4853 File getDataPathForUser(int userId) { 4854 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId); 4855 } 4856 4857 private File getDataPathForPackage(String packageName, int userId) { 4858 /* 4859 * Until we fully support multiple users, return the directory we 4860 * previously would have. The PackageManagerTests will need to be 4861 * revised when this is changed back.. 4862 */ 4863 if (userId == 0) { 4864 return new File(mAppDataDir, packageName); 4865 } else { 4866 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 4867 + File.separator + packageName); 4868 } 4869 } 4870 4871 private int createDataDirsLI(String packageName, int uid, String seinfo) { 4872 int[] users = sUserManager.getUserIds(); 4873 int res = mInstaller.install(packageName, uid, uid, seinfo); 4874 if (res < 0) { 4875 return res; 4876 } 4877 for (int user : users) { 4878 if (user != 0) { 4879 res = mInstaller.createUserData(packageName, 4880 UserHandle.getUid(user, uid), user, seinfo); 4881 if (res < 0) { 4882 return res; 4883 } 4884 } 4885 } 4886 return res; 4887 } 4888 4889 private int removeDataDirsLI(String packageName) { 4890 int[] users = sUserManager.getUserIds(); 4891 int res = 0; 4892 for (int user : users) { 4893 int resInner = mInstaller.remove(packageName, user); 4894 if (resInner < 0) { 4895 res = resInner; 4896 } 4897 } 4898 4899 return res; 4900 } 4901 4902 private int deleteCodeCacheDirsLI(String packageName) { 4903 int[] users = sUserManager.getUserIds(); 4904 int res = 0; 4905 for (int user : users) { 4906 int resInner = mInstaller.deleteCodeCacheFiles(packageName, user); 4907 if (resInner < 0) { 4908 res = resInner; 4909 } 4910 } 4911 return res; 4912 } 4913 4914 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 4915 PackageParser.Package changingLib) { 4916 if (file.path != null) { 4917 usesLibraryFiles.add(file.path); 4918 return; 4919 } 4920 PackageParser.Package p = mPackages.get(file.apk); 4921 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 4922 // If we are doing this while in the middle of updating a library apk, 4923 // then we need to make sure to use that new apk for determining the 4924 // dependencies here. (We haven't yet finished committing the new apk 4925 // to the package manager state.) 4926 if (p == null || p.packageName.equals(changingLib.packageName)) { 4927 p = changingLib; 4928 } 4929 } 4930 if (p != null) { 4931 usesLibraryFiles.addAll(p.getAllCodePaths()); 4932 } 4933 } 4934 4935 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 4936 PackageParser.Package changingLib) throws PackageManagerException { 4937 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 4938 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 4939 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 4940 for (int i=0; i<N; i++) { 4941 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 4942 if (file == null) { 4943 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 4944 "Package " + pkg.packageName + " requires unavailable shared library " 4945 + pkg.usesLibraries.get(i) + "; failing!"); 4946 } 4947 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4948 } 4949 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 4950 for (int i=0; i<N; i++) { 4951 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 4952 if (file == null) { 4953 Slog.w(TAG, "Package " + pkg.packageName 4954 + " desires unavailable shared library " 4955 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 4956 } else { 4957 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4958 } 4959 } 4960 N = usesLibraryFiles.size(); 4961 if (N > 0) { 4962 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 4963 } else { 4964 pkg.usesLibraryFiles = null; 4965 } 4966 } 4967 } 4968 4969 private static boolean hasString(List<String> list, List<String> which) { 4970 if (list == null) { 4971 return false; 4972 } 4973 for (int i=list.size()-1; i>=0; i--) { 4974 for (int j=which.size()-1; j>=0; j--) { 4975 if (which.get(j).equals(list.get(i))) { 4976 return true; 4977 } 4978 } 4979 } 4980 return false; 4981 } 4982 4983 private void updateAllSharedLibrariesLPw() { 4984 for (PackageParser.Package pkg : mPackages.values()) { 4985 try { 4986 updateSharedLibrariesLPw(pkg, null); 4987 } catch (PackageManagerException e) { 4988 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 4989 } 4990 } 4991 } 4992 4993 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 4994 PackageParser.Package changingPkg) { 4995 ArrayList<PackageParser.Package> res = null; 4996 for (PackageParser.Package pkg : mPackages.values()) { 4997 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 4998 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 4999 if (res == null) { 5000 res = new ArrayList<PackageParser.Package>(); 5001 } 5002 res.add(pkg); 5003 try { 5004 updateSharedLibrariesLPw(pkg, changingPkg); 5005 } catch (PackageManagerException e) { 5006 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5007 } 5008 } 5009 } 5010 return res; 5011 } 5012 5013 /** 5014 * Derive the value of the {@code cpuAbiOverride} based on the provided 5015 * value and an optional stored value from the package settings. 5016 */ 5017 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5018 String cpuAbiOverride = null; 5019 5020 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5021 cpuAbiOverride = null; 5022 } else if (abiOverride != null) { 5023 cpuAbiOverride = abiOverride; 5024 } else if (settings != null) { 5025 cpuAbiOverride = settings.cpuAbiOverrideString; 5026 } 5027 5028 return cpuAbiOverride; 5029 } 5030 5031 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5032 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5033 final File scanFile = new File(pkg.codePath); 5034 if (pkg.applicationInfo.getCodePath() == null || 5035 pkg.applicationInfo.getResourcePath() == null) { 5036 // Bail out. The resource and code paths haven't been set. 5037 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5038 "Code and resource paths haven't been set correctly"); 5039 } 5040 5041 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5042 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5043 } 5044 5045 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5046 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED; 5047 } 5048 5049 if (mCustomResolverComponentName != null && 5050 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5051 setUpCustomResolverActivity(pkg); 5052 } 5053 5054 if (pkg.packageName.equals("android")) { 5055 synchronized (mPackages) { 5056 if (mAndroidApplication != null) { 5057 Slog.w(TAG, "*************************************************"); 5058 Slog.w(TAG, "Core android package being redefined. Skipping."); 5059 Slog.w(TAG, " file=" + scanFile); 5060 Slog.w(TAG, "*************************************************"); 5061 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5062 "Core android package being redefined. Skipping."); 5063 } 5064 5065 // Set up information for our fall-back user intent resolution activity. 5066 mPlatformPackage = pkg; 5067 pkg.mVersionCode = mSdkVersion; 5068 mAndroidApplication = pkg.applicationInfo; 5069 5070 if (!mResolverReplaced) { 5071 mResolveActivity.applicationInfo = mAndroidApplication; 5072 mResolveActivity.name = ResolverActivity.class.getName(); 5073 mResolveActivity.packageName = mAndroidApplication.packageName; 5074 mResolveActivity.processName = "system:ui"; 5075 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5076 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5077 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5078 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5079 mResolveActivity.exported = true; 5080 mResolveActivity.enabled = true; 5081 mResolveInfo.activityInfo = mResolveActivity; 5082 mResolveInfo.priority = 0; 5083 mResolveInfo.preferredOrder = 0; 5084 mResolveInfo.match = 0; 5085 mResolveComponentName = new ComponentName( 5086 mAndroidApplication.packageName, mResolveActivity.name); 5087 } 5088 } 5089 } 5090 5091 if (DEBUG_PACKAGE_SCANNING) { 5092 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5093 Log.d(TAG, "Scanning package " + pkg.packageName); 5094 } 5095 5096 if (mPackages.containsKey(pkg.packageName) 5097 || mSharedLibraries.containsKey(pkg.packageName)) { 5098 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5099 "Application package " + pkg.packageName 5100 + " already installed. Skipping duplicate."); 5101 } 5102 5103 // Initialize package source and resource directories 5104 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5105 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5106 5107 SharedUserSetting suid = null; 5108 PackageSetting pkgSetting = null; 5109 5110 if (!isSystemApp(pkg)) { 5111 // Only system apps can use these features. 5112 pkg.mOriginalPackages = null; 5113 pkg.mRealPackage = null; 5114 pkg.mAdoptPermissions = null; 5115 } 5116 5117 // writer 5118 synchronized (mPackages) { 5119 if (pkg.mSharedUserId != null) { 5120 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true); 5121 if (suid == null) { 5122 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5123 "Creating application package " + pkg.packageName 5124 + " for shared user failed"); 5125 } 5126 if (DEBUG_PACKAGE_SCANNING) { 5127 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5128 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5129 + "): packages=" + suid.packages); 5130 } 5131 } 5132 5133 // Check if we are renaming from an original package name. 5134 PackageSetting origPackage = null; 5135 String realName = null; 5136 if (pkg.mOriginalPackages != null) { 5137 // This package may need to be renamed to a previously 5138 // installed name. Let's check on that... 5139 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5140 if (pkg.mOriginalPackages.contains(renamed)) { 5141 // This package had originally been installed as the 5142 // original name, and we have already taken care of 5143 // transitioning to the new one. Just update the new 5144 // one to continue using the old name. 5145 realName = pkg.mRealPackage; 5146 if (!pkg.packageName.equals(renamed)) { 5147 // Callers into this function may have already taken 5148 // care of renaming the package; only do it here if 5149 // it is not already done. 5150 pkg.setPackageName(renamed); 5151 } 5152 5153 } else { 5154 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5155 if ((origPackage = mSettings.peekPackageLPr( 5156 pkg.mOriginalPackages.get(i))) != null) { 5157 // We do have the package already installed under its 5158 // original name... should we use it? 5159 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5160 // New package is not compatible with original. 5161 origPackage = null; 5162 continue; 5163 } else if (origPackage.sharedUser != null) { 5164 // Make sure uid is compatible between packages. 5165 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5166 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5167 + " to " + pkg.packageName + ": old uid " 5168 + origPackage.sharedUser.name 5169 + " differs from " + pkg.mSharedUserId); 5170 origPackage = null; 5171 continue; 5172 } 5173 } else { 5174 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5175 + pkg.packageName + " to old name " + origPackage.name); 5176 } 5177 break; 5178 } 5179 } 5180 } 5181 } 5182 5183 if (mTransferedPackages.contains(pkg.packageName)) { 5184 Slog.w(TAG, "Package " + pkg.packageName 5185 + " was transferred to another, but its .apk remains"); 5186 } 5187 5188 // Just create the setting, don't add it yet. For already existing packages 5189 // the PkgSetting exists already and doesn't have to be created. 5190 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5191 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 5192 pkg.applicationInfo.primaryCpuAbi, 5193 pkg.applicationInfo.secondaryCpuAbi, 5194 pkg.applicationInfo.flags, user, false); 5195 if (pkgSetting == null) { 5196 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5197 "Creating application package " + pkg.packageName + " failed"); 5198 } 5199 5200 if (pkgSetting.origPackage != null) { 5201 // If we are first transitioning from an original package, 5202 // fix up the new package's name now. We need to do this after 5203 // looking up the package under its new name, so getPackageLP 5204 // can take care of fiddling things correctly. 5205 pkg.setPackageName(origPackage.name); 5206 5207 // File a report about this. 5208 String msg = "New package " + pkgSetting.realName 5209 + " renamed to replace old package " + pkgSetting.name; 5210 reportSettingsProblem(Log.WARN, msg); 5211 5212 // Make a note of it. 5213 mTransferedPackages.add(origPackage.name); 5214 5215 // No longer need to retain this. 5216 pkgSetting.origPackage = null; 5217 } 5218 5219 if (realName != null) { 5220 // Make a note of it. 5221 mTransferedPackages.add(pkg.packageName); 5222 } 5223 5224 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5225 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5226 } 5227 5228 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5229 // Check all shared libraries and map to their actual file path. 5230 // We only do this here for apps not on a system dir, because those 5231 // are the only ones that can fail an install due to this. We 5232 // will take care of the system apps by updating all of their 5233 // library paths after the scan is done. 5234 updateSharedLibrariesLPw(pkg, null); 5235 } 5236 5237 if (mFoundPolicyFile) { 5238 SELinuxMMAC.assignSeinfoValue(pkg); 5239 } 5240 5241 pkg.applicationInfo.uid = pkgSetting.appId; 5242 pkg.mExtras = pkgSetting; 5243 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5244 try { 5245 verifySignaturesLP(pkgSetting, pkg); 5246 } catch (PackageManagerException e) { 5247 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5248 throw e; 5249 } 5250 // The signature has changed, but this package is in the system 5251 // image... let's recover! 5252 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5253 // However... if this package is part of a shared user, but it 5254 // doesn't match the signature of the shared user, let's fail. 5255 // What this means is that you can't change the signatures 5256 // associated with an overall shared user, which doesn't seem all 5257 // that unreasonable. 5258 if (pkgSetting.sharedUser != null) { 5259 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5260 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5261 throw new PackageManagerException( 5262 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 5263 "Signature mismatch for shared user : " 5264 + pkgSetting.sharedUser); 5265 } 5266 } 5267 // File a report about this. 5268 String msg = "System package " + pkg.packageName 5269 + " signature changed; retaining data."; 5270 reportSettingsProblem(Log.WARN, msg); 5271 } 5272 } else { 5273 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 5274 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5275 + pkg.packageName + " upgrade keys do not match the " 5276 + "previously installed version"); 5277 } else { 5278 // signatures may have changed as result of upgrade 5279 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5280 } 5281 } 5282 // Verify that this new package doesn't have any content providers 5283 // that conflict with existing packages. Only do this if the 5284 // package isn't already installed, since we don't want to break 5285 // things that are installed. 5286 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 5287 final int N = pkg.providers.size(); 5288 int i; 5289 for (i=0; i<N; i++) { 5290 PackageParser.Provider p = pkg.providers.get(i); 5291 if (p.info.authority != null) { 5292 String names[] = p.info.authority.split(";"); 5293 for (int j = 0; j < names.length; j++) { 5294 if (mProvidersByAuthority.containsKey(names[j])) { 5295 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5296 final String otherPackageName = 5297 ((other != null && other.getComponentName() != null) ? 5298 other.getComponentName().getPackageName() : "?"); 5299 throw new PackageManagerException( 5300 INSTALL_FAILED_CONFLICTING_PROVIDER, 5301 "Can't install because provider name " + names[j] 5302 + " (in package " + pkg.applicationInfo.packageName 5303 + ") is already used by " + otherPackageName); 5304 } 5305 } 5306 } 5307 } 5308 } 5309 5310 if (pkg.mAdoptPermissions != null) { 5311 // This package wants to adopt ownership of permissions from 5312 // another package. 5313 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 5314 final String origName = pkg.mAdoptPermissions.get(i); 5315 final PackageSetting orig = mSettings.peekPackageLPr(origName); 5316 if (orig != null) { 5317 if (verifyPackageUpdateLPr(orig, pkg)) { 5318 Slog.i(TAG, "Adopting permissions from " + origName + " to " 5319 + pkg.packageName); 5320 mSettings.transferPermissionsLPw(origName, pkg.packageName); 5321 } 5322 } 5323 } 5324 } 5325 } 5326 5327 final String pkgName = pkg.packageName; 5328 5329 final long scanFileTime = scanFile.lastModified(); 5330 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 5331 pkg.applicationInfo.processName = fixProcessName( 5332 pkg.applicationInfo.packageName, 5333 pkg.applicationInfo.processName, 5334 pkg.applicationInfo.uid); 5335 5336 File dataPath; 5337 if (mPlatformPackage == pkg) { 5338 // The system package is special. 5339 dataPath = new File (Environment.getDataDirectory(), "system"); 5340 pkg.applicationInfo.dataDir = dataPath.getPath(); 5341 5342 } else { 5343 // This is a normal package, need to make its data directory. 5344 dataPath = getDataPathForPackage(pkg.packageName, 0); 5345 5346 boolean uidError = false; 5347 5348 if (dataPath.exists()) { 5349 int currentUid = 0; 5350 try { 5351 StructStat stat = Os.stat(dataPath.getPath()); 5352 currentUid = stat.st_uid; 5353 } catch (ErrnoException e) { 5354 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 5355 } 5356 5357 // If we have mismatched owners for the data path, we have a problem. 5358 if (currentUid != pkg.applicationInfo.uid) { 5359 boolean recovered = false; 5360 if (currentUid == 0) { 5361 // The directory somehow became owned by root. Wow. 5362 // This is probably because the system was stopped while 5363 // installd was in the middle of messing with its libs 5364 // directory. Ask installd to fix that. 5365 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 5366 pkg.applicationInfo.uid); 5367 if (ret >= 0) { 5368 recovered = true; 5369 String msg = "Package " + pkg.packageName 5370 + " unexpectedly changed to uid 0; recovered to " + 5371 + pkg.applicationInfo.uid; 5372 reportSettingsProblem(Log.WARN, msg); 5373 } 5374 } 5375 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5376 || (scanFlags&SCAN_BOOTING) != 0)) { 5377 // If this is a system app, we can at least delete its 5378 // current data so the application will still work. 5379 int ret = removeDataDirsLI(pkgName); 5380 if (ret >= 0) { 5381 // TODO: Kill the processes first 5382 // Old data gone! 5383 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5384 ? "System package " : "Third party package "; 5385 String msg = prefix + pkg.packageName 5386 + " has changed from uid: " 5387 + currentUid + " to " 5388 + pkg.applicationInfo.uid + "; old data erased"; 5389 reportSettingsProblem(Log.WARN, msg); 5390 recovered = true; 5391 5392 // And now re-install the app. 5393 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5394 pkg.applicationInfo.seinfo); 5395 if (ret == -1) { 5396 // Ack should not happen! 5397 msg = prefix + pkg.packageName 5398 + " could not have data directory re-created after delete."; 5399 reportSettingsProblem(Log.WARN, msg); 5400 throw new PackageManagerException( 5401 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 5402 } 5403 } 5404 if (!recovered) { 5405 mHasSystemUidErrors = true; 5406 } 5407 } else if (!recovered) { 5408 // If we allow this install to proceed, we will be broken. 5409 // Abort, abort! 5410 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 5411 "scanPackageLI"); 5412 } 5413 if (!recovered) { 5414 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 5415 + pkg.applicationInfo.uid + "/fs_" 5416 + currentUid; 5417 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 5418 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 5419 String msg = "Package " + pkg.packageName 5420 + " has mismatched uid: " 5421 + currentUid + " on disk, " 5422 + pkg.applicationInfo.uid + " in settings"; 5423 // writer 5424 synchronized (mPackages) { 5425 mSettings.mReadMessages.append(msg); 5426 mSettings.mReadMessages.append('\n'); 5427 uidError = true; 5428 if (!pkgSetting.uidError) { 5429 reportSettingsProblem(Log.ERROR, msg); 5430 } 5431 } 5432 } 5433 } 5434 pkg.applicationInfo.dataDir = dataPath.getPath(); 5435 if (mShouldRestoreconData) { 5436 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 5437 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 5438 pkg.applicationInfo.uid); 5439 } 5440 } else { 5441 if (DEBUG_PACKAGE_SCANNING) { 5442 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5443 Log.v(TAG, "Want this data dir: " + dataPath); 5444 } 5445 //invoke installer to do the actual installation 5446 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5447 pkg.applicationInfo.seinfo); 5448 if (ret < 0) { 5449 // Error from installer 5450 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5451 "Unable to create data dirs [errorCode=" + ret + "]"); 5452 } 5453 5454 if (dataPath.exists()) { 5455 pkg.applicationInfo.dataDir = dataPath.getPath(); 5456 } else { 5457 Slog.w(TAG, "Unable to create data directory: " + dataPath); 5458 pkg.applicationInfo.dataDir = null; 5459 } 5460 } 5461 5462 pkgSetting.uidError = uidError; 5463 } 5464 5465 final String path = scanFile.getPath(); 5466 final String codePath = pkg.applicationInfo.getCodePath(); 5467 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 5468 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 5469 setBundledAppAbisAndRoots(pkg, pkgSetting); 5470 5471 // If we haven't found any native libraries for the app, check if it has 5472 // renderscript code. We'll need to force the app to 32 bit if it has 5473 // renderscript bitcode. 5474 if (pkg.applicationInfo.primaryCpuAbi == null 5475 && pkg.applicationInfo.secondaryCpuAbi == null 5476 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5477 NativeLibraryHelper.Handle handle = null; 5478 try { 5479 handle = NativeLibraryHelper.Handle.create(scanFile); 5480 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5481 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 5482 } 5483 } catch (IOException ioe) { 5484 Slog.w(TAG, "Error scanning system app : " + ioe); 5485 } finally { 5486 IoUtils.closeQuietly(handle); 5487 } 5488 } 5489 5490 setNativeLibraryPaths(pkg); 5491 } else { 5492 // TODO: We can probably be smarter about this stuff. For installed apps, 5493 // we can calculate this information at install time once and for all. For 5494 // system apps, we can probably assume that this information doesn't change 5495 // after the first boot scan. As things stand, we do lots of unnecessary work. 5496 5497 // Give ourselves some initial paths; we'll come back for another 5498 // pass once we've determined ABI below. 5499 setNativeLibraryPaths(pkg); 5500 5501 final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg); 5502 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 5503 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 5504 5505 NativeLibraryHelper.Handle handle = null; 5506 try { 5507 handle = NativeLibraryHelper.Handle.create(scanFile); 5508 // TODO(multiArch): This can be null for apps that didn't go through the 5509 // usual installation process. We can calculate it again, like we 5510 // do during install time. 5511 // 5512 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 5513 // unnecessary. 5514 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 5515 5516 // Null out the abis so that they can be recalculated. 5517 pkg.applicationInfo.primaryCpuAbi = null; 5518 pkg.applicationInfo.secondaryCpuAbi = null; 5519 if (isMultiArch(pkg.applicationInfo)) { 5520 // Warn if we've set an abiOverride for multi-lib packages.. 5521 // By definition, we need to copy both 32 and 64 bit libraries for 5522 // such packages. 5523 if (pkg.cpuAbiOverride != null 5524 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 5525 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 5526 } 5527 5528 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 5529 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 5530 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 5531 if (isAsec) { 5532 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 5533 } else { 5534 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5535 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 5536 useIsaSpecificSubdirs); 5537 } 5538 } 5539 5540 maybeThrowExceptionForMultiArchCopy( 5541 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 5542 5543 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5544 if (isAsec) { 5545 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 5546 } else { 5547 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5548 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 5549 useIsaSpecificSubdirs); 5550 } 5551 } 5552 5553 maybeThrowExceptionForMultiArchCopy( 5554 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 5555 5556 if (abi64 >= 0) { 5557 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 5558 } 5559 5560 if (abi32 >= 0) { 5561 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 5562 if (abi64 >= 0) { 5563 pkg.applicationInfo.secondaryCpuAbi = abi; 5564 } else { 5565 pkg.applicationInfo.primaryCpuAbi = abi; 5566 } 5567 } 5568 } else { 5569 String[] abiList = (cpuAbiOverride != null) ? 5570 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 5571 5572 // Enable gross and lame hacks for apps that are built with old 5573 // SDK tools. We must scan their APKs for renderscript bitcode and 5574 // not launch them if it's present. Don't bother checking on devices 5575 // that don't have 64 bit support. 5576 boolean needsRenderScriptOverride = false; 5577 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 5578 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5579 abiList = Build.SUPPORTED_32_BIT_ABIS; 5580 needsRenderScriptOverride = true; 5581 } 5582 5583 final int copyRet; 5584 if (isAsec) { 5585 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 5586 } else { 5587 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5588 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 5589 } 5590 5591 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5592 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5593 "Error unpackaging native libs for app, errorCode=" + copyRet); 5594 } 5595 5596 if (copyRet >= 0) { 5597 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 5598 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 5599 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 5600 } else if (needsRenderScriptOverride) { 5601 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 5602 } 5603 } 5604 } catch (IOException ioe) { 5605 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 5606 } finally { 5607 IoUtils.closeQuietly(handle); 5608 } 5609 5610 // Now that we've calculated the ABIs and determined if it's an internal app, 5611 // we will go ahead and populate the nativeLibraryPath. 5612 setNativeLibraryPaths(pkg); 5613 5614 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 5615 final int[] userIds = sUserManager.getUserIds(); 5616 synchronized (mInstallLock) { 5617 // Create a native library symlink only if we have native libraries 5618 // and if the native libraries are 32 bit libraries. We do not provide 5619 // this symlink for 64 bit libraries. 5620 if (pkg.applicationInfo.primaryCpuAbi != null && 5621 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 5622 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 5623 for (int userId : userIds) { 5624 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 5625 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5626 "Failed linking native library dir (user=" + userId + ")"); 5627 } 5628 } 5629 } 5630 } 5631 } 5632 5633 // This is a special case for the "system" package, where the ABI is 5634 // dictated by the zygote configuration (and init.rc). We should keep track 5635 // of this ABI so that we can deal with "normal" applications that run under 5636 // the same UID correctly. 5637 if (mPlatformPackage == pkg) { 5638 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 5639 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 5640 } 5641 5642 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 5643 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 5644 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 5645 // Copy the derived override back to the parsed package, so that we can 5646 // update the package settings accordingly. 5647 pkg.cpuAbiOverride = cpuAbiOverride; 5648 5649 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 5650 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 5651 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 5652 5653 // Push the derived path down into PackageSettings so we know what to 5654 // clean up at uninstall time. 5655 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 5656 5657 if (DEBUG_ABI_SELECTION) { 5658 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 5659 " primary=" + pkg.applicationInfo.primaryCpuAbi + 5660 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 5661 } 5662 5663 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 5664 // We don't do this here during boot because we can do it all 5665 // at once after scanning all existing packages. 5666 // 5667 // We also do this *before* we perform dexopt on this package, so that 5668 // we can avoid redundant dexopts, and also to make sure we've got the 5669 // code and package path correct. 5670 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 5671 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 5672 } 5673 5674 if ((scanFlags&SCAN_NO_DEX) == 0) { 5675 if (performDexOptLI(pkg, null /* instruction sets */, forceDex, (scanFlags&SCAN_DEFER_DEX) != 0, false) 5676 == DEX_OPT_FAILED) { 5677 if ((scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5678 removeDataDirsLI(pkg.packageName); 5679 } 5680 5681 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 5682 } 5683 } 5684 5685 if (mFactoryTest && pkg.requestedPermissions.contains( 5686 android.Manifest.permission.FACTORY_TEST)) { 5687 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 5688 } 5689 5690 ArrayList<PackageParser.Package> clientLibPkgs = null; 5691 5692 // writer 5693 synchronized (mPackages) { 5694 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5695 // Only system apps can add new shared libraries. 5696 if (pkg.libraryNames != null) { 5697 for (int i=0; i<pkg.libraryNames.size(); i++) { 5698 String name = pkg.libraryNames.get(i); 5699 boolean allowed = false; 5700 if (isUpdatedSystemApp(pkg)) { 5701 // New library entries can only be added through the 5702 // system image. This is important to get rid of a lot 5703 // of nasty edge cases: for example if we allowed a non- 5704 // system update of the app to add a library, then uninstalling 5705 // the update would make the library go away, and assumptions 5706 // we made such as through app install filtering would now 5707 // have allowed apps on the device which aren't compatible 5708 // with it. Better to just have the restriction here, be 5709 // conservative, and create many fewer cases that can negatively 5710 // impact the user experience. 5711 final PackageSetting sysPs = mSettings 5712 .getDisabledSystemPkgLPr(pkg.packageName); 5713 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 5714 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 5715 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 5716 allowed = true; 5717 allowed = true; 5718 break; 5719 } 5720 } 5721 } 5722 } else { 5723 allowed = true; 5724 } 5725 if (allowed) { 5726 if (!mSharedLibraries.containsKey(name)) { 5727 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 5728 } else if (!name.equals(pkg.packageName)) { 5729 Slog.w(TAG, "Package " + pkg.packageName + " library " 5730 + name + " already exists; skipping"); 5731 } 5732 } else { 5733 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 5734 + name + " that is not declared on system image; skipping"); 5735 } 5736 } 5737 if ((scanFlags&SCAN_BOOTING) == 0) { 5738 // If we are not booting, we need to update any applications 5739 // that are clients of our shared library. If we are booting, 5740 // this will all be done once the scan is complete. 5741 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 5742 } 5743 } 5744 } 5745 } 5746 5747 // We also need to dexopt any apps that are dependent on this library. Note that 5748 // if these fail, we should abort the install since installing the library will 5749 // result in some apps being broken. 5750 if (clientLibPkgs != null) { 5751 if ((scanFlags&SCAN_NO_DEX) == 0) { 5752 for (int i=0; i<clientLibPkgs.size(); i++) { 5753 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5754 if (performDexOptLI(clientPkg, null /* instruction sets */, 5755 forceDex, (scanFlags&SCAN_DEFER_DEX) != 0, false) 5756 == DEX_OPT_FAILED) { 5757 if ((scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5758 removeDataDirsLI(pkg.packageName); 5759 } 5760 5761 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 5762 "scanPackageLI failed to dexopt clientLibPkgs"); 5763 } 5764 } 5765 } 5766 } 5767 5768 // Request the ActivityManager to kill the process(only for existing packages) 5769 // so that we do not end up in a confused state while the user is still using the older 5770 // version of the application while the new one gets installed. 5771 if ((scanFlags & SCAN_REPLACING) != 0) { 5772 killApplication(pkg.applicationInfo.packageName, 5773 pkg.applicationInfo.uid, "update pkg"); 5774 } 5775 5776 // Also need to kill any apps that are dependent on the library. 5777 if (clientLibPkgs != null) { 5778 for (int i=0; i<clientLibPkgs.size(); i++) { 5779 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5780 killApplication(clientPkg.applicationInfo.packageName, 5781 clientPkg.applicationInfo.uid, "update lib"); 5782 } 5783 } 5784 5785 // writer 5786 synchronized (mPackages) { 5787 // We don't expect installation to fail beyond this point 5788 5789 // Add the new setting to mSettings 5790 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 5791 // Add the new setting to mPackages 5792 mPackages.put(pkg.applicationInfo.packageName, pkg); 5793 // Make sure we don't accidentally delete its data. 5794 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 5795 while (iter.hasNext()) { 5796 PackageCleanItem item = iter.next(); 5797 if (pkgName.equals(item.packageName)) { 5798 iter.remove(); 5799 } 5800 } 5801 5802 // Take care of first install / last update times. 5803 if (currentTime != 0) { 5804 if (pkgSetting.firstInstallTime == 0) { 5805 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 5806 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 5807 pkgSetting.lastUpdateTime = currentTime; 5808 } 5809 } else if (pkgSetting.firstInstallTime == 0) { 5810 // We need *something*. Take time time stamp of the file. 5811 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 5812 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 5813 if (scanFileTime != pkgSetting.timeStamp) { 5814 // A package on the system image has changed; consider this 5815 // to be an update. 5816 pkgSetting.lastUpdateTime = scanFileTime; 5817 } 5818 } 5819 5820 // Add the package's KeySets to the global KeySetManagerService 5821 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5822 try { 5823 // Old KeySetData no longer valid. 5824 ksms.removeAppKeySetDataLPw(pkg.packageName); 5825 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 5826 if (pkg.mKeySetMapping != null) { 5827 for (Map.Entry<String, ArraySet<PublicKey>> entry : 5828 pkg.mKeySetMapping.entrySet()) { 5829 if (entry.getValue() != null) { 5830 ksms.addDefinedKeySetToPackageLPw(pkg.packageName, 5831 entry.getValue(), entry.getKey()); 5832 } 5833 } 5834 if (pkg.mUpgradeKeySets != null) { 5835 for (String upgradeAlias : pkg.mUpgradeKeySets) { 5836 ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias); 5837 } 5838 } 5839 } 5840 } catch (NullPointerException e) { 5841 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 5842 } catch (IllegalArgumentException e) { 5843 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 5844 } 5845 5846 int N = pkg.providers.size(); 5847 StringBuilder r = null; 5848 int i; 5849 for (i=0; i<N; i++) { 5850 PackageParser.Provider p = pkg.providers.get(i); 5851 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 5852 p.info.processName, pkg.applicationInfo.uid); 5853 mProviders.addProvider(p); 5854 p.syncable = p.info.isSyncable; 5855 if (p.info.authority != null) { 5856 String names[] = p.info.authority.split(";"); 5857 p.info.authority = null; 5858 for (int j = 0; j < names.length; j++) { 5859 if (j == 1 && p.syncable) { 5860 // We only want the first authority for a provider to possibly be 5861 // syncable, so if we already added this provider using a different 5862 // authority clear the syncable flag. We copy the provider before 5863 // changing it because the mProviders object contains a reference 5864 // to a provider that we don't want to change. 5865 // Only do this for the second authority since the resulting provider 5866 // object can be the same for all future authorities for this provider. 5867 p = new PackageParser.Provider(p); 5868 p.syncable = false; 5869 } 5870 if (!mProvidersByAuthority.containsKey(names[j])) { 5871 mProvidersByAuthority.put(names[j], p); 5872 if (p.info.authority == null) { 5873 p.info.authority = names[j]; 5874 } else { 5875 p.info.authority = p.info.authority + ";" + names[j]; 5876 } 5877 if (DEBUG_PACKAGE_SCANNING) { 5878 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5879 Log.d(TAG, "Registered content provider: " + names[j] 5880 + ", className = " + p.info.name + ", isSyncable = " 5881 + p.info.isSyncable); 5882 } 5883 } else { 5884 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5885 Slog.w(TAG, "Skipping provider name " + names[j] + 5886 " (in package " + pkg.applicationInfo.packageName + 5887 "): name already used by " 5888 + ((other != null && other.getComponentName() != null) 5889 ? other.getComponentName().getPackageName() : "?")); 5890 } 5891 } 5892 } 5893 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5894 if (r == null) { 5895 r = new StringBuilder(256); 5896 } else { 5897 r.append(' '); 5898 } 5899 r.append(p.info.name); 5900 } 5901 } 5902 if (r != null) { 5903 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 5904 } 5905 5906 N = pkg.services.size(); 5907 r = null; 5908 for (i=0; i<N; i++) { 5909 PackageParser.Service s = pkg.services.get(i); 5910 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 5911 s.info.processName, pkg.applicationInfo.uid); 5912 mServices.addService(s); 5913 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5914 if (r == null) { 5915 r = new StringBuilder(256); 5916 } else { 5917 r.append(' '); 5918 } 5919 r.append(s.info.name); 5920 } 5921 } 5922 if (r != null) { 5923 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 5924 } 5925 5926 N = pkg.receivers.size(); 5927 r = null; 5928 for (i=0; i<N; i++) { 5929 PackageParser.Activity a = pkg.receivers.get(i); 5930 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5931 a.info.processName, pkg.applicationInfo.uid); 5932 mReceivers.addActivity(a, "receiver"); 5933 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5934 if (r == null) { 5935 r = new StringBuilder(256); 5936 } else { 5937 r.append(' '); 5938 } 5939 r.append(a.info.name); 5940 } 5941 } 5942 if (r != null) { 5943 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 5944 } 5945 5946 N = pkg.activities.size(); 5947 r = null; 5948 for (i=0; i<N; i++) { 5949 PackageParser.Activity a = pkg.activities.get(i); 5950 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5951 a.info.processName, pkg.applicationInfo.uid); 5952 mActivities.addActivity(a, "activity"); 5953 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5954 if (r == null) { 5955 r = new StringBuilder(256); 5956 } else { 5957 r.append(' '); 5958 } 5959 r.append(a.info.name); 5960 } 5961 } 5962 if (r != null) { 5963 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 5964 } 5965 5966 N = pkg.permissionGroups.size(); 5967 r = null; 5968 for (i=0; i<N; i++) { 5969 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 5970 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 5971 if (cur == null) { 5972 mPermissionGroups.put(pg.info.name, pg); 5973 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5974 if (r == null) { 5975 r = new StringBuilder(256); 5976 } else { 5977 r.append(' '); 5978 } 5979 r.append(pg.info.name); 5980 } 5981 } else { 5982 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 5983 + pg.info.packageName + " ignored: original from " 5984 + cur.info.packageName); 5985 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5986 if (r == null) { 5987 r = new StringBuilder(256); 5988 } else { 5989 r.append(' '); 5990 } 5991 r.append("DUP:"); 5992 r.append(pg.info.name); 5993 } 5994 } 5995 } 5996 if (r != null) { 5997 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 5998 } 5999 6000 N = pkg.permissions.size(); 6001 r = null; 6002 for (i=0; i<N; i++) { 6003 PackageParser.Permission p = pkg.permissions.get(i); 6004 HashMap<String, BasePermission> permissionMap = 6005 p.tree ? mSettings.mPermissionTrees 6006 : mSettings.mPermissions; 6007 p.group = mPermissionGroups.get(p.info.group); 6008 if (p.info.group == null || p.group != null) { 6009 BasePermission bp = permissionMap.get(p.info.name); 6010 if (bp == null) { 6011 bp = new BasePermission(p.info.name, p.info.packageName, 6012 BasePermission.TYPE_NORMAL); 6013 permissionMap.put(p.info.name, bp); 6014 } 6015 if (bp.perm == null) { 6016 if (bp.sourcePackage != null 6017 && !bp.sourcePackage.equals(p.info.packageName)) { 6018 // If this is a permission that was formerly defined by a non-system 6019 // app, but is now defined by a system app (following an upgrade), 6020 // discard the previous declaration and consider the system's to be 6021 // canonical. 6022 if (isSystemApp(p.owner)) { 6023 String msg = "New decl " + p.owner + " of permission " 6024 + p.info.name + " is system"; 6025 reportSettingsProblem(Log.WARN, msg); 6026 bp.sourcePackage = null; 6027 } 6028 } 6029 if (bp.sourcePackage == null 6030 || bp.sourcePackage.equals(p.info.packageName)) { 6031 BasePermission tree = findPermissionTreeLP(p.info.name); 6032 if (tree == null 6033 || tree.sourcePackage.equals(p.info.packageName)) { 6034 bp.packageSetting = pkgSetting; 6035 bp.perm = p; 6036 bp.uid = pkg.applicationInfo.uid; 6037 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6038 if (r == null) { 6039 r = new StringBuilder(256); 6040 } else { 6041 r.append(' '); 6042 } 6043 r.append(p.info.name); 6044 } 6045 } else { 6046 Slog.w(TAG, "Permission " + p.info.name + " from package " 6047 + p.info.packageName + " ignored: base tree " 6048 + tree.name + " is from package " 6049 + tree.sourcePackage); 6050 } 6051 } else { 6052 Slog.w(TAG, "Permission " + p.info.name + " from package " 6053 + p.info.packageName + " ignored: original from " 6054 + bp.sourcePackage); 6055 } 6056 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6057 if (r == null) { 6058 r = new StringBuilder(256); 6059 } else { 6060 r.append(' '); 6061 } 6062 r.append("DUP:"); 6063 r.append(p.info.name); 6064 } 6065 if (bp.perm == p) { 6066 bp.protectionLevel = p.info.protectionLevel; 6067 } 6068 } else { 6069 Slog.w(TAG, "Permission " + p.info.name + " from package " 6070 + p.info.packageName + " ignored: no group " 6071 + p.group); 6072 } 6073 } 6074 if (r != null) { 6075 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6076 } 6077 6078 N = pkg.instrumentation.size(); 6079 r = null; 6080 for (i=0; i<N; i++) { 6081 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6082 a.info.packageName = pkg.applicationInfo.packageName; 6083 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6084 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6085 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6086 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6087 a.info.dataDir = pkg.applicationInfo.dataDir; 6088 6089 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6090 // need other information about the application, like the ABI and what not ? 6091 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6092 mInstrumentation.put(a.getComponentName(), a); 6093 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6094 if (r == null) { 6095 r = new StringBuilder(256); 6096 } else { 6097 r.append(' '); 6098 } 6099 r.append(a.info.name); 6100 } 6101 } 6102 if (r != null) { 6103 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6104 } 6105 6106 if (pkg.protectedBroadcasts != null) { 6107 N = pkg.protectedBroadcasts.size(); 6108 for (i=0; i<N; i++) { 6109 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6110 } 6111 } 6112 6113 pkgSetting.setTimeStamp(scanFileTime); 6114 6115 // Create idmap files for pairs of (packages, overlay packages). 6116 // Note: "android", ie framework-res.apk, is handled by native layers. 6117 if (pkg.mOverlayTarget != null) { 6118 // This is an overlay package. 6119 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6120 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6121 mOverlays.put(pkg.mOverlayTarget, 6122 new HashMap<String, PackageParser.Package>()); 6123 } 6124 HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6125 map.put(pkg.packageName, pkg); 6126 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6127 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6128 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6129 "scanPackageLI failed to createIdmap"); 6130 } 6131 } 6132 } else if (mOverlays.containsKey(pkg.packageName) && 6133 !pkg.packageName.equals("android")) { 6134 // This is a regular package, with one or more known overlay packages. 6135 createIdmapsForPackageLI(pkg); 6136 } 6137 } 6138 6139 return pkg; 6140 } 6141 6142 /** 6143 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6144 * i.e, so that all packages can be run inside a single process if required. 6145 * 6146 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6147 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6148 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6149 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6150 * updating a package that belongs to a shared user. 6151 * 6152 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6153 * adds unnecessary complexity. 6154 */ 6155 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6156 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6157 String requiredInstructionSet = null; 6158 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6159 requiredInstructionSet = VMRuntime.getInstructionSet( 6160 scannedPackage.applicationInfo.primaryCpuAbi); 6161 } 6162 6163 PackageSetting requirer = null; 6164 for (PackageSetting ps : packagesForUser) { 6165 // If packagesForUser contains scannedPackage, we skip it. This will happen 6166 // when scannedPackage is an update of an existing package. Without this check, 6167 // we will never be able to change the ABI of any package belonging to a shared 6168 // user, even if it's compatible with other packages. 6169 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6170 if (ps.primaryCpuAbiString == null) { 6171 continue; 6172 } 6173 6174 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6175 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6176 // We have a mismatch between instruction sets (say arm vs arm64) warn about 6177 // this but there's not much we can do. 6178 String errorMessage = "Instruction set mismatch, " 6179 + ((requirer == null) ? "[caller]" : requirer) 6180 + " requires " + requiredInstructionSet + " whereas " + ps 6181 + " requires " + instructionSet; 6182 Slog.w(TAG, errorMessage); 6183 } 6184 6185 if (requiredInstructionSet == null) { 6186 requiredInstructionSet = instructionSet; 6187 requirer = ps; 6188 } 6189 } 6190 } 6191 6192 if (requiredInstructionSet != null) { 6193 String adjustedAbi; 6194 if (requirer != null) { 6195 // requirer != null implies that either scannedPackage was null or that scannedPackage 6196 // did not require an ABI, in which case we have to adjust scannedPackage to match 6197 // the ABI of the set (which is the same as requirer's ABI) 6198 adjustedAbi = requirer.primaryCpuAbiString; 6199 if (scannedPackage != null) { 6200 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6201 } 6202 } else { 6203 // requirer == null implies that we're updating all ABIs in the set to 6204 // match scannedPackage. 6205 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6206 } 6207 6208 for (PackageSetting ps : packagesForUser) { 6209 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6210 if (ps.primaryCpuAbiString != null) { 6211 continue; 6212 } 6213 6214 ps.primaryCpuAbiString = adjustedAbi; 6215 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6216 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6217 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6218 6219 if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt, 6220 deferDexOpt, true) == DEX_OPT_FAILED) { 6221 ps.primaryCpuAbiString = null; 6222 ps.pkg.applicationInfo.primaryCpuAbi = null; 6223 return; 6224 } else { 6225 mInstaller.rmdex(ps.codePathString, 6226 getDexCodeInstructionSet(getPreferredInstructionSet())); 6227 } 6228 } 6229 } 6230 } 6231 } 6232 } 6233 6234 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6235 synchronized (mPackages) { 6236 mResolverReplaced = true; 6237 // Set up information for custom user intent resolution activity. 6238 mResolveActivity.applicationInfo = pkg.applicationInfo; 6239 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6240 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6241 mResolveActivity.processName = null; 6242 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6243 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6244 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6245 mResolveActivity.theme = 0; 6246 mResolveActivity.exported = true; 6247 mResolveActivity.enabled = true; 6248 mResolveInfo.activityInfo = mResolveActivity; 6249 mResolveInfo.priority = 0; 6250 mResolveInfo.preferredOrder = 0; 6251 mResolveInfo.match = 0; 6252 mResolveComponentName = mCustomResolverComponentName; 6253 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6254 mResolveComponentName); 6255 } 6256 } 6257 6258 private static String calculateBundledApkRoot(final String codePathString) { 6259 final File codePath = new File(codePathString); 6260 final File codeRoot; 6261 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6262 codeRoot = Environment.getRootDirectory(); 6263 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6264 codeRoot = Environment.getOemDirectory(); 6265 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6266 codeRoot = Environment.getVendorDirectory(); 6267 } else { 6268 // Unrecognized code path; take its top real segment as the apk root: 6269 // e.g. /something/app/blah.apk => /something 6270 try { 6271 File f = codePath.getCanonicalFile(); 6272 File parent = f.getParentFile(); // non-null because codePath is a file 6273 File tmp; 6274 while ((tmp = parent.getParentFile()) != null) { 6275 f = parent; 6276 parent = tmp; 6277 } 6278 codeRoot = f; 6279 Slog.w(TAG, "Unrecognized code path " 6280 + codePath + " - using " + codeRoot); 6281 } catch (IOException e) { 6282 // Can't canonicalize the code path -- shenanigans? 6283 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6284 return Environment.getRootDirectory().getPath(); 6285 } 6286 } 6287 return codeRoot.getPath(); 6288 } 6289 6290 /** 6291 * Derive and set the location of native libraries for the given package, 6292 * which varies depending on where and how the package was installed. 6293 */ 6294 private void setNativeLibraryPaths(PackageParser.Package pkg) { 6295 final ApplicationInfo info = pkg.applicationInfo; 6296 final String codePath = pkg.codePath; 6297 final File codeFile = new File(codePath); 6298 final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info); 6299 final boolean asecApp = isForwardLocked(info) || isExternal(info); 6300 6301 info.nativeLibraryRootDir = null; 6302 info.nativeLibraryRootRequiresIsa = false; 6303 info.nativeLibraryDir = null; 6304 info.secondaryNativeLibraryDir = null; 6305 6306 if (isApkFile(codeFile)) { 6307 // Monolithic install 6308 if (bundledApp) { 6309 // If "/system/lib64/apkname" exists, assume that is the per-package 6310 // native library directory to use; otherwise use "/system/lib/apkname". 6311 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 6312 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 6313 getPrimaryInstructionSet(info)); 6314 6315 // This is a bundled system app so choose the path based on the ABI. 6316 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 6317 // is just the default path. 6318 final String apkName = deriveCodePathName(codePath); 6319 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 6320 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 6321 apkName).getAbsolutePath(); 6322 6323 if (info.secondaryCpuAbi != null) { 6324 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 6325 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 6326 secondaryLibDir, apkName).getAbsolutePath(); 6327 } 6328 } else if (asecApp) { 6329 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 6330 .getAbsolutePath(); 6331 } else { 6332 final String apkName = deriveCodePathName(codePath); 6333 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 6334 .getAbsolutePath(); 6335 } 6336 6337 info.nativeLibraryRootRequiresIsa = false; 6338 info.nativeLibraryDir = info.nativeLibraryRootDir; 6339 } else { 6340 // Cluster install 6341 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 6342 info.nativeLibraryRootRequiresIsa = true; 6343 6344 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 6345 getPrimaryInstructionSet(info)).getAbsolutePath(); 6346 6347 if (info.secondaryCpuAbi != null) { 6348 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 6349 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 6350 } 6351 } 6352 } 6353 6354 /** 6355 * Calculate the abis and roots for a bundled app. These can uniquely 6356 * be determined from the contents of the system partition, i.e whether 6357 * it contains 64 or 32 bit shared libraries etc. We do not validate any 6358 * of this information, and instead assume that the system was built 6359 * sensibly. 6360 */ 6361 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 6362 PackageSetting pkgSetting) { 6363 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 6364 6365 // If "/system/lib64/apkname" exists, assume that is the per-package 6366 // native library directory to use; otherwise use "/system/lib/apkname". 6367 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 6368 setBundledAppAbi(pkg, apkRoot, apkName); 6369 // pkgSetting might be null during rescan following uninstall of updates 6370 // to a bundled app, so accommodate that possibility. The settings in 6371 // that case will be established later from the parsed package. 6372 // 6373 // If the settings aren't null, sync them up with what we've just derived. 6374 // note that apkRoot isn't stored in the package settings. 6375 if (pkgSetting != null) { 6376 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6377 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6378 } 6379 } 6380 6381 /** 6382 * Deduces the ABI of a bundled app and sets the relevant fields on the 6383 * parsed pkg object. 6384 * 6385 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 6386 * under which system libraries are installed. 6387 * @param apkName the name of the installed package. 6388 */ 6389 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 6390 final File codeFile = new File(pkg.codePath); 6391 6392 final boolean has64BitLibs; 6393 final boolean has32BitLibs; 6394 if (isApkFile(codeFile)) { 6395 // Monolithic install 6396 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 6397 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 6398 } else { 6399 // Cluster install 6400 final File rootDir = new File(codeFile, LIB_DIR_NAME); 6401 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 6402 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 6403 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 6404 has64BitLibs = (new File(rootDir, isa)).exists(); 6405 } else { 6406 has64BitLibs = false; 6407 } 6408 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 6409 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 6410 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 6411 has32BitLibs = (new File(rootDir, isa)).exists(); 6412 } else { 6413 has32BitLibs = false; 6414 } 6415 } 6416 6417 if (has64BitLibs && !has32BitLibs) { 6418 // The package has 64 bit libs, but not 32 bit libs. Its primary 6419 // ABI should be 64 bit. We can safely assume here that the bundled 6420 // native libraries correspond to the most preferred ABI in the list. 6421 6422 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6423 pkg.applicationInfo.secondaryCpuAbi = null; 6424 } else if (has32BitLibs && !has64BitLibs) { 6425 // The package has 32 bit libs but not 64 bit libs. Its primary 6426 // ABI should be 32 bit. 6427 6428 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6429 pkg.applicationInfo.secondaryCpuAbi = null; 6430 } else if (has32BitLibs && has64BitLibs) { 6431 // The application has both 64 and 32 bit bundled libraries. We check 6432 // here that the app declares multiArch support, and warn if it doesn't. 6433 // 6434 // We will be lenient here and record both ABIs. The primary will be the 6435 // ABI that's higher on the list, i.e, a device that's configured to prefer 6436 // 64 bit apps will see a 64 bit primary ABI, 6437 6438 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 6439 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 6440 } 6441 6442 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 6443 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6444 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6445 } else { 6446 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6447 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6448 } 6449 } else { 6450 pkg.applicationInfo.primaryCpuAbi = null; 6451 pkg.applicationInfo.secondaryCpuAbi = null; 6452 } 6453 } 6454 6455 private void killApplication(String pkgName, int appId, String reason) { 6456 // Request the ActivityManager to kill the process(only for existing packages) 6457 // so that we do not end up in a confused state while the user is still using the older 6458 // version of the application while the new one gets installed. 6459 IActivityManager am = ActivityManagerNative.getDefault(); 6460 if (am != null) { 6461 try { 6462 am.killApplicationWithAppId(pkgName, appId, reason); 6463 } catch (RemoteException e) { 6464 } 6465 } 6466 } 6467 6468 void removePackageLI(PackageSetting ps, boolean chatty) { 6469 if (DEBUG_INSTALL) { 6470 if (chatty) 6471 Log.d(TAG, "Removing package " + ps.name); 6472 } 6473 6474 // writer 6475 synchronized (mPackages) { 6476 mPackages.remove(ps.name); 6477 final PackageParser.Package pkg = ps.pkg; 6478 if (pkg != null) { 6479 cleanPackageDataStructuresLILPw(pkg, chatty); 6480 } 6481 } 6482 } 6483 6484 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 6485 if (DEBUG_INSTALL) { 6486 if (chatty) 6487 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 6488 } 6489 6490 // writer 6491 synchronized (mPackages) { 6492 mPackages.remove(pkg.applicationInfo.packageName); 6493 cleanPackageDataStructuresLILPw(pkg, chatty); 6494 } 6495 } 6496 6497 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 6498 int N = pkg.providers.size(); 6499 StringBuilder r = null; 6500 int i; 6501 for (i=0; i<N; i++) { 6502 PackageParser.Provider p = pkg.providers.get(i); 6503 mProviders.removeProvider(p); 6504 if (p.info.authority == null) { 6505 6506 /* There was another ContentProvider with this authority when 6507 * this app was installed so this authority is null, 6508 * Ignore it as we don't have to unregister the provider. 6509 */ 6510 continue; 6511 } 6512 String names[] = p.info.authority.split(";"); 6513 for (int j = 0; j < names.length; j++) { 6514 if (mProvidersByAuthority.get(names[j]) == p) { 6515 mProvidersByAuthority.remove(names[j]); 6516 if (DEBUG_REMOVE) { 6517 if (chatty) 6518 Log.d(TAG, "Unregistered content provider: " + names[j] 6519 + ", className = " + p.info.name + ", isSyncable = " 6520 + p.info.isSyncable); 6521 } 6522 } 6523 } 6524 if (DEBUG_REMOVE && chatty) { 6525 if (r == null) { 6526 r = new StringBuilder(256); 6527 } else { 6528 r.append(' '); 6529 } 6530 r.append(p.info.name); 6531 } 6532 } 6533 if (r != null) { 6534 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 6535 } 6536 6537 N = pkg.services.size(); 6538 r = null; 6539 for (i=0; i<N; i++) { 6540 PackageParser.Service s = pkg.services.get(i); 6541 mServices.removeService(s); 6542 if (chatty) { 6543 if (r == null) { 6544 r = new StringBuilder(256); 6545 } else { 6546 r.append(' '); 6547 } 6548 r.append(s.info.name); 6549 } 6550 } 6551 if (r != null) { 6552 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 6553 } 6554 6555 N = pkg.receivers.size(); 6556 r = null; 6557 for (i=0; i<N; i++) { 6558 PackageParser.Activity a = pkg.receivers.get(i); 6559 mReceivers.removeActivity(a, "receiver"); 6560 if (DEBUG_REMOVE && chatty) { 6561 if (r == null) { 6562 r = new StringBuilder(256); 6563 } else { 6564 r.append(' '); 6565 } 6566 r.append(a.info.name); 6567 } 6568 } 6569 if (r != null) { 6570 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 6571 } 6572 6573 N = pkg.activities.size(); 6574 r = null; 6575 for (i=0; i<N; i++) { 6576 PackageParser.Activity a = pkg.activities.get(i); 6577 mActivities.removeActivity(a, "activity"); 6578 if (DEBUG_REMOVE && chatty) { 6579 if (r == null) { 6580 r = new StringBuilder(256); 6581 } else { 6582 r.append(' '); 6583 } 6584 r.append(a.info.name); 6585 } 6586 } 6587 if (r != null) { 6588 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 6589 } 6590 6591 N = pkg.permissions.size(); 6592 r = null; 6593 for (i=0; i<N; i++) { 6594 PackageParser.Permission p = pkg.permissions.get(i); 6595 BasePermission bp = mSettings.mPermissions.get(p.info.name); 6596 if (bp == null) { 6597 bp = mSettings.mPermissionTrees.get(p.info.name); 6598 } 6599 if (bp != null && bp.perm == p) { 6600 bp.perm = null; 6601 if (DEBUG_REMOVE && chatty) { 6602 if (r == null) { 6603 r = new StringBuilder(256); 6604 } else { 6605 r.append(' '); 6606 } 6607 r.append(p.info.name); 6608 } 6609 } 6610 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6611 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 6612 if (appOpPerms != null) { 6613 appOpPerms.remove(pkg.packageName); 6614 } 6615 } 6616 } 6617 if (r != null) { 6618 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6619 } 6620 6621 N = pkg.requestedPermissions.size(); 6622 r = null; 6623 for (i=0; i<N; i++) { 6624 String perm = pkg.requestedPermissions.get(i); 6625 BasePermission bp = mSettings.mPermissions.get(perm); 6626 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6627 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 6628 if (appOpPerms != null) { 6629 appOpPerms.remove(pkg.packageName); 6630 if (appOpPerms.isEmpty()) { 6631 mAppOpPermissionPackages.remove(perm); 6632 } 6633 } 6634 } 6635 } 6636 if (r != null) { 6637 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6638 } 6639 6640 N = pkg.instrumentation.size(); 6641 r = null; 6642 for (i=0; i<N; i++) { 6643 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6644 mInstrumentation.remove(a.getComponentName()); 6645 if (DEBUG_REMOVE && chatty) { 6646 if (r == null) { 6647 r = new StringBuilder(256); 6648 } else { 6649 r.append(' '); 6650 } 6651 r.append(a.info.name); 6652 } 6653 } 6654 if (r != null) { 6655 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 6656 } 6657 6658 r = null; 6659 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6660 // Only system apps can hold shared libraries. 6661 if (pkg.libraryNames != null) { 6662 for (i=0; i<pkg.libraryNames.size(); i++) { 6663 String name = pkg.libraryNames.get(i); 6664 SharedLibraryEntry cur = mSharedLibraries.get(name); 6665 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 6666 mSharedLibraries.remove(name); 6667 if (DEBUG_REMOVE && chatty) { 6668 if (r == null) { 6669 r = new StringBuilder(256); 6670 } else { 6671 r.append(' '); 6672 } 6673 r.append(name); 6674 } 6675 } 6676 } 6677 } 6678 } 6679 if (r != null) { 6680 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 6681 } 6682 } 6683 6684 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 6685 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 6686 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 6687 return true; 6688 } 6689 } 6690 return false; 6691 } 6692 6693 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 6694 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 6695 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 6696 6697 private void updatePermissionsLPw(String changingPkg, 6698 PackageParser.Package pkgInfo, int flags) { 6699 // Make sure there are no dangling permission trees. 6700 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 6701 while (it.hasNext()) { 6702 final BasePermission bp = it.next(); 6703 if (bp.packageSetting == null) { 6704 // We may not yet have parsed the package, so just see if 6705 // we still know about its settings. 6706 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6707 } 6708 if (bp.packageSetting == null) { 6709 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 6710 + " from package " + bp.sourcePackage); 6711 it.remove(); 6712 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6713 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6714 Slog.i(TAG, "Removing old permission tree: " + bp.name 6715 + " from package " + bp.sourcePackage); 6716 flags |= UPDATE_PERMISSIONS_ALL; 6717 it.remove(); 6718 } 6719 } 6720 } 6721 6722 // Make sure all dynamic permissions have been assigned to a package, 6723 // and make sure there are no dangling permissions. 6724 it = mSettings.mPermissions.values().iterator(); 6725 while (it.hasNext()) { 6726 final BasePermission bp = it.next(); 6727 if (bp.type == BasePermission.TYPE_DYNAMIC) { 6728 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 6729 + bp.name + " pkg=" + bp.sourcePackage 6730 + " info=" + bp.pendingInfo); 6731 if (bp.packageSetting == null && bp.pendingInfo != null) { 6732 final BasePermission tree = findPermissionTreeLP(bp.name); 6733 if (tree != null && tree.perm != null) { 6734 bp.packageSetting = tree.packageSetting; 6735 bp.perm = new PackageParser.Permission(tree.perm.owner, 6736 new PermissionInfo(bp.pendingInfo)); 6737 bp.perm.info.packageName = tree.perm.info.packageName; 6738 bp.perm.info.name = bp.name; 6739 bp.uid = tree.uid; 6740 } 6741 } 6742 } 6743 if (bp.packageSetting == null) { 6744 // We may not yet have parsed the package, so just see if 6745 // we still know about its settings. 6746 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6747 } 6748 if (bp.packageSetting == null) { 6749 Slog.w(TAG, "Removing dangling permission: " + bp.name 6750 + " from package " + bp.sourcePackage); 6751 it.remove(); 6752 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6753 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6754 Slog.i(TAG, "Removing old permission: " + bp.name 6755 + " from package " + bp.sourcePackage); 6756 flags |= UPDATE_PERMISSIONS_ALL; 6757 it.remove(); 6758 } 6759 } 6760 } 6761 6762 // Now update the permissions for all packages, in particular 6763 // replace the granted permissions of the system packages. 6764 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 6765 for (PackageParser.Package pkg : mPackages.values()) { 6766 if (pkg != pkgInfo) { 6767 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0); 6768 } 6769 } 6770 } 6771 6772 if (pkgInfo != null) { 6773 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0); 6774 } 6775 } 6776 6777 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) { 6778 final PackageSetting ps = (PackageSetting) pkg.mExtras; 6779 if (ps == null) { 6780 return; 6781 } 6782 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 6783 HashSet<String> origPermissions = gp.grantedPermissions; 6784 boolean changedPermission = false; 6785 6786 if (replace) { 6787 ps.permissionsFixed = false; 6788 if (gp == ps) { 6789 origPermissions = new HashSet<String>(gp.grantedPermissions); 6790 gp.grantedPermissions.clear(); 6791 gp.gids = mGlobalGids; 6792 } 6793 } 6794 6795 if (gp.gids == null) { 6796 gp.gids = mGlobalGids; 6797 } 6798 6799 final int N = pkg.requestedPermissions.size(); 6800 for (int i=0; i<N; i++) { 6801 final String name = pkg.requestedPermissions.get(i); 6802 final boolean required = pkg.requestedPermissionsRequired.get(i); 6803 final BasePermission bp = mSettings.mPermissions.get(name); 6804 if (DEBUG_INSTALL) { 6805 if (gp != ps) { 6806 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 6807 } 6808 } 6809 6810 if (bp == null || bp.packageSetting == null) { 6811 Slog.w(TAG, "Unknown permission " + name 6812 + " in package " + pkg.packageName); 6813 continue; 6814 } 6815 6816 final String perm = bp.name; 6817 boolean allowed; 6818 boolean allowedSig = false; 6819 if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6820 // Keep track of app op permissions. 6821 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 6822 if (pkgs == null) { 6823 pkgs = new ArraySet<>(); 6824 mAppOpPermissionPackages.put(bp.name, pkgs); 6825 } 6826 pkgs.add(pkg.packageName); 6827 } 6828 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 6829 if (level == PermissionInfo.PROTECTION_NORMAL 6830 || level == PermissionInfo.PROTECTION_DANGEROUS) { 6831 // We grant a normal or dangerous permission if any of the following 6832 // are true: 6833 // 1) The permission is required 6834 // 2) The permission is optional, but was granted in the past 6835 // 3) The permission is optional, but was requested by an 6836 // app in /system (not /data) 6837 // 6838 // Otherwise, reject the permission. 6839 allowed = (required || origPermissions.contains(perm) 6840 || (isSystemApp(ps) && !isUpdatedSystemApp(ps))); 6841 } else if (bp.packageSetting == null) { 6842 // This permission is invalid; skip it. 6843 allowed = false; 6844 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 6845 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions); 6846 if (allowed) { 6847 allowedSig = true; 6848 } 6849 } else { 6850 allowed = false; 6851 } 6852 if (DEBUG_INSTALL) { 6853 if (gp != ps) { 6854 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 6855 } 6856 } 6857 if (allowed) { 6858 if (!isSystemApp(ps) && ps.permissionsFixed) { 6859 // If this is an existing, non-system package, then 6860 // we can't add any new permissions to it. 6861 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 6862 // Except... if this is a permission that was added 6863 // to the platform (note: need to only do this when 6864 // updating the platform). 6865 allowed = isNewPlatformPermissionForPackage(perm, pkg); 6866 } 6867 } 6868 if (allowed) { 6869 if (!gp.grantedPermissions.contains(perm)) { 6870 changedPermission = true; 6871 gp.grantedPermissions.add(perm); 6872 gp.gids = appendInts(gp.gids, bp.gids); 6873 } else if (!ps.haveGids) { 6874 gp.gids = appendInts(gp.gids, bp.gids); 6875 } 6876 } else { 6877 Slog.w(TAG, "Not granting permission " + perm 6878 + " to package " + pkg.packageName 6879 + " because it was previously installed without"); 6880 } 6881 } else { 6882 if (gp.grantedPermissions.remove(perm)) { 6883 changedPermission = true; 6884 gp.gids = removeInts(gp.gids, bp.gids); 6885 Slog.i(TAG, "Un-granting permission " + perm 6886 + " from package " + pkg.packageName 6887 + " (protectionLevel=" + bp.protectionLevel 6888 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6889 + ")"); 6890 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 6891 // Don't print warning for app op permissions, since it is fine for them 6892 // not to be granted, there is a UI for the user to decide. 6893 Slog.w(TAG, "Not granting permission " + perm 6894 + " to package " + pkg.packageName 6895 + " (protectionLevel=" + bp.protectionLevel 6896 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6897 + ")"); 6898 } 6899 } 6900 } 6901 6902 if ((changedPermission || replace) && !ps.permissionsFixed && 6903 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 6904 // This is the first that we have heard about this package, so the 6905 // permissions we have now selected are fixed until explicitly 6906 // changed. 6907 ps.permissionsFixed = true; 6908 } 6909 ps.haveGids = true; 6910 } 6911 6912 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 6913 boolean allowed = false; 6914 final int NP = PackageParser.NEW_PERMISSIONS.length; 6915 for (int ip=0; ip<NP; ip++) { 6916 final PackageParser.NewPermissionInfo npi 6917 = PackageParser.NEW_PERMISSIONS[ip]; 6918 if (npi.name.equals(perm) 6919 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 6920 allowed = true; 6921 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 6922 + pkg.packageName); 6923 break; 6924 } 6925 } 6926 return allowed; 6927 } 6928 6929 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 6930 BasePermission bp, HashSet<String> origPermissions) { 6931 boolean allowed; 6932 allowed = (compareSignatures( 6933 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 6934 == PackageManager.SIGNATURE_MATCH) 6935 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 6936 == PackageManager.SIGNATURE_MATCH); 6937 if (!allowed && (bp.protectionLevel 6938 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 6939 if (isSystemApp(pkg)) { 6940 // For updated system applications, a system permission 6941 // is granted only if it had been defined by the original application. 6942 if (isUpdatedSystemApp(pkg)) { 6943 final PackageSetting sysPs = mSettings 6944 .getDisabledSystemPkgLPr(pkg.packageName); 6945 final GrantedPermissions origGp = sysPs.sharedUser != null 6946 ? sysPs.sharedUser : sysPs; 6947 6948 if (origGp.grantedPermissions.contains(perm)) { 6949 // If the original was granted this permission, we take 6950 // that grant decision as read and propagate it to the 6951 // update. 6952 allowed = true; 6953 } else { 6954 // The system apk may have been updated with an older 6955 // version of the one on the data partition, but which 6956 // granted a new system permission that it didn't have 6957 // before. In this case we do want to allow the app to 6958 // now get the new permission if the ancestral apk is 6959 // privileged to get it. 6960 if (sysPs.pkg != null && sysPs.isPrivileged()) { 6961 for (int j=0; 6962 j<sysPs.pkg.requestedPermissions.size(); j++) { 6963 if (perm.equals( 6964 sysPs.pkg.requestedPermissions.get(j))) { 6965 allowed = true; 6966 break; 6967 } 6968 } 6969 } 6970 } 6971 } else { 6972 allowed = isPrivilegedApp(pkg); 6973 } 6974 } 6975 } 6976 if (!allowed && (bp.protectionLevel 6977 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 6978 // For development permissions, a development permission 6979 // is granted only if it was already granted. 6980 allowed = origPermissions.contains(perm); 6981 } 6982 return allowed; 6983 } 6984 6985 final class ActivityIntentResolver 6986 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 6987 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 6988 boolean defaultOnly, int userId) { 6989 if (!sUserManager.exists(userId)) return null; 6990 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 6991 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 6992 } 6993 6994 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 6995 int userId) { 6996 if (!sUserManager.exists(userId)) return null; 6997 mFlags = flags; 6998 return super.queryIntent(intent, resolvedType, 6999 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7000 } 7001 7002 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7003 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 7004 if (!sUserManager.exists(userId)) return null; 7005 if (packageActivities == null) { 7006 return null; 7007 } 7008 mFlags = flags; 7009 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7010 final int N = packageActivities.size(); 7011 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 7012 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 7013 7014 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 7015 for (int i = 0; i < N; ++i) { 7016 intentFilters = packageActivities.get(i).intents; 7017 if (intentFilters != null && intentFilters.size() > 0) { 7018 PackageParser.ActivityIntentInfo[] array = 7019 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 7020 intentFilters.toArray(array); 7021 listCut.add(array); 7022 } 7023 } 7024 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7025 } 7026 7027 public final void addActivity(PackageParser.Activity a, String type) { 7028 final boolean systemApp = isSystemApp(a.info.applicationInfo); 7029 mActivities.put(a.getComponentName(), a); 7030 if (DEBUG_SHOW_INFO) 7031 Log.v( 7032 TAG, " " + type + " " + 7033 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 7034 if (DEBUG_SHOW_INFO) 7035 Log.v(TAG, " Class=" + a.info.name); 7036 final int NI = a.intents.size(); 7037 for (int j=0; j<NI; j++) { 7038 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7039 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 7040 intent.setPriority(0); 7041 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 7042 + a.className + " with priority > 0, forcing to 0"); 7043 } 7044 if (DEBUG_SHOW_INFO) { 7045 Log.v(TAG, " IntentFilter:"); 7046 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7047 } 7048 if (!intent.debugCheck()) { 7049 Log.w(TAG, "==> For Activity " + a.info.name); 7050 } 7051 addFilter(intent); 7052 } 7053 } 7054 7055 public final void removeActivity(PackageParser.Activity a, String type) { 7056 mActivities.remove(a.getComponentName()); 7057 if (DEBUG_SHOW_INFO) { 7058 Log.v(TAG, " " + type + " " 7059 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 7060 : a.info.name) + ":"); 7061 Log.v(TAG, " Class=" + a.info.name); 7062 } 7063 final int NI = a.intents.size(); 7064 for (int j=0; j<NI; j++) { 7065 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7066 if (DEBUG_SHOW_INFO) { 7067 Log.v(TAG, " IntentFilter:"); 7068 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7069 } 7070 removeFilter(intent); 7071 } 7072 } 7073 7074 @Override 7075 protected boolean allowFilterResult( 7076 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 7077 ActivityInfo filterAi = filter.activity.info; 7078 for (int i=dest.size()-1; i>=0; i--) { 7079 ActivityInfo destAi = dest.get(i).activityInfo; 7080 if (destAi.name == filterAi.name 7081 && destAi.packageName == filterAi.packageName) { 7082 return false; 7083 } 7084 } 7085 return true; 7086 } 7087 7088 @Override 7089 protected ActivityIntentInfo[] newArray(int size) { 7090 return new ActivityIntentInfo[size]; 7091 } 7092 7093 @Override 7094 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 7095 if (!sUserManager.exists(userId)) return true; 7096 PackageParser.Package p = filter.activity.owner; 7097 if (p != null) { 7098 PackageSetting ps = (PackageSetting)p.mExtras; 7099 if (ps != null) { 7100 // System apps are never considered stopped for purposes of 7101 // filtering, because there may be no way for the user to 7102 // actually re-launch them. 7103 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 7104 && ps.getStopped(userId); 7105 } 7106 } 7107 return false; 7108 } 7109 7110 @Override 7111 protected boolean isPackageForFilter(String packageName, 7112 PackageParser.ActivityIntentInfo info) { 7113 return packageName.equals(info.activity.owner.packageName); 7114 } 7115 7116 @Override 7117 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7118 int match, int userId) { 7119 if (!sUserManager.exists(userId)) return null; 7120 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7121 return null; 7122 } 7123 final PackageParser.Activity activity = info.activity; 7124 if (mSafeMode && (activity.info.applicationInfo.flags 7125 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7126 return null; 7127 } 7128 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7129 if (ps == null) { 7130 return null; 7131 } 7132 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7133 ps.readUserState(userId), userId); 7134 if (ai == null) { 7135 return null; 7136 } 7137 final ResolveInfo res = new ResolveInfo(); 7138 res.activityInfo = ai; 7139 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7140 res.filter = info; 7141 } 7142 res.priority = info.getPriority(); 7143 res.preferredOrder = activity.owner.mPreferredOrder; 7144 //System.out.println("Result: " + res.activityInfo.className + 7145 // " = " + res.priority); 7146 res.match = match; 7147 res.isDefault = info.hasDefault; 7148 res.labelRes = info.labelRes; 7149 res.nonLocalizedLabel = info.nonLocalizedLabel; 7150 if (userNeedsBadging(userId)) { 7151 res.noResourceId = true; 7152 } else { 7153 res.icon = info.icon; 7154 } 7155 res.system = isSystemApp(res.activityInfo.applicationInfo); 7156 return res; 7157 } 7158 7159 @Override 7160 protected void sortResults(List<ResolveInfo> results) { 7161 Collections.sort(results, mResolvePrioritySorter); 7162 } 7163 7164 @Override 7165 protected void dumpFilter(PrintWriter out, String prefix, 7166 PackageParser.ActivityIntentInfo filter) { 7167 out.print(prefix); out.print( 7168 Integer.toHexString(System.identityHashCode(filter.activity))); 7169 out.print(' '); 7170 filter.activity.printComponentShortName(out); 7171 out.print(" filter "); 7172 out.println(Integer.toHexString(System.identityHashCode(filter))); 7173 } 7174 7175// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7176// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7177// final List<ResolveInfo> retList = Lists.newArrayList(); 7178// while (i.hasNext()) { 7179// final ResolveInfo resolveInfo = i.next(); 7180// if (isEnabledLP(resolveInfo.activityInfo)) { 7181// retList.add(resolveInfo); 7182// } 7183// } 7184// return retList; 7185// } 7186 7187 // Keys are String (activity class name), values are Activity. 7188 private final HashMap<ComponentName, PackageParser.Activity> mActivities 7189 = new HashMap<ComponentName, PackageParser.Activity>(); 7190 private int mFlags; 7191 } 7192 7193 private final class ServiceIntentResolver 7194 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 7195 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7196 boolean defaultOnly, int userId) { 7197 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7198 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7199 } 7200 7201 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7202 int userId) { 7203 if (!sUserManager.exists(userId)) return null; 7204 mFlags = flags; 7205 return super.queryIntent(intent, resolvedType, 7206 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7207 } 7208 7209 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7210 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 7211 if (!sUserManager.exists(userId)) return null; 7212 if (packageServices == null) { 7213 return null; 7214 } 7215 mFlags = flags; 7216 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7217 final int N = packageServices.size(); 7218 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 7219 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 7220 7221 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 7222 for (int i = 0; i < N; ++i) { 7223 intentFilters = packageServices.get(i).intents; 7224 if (intentFilters != null && intentFilters.size() > 0) { 7225 PackageParser.ServiceIntentInfo[] array = 7226 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 7227 intentFilters.toArray(array); 7228 listCut.add(array); 7229 } 7230 } 7231 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7232 } 7233 7234 public final void addService(PackageParser.Service s) { 7235 mServices.put(s.getComponentName(), s); 7236 if (DEBUG_SHOW_INFO) { 7237 Log.v(TAG, " " 7238 + (s.info.nonLocalizedLabel != null 7239 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7240 Log.v(TAG, " Class=" + s.info.name); 7241 } 7242 final int NI = s.intents.size(); 7243 int j; 7244 for (j=0; j<NI; j++) { 7245 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7246 if (DEBUG_SHOW_INFO) { 7247 Log.v(TAG, " IntentFilter:"); 7248 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7249 } 7250 if (!intent.debugCheck()) { 7251 Log.w(TAG, "==> For Service " + s.info.name); 7252 } 7253 addFilter(intent); 7254 } 7255 } 7256 7257 public final void removeService(PackageParser.Service s) { 7258 mServices.remove(s.getComponentName()); 7259 if (DEBUG_SHOW_INFO) { 7260 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 7261 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7262 Log.v(TAG, " Class=" + s.info.name); 7263 } 7264 final int NI = s.intents.size(); 7265 int j; 7266 for (j=0; j<NI; j++) { 7267 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7268 if (DEBUG_SHOW_INFO) { 7269 Log.v(TAG, " IntentFilter:"); 7270 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7271 } 7272 removeFilter(intent); 7273 } 7274 } 7275 7276 @Override 7277 protected boolean allowFilterResult( 7278 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 7279 ServiceInfo filterSi = filter.service.info; 7280 for (int i=dest.size()-1; i>=0; i--) { 7281 ServiceInfo destAi = dest.get(i).serviceInfo; 7282 if (destAi.name == filterSi.name 7283 && destAi.packageName == filterSi.packageName) { 7284 return false; 7285 } 7286 } 7287 return true; 7288 } 7289 7290 @Override 7291 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 7292 return new PackageParser.ServiceIntentInfo[size]; 7293 } 7294 7295 @Override 7296 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 7297 if (!sUserManager.exists(userId)) return true; 7298 PackageParser.Package p = filter.service.owner; 7299 if (p != null) { 7300 PackageSetting ps = (PackageSetting)p.mExtras; 7301 if (ps != null) { 7302 // System apps are never considered stopped for purposes of 7303 // filtering, because there may be no way for the user to 7304 // actually re-launch them. 7305 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7306 && ps.getStopped(userId); 7307 } 7308 } 7309 return false; 7310 } 7311 7312 @Override 7313 protected boolean isPackageForFilter(String packageName, 7314 PackageParser.ServiceIntentInfo info) { 7315 return packageName.equals(info.service.owner.packageName); 7316 } 7317 7318 @Override 7319 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 7320 int match, int userId) { 7321 if (!sUserManager.exists(userId)) return null; 7322 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 7323 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 7324 return null; 7325 } 7326 final PackageParser.Service service = info.service; 7327 if (mSafeMode && (service.info.applicationInfo.flags 7328 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7329 return null; 7330 } 7331 PackageSetting ps = (PackageSetting) service.owner.mExtras; 7332 if (ps == null) { 7333 return null; 7334 } 7335 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 7336 ps.readUserState(userId), userId); 7337 if (si == null) { 7338 return null; 7339 } 7340 final ResolveInfo res = new ResolveInfo(); 7341 res.serviceInfo = si; 7342 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7343 res.filter = filter; 7344 } 7345 res.priority = info.getPriority(); 7346 res.preferredOrder = service.owner.mPreferredOrder; 7347 //System.out.println("Result: " + res.activityInfo.className + 7348 // " = " + res.priority); 7349 res.match = match; 7350 res.isDefault = info.hasDefault; 7351 res.labelRes = info.labelRes; 7352 res.nonLocalizedLabel = info.nonLocalizedLabel; 7353 res.icon = info.icon; 7354 res.system = isSystemApp(res.serviceInfo.applicationInfo); 7355 return res; 7356 } 7357 7358 @Override 7359 protected void sortResults(List<ResolveInfo> results) { 7360 Collections.sort(results, mResolvePrioritySorter); 7361 } 7362 7363 @Override 7364 protected void dumpFilter(PrintWriter out, String prefix, 7365 PackageParser.ServiceIntentInfo filter) { 7366 out.print(prefix); out.print( 7367 Integer.toHexString(System.identityHashCode(filter.service))); 7368 out.print(' '); 7369 filter.service.printComponentShortName(out); 7370 out.print(" filter "); 7371 out.println(Integer.toHexString(System.identityHashCode(filter))); 7372 } 7373 7374// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7375// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7376// final List<ResolveInfo> retList = Lists.newArrayList(); 7377// while (i.hasNext()) { 7378// final ResolveInfo resolveInfo = (ResolveInfo) i; 7379// if (isEnabledLP(resolveInfo.serviceInfo)) { 7380// retList.add(resolveInfo); 7381// } 7382// } 7383// return retList; 7384// } 7385 7386 // Keys are String (activity class name), values are Activity. 7387 private final HashMap<ComponentName, PackageParser.Service> mServices 7388 = new HashMap<ComponentName, PackageParser.Service>(); 7389 private int mFlags; 7390 }; 7391 7392 private final class ProviderIntentResolver 7393 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 7394 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7395 boolean defaultOnly, int userId) { 7396 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7397 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7398 } 7399 7400 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7401 int userId) { 7402 if (!sUserManager.exists(userId)) 7403 return null; 7404 mFlags = flags; 7405 return super.queryIntent(intent, resolvedType, 7406 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7407 } 7408 7409 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7410 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 7411 if (!sUserManager.exists(userId)) 7412 return null; 7413 if (packageProviders == null) { 7414 return null; 7415 } 7416 mFlags = flags; 7417 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 7418 final int N = packageProviders.size(); 7419 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 7420 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 7421 7422 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 7423 for (int i = 0; i < N; ++i) { 7424 intentFilters = packageProviders.get(i).intents; 7425 if (intentFilters != null && intentFilters.size() > 0) { 7426 PackageParser.ProviderIntentInfo[] array = 7427 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 7428 intentFilters.toArray(array); 7429 listCut.add(array); 7430 } 7431 } 7432 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7433 } 7434 7435 public final void addProvider(PackageParser.Provider p) { 7436 if (mProviders.containsKey(p.getComponentName())) { 7437 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 7438 return; 7439 } 7440 7441 mProviders.put(p.getComponentName(), p); 7442 if (DEBUG_SHOW_INFO) { 7443 Log.v(TAG, " " 7444 + (p.info.nonLocalizedLabel != null 7445 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7446 Log.v(TAG, " Class=" + p.info.name); 7447 } 7448 final int NI = p.intents.size(); 7449 int j; 7450 for (j = 0; j < NI; j++) { 7451 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7452 if (DEBUG_SHOW_INFO) { 7453 Log.v(TAG, " IntentFilter:"); 7454 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7455 } 7456 if (!intent.debugCheck()) { 7457 Log.w(TAG, "==> For Provider " + p.info.name); 7458 } 7459 addFilter(intent); 7460 } 7461 } 7462 7463 public final void removeProvider(PackageParser.Provider p) { 7464 mProviders.remove(p.getComponentName()); 7465 if (DEBUG_SHOW_INFO) { 7466 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 7467 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7468 Log.v(TAG, " Class=" + p.info.name); 7469 } 7470 final int NI = p.intents.size(); 7471 int j; 7472 for (j = 0; j < NI; j++) { 7473 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7474 if (DEBUG_SHOW_INFO) { 7475 Log.v(TAG, " IntentFilter:"); 7476 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7477 } 7478 removeFilter(intent); 7479 } 7480 } 7481 7482 @Override 7483 protected boolean allowFilterResult( 7484 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 7485 ProviderInfo filterPi = filter.provider.info; 7486 for (int i = dest.size() - 1; i >= 0; i--) { 7487 ProviderInfo destPi = dest.get(i).providerInfo; 7488 if (destPi.name == filterPi.name 7489 && destPi.packageName == filterPi.packageName) { 7490 return false; 7491 } 7492 } 7493 return true; 7494 } 7495 7496 @Override 7497 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 7498 return new PackageParser.ProviderIntentInfo[size]; 7499 } 7500 7501 @Override 7502 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 7503 if (!sUserManager.exists(userId)) 7504 return true; 7505 PackageParser.Package p = filter.provider.owner; 7506 if (p != null) { 7507 PackageSetting ps = (PackageSetting) p.mExtras; 7508 if (ps != null) { 7509 // System apps are never considered stopped for purposes of 7510 // filtering, because there may be no way for the user to 7511 // actually re-launch them. 7512 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7513 && ps.getStopped(userId); 7514 } 7515 } 7516 return false; 7517 } 7518 7519 @Override 7520 protected boolean isPackageForFilter(String packageName, 7521 PackageParser.ProviderIntentInfo info) { 7522 return packageName.equals(info.provider.owner.packageName); 7523 } 7524 7525 @Override 7526 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 7527 int match, int userId) { 7528 if (!sUserManager.exists(userId)) 7529 return null; 7530 final PackageParser.ProviderIntentInfo info = filter; 7531 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 7532 return null; 7533 } 7534 final PackageParser.Provider provider = info.provider; 7535 if (mSafeMode && (provider.info.applicationInfo.flags 7536 & ApplicationInfo.FLAG_SYSTEM) == 0) { 7537 return null; 7538 } 7539 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 7540 if (ps == null) { 7541 return null; 7542 } 7543 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 7544 ps.readUserState(userId), userId); 7545 if (pi == null) { 7546 return null; 7547 } 7548 final ResolveInfo res = new ResolveInfo(); 7549 res.providerInfo = pi; 7550 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 7551 res.filter = filter; 7552 } 7553 res.priority = info.getPriority(); 7554 res.preferredOrder = provider.owner.mPreferredOrder; 7555 res.match = match; 7556 res.isDefault = info.hasDefault; 7557 res.labelRes = info.labelRes; 7558 res.nonLocalizedLabel = info.nonLocalizedLabel; 7559 res.icon = info.icon; 7560 res.system = isSystemApp(res.providerInfo.applicationInfo); 7561 return res; 7562 } 7563 7564 @Override 7565 protected void sortResults(List<ResolveInfo> results) { 7566 Collections.sort(results, mResolvePrioritySorter); 7567 } 7568 7569 @Override 7570 protected void dumpFilter(PrintWriter out, String prefix, 7571 PackageParser.ProviderIntentInfo filter) { 7572 out.print(prefix); 7573 out.print( 7574 Integer.toHexString(System.identityHashCode(filter.provider))); 7575 out.print(' '); 7576 filter.provider.printComponentShortName(out); 7577 out.print(" filter "); 7578 out.println(Integer.toHexString(System.identityHashCode(filter))); 7579 } 7580 7581 private final HashMap<ComponentName, PackageParser.Provider> mProviders 7582 = new HashMap<ComponentName, PackageParser.Provider>(); 7583 private int mFlags; 7584 }; 7585 7586 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 7587 new Comparator<ResolveInfo>() { 7588 public int compare(ResolveInfo r1, ResolveInfo r2) { 7589 int v1 = r1.priority; 7590 int v2 = r2.priority; 7591 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 7592 if (v1 != v2) { 7593 return (v1 > v2) ? -1 : 1; 7594 } 7595 v1 = r1.preferredOrder; 7596 v2 = r2.preferredOrder; 7597 if (v1 != v2) { 7598 return (v1 > v2) ? -1 : 1; 7599 } 7600 if (r1.isDefault != r2.isDefault) { 7601 return r1.isDefault ? -1 : 1; 7602 } 7603 v1 = r1.match; 7604 v2 = r2.match; 7605 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 7606 if (v1 != v2) { 7607 return (v1 > v2) ? -1 : 1; 7608 } 7609 if (r1.system != r2.system) { 7610 return r1.system ? -1 : 1; 7611 } 7612 return 0; 7613 } 7614 }; 7615 7616 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 7617 new Comparator<ProviderInfo>() { 7618 public int compare(ProviderInfo p1, ProviderInfo p2) { 7619 final int v1 = p1.initOrder; 7620 final int v2 = p2.initOrder; 7621 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 7622 } 7623 }; 7624 7625 static final void sendPackageBroadcast(String action, String pkg, 7626 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 7627 int[] userIds) { 7628 IActivityManager am = ActivityManagerNative.getDefault(); 7629 if (am != null) { 7630 try { 7631 if (userIds == null) { 7632 userIds = am.getRunningUserIds(); 7633 } 7634 for (int id : userIds) { 7635 final Intent intent = new Intent(action, 7636 pkg != null ? Uri.fromParts("package", pkg, null) : null); 7637 if (extras != null) { 7638 intent.putExtras(extras); 7639 } 7640 if (targetPkg != null) { 7641 intent.setPackage(targetPkg); 7642 } 7643 // Modify the UID when posting to other users 7644 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 7645 if (uid > 0 && UserHandle.getUserId(uid) != id) { 7646 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 7647 intent.putExtra(Intent.EXTRA_UID, uid); 7648 } 7649 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 7650 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 7651 if (DEBUG_BROADCASTS) { 7652 RuntimeException here = new RuntimeException("here"); 7653 here.fillInStackTrace(); 7654 Slog.d(TAG, "Sending to user " + id + ": " 7655 + intent.toShortString(false, true, false, false) 7656 + " " + intent.getExtras(), here); 7657 } 7658 am.broadcastIntent(null, intent, null, finishedReceiver, 7659 0, null, null, null, android.app.AppOpsManager.OP_NONE, 7660 finishedReceiver != null, false, id); 7661 } 7662 } catch (RemoteException ex) { 7663 } 7664 } 7665 } 7666 7667 /** 7668 * Check if the external storage media is available. This is true if there 7669 * is a mounted external storage medium or if the external storage is 7670 * emulated. 7671 */ 7672 private boolean isExternalMediaAvailable() { 7673 return mMediaMounted || Environment.isExternalStorageEmulated(); 7674 } 7675 7676 @Override 7677 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 7678 // writer 7679 synchronized (mPackages) { 7680 if (!isExternalMediaAvailable()) { 7681 // If the external storage is no longer mounted at this point, 7682 // the caller may not have been able to delete all of this 7683 // packages files and can not delete any more. Bail. 7684 return null; 7685 } 7686 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 7687 if (lastPackage != null) { 7688 pkgs.remove(lastPackage); 7689 } 7690 if (pkgs.size() > 0) { 7691 return pkgs.get(0); 7692 } 7693 } 7694 return null; 7695 } 7696 7697 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 7698 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 7699 userId, andCode ? 1 : 0, packageName); 7700 if (mSystemReady) { 7701 msg.sendToTarget(); 7702 } else { 7703 if (mPostSystemReadyMessages == null) { 7704 mPostSystemReadyMessages = new ArrayList<>(); 7705 } 7706 mPostSystemReadyMessages.add(msg); 7707 } 7708 } 7709 7710 void startCleaningPackages() { 7711 // reader 7712 synchronized (mPackages) { 7713 if (!isExternalMediaAvailable()) { 7714 return; 7715 } 7716 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 7717 return; 7718 } 7719 } 7720 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 7721 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 7722 IActivityManager am = ActivityManagerNative.getDefault(); 7723 if (am != null) { 7724 try { 7725 am.startService(null, intent, null, UserHandle.USER_OWNER); 7726 } catch (RemoteException e) { 7727 } 7728 } 7729 } 7730 7731 @Override 7732 public void installPackage(String originPath, IPackageInstallObserver2 observer, 7733 int installFlags, String installerPackageName, VerificationParams verificationParams, 7734 String packageAbiOverride) { 7735 installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams, 7736 packageAbiOverride, UserHandle.getCallingUserId()); 7737 } 7738 7739 @Override 7740 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 7741 int installFlags, String installerPackageName, VerificationParams verificationParams, 7742 String packageAbiOverride, int userId) { 7743 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7744 null); 7745 if (UserHandle.getCallingUserId() != userId) { 7746 mContext.enforceCallingOrSelfPermission( 7747 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 7748 "installPackage " + userId); 7749 } 7750 7751 final File originFile = new File(originPath); 7752 final int uid = Binder.getCallingUid(); 7753 if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) { 7754 try { 7755 if (observer != null) { 7756 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 7757 } 7758 } catch (RemoteException re) { 7759 } 7760 return; 7761 } 7762 7763 UserHandle user; 7764 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 7765 user = UserHandle.ALL; 7766 } else { 7767 user = new UserHandle(userId); 7768 } 7769 7770 final int filteredInstallFlags; 7771 if (uid == Process.SHELL_UID || uid == 0) { 7772 if (DEBUG_INSTALL) { 7773 Slog.v(TAG, "Install from ADB"); 7774 } 7775 filteredInstallFlags = installFlags | PackageManager.INSTALL_FROM_ADB; 7776 } else { 7777 filteredInstallFlags = installFlags & ~PackageManager.INSTALL_FROM_ADB; 7778 } 7779 7780 verificationParams.setInstallerUid(uid); 7781 7782 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 7783 7784 final Message msg = mHandler.obtainMessage(INIT_COPY); 7785 msg.obj = new InstallParams(origin, observer, filteredInstallFlags, 7786 installerPackageName, verificationParams, user, packageAbiOverride); 7787 mHandler.sendMessage(msg); 7788 } 7789 7790 void installStage(String packageName, File stagedDir, String stagedCid, 7791 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 7792 String installerPackageName, int installerUid, UserHandle user) { 7793 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 7794 params.referrerUri, installerUid, null); 7795 7796 final OriginInfo origin; 7797 if (stagedDir != null) { 7798 origin = OriginInfo.fromStagedFile(stagedDir); 7799 } else { 7800 origin = OriginInfo.fromStagedContainer(stagedCid); 7801 } 7802 7803 final Message msg = mHandler.obtainMessage(INIT_COPY); 7804 msg.obj = new InstallParams(origin, observer, params.installFlags, 7805 installerPackageName, verifParams, user, params.abiOverride); 7806 mHandler.sendMessage(msg); 7807 } 7808 7809 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 7810 Bundle extras = new Bundle(1); 7811 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 7812 7813 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 7814 packageName, extras, null, null, new int[] {userId}); 7815 try { 7816 IActivityManager am = ActivityManagerNative.getDefault(); 7817 final boolean isSystem = 7818 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 7819 if (isSystem && am.isUserRunning(userId, false)) { 7820 // The just-installed/enabled app is bundled on the system, so presumed 7821 // to be able to run automatically without needing an explicit launch. 7822 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 7823 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 7824 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 7825 .setPackage(packageName); 7826 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 7827 android.app.AppOpsManager.OP_NONE, false, false, userId); 7828 } 7829 } catch (RemoteException e) { 7830 // shouldn't happen 7831 Slog.w(TAG, "Unable to bootstrap installed package", e); 7832 } 7833 } 7834 7835 @Override 7836 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 7837 int userId) { 7838 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7839 PackageSetting pkgSetting; 7840 final int uid = Binder.getCallingUid(); 7841 if (UserHandle.getUserId(uid) != userId) { 7842 mContext.enforceCallingOrSelfPermission( 7843 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 7844 "setApplicationHiddenSetting for user " + userId); 7845 } 7846 7847 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 7848 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 7849 return false; 7850 } 7851 7852 long callingId = Binder.clearCallingIdentity(); 7853 try { 7854 boolean sendAdded = false; 7855 boolean sendRemoved = false; 7856 // writer 7857 synchronized (mPackages) { 7858 pkgSetting = mSettings.mPackages.get(packageName); 7859 if (pkgSetting == null) { 7860 return false; 7861 } 7862 if (pkgSetting.getHidden(userId) != hidden) { 7863 pkgSetting.setHidden(hidden, userId); 7864 mSettings.writePackageRestrictionsLPr(userId); 7865 if (hidden) { 7866 sendRemoved = true; 7867 } else { 7868 sendAdded = true; 7869 } 7870 } 7871 } 7872 if (sendAdded) { 7873 sendPackageAddedForUser(packageName, pkgSetting, userId); 7874 return true; 7875 } 7876 if (sendRemoved) { 7877 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 7878 "hiding pkg"); 7879 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 7880 } 7881 } finally { 7882 Binder.restoreCallingIdentity(callingId); 7883 } 7884 return false; 7885 } 7886 7887 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 7888 int userId) { 7889 final PackageRemovedInfo info = new PackageRemovedInfo(); 7890 info.removedPackage = packageName; 7891 info.removedUsers = new int[] {userId}; 7892 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 7893 info.sendBroadcast(false, false, false); 7894 } 7895 7896 /** 7897 * Returns true if application is not found or there was an error. Otherwise it returns 7898 * the hidden state of the package for the given user. 7899 */ 7900 @Override 7901 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 7902 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7903 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 7904 "getApplicationHidden for user " + userId); 7905 PackageSetting pkgSetting; 7906 long callingId = Binder.clearCallingIdentity(); 7907 try { 7908 // writer 7909 synchronized (mPackages) { 7910 pkgSetting = mSettings.mPackages.get(packageName); 7911 if (pkgSetting == null) { 7912 return true; 7913 } 7914 return pkgSetting.getHidden(userId); 7915 } 7916 } finally { 7917 Binder.restoreCallingIdentity(callingId); 7918 } 7919 } 7920 7921 /** 7922 * @hide 7923 */ 7924 @Override 7925 public int installExistingPackageAsUser(String packageName, int userId) { 7926 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7927 null); 7928 PackageSetting pkgSetting; 7929 final int uid = Binder.getCallingUid(); 7930 enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId); 7931 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 7932 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 7933 } 7934 7935 long callingId = Binder.clearCallingIdentity(); 7936 try { 7937 boolean sendAdded = false; 7938 Bundle extras = new Bundle(1); 7939 7940 // writer 7941 synchronized (mPackages) { 7942 pkgSetting = mSettings.mPackages.get(packageName); 7943 if (pkgSetting == null) { 7944 return PackageManager.INSTALL_FAILED_INVALID_URI; 7945 } 7946 if (!pkgSetting.getInstalled(userId)) { 7947 pkgSetting.setInstalled(true, userId); 7948 pkgSetting.setHidden(false, userId); 7949 mSettings.writePackageRestrictionsLPr(userId); 7950 sendAdded = true; 7951 } 7952 } 7953 7954 if (sendAdded) { 7955 sendPackageAddedForUser(packageName, pkgSetting, userId); 7956 } 7957 } finally { 7958 Binder.restoreCallingIdentity(callingId); 7959 } 7960 7961 return PackageManager.INSTALL_SUCCEEDED; 7962 } 7963 7964 boolean isUserRestricted(int userId, String restrictionKey) { 7965 Bundle restrictions = sUserManager.getUserRestrictions(userId); 7966 if (restrictions.getBoolean(restrictionKey, false)) { 7967 Log.w(TAG, "User is restricted: " + restrictionKey); 7968 return true; 7969 } 7970 return false; 7971 } 7972 7973 @Override 7974 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 7975 mContext.enforceCallingOrSelfPermission( 7976 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7977 "Only package verification agents can verify applications"); 7978 7979 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7980 final PackageVerificationResponse response = new PackageVerificationResponse( 7981 verificationCode, Binder.getCallingUid()); 7982 msg.arg1 = id; 7983 msg.obj = response; 7984 mHandler.sendMessage(msg); 7985 } 7986 7987 @Override 7988 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 7989 long millisecondsToDelay) { 7990 mContext.enforceCallingOrSelfPermission( 7991 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7992 "Only package verification agents can extend verification timeouts"); 7993 7994 final PackageVerificationState state = mPendingVerification.get(id); 7995 final PackageVerificationResponse response = new PackageVerificationResponse( 7996 verificationCodeAtTimeout, Binder.getCallingUid()); 7997 7998 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 7999 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 8000 } 8001 if (millisecondsToDelay < 0) { 8002 millisecondsToDelay = 0; 8003 } 8004 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 8005 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 8006 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 8007 } 8008 8009 if ((state != null) && !state.timeoutExtended()) { 8010 state.extendTimeout(); 8011 8012 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8013 msg.arg1 = id; 8014 msg.obj = response; 8015 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 8016 } 8017 } 8018 8019 private void broadcastPackageVerified(int verificationId, Uri packageUri, 8020 int verificationCode, UserHandle user) { 8021 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 8022 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 8023 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8024 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8025 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 8026 8027 mContext.sendBroadcastAsUser(intent, user, 8028 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 8029 } 8030 8031 private ComponentName matchComponentForVerifier(String packageName, 8032 List<ResolveInfo> receivers) { 8033 ActivityInfo targetReceiver = null; 8034 8035 final int NR = receivers.size(); 8036 for (int i = 0; i < NR; i++) { 8037 final ResolveInfo info = receivers.get(i); 8038 if (info.activityInfo == null) { 8039 continue; 8040 } 8041 8042 if (packageName.equals(info.activityInfo.packageName)) { 8043 targetReceiver = info.activityInfo; 8044 break; 8045 } 8046 } 8047 8048 if (targetReceiver == null) { 8049 return null; 8050 } 8051 8052 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8053 } 8054 8055 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8056 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8057 if (pkgInfo.verifiers.length == 0) { 8058 return null; 8059 } 8060 8061 final int N = pkgInfo.verifiers.length; 8062 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8063 for (int i = 0; i < N; i++) { 8064 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8065 8066 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8067 receivers); 8068 if (comp == null) { 8069 continue; 8070 } 8071 8072 final int verifierUid = getUidForVerifier(verifierInfo); 8073 if (verifierUid == -1) { 8074 continue; 8075 } 8076 8077 if (DEBUG_VERIFY) { 8078 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8079 + " with the correct signature"); 8080 } 8081 sufficientVerifiers.add(comp); 8082 verificationState.addSufficientVerifier(verifierUid); 8083 } 8084 8085 return sufficientVerifiers; 8086 } 8087 8088 private int getUidForVerifier(VerifierInfo verifierInfo) { 8089 synchronized (mPackages) { 8090 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8091 if (pkg == null) { 8092 return -1; 8093 } else if (pkg.mSignatures.length != 1) { 8094 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8095 + " has more than one signature; ignoring"); 8096 return -1; 8097 } 8098 8099 /* 8100 * If the public key of the package's signature does not match 8101 * our expected public key, then this is a different package and 8102 * we should skip. 8103 */ 8104 8105 final byte[] expectedPublicKey; 8106 try { 8107 final Signature verifierSig = pkg.mSignatures[0]; 8108 final PublicKey publicKey = verifierSig.getPublicKey(); 8109 expectedPublicKey = publicKey.getEncoded(); 8110 } catch (CertificateException e) { 8111 return -1; 8112 } 8113 8114 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8115 8116 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8117 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8118 + " does not have the expected public key; ignoring"); 8119 return -1; 8120 } 8121 8122 return pkg.applicationInfo.uid; 8123 } 8124 } 8125 8126 @Override 8127 public void finishPackageInstall(int token) { 8128 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8129 8130 if (DEBUG_INSTALL) { 8131 Slog.v(TAG, "BM finishing package install for " + token); 8132 } 8133 8134 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8135 mHandler.sendMessage(msg); 8136 } 8137 8138 /** 8139 * Get the verification agent timeout. 8140 * 8141 * @return verification timeout in milliseconds 8142 */ 8143 private long getVerificationTimeout() { 8144 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8145 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8146 DEFAULT_VERIFICATION_TIMEOUT); 8147 } 8148 8149 /** 8150 * Get the default verification agent response code. 8151 * 8152 * @return default verification response code 8153 */ 8154 private int getDefaultVerificationResponse() { 8155 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8156 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8157 DEFAULT_VERIFICATION_RESPONSE); 8158 } 8159 8160 /** 8161 * Check whether or not package verification has been enabled. 8162 * 8163 * @return true if verification should be performed 8164 */ 8165 private boolean isVerificationEnabled(int userId, int installFlags) { 8166 if (!DEFAULT_VERIFY_ENABLE) { 8167 return false; 8168 } 8169 8170 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 8171 8172 // Check if installing from ADB 8173 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 8174 // Do not run verification in a test harness environment 8175 if (ActivityManager.isRunningInTestHarness()) { 8176 return false; 8177 } 8178 if (ensureVerifyAppsEnabled) { 8179 return true; 8180 } 8181 // Check if the developer does not want package verification for ADB installs 8182 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8183 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8184 return false; 8185 } 8186 } 8187 8188 if (ensureVerifyAppsEnabled) { 8189 return true; 8190 } 8191 8192 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8193 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8194 } 8195 8196 /** 8197 * Get the "allow unknown sources" setting. 8198 * 8199 * @return the current "allow unknown sources" setting 8200 */ 8201 private int getUnknownSourcesSettings() { 8202 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8203 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 8204 -1); 8205 } 8206 8207 @Override 8208 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 8209 final int uid = Binder.getCallingUid(); 8210 // writer 8211 synchronized (mPackages) { 8212 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 8213 if (targetPackageSetting == null) { 8214 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 8215 } 8216 8217 PackageSetting installerPackageSetting; 8218 if (installerPackageName != null) { 8219 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 8220 if (installerPackageSetting == null) { 8221 throw new IllegalArgumentException("Unknown installer package: " 8222 + installerPackageName); 8223 } 8224 } else { 8225 installerPackageSetting = null; 8226 } 8227 8228 Signature[] callerSignature; 8229 Object obj = mSettings.getUserIdLPr(uid); 8230 if (obj != null) { 8231 if (obj instanceof SharedUserSetting) { 8232 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 8233 } else if (obj instanceof PackageSetting) { 8234 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 8235 } else { 8236 throw new SecurityException("Bad object " + obj + " for uid " + uid); 8237 } 8238 } else { 8239 throw new SecurityException("Unknown calling uid " + uid); 8240 } 8241 8242 // Verify: can't set installerPackageName to a package that is 8243 // not signed with the same cert as the caller. 8244 if (installerPackageSetting != null) { 8245 if (compareSignatures(callerSignature, 8246 installerPackageSetting.signatures.mSignatures) 8247 != PackageManager.SIGNATURE_MATCH) { 8248 throw new SecurityException( 8249 "Caller does not have same cert as new installer package " 8250 + installerPackageName); 8251 } 8252 } 8253 8254 // Verify: if target already has an installer package, it must 8255 // be signed with the same cert as the caller. 8256 if (targetPackageSetting.installerPackageName != null) { 8257 PackageSetting setting = mSettings.mPackages.get( 8258 targetPackageSetting.installerPackageName); 8259 // If the currently set package isn't valid, then it's always 8260 // okay to change it. 8261 if (setting != null) { 8262 if (compareSignatures(callerSignature, 8263 setting.signatures.mSignatures) 8264 != PackageManager.SIGNATURE_MATCH) { 8265 throw new SecurityException( 8266 "Caller does not have same cert as old installer package " 8267 + targetPackageSetting.installerPackageName); 8268 } 8269 } 8270 } 8271 8272 // Okay! 8273 targetPackageSetting.installerPackageName = installerPackageName; 8274 scheduleWriteSettingsLocked(); 8275 } 8276 } 8277 8278 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 8279 // Queue up an async operation since the package installation may take a little while. 8280 mHandler.post(new Runnable() { 8281 public void run() { 8282 mHandler.removeCallbacks(this); 8283 // Result object to be returned 8284 PackageInstalledInfo res = new PackageInstalledInfo(); 8285 res.returnCode = currentStatus; 8286 res.uid = -1; 8287 res.pkg = null; 8288 res.removedInfo = new PackageRemovedInfo(); 8289 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 8290 args.doPreInstall(res.returnCode); 8291 synchronized (mInstallLock) { 8292 installPackageLI(args, res); 8293 } 8294 args.doPostInstall(res.returnCode, res.uid); 8295 } 8296 8297 // A restore should be performed at this point if (a) the install 8298 // succeeded, (b) the operation is not an update, and (c) the new 8299 // package has not opted out of backup participation. 8300 final boolean update = res.removedInfo.removedPackage != null; 8301 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 8302 boolean doRestore = !update 8303 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 8304 8305 // Set up the post-install work request bookkeeping. This will be used 8306 // and cleaned up by the post-install event handling regardless of whether 8307 // there's a restore pass performed. Token values are >= 1. 8308 int token; 8309 if (mNextInstallToken < 0) mNextInstallToken = 1; 8310 token = mNextInstallToken++; 8311 8312 PostInstallData data = new PostInstallData(args, res); 8313 mRunningInstalls.put(token, data); 8314 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 8315 8316 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 8317 // Pass responsibility to the Backup Manager. It will perform a 8318 // restore if appropriate, then pass responsibility back to the 8319 // Package Manager to run the post-install observer callbacks 8320 // and broadcasts. 8321 IBackupManager bm = IBackupManager.Stub.asInterface( 8322 ServiceManager.getService(Context.BACKUP_SERVICE)); 8323 if (bm != null) { 8324 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 8325 + " to BM for possible restore"); 8326 try { 8327 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 8328 } catch (RemoteException e) { 8329 // can't happen; the backup manager is local 8330 } catch (Exception e) { 8331 Slog.e(TAG, "Exception trying to enqueue restore", e); 8332 doRestore = false; 8333 } 8334 } else { 8335 Slog.e(TAG, "Backup Manager not found!"); 8336 doRestore = false; 8337 } 8338 } 8339 8340 if (!doRestore) { 8341 // No restore possible, or the Backup Manager was mysteriously not 8342 // available -- just fire the post-install work request directly. 8343 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 8344 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8345 mHandler.sendMessage(msg); 8346 } 8347 } 8348 }); 8349 } 8350 8351 private abstract class HandlerParams { 8352 private static final int MAX_RETRIES = 4; 8353 8354 /** 8355 * Number of times startCopy() has been attempted and had a non-fatal 8356 * error. 8357 */ 8358 private int mRetries = 0; 8359 8360 /** User handle for the user requesting the information or installation. */ 8361 private final UserHandle mUser; 8362 8363 HandlerParams(UserHandle user) { 8364 mUser = user; 8365 } 8366 8367 UserHandle getUser() { 8368 return mUser; 8369 } 8370 8371 final boolean startCopy() { 8372 boolean res; 8373 try { 8374 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 8375 8376 if (++mRetries > MAX_RETRIES) { 8377 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 8378 mHandler.sendEmptyMessage(MCS_GIVE_UP); 8379 handleServiceError(); 8380 return false; 8381 } else { 8382 handleStartCopy(); 8383 res = true; 8384 } 8385 } catch (RemoteException e) { 8386 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 8387 mHandler.sendEmptyMessage(MCS_RECONNECT); 8388 res = false; 8389 } 8390 handleReturnCode(); 8391 return res; 8392 } 8393 8394 final void serviceError() { 8395 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 8396 handleServiceError(); 8397 handleReturnCode(); 8398 } 8399 8400 abstract void handleStartCopy() throws RemoteException; 8401 abstract void handleServiceError(); 8402 abstract void handleReturnCode(); 8403 } 8404 8405 class MeasureParams extends HandlerParams { 8406 private final PackageStats mStats; 8407 private boolean mSuccess; 8408 8409 private final IPackageStatsObserver mObserver; 8410 8411 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 8412 super(new UserHandle(stats.userHandle)); 8413 mObserver = observer; 8414 mStats = stats; 8415 } 8416 8417 @Override 8418 public String toString() { 8419 return "MeasureParams{" 8420 + Integer.toHexString(System.identityHashCode(this)) 8421 + " " + mStats.packageName + "}"; 8422 } 8423 8424 @Override 8425 void handleStartCopy() throws RemoteException { 8426 synchronized (mInstallLock) { 8427 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 8428 } 8429 8430 if (mSuccess) { 8431 final boolean mounted; 8432 if (Environment.isExternalStorageEmulated()) { 8433 mounted = true; 8434 } else { 8435 final String status = Environment.getExternalStorageState(); 8436 mounted = (Environment.MEDIA_MOUNTED.equals(status) 8437 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 8438 } 8439 8440 if (mounted) { 8441 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 8442 8443 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 8444 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 8445 8446 mStats.externalDataSize = calculateDirectorySize(mContainerService, 8447 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 8448 8449 // Always subtract cache size, since it's a subdirectory 8450 mStats.externalDataSize -= mStats.externalCacheSize; 8451 8452 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 8453 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 8454 8455 mStats.externalObbSize = calculateDirectorySize(mContainerService, 8456 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 8457 } 8458 } 8459 } 8460 8461 @Override 8462 void handleReturnCode() { 8463 if (mObserver != null) { 8464 try { 8465 mObserver.onGetStatsCompleted(mStats, mSuccess); 8466 } catch (RemoteException e) { 8467 Slog.i(TAG, "Observer no longer exists."); 8468 } 8469 } 8470 } 8471 8472 @Override 8473 void handleServiceError() { 8474 Slog.e(TAG, "Could not measure application " + mStats.packageName 8475 + " external storage"); 8476 } 8477 } 8478 8479 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 8480 throws RemoteException { 8481 long result = 0; 8482 for (File path : paths) { 8483 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 8484 } 8485 return result; 8486 } 8487 8488 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 8489 for (File path : paths) { 8490 try { 8491 mcs.clearDirectory(path.getAbsolutePath()); 8492 } catch (RemoteException e) { 8493 } 8494 } 8495 } 8496 8497 static class OriginInfo { 8498 /** 8499 * Location where install is coming from, before it has been 8500 * copied/renamed into place. This could be a single monolithic APK 8501 * file, or a cluster directory. This location may be untrusted. 8502 */ 8503 final File file; 8504 final String cid; 8505 8506 /** 8507 * Flag indicating that {@link #file} or {@link #cid} has already been 8508 * staged, meaning downstream users don't need to defensively copy the 8509 * contents. 8510 */ 8511 final boolean staged; 8512 8513 /** 8514 * Flag indicating that {@link #file} or {@link #cid} is an already 8515 * installed app that is being moved. 8516 */ 8517 final boolean existing; 8518 8519 final String resolvedPath; 8520 final File resolvedFile; 8521 8522 static OriginInfo fromNothing() { 8523 return new OriginInfo(null, null, false, false); 8524 } 8525 8526 static OriginInfo fromUntrustedFile(File file) { 8527 return new OriginInfo(file, null, false, false); 8528 } 8529 8530 static OriginInfo fromExistingFile(File file) { 8531 return new OriginInfo(file, null, false, true); 8532 } 8533 8534 static OriginInfo fromStagedFile(File file) { 8535 return new OriginInfo(file, null, true, false); 8536 } 8537 8538 static OriginInfo fromStagedContainer(String cid) { 8539 return new OriginInfo(null, cid, true, false); 8540 } 8541 8542 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 8543 this.file = file; 8544 this.cid = cid; 8545 this.staged = staged; 8546 this.existing = existing; 8547 8548 if (cid != null) { 8549 resolvedPath = PackageHelper.getSdDir(cid); 8550 resolvedFile = new File(resolvedPath); 8551 } else if (file != null) { 8552 resolvedPath = file.getAbsolutePath(); 8553 resolvedFile = file; 8554 } else { 8555 resolvedPath = null; 8556 resolvedFile = null; 8557 } 8558 } 8559 } 8560 8561 class InstallParams extends HandlerParams { 8562 final OriginInfo origin; 8563 final IPackageInstallObserver2 observer; 8564 int installFlags; 8565 final String installerPackageName; 8566 final VerificationParams verificationParams; 8567 private InstallArgs mArgs; 8568 private int mRet; 8569 final String packageAbiOverride; 8570 8571 InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 8572 String installerPackageName, VerificationParams verificationParams, UserHandle user, 8573 String packageAbiOverride) { 8574 super(user); 8575 this.origin = origin; 8576 this.observer = observer; 8577 this.installFlags = installFlags; 8578 this.installerPackageName = installerPackageName; 8579 this.verificationParams = verificationParams; 8580 this.packageAbiOverride = packageAbiOverride; 8581 } 8582 8583 @Override 8584 public String toString() { 8585 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 8586 + " file=" + origin.file + " cid=" + origin.cid + "}"; 8587 } 8588 8589 public ManifestDigest getManifestDigest() { 8590 if (verificationParams == null) { 8591 return null; 8592 } 8593 return verificationParams.getManifestDigest(); 8594 } 8595 8596 private int installLocationPolicy(PackageInfoLite pkgLite) { 8597 String packageName = pkgLite.packageName; 8598 int installLocation = pkgLite.installLocation; 8599 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 8600 // reader 8601 synchronized (mPackages) { 8602 PackageParser.Package pkg = mPackages.get(packageName); 8603 if (pkg != null) { 8604 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 8605 // Check for downgrading. 8606 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 8607 if (pkgLite.versionCode < pkg.mVersionCode) { 8608 Slog.w(TAG, "Can't install update of " + packageName 8609 + " update version " + pkgLite.versionCode 8610 + " is older than installed version " 8611 + pkg.mVersionCode); 8612 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 8613 } 8614 } 8615 // Check for updated system application. 8616 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8617 if (onSd) { 8618 Slog.w(TAG, "Cannot install update to system app on sdcard"); 8619 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 8620 } 8621 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8622 } else { 8623 if (onSd) { 8624 // Install flag overrides everything. 8625 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8626 } 8627 // If current upgrade specifies particular preference 8628 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 8629 // Application explicitly specified internal. 8630 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8631 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 8632 // App explictly prefers external. Let policy decide 8633 } else { 8634 // Prefer previous location 8635 if (isExternal(pkg)) { 8636 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8637 } 8638 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8639 } 8640 } 8641 } else { 8642 // Invalid install. Return error code 8643 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 8644 } 8645 } 8646 } 8647 // All the special cases have been taken care of. 8648 // Return result based on recommended install location. 8649 if (onSd) { 8650 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8651 } 8652 return pkgLite.recommendedInstallLocation; 8653 } 8654 8655 /* 8656 * Invoke remote method to get package information and install 8657 * location values. Override install location based on default 8658 * policy if needed and then create install arguments based 8659 * on the install location. 8660 */ 8661 public void handleStartCopy() throws RemoteException { 8662 int ret = PackageManager.INSTALL_SUCCEEDED; 8663 8664 // If we're already staged, we've firmly committed to an install location 8665 if (origin.staged) { 8666 if (origin.file != null) { 8667 installFlags |= PackageManager.INSTALL_INTERNAL; 8668 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 8669 } else if (origin.cid != null) { 8670 installFlags |= PackageManager.INSTALL_EXTERNAL; 8671 installFlags &= ~PackageManager.INSTALL_INTERNAL; 8672 } else { 8673 throw new IllegalStateException("Invalid stage location"); 8674 } 8675 } 8676 8677 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 8678 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 8679 8680 PackageInfoLite pkgLite = null; 8681 8682 if (onInt && onSd) { 8683 // Check if both bits are set. 8684 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 8685 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8686 } else { 8687 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 8688 packageAbiOverride); 8689 8690 /* 8691 * If we have too little free space, try to free cache 8692 * before giving up. 8693 */ 8694 if (!origin.staged && pkgLite.recommendedInstallLocation 8695 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8696 // TODO: focus freeing disk space on the target device 8697 final StorageManager storage = StorageManager.from(mContext); 8698 final long lowThreshold = storage.getStorageLowBytes( 8699 Environment.getDataDirectory()); 8700 8701 final long sizeBytes = mContainerService.calculateInstalledSize( 8702 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 8703 8704 if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) { 8705 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 8706 installFlags, packageAbiOverride); 8707 } 8708 8709 /* 8710 * The cache free must have deleted the file we 8711 * downloaded to install. 8712 * 8713 * TODO: fix the "freeCache" call to not delete 8714 * the file we care about. 8715 */ 8716 if (pkgLite.recommendedInstallLocation 8717 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8718 pkgLite.recommendedInstallLocation 8719 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 8720 } 8721 } 8722 } 8723 8724 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8725 int loc = pkgLite.recommendedInstallLocation; 8726 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 8727 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8728 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 8729 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 8730 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8731 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8732 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 8733 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 8734 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8735 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 8736 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 8737 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 8738 } else { 8739 // Override with defaults if needed. 8740 loc = installLocationPolicy(pkgLite); 8741 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 8742 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 8743 } else if (!onSd && !onInt) { 8744 // Override install location with flags 8745 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 8746 // Set the flag to install on external media. 8747 installFlags |= PackageManager.INSTALL_EXTERNAL; 8748 installFlags &= ~PackageManager.INSTALL_INTERNAL; 8749 } else { 8750 // Make sure the flag for installing on external 8751 // media is unset 8752 installFlags |= PackageManager.INSTALL_INTERNAL; 8753 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 8754 } 8755 } 8756 } 8757 } 8758 8759 final InstallArgs args = createInstallArgs(this); 8760 mArgs = args; 8761 8762 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8763 /* 8764 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 8765 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 8766 */ 8767 int userIdentifier = getUser().getIdentifier(); 8768 if (userIdentifier == UserHandle.USER_ALL 8769 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 8770 userIdentifier = UserHandle.USER_OWNER; 8771 } 8772 8773 /* 8774 * Determine if we have any installed package verifiers. If we 8775 * do, then we'll defer to them to verify the packages. 8776 */ 8777 final int requiredUid = mRequiredVerifierPackage == null ? -1 8778 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 8779 if (!origin.existing && requiredUid != -1 8780 && isVerificationEnabled(userIdentifier, installFlags)) { 8781 final Intent verification = new Intent( 8782 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 8783 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 8784 PACKAGE_MIME_TYPE); 8785 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8786 8787 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 8788 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 8789 0 /* TODO: Which userId? */); 8790 8791 if (DEBUG_VERIFY) { 8792 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 8793 + verification.toString() + " with " + pkgLite.verifiers.length 8794 + " optional verifiers"); 8795 } 8796 8797 final int verificationId = mPendingVerificationToken++; 8798 8799 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8800 8801 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 8802 installerPackageName); 8803 8804 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 8805 installFlags); 8806 8807 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 8808 pkgLite.packageName); 8809 8810 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 8811 pkgLite.versionCode); 8812 8813 if (verificationParams != null) { 8814 if (verificationParams.getVerificationURI() != null) { 8815 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 8816 verificationParams.getVerificationURI()); 8817 } 8818 if (verificationParams.getOriginatingURI() != null) { 8819 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 8820 verificationParams.getOriginatingURI()); 8821 } 8822 if (verificationParams.getReferrer() != null) { 8823 verification.putExtra(Intent.EXTRA_REFERRER, 8824 verificationParams.getReferrer()); 8825 } 8826 if (verificationParams.getOriginatingUid() >= 0) { 8827 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 8828 verificationParams.getOriginatingUid()); 8829 } 8830 if (verificationParams.getInstallerUid() >= 0) { 8831 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 8832 verificationParams.getInstallerUid()); 8833 } 8834 } 8835 8836 final PackageVerificationState verificationState = new PackageVerificationState( 8837 requiredUid, args); 8838 8839 mPendingVerification.append(verificationId, verificationState); 8840 8841 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 8842 receivers, verificationState); 8843 8844 /* 8845 * If any sufficient verifiers were listed in the package 8846 * manifest, attempt to ask them. 8847 */ 8848 if (sufficientVerifiers != null) { 8849 final int N = sufficientVerifiers.size(); 8850 if (N == 0) { 8851 Slog.i(TAG, "Additional verifiers required, but none installed."); 8852 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 8853 } else { 8854 for (int i = 0; i < N; i++) { 8855 final ComponentName verifierComponent = sufficientVerifiers.get(i); 8856 8857 final Intent sufficientIntent = new Intent(verification); 8858 sufficientIntent.setComponent(verifierComponent); 8859 8860 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 8861 } 8862 } 8863 } 8864 8865 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 8866 mRequiredVerifierPackage, receivers); 8867 if (ret == PackageManager.INSTALL_SUCCEEDED 8868 && mRequiredVerifierPackage != null) { 8869 /* 8870 * Send the intent to the required verification agent, 8871 * but only start the verification timeout after the 8872 * target BroadcastReceivers have run. 8873 */ 8874 verification.setComponent(requiredVerifierComponent); 8875 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 8876 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8877 new BroadcastReceiver() { 8878 @Override 8879 public void onReceive(Context context, Intent intent) { 8880 final Message msg = mHandler 8881 .obtainMessage(CHECK_PENDING_VERIFICATION); 8882 msg.arg1 = verificationId; 8883 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 8884 } 8885 }, null, 0, null, null); 8886 8887 /* 8888 * We don't want the copy to proceed until verification 8889 * succeeds, so null out this field. 8890 */ 8891 mArgs = null; 8892 } 8893 } else { 8894 /* 8895 * No package verification is enabled, so immediately start 8896 * the remote call to initiate copy using temporary file. 8897 */ 8898 ret = args.copyApk(mContainerService, true); 8899 } 8900 } 8901 8902 mRet = ret; 8903 } 8904 8905 @Override 8906 void handleReturnCode() { 8907 // If mArgs is null, then MCS couldn't be reached. When it 8908 // reconnects, it will try again to install. At that point, this 8909 // will succeed. 8910 if (mArgs != null) { 8911 processPendingInstall(mArgs, mRet); 8912 } 8913 } 8914 8915 @Override 8916 void handleServiceError() { 8917 mArgs = createInstallArgs(this); 8918 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8919 } 8920 8921 public boolean isForwardLocked() { 8922 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8923 } 8924 } 8925 8926 /** 8927 * Used during creation of InstallArgs 8928 * 8929 * @param installFlags package installation flags 8930 * @return true if should be installed on external storage 8931 */ 8932 private static boolean installOnSd(int installFlags) { 8933 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 8934 return false; 8935 } 8936 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 8937 return true; 8938 } 8939 return false; 8940 } 8941 8942 /** 8943 * Used during creation of InstallArgs 8944 * 8945 * @param installFlags package installation flags 8946 * @return true if should be installed as forward locked 8947 */ 8948 private static boolean installForwardLocked(int installFlags) { 8949 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8950 } 8951 8952 private InstallArgs createInstallArgs(InstallParams params) { 8953 if (installOnSd(params.installFlags) || params.isForwardLocked()) { 8954 return new AsecInstallArgs(params); 8955 } else { 8956 return new FileInstallArgs(params); 8957 } 8958 } 8959 8960 /** 8961 * Create args that describe an existing installed package. Typically used 8962 * when cleaning up old installs, or used as a move source. 8963 */ 8964 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 8965 String resourcePath, String nativeLibraryRoot, String[] instructionSets) { 8966 final boolean isInAsec; 8967 if (installOnSd(installFlags)) { 8968 /* Apps on SD card are always in ASEC containers. */ 8969 isInAsec = true; 8970 } else if (installForwardLocked(installFlags) 8971 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 8972 /* 8973 * Forward-locked apps are only in ASEC containers if they're the 8974 * new style 8975 */ 8976 isInAsec = true; 8977 } else { 8978 isInAsec = false; 8979 } 8980 8981 if (isInAsec) { 8982 return new AsecInstallArgs(codePath, instructionSets, 8983 installOnSd(installFlags), installForwardLocked(installFlags)); 8984 } else { 8985 return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot, 8986 instructionSets); 8987 } 8988 } 8989 8990 static abstract class InstallArgs { 8991 /** @see InstallParams#origin */ 8992 final OriginInfo origin; 8993 8994 final IPackageInstallObserver2 observer; 8995 // Always refers to PackageManager flags only 8996 final int installFlags; 8997 final String installerPackageName; 8998 final ManifestDigest manifestDigest; 8999 final UserHandle user; 9000 final String abiOverride; 9001 9002 // The list of instruction sets supported by this app. This is currently 9003 // only used during the rmdex() phase to clean up resources. We can get rid of this 9004 // if we move dex files under the common app path. 9005 /* nullable */ String[] instructionSets; 9006 9007 InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 9008 String installerPackageName, ManifestDigest manifestDigest, UserHandle user, 9009 String[] instructionSets, String abiOverride) { 9010 this.origin = origin; 9011 this.installFlags = installFlags; 9012 this.observer = observer; 9013 this.installerPackageName = installerPackageName; 9014 this.manifestDigest = manifestDigest; 9015 this.user = user; 9016 this.instructionSets = instructionSets; 9017 this.abiOverride = abiOverride; 9018 } 9019 9020 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 9021 abstract int doPreInstall(int status); 9022 9023 /** 9024 * Rename package into final resting place. All paths on the given 9025 * scanned package should be updated to reflect the rename. 9026 */ 9027 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 9028 abstract int doPostInstall(int status, int uid); 9029 9030 /** @see PackageSettingBase#codePathString */ 9031 abstract String getCodePath(); 9032 /** @see PackageSettingBase#resourcePathString */ 9033 abstract String getResourcePath(); 9034 abstract String getLegacyNativeLibraryPath(); 9035 9036 // Need installer lock especially for dex file removal. 9037 abstract void cleanUpResourcesLI(); 9038 abstract boolean doPostDeleteLI(boolean delete); 9039 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9040 9041 /** 9042 * Called before the source arguments are copied. This is used mostly 9043 * for MoveParams when it needs to read the source file to put it in the 9044 * destination. 9045 */ 9046 int doPreCopy() { 9047 return PackageManager.INSTALL_SUCCEEDED; 9048 } 9049 9050 /** 9051 * Called after the source arguments are copied. This is used mostly for 9052 * MoveParams when it needs to read the source file to put it in the 9053 * destination. 9054 * 9055 * @return 9056 */ 9057 int doPostCopy(int uid) { 9058 return PackageManager.INSTALL_SUCCEEDED; 9059 } 9060 9061 protected boolean isFwdLocked() { 9062 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9063 } 9064 9065 protected boolean isExternal() { 9066 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9067 } 9068 9069 UserHandle getUser() { 9070 return user; 9071 } 9072 } 9073 9074 /** 9075 * Logic to handle installation of non-ASEC applications, including copying 9076 * and renaming logic. 9077 */ 9078 class FileInstallArgs extends InstallArgs { 9079 private File codeFile; 9080 private File resourceFile; 9081 private File legacyNativeLibraryPath; 9082 9083 // Example topology: 9084 // /data/app/com.example/base.apk 9085 // /data/app/com.example/split_foo.apk 9086 // /data/app/com.example/lib/arm/libfoo.so 9087 // /data/app/com.example/lib/arm64/libfoo.so 9088 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 9089 9090 /** New install */ 9091 FileInstallArgs(InstallParams params) { 9092 super(params.origin, params.observer, params.installFlags, 9093 params.installerPackageName, params.getManifestDigest(), params.getUser(), 9094 null /* instruction sets */, params.packageAbiOverride); 9095 if (isFwdLocked()) { 9096 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 9097 } 9098 } 9099 9100 /** Existing install */ 9101 FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath, 9102 String[] instructionSets) { 9103 super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null); 9104 this.codeFile = (codePath != null) ? new File(codePath) : null; 9105 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 9106 this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ? 9107 new File(legacyNativeLibraryPath) : null; 9108 } 9109 9110 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9111 final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(), 9112 isFwdLocked(), abiOverride); 9113 9114 final StorageManager storage = StorageManager.from(mContext); 9115 return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory())); 9116 } 9117 9118 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9119 if (origin.staged) { 9120 Slog.d(TAG, origin.file + " already staged; skipping copy"); 9121 codeFile = origin.file; 9122 resourceFile = origin.file; 9123 return PackageManager.INSTALL_SUCCEEDED; 9124 } 9125 9126 try { 9127 final File tempDir = mInstallerService.allocateInternalStageDirLegacy(); 9128 codeFile = tempDir; 9129 resourceFile = tempDir; 9130 } catch (IOException e) { 9131 Slog.w(TAG, "Failed to create copy file: " + e); 9132 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9133 } 9134 9135 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 9136 @Override 9137 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 9138 if (!FileUtils.isValidExtFilename(name)) { 9139 throw new IllegalArgumentException("Invalid filename: " + name); 9140 } 9141 try { 9142 final File file = new File(codeFile, name); 9143 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 9144 O_RDWR | O_CREAT, 0644); 9145 Os.chmod(file.getAbsolutePath(), 0644); 9146 return new ParcelFileDescriptor(fd); 9147 } catch (ErrnoException e) { 9148 throw new RemoteException("Failed to open: " + e.getMessage()); 9149 } 9150 } 9151 }; 9152 9153 int ret = PackageManager.INSTALL_SUCCEEDED; 9154 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 9155 if (ret != PackageManager.INSTALL_SUCCEEDED) { 9156 Slog.e(TAG, "Failed to copy package"); 9157 return ret; 9158 } 9159 9160 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 9161 NativeLibraryHelper.Handle handle = null; 9162 try { 9163 handle = NativeLibraryHelper.Handle.create(codeFile); 9164 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 9165 abiOverride); 9166 } catch (IOException e) { 9167 Slog.e(TAG, "Copying native libraries failed", e); 9168 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9169 } finally { 9170 IoUtils.closeQuietly(handle); 9171 } 9172 9173 return ret; 9174 } 9175 9176 int doPreInstall(int status) { 9177 if (status != PackageManager.INSTALL_SUCCEEDED) { 9178 cleanUp(); 9179 } 9180 return status; 9181 } 9182 9183 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9184 if (status != PackageManager.INSTALL_SUCCEEDED) { 9185 cleanUp(); 9186 return false; 9187 } else { 9188 final File beforeCodeFile = codeFile; 9189 final File afterCodeFile = getNextCodePath(pkg.packageName); 9190 9191 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 9192 try { 9193 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 9194 } catch (ErrnoException e) { 9195 Slog.d(TAG, "Failed to rename", e); 9196 return false; 9197 } 9198 9199 if (!SELinux.restoreconRecursive(afterCodeFile)) { 9200 Slog.d(TAG, "Failed to restorecon"); 9201 return false; 9202 } 9203 9204 // Reflect the rename internally 9205 codeFile = afterCodeFile; 9206 resourceFile = afterCodeFile; 9207 9208 // Reflect the rename in scanned details 9209 pkg.codePath = afterCodeFile.getAbsolutePath(); 9210 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9211 pkg.baseCodePath); 9212 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9213 pkg.splitCodePaths); 9214 9215 // Reflect the rename in app info 9216 pkg.applicationInfo.setCodePath(pkg.codePath); 9217 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9218 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9219 pkg.applicationInfo.setResourcePath(pkg.codePath); 9220 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9221 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9222 9223 return true; 9224 } 9225 } 9226 9227 int doPostInstall(int status, int uid) { 9228 if (status != PackageManager.INSTALL_SUCCEEDED) { 9229 cleanUp(); 9230 } 9231 return status; 9232 } 9233 9234 @Override 9235 String getCodePath() { 9236 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 9237 } 9238 9239 @Override 9240 String getResourcePath() { 9241 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 9242 } 9243 9244 @Override 9245 String getLegacyNativeLibraryPath() { 9246 return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null; 9247 } 9248 9249 private boolean cleanUp() { 9250 if (codeFile == null || !codeFile.exists()) { 9251 return false; 9252 } 9253 9254 if (codeFile.isDirectory()) { 9255 FileUtils.deleteContents(codeFile); 9256 } 9257 codeFile.delete(); 9258 9259 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 9260 resourceFile.delete(); 9261 } 9262 9263 if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) { 9264 if (!FileUtils.deleteContents(legacyNativeLibraryPath)) { 9265 Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath); 9266 } 9267 legacyNativeLibraryPath.delete(); 9268 } 9269 9270 return true; 9271 } 9272 9273 void cleanUpResourcesLI() { 9274 // Try enumerating all code paths before deleting 9275 List<String> allCodePaths = Collections.EMPTY_LIST; 9276 if (codeFile != null && codeFile.exists()) { 9277 try { 9278 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9279 allCodePaths = pkg.getAllCodePaths(); 9280 } catch (PackageParserException e) { 9281 // Ignored; we tried our best 9282 } 9283 } 9284 9285 cleanUp(); 9286 9287 if (!allCodePaths.isEmpty()) { 9288 if (instructionSets == null) { 9289 throw new IllegalStateException("instructionSet == null"); 9290 } 9291 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9292 for (String codePath : allCodePaths) { 9293 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9294 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9295 if (retCode < 0) { 9296 Slog.w(TAG, "Couldn't remove dex file for package: " 9297 + " at location " + codePath + ", retcode=" + retCode); 9298 // we don't consider this to be a failure of the core package deletion 9299 } 9300 } 9301 } 9302 } 9303 } 9304 9305 boolean doPostDeleteLI(boolean delete) { 9306 // XXX err, shouldn't we respect the delete flag? 9307 cleanUpResourcesLI(); 9308 return true; 9309 } 9310 } 9311 9312 private boolean isAsecExternal(String cid) { 9313 final String asecPath = PackageHelper.getSdFilesystem(cid); 9314 return !asecPath.startsWith(mAsecInternalPath); 9315 } 9316 9317 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 9318 PackageManagerException { 9319 if (copyRet < 0) { 9320 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 9321 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 9322 throw new PackageManagerException(copyRet, message); 9323 } 9324 } 9325 } 9326 9327 /** 9328 * Extract the MountService "container ID" from the full code path of an 9329 * .apk. 9330 */ 9331 static String cidFromCodePath(String fullCodePath) { 9332 int eidx = fullCodePath.lastIndexOf("/"); 9333 String subStr1 = fullCodePath.substring(0, eidx); 9334 int sidx = subStr1.lastIndexOf("/"); 9335 return subStr1.substring(sidx+1, eidx); 9336 } 9337 9338 /** 9339 * Logic to handle installation of ASEC applications, including copying and 9340 * renaming logic. 9341 */ 9342 class AsecInstallArgs extends InstallArgs { 9343 static final String RES_FILE_NAME = "pkg.apk"; 9344 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 9345 9346 String cid; 9347 String packagePath; 9348 String resourcePath; 9349 String legacyNativeLibraryDir; 9350 9351 /** New install */ 9352 AsecInstallArgs(InstallParams params) { 9353 super(params.origin, params.observer, params.installFlags, 9354 params.installerPackageName, params.getManifestDigest(), 9355 params.getUser(), null /* instruction sets */, 9356 params.packageAbiOverride); 9357 } 9358 9359 /** Existing install */ 9360 AsecInstallArgs(String fullCodePath, String[] instructionSets, 9361 boolean isExternal, boolean isForwardLocked) { 9362 super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0) 9363 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9364 instructionSets, null); 9365 // Hackily pretend we're still looking at a full code path 9366 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 9367 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 9368 } 9369 9370 // Extract cid from fullCodePath 9371 int eidx = fullCodePath.lastIndexOf("/"); 9372 String subStr1 = fullCodePath.substring(0, eidx); 9373 int sidx = subStr1.lastIndexOf("/"); 9374 cid = subStr1.substring(sidx+1, eidx); 9375 setMountPath(subStr1); 9376 } 9377 9378 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 9379 super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 9380 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9381 instructionSets, null); 9382 this.cid = cid; 9383 setMountPath(PackageHelper.getSdDir(cid)); 9384 } 9385 9386 void createCopyFile() { 9387 cid = mInstallerService.allocateExternalStageCidLegacy(); 9388 } 9389 9390 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9391 final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(), 9392 abiOverride); 9393 9394 final File target; 9395 if (isExternal()) { 9396 target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory(); 9397 } else { 9398 target = Environment.getDataDirectory(); 9399 } 9400 9401 final StorageManager storage = StorageManager.from(mContext); 9402 return (sizeBytes <= storage.getStorageBytesUntilLow(target)); 9403 } 9404 9405 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9406 if (origin.staged) { 9407 Slog.d(TAG, origin.cid + " already staged; skipping copy"); 9408 cid = origin.cid; 9409 setMountPath(PackageHelper.getSdDir(cid)); 9410 return PackageManager.INSTALL_SUCCEEDED; 9411 } 9412 9413 if (temp) { 9414 createCopyFile(); 9415 } else { 9416 /* 9417 * Pre-emptively destroy the container since it's destroyed if 9418 * copying fails due to it existing anyway. 9419 */ 9420 PackageHelper.destroySdDir(cid); 9421 } 9422 9423 final String newMountPath = imcs.copyPackageToContainer( 9424 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(), 9425 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 9426 9427 if (newMountPath != null) { 9428 setMountPath(newMountPath); 9429 return PackageManager.INSTALL_SUCCEEDED; 9430 } else { 9431 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9432 } 9433 } 9434 9435 @Override 9436 String getCodePath() { 9437 return packagePath; 9438 } 9439 9440 @Override 9441 String getResourcePath() { 9442 return resourcePath; 9443 } 9444 9445 @Override 9446 String getLegacyNativeLibraryPath() { 9447 return legacyNativeLibraryDir; 9448 } 9449 9450 int doPreInstall(int status) { 9451 if (status != PackageManager.INSTALL_SUCCEEDED) { 9452 // Destroy container 9453 PackageHelper.destroySdDir(cid); 9454 } else { 9455 boolean mounted = PackageHelper.isContainerMounted(cid); 9456 if (!mounted) { 9457 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 9458 Process.SYSTEM_UID); 9459 if (newMountPath != null) { 9460 setMountPath(newMountPath); 9461 } else { 9462 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9463 } 9464 } 9465 } 9466 return status; 9467 } 9468 9469 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9470 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 9471 String newMountPath = null; 9472 if (PackageHelper.isContainerMounted(cid)) { 9473 // Unmount the container 9474 if (!PackageHelper.unMountSdDir(cid)) { 9475 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9476 return false; 9477 } 9478 } 9479 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9480 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9481 " which might be stale. Will try to clean up."); 9482 // Clean up the stale container and proceed to recreate. 9483 if (!PackageHelper.destroySdDir(newCacheId)) { 9484 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9485 return false; 9486 } 9487 // Successfully cleaned up stale container. Try to rename again. 9488 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9489 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9490 + " inspite of cleaning it up."); 9491 return false; 9492 } 9493 } 9494 if (!PackageHelper.isContainerMounted(newCacheId)) { 9495 Slog.w(TAG, "Mounting container " + newCacheId); 9496 newMountPath = PackageHelper.mountSdDir(newCacheId, 9497 getEncryptKey(), Process.SYSTEM_UID); 9498 } else { 9499 newMountPath = PackageHelper.getSdDir(newCacheId); 9500 } 9501 if (newMountPath == null) { 9502 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9503 return false; 9504 } 9505 Log.i(TAG, "Succesfully renamed " + cid + 9506 " to " + newCacheId + 9507 " at new path: " + newMountPath); 9508 cid = newCacheId; 9509 9510 final File beforeCodeFile = new File(packagePath); 9511 setMountPath(newMountPath); 9512 final File afterCodeFile = new File(packagePath); 9513 9514 // Reflect the rename in scanned details 9515 pkg.codePath = afterCodeFile.getAbsolutePath(); 9516 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9517 pkg.baseCodePath); 9518 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9519 pkg.splitCodePaths); 9520 9521 // Reflect the rename in app info 9522 pkg.applicationInfo.setCodePath(pkg.codePath); 9523 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9524 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9525 pkg.applicationInfo.setResourcePath(pkg.codePath); 9526 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9527 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9528 9529 return true; 9530 } 9531 9532 private void setMountPath(String mountPath) { 9533 final File mountFile = new File(mountPath); 9534 9535 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 9536 if (monolithicFile.exists()) { 9537 packagePath = monolithicFile.getAbsolutePath(); 9538 if (isFwdLocked()) { 9539 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 9540 } else { 9541 resourcePath = packagePath; 9542 } 9543 } else { 9544 packagePath = mountFile.getAbsolutePath(); 9545 resourcePath = packagePath; 9546 } 9547 9548 legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath(); 9549 } 9550 9551 int doPostInstall(int status, int uid) { 9552 if (status != PackageManager.INSTALL_SUCCEEDED) { 9553 cleanUp(); 9554 } else { 9555 final int groupOwner; 9556 final String protectedFile; 9557 if (isFwdLocked()) { 9558 groupOwner = UserHandle.getSharedAppGid(uid); 9559 protectedFile = RES_FILE_NAME; 9560 } else { 9561 groupOwner = -1; 9562 protectedFile = null; 9563 } 9564 9565 if (uid < Process.FIRST_APPLICATION_UID 9566 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9567 Slog.e(TAG, "Failed to finalize " + cid); 9568 PackageHelper.destroySdDir(cid); 9569 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9570 } 9571 9572 boolean mounted = PackageHelper.isContainerMounted(cid); 9573 if (!mounted) { 9574 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9575 } 9576 } 9577 return status; 9578 } 9579 9580 private void cleanUp() { 9581 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9582 9583 // Destroy secure container 9584 PackageHelper.destroySdDir(cid); 9585 } 9586 9587 private List<String> getAllCodePaths() { 9588 final File codeFile = new File(getCodePath()); 9589 if (codeFile != null && codeFile.exists()) { 9590 try { 9591 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9592 return pkg.getAllCodePaths(); 9593 } catch (PackageParserException e) { 9594 // Ignored; we tried our best 9595 } 9596 } 9597 return Collections.EMPTY_LIST; 9598 } 9599 9600 void cleanUpResourcesLI() { 9601 // Enumerate all code paths before deleting 9602 cleanUpResourcesLI(getAllCodePaths()); 9603 } 9604 9605 private void cleanUpResourcesLI(List<String> allCodePaths) { 9606 cleanUp(); 9607 9608 if (!allCodePaths.isEmpty()) { 9609 if (instructionSets == null) { 9610 throw new IllegalStateException("instructionSet == null"); 9611 } 9612 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9613 for (String codePath : allCodePaths) { 9614 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9615 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9616 if (retCode < 0) { 9617 Slog.w(TAG, "Couldn't remove dex file for package: " 9618 + " at location " + codePath + ", retcode=" + retCode); 9619 // we don't consider this to be a failure of the core package deletion 9620 } 9621 } 9622 } 9623 } 9624 } 9625 9626 boolean matchContainer(String app) { 9627 if (cid.startsWith(app)) { 9628 return true; 9629 } 9630 return false; 9631 } 9632 9633 String getPackageName() { 9634 return getAsecPackageName(cid); 9635 } 9636 9637 boolean doPostDeleteLI(boolean delete) { 9638 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 9639 final List<String> allCodePaths = getAllCodePaths(); 9640 boolean mounted = PackageHelper.isContainerMounted(cid); 9641 if (mounted) { 9642 // Unmount first 9643 if (PackageHelper.unMountSdDir(cid)) { 9644 mounted = false; 9645 } 9646 } 9647 if (!mounted && delete) { 9648 cleanUpResourcesLI(allCodePaths); 9649 } 9650 return !mounted; 9651 } 9652 9653 @Override 9654 int doPreCopy() { 9655 if (isFwdLocked()) { 9656 if (!PackageHelper.fixSdPermissions(cid, 9657 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 9658 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9659 } 9660 } 9661 9662 return PackageManager.INSTALL_SUCCEEDED; 9663 } 9664 9665 @Override 9666 int doPostCopy(int uid) { 9667 if (isFwdLocked()) { 9668 if (uid < Process.FIRST_APPLICATION_UID 9669 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 9670 RES_FILE_NAME)) { 9671 Slog.e(TAG, "Failed to finalize " + cid); 9672 PackageHelper.destroySdDir(cid); 9673 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9674 } 9675 } 9676 9677 return PackageManager.INSTALL_SUCCEEDED; 9678 } 9679 } 9680 9681 static String getAsecPackageName(String packageCid) { 9682 int idx = packageCid.lastIndexOf("-"); 9683 if (idx == -1) { 9684 return packageCid; 9685 } 9686 return packageCid.substring(0, idx); 9687 } 9688 9689 // Utility method used to create code paths based on package name and available index. 9690 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 9691 String idxStr = ""; 9692 int idx = 1; 9693 // Fall back to default value of idx=1 if prefix is not 9694 // part of oldCodePath 9695 if (oldCodePath != null) { 9696 String subStr = oldCodePath; 9697 // Drop the suffix right away 9698 if (suffix != null && subStr.endsWith(suffix)) { 9699 subStr = subStr.substring(0, subStr.length() - suffix.length()); 9700 } 9701 // If oldCodePath already contains prefix find out the 9702 // ending index to either increment or decrement. 9703 int sidx = subStr.lastIndexOf(prefix); 9704 if (sidx != -1) { 9705 subStr = subStr.substring(sidx + prefix.length()); 9706 if (subStr != null) { 9707 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 9708 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 9709 } 9710 try { 9711 idx = Integer.parseInt(subStr); 9712 if (idx <= 1) { 9713 idx++; 9714 } else { 9715 idx--; 9716 } 9717 } catch(NumberFormatException e) { 9718 } 9719 } 9720 } 9721 } 9722 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 9723 return prefix + idxStr; 9724 } 9725 9726 private File getNextCodePath(String packageName) { 9727 int suffix = 1; 9728 File result; 9729 do { 9730 result = new File(mAppInstallDir, packageName + "-" + suffix); 9731 suffix++; 9732 } while (result.exists()); 9733 return result; 9734 } 9735 9736 // Utility method used to ignore ADD/REMOVE events 9737 // by directory observer. 9738 private static boolean ignoreCodePath(String fullPathStr) { 9739 String apkName = deriveCodePathName(fullPathStr); 9740 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 9741 if (idx != -1 && ((idx+1) < apkName.length())) { 9742 // Make sure the package ends with a numeral 9743 String version = apkName.substring(idx+1); 9744 try { 9745 Integer.parseInt(version); 9746 return true; 9747 } catch (NumberFormatException e) {} 9748 } 9749 return false; 9750 } 9751 9752 // Utility method that returns the relative package path with respect 9753 // to the installation directory. Like say for /data/data/com.test-1.apk 9754 // string com.test-1 is returned. 9755 static String deriveCodePathName(String codePath) { 9756 if (codePath == null) { 9757 return null; 9758 } 9759 final File codeFile = new File(codePath); 9760 final String name = codeFile.getName(); 9761 if (codeFile.isDirectory()) { 9762 return name; 9763 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 9764 final int lastDot = name.lastIndexOf('.'); 9765 return name.substring(0, lastDot); 9766 } else { 9767 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 9768 return null; 9769 } 9770 } 9771 9772 class PackageInstalledInfo { 9773 String name; 9774 int uid; 9775 // The set of users that originally had this package installed. 9776 int[] origUsers; 9777 // The set of users that now have this package installed. 9778 int[] newUsers; 9779 PackageParser.Package pkg; 9780 int returnCode; 9781 String returnMsg; 9782 PackageRemovedInfo removedInfo; 9783 9784 public void setError(int code, String msg) { 9785 returnCode = code; 9786 returnMsg = msg; 9787 Slog.w(TAG, msg); 9788 } 9789 9790 public void setError(String msg, PackageParserException e) { 9791 returnCode = e.error; 9792 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9793 Slog.w(TAG, msg, e); 9794 } 9795 9796 public void setError(String msg, PackageManagerException e) { 9797 returnCode = e.error; 9798 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9799 Slog.w(TAG, msg, e); 9800 } 9801 9802 // In some error cases we want to convey more info back to the observer 9803 String origPackage; 9804 String origPermission; 9805 } 9806 9807 /* 9808 * Install a non-existing package. 9809 */ 9810 private void installNewPackageLI(PackageParser.Package pkg, 9811 int parseFlags, int scanFlags, UserHandle user, 9812 String installerPackageName, PackageInstalledInfo res) { 9813 // Remember this for later, in case we need to rollback this install 9814 String pkgName = pkg.packageName; 9815 9816 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 9817 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 9818 synchronized(mPackages) { 9819 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 9820 // A package with the same name is already installed, though 9821 // it has been renamed to an older name. The package we 9822 // are trying to install should be installed as an update to 9823 // the existing one, but that has not been requested, so bail. 9824 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9825 + " without first uninstalling package running as " 9826 + mSettings.mRenamedPackages.get(pkgName)); 9827 return; 9828 } 9829 if (mPackages.containsKey(pkgName)) { 9830 // Don't allow installation over an existing package with the same name. 9831 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9832 + " without first uninstalling."); 9833 return; 9834 } 9835 } 9836 9837 try { 9838 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 9839 System.currentTimeMillis(), user); 9840 9841 updateSettingsLI(newPackage, installerPackageName, null, null, res); 9842 // delete the partially installed application. the data directory will have to be 9843 // restored if it was already existing 9844 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9845 // remove package from internal structures. Note that we want deletePackageX to 9846 // delete the package data and cache directories that it created in 9847 // scanPackageLocked, unless those directories existed before we even tried to 9848 // install. 9849 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 9850 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 9851 res.removedInfo, true); 9852 } 9853 9854 } catch (PackageManagerException e) { 9855 res.setError("Package couldn't be installed in " + pkg.codePath, e); 9856 } 9857 } 9858 9859 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 9860 // Upgrade keysets are being used. Determine if new package has a superset of the 9861 // required keys. 9862 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 9863 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9864 for (int i = 0; i < upgradeKeySets.length; i++) { 9865 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 9866 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 9867 return true; 9868 } 9869 } 9870 return false; 9871 } 9872 9873 private void replacePackageLI(PackageParser.Package pkg, 9874 int parseFlags, int scanFlags, UserHandle user, 9875 String installerPackageName, PackageInstalledInfo res) { 9876 PackageParser.Package oldPackage; 9877 String pkgName = pkg.packageName; 9878 int[] allUsers; 9879 boolean[] perUserInstalled; 9880 9881 // First find the old package info and check signatures 9882 synchronized(mPackages) { 9883 oldPackage = mPackages.get(pkgName); 9884 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 9885 PackageSetting ps = mSettings.mPackages.get(pkgName); 9886 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 9887 // default to original signature matching 9888 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 9889 != PackageManager.SIGNATURE_MATCH) { 9890 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9891 "New package has a different signature: " + pkgName); 9892 return; 9893 } 9894 } else { 9895 if(!checkUpgradeKeySetLP(ps, pkg)) { 9896 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9897 "New package not signed by keys specified by upgrade-keysets: " 9898 + pkgName); 9899 return; 9900 } 9901 } 9902 9903 // In case of rollback, remember per-user/profile install state 9904 allUsers = sUserManager.getUserIds(); 9905 perUserInstalled = new boolean[allUsers.length]; 9906 for (int i = 0; i < allUsers.length; i++) { 9907 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 9908 } 9909 } 9910 9911 boolean sysPkg = (isSystemApp(oldPackage)); 9912 if (sysPkg) { 9913 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 9914 user, allUsers, perUserInstalled, installerPackageName, res); 9915 } else { 9916 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 9917 user, allUsers, perUserInstalled, installerPackageName, res); 9918 } 9919 } 9920 9921 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 9922 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 9923 int[] allUsers, boolean[] perUserInstalled, 9924 String installerPackageName, PackageInstalledInfo res) { 9925 String pkgName = deletedPackage.packageName; 9926 boolean deletedPkg = true; 9927 boolean updatedSettings = false; 9928 9929 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 9930 + deletedPackage); 9931 long origUpdateTime; 9932 if (pkg.mExtras != null) { 9933 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 9934 } else { 9935 origUpdateTime = 0; 9936 } 9937 9938 // First delete the existing package while retaining the data directory 9939 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 9940 res.removedInfo, true)) { 9941 // If the existing package wasn't successfully deleted 9942 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 9943 deletedPkg = false; 9944 } else { 9945 // Successfully deleted the old package; proceed with replace. 9946 9947 // If deleted package lived in a container, give users a chance to 9948 // relinquish resources before killing. 9949 if (isForwardLocked(deletedPackage) || isExternal(deletedPackage)) { 9950 if (DEBUG_INSTALL) { 9951 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 9952 } 9953 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 9954 final ArrayList<String> pkgList = new ArrayList<String>(1); 9955 pkgList.add(deletedPackage.applicationInfo.packageName); 9956 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 9957 } 9958 9959 deleteCodeCacheDirsLI(pkgName); 9960 try { 9961 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 9962 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 9963 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 9964 updatedSettings = true; 9965 } catch (PackageManagerException e) { 9966 res.setError("Package couldn't be installed in " + pkg.codePath, e); 9967 } 9968 } 9969 9970 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9971 // remove package from internal structures. Note that we want deletePackageX to 9972 // delete the package data and cache directories that it created in 9973 // scanPackageLocked, unless those directories existed before we even tried to 9974 // install. 9975 if(updatedSettings) { 9976 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 9977 deletePackageLI( 9978 pkgName, null, true, allUsers, perUserInstalled, 9979 PackageManager.DELETE_KEEP_DATA, 9980 res.removedInfo, true); 9981 } 9982 // Since we failed to install the new package we need to restore the old 9983 // package that we deleted. 9984 if (deletedPkg) { 9985 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 9986 File restoreFile = new File(deletedPackage.codePath); 9987 // Parse old package 9988 boolean oldOnSd = isExternal(deletedPackage); 9989 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 9990 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) | 9991 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 9992 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 9993 try { 9994 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 9995 } catch (PackageManagerException e) { 9996 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 9997 + e.getMessage()); 9998 return; 9999 } 10000 // Restore of old package succeeded. Update permissions. 10001 // writer 10002 synchronized (mPackages) { 10003 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 10004 UPDATE_PERMISSIONS_ALL); 10005 // can downgrade to reader 10006 mSettings.writeLPr(); 10007 } 10008 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 10009 } 10010 } 10011 } 10012 10013 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 10014 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10015 int[] allUsers, boolean[] perUserInstalled, 10016 String installerPackageName, PackageInstalledInfo res) { 10017 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 10018 + ", old=" + deletedPackage); 10019 boolean updatedSettings = false; 10020 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 10021 if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) { 10022 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10023 } 10024 String packageName = deletedPackage.packageName; 10025 if (packageName == null) { 10026 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10027 "Attempt to delete null packageName."); 10028 return; 10029 } 10030 PackageParser.Package oldPkg; 10031 PackageSetting oldPkgSetting; 10032 // reader 10033 synchronized (mPackages) { 10034 oldPkg = mPackages.get(packageName); 10035 oldPkgSetting = mSettings.mPackages.get(packageName); 10036 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 10037 (oldPkgSetting == null)) { 10038 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10039 "Couldn't find package:" + packageName + " information"); 10040 return; 10041 } 10042 } 10043 10044 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 10045 10046 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10047 res.removedInfo.removedPackage = packageName; 10048 // Remove existing system package 10049 removePackageLI(oldPkgSetting, true); 10050 // writer 10051 synchronized (mPackages) { 10052 if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) { 10053 // We didn't need to disable the .apk as a current system package, 10054 // which means we are replacing another update that is already 10055 // installed. We need to make sure to delete the older one's .apk. 10056 res.removedInfo.args = createInstallArgsForExisting(0, 10057 deletedPackage.applicationInfo.getCodePath(), 10058 deletedPackage.applicationInfo.getResourcePath(), 10059 deletedPackage.applicationInfo.nativeLibraryRootDir, 10060 getAppDexInstructionSets(deletedPackage.applicationInfo)); 10061 } else { 10062 res.removedInfo.args = null; 10063 } 10064 } 10065 10066 // Successfully disabled the old package. Now proceed with re-installation 10067 deleteCodeCacheDirsLI(packageName); 10068 10069 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10070 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10071 10072 PackageParser.Package newPackage = null; 10073 try { 10074 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 10075 if (newPackage.mExtras != null) { 10076 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 10077 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10078 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10079 10080 // is the update attempting to change shared user? that isn't going to work... 10081 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10082 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 10083 "Forbidding shared user change from " + oldPkgSetting.sharedUser 10084 + " to " + newPkgSetting.sharedUser); 10085 updatedSettings = true; 10086 } 10087 } 10088 10089 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10090 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10091 updatedSettings = true; 10092 } 10093 10094 } catch (PackageManagerException e) { 10095 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10096 } 10097 10098 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10099 // Re installation failed. Restore old information 10100 // Remove new pkg information 10101 if (newPackage != null) { 10102 removeInstalledPackageLI(newPackage, true); 10103 } 10104 // Add back the old system package 10105 try { 10106 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 10107 } catch (PackageManagerException e) { 10108 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 10109 } 10110 // Restore the old system information in Settings 10111 synchronized(mPackages) { 10112 if (updatedSettings) { 10113 mSettings.enableSystemPackageLPw(packageName); 10114 mSettings.setInstallerPackageName(packageName, 10115 oldPkgSetting.installerPackageName); 10116 } 10117 mSettings.writeLPr(); 10118 } 10119 } 10120 } 10121 10122 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10123 int[] allUsers, boolean[] perUserInstalled, 10124 PackageInstalledInfo res) { 10125 String pkgName = newPackage.packageName; 10126 synchronized (mPackages) { 10127 //write settings. the installStatus will be incomplete at this stage. 10128 //note that the new package setting would have already been 10129 //added to mPackages. It hasn't been persisted yet. 10130 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10131 mSettings.writeLPr(); 10132 } 10133 10134 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10135 10136 synchronized (mPackages) { 10137 updatePermissionsLPw(newPackage.packageName, newPackage, 10138 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10139 ? UPDATE_PERMISSIONS_ALL : 0)); 10140 // For system-bundled packages, we assume that installing an upgraded version 10141 // of the package implies that the user actually wants to run that new code, 10142 // so we enable the package. 10143 if (isSystemApp(newPackage)) { 10144 // NB: implicit assumption that system package upgrades apply to all users 10145 if (DEBUG_INSTALL) { 10146 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10147 } 10148 PackageSetting ps = mSettings.mPackages.get(pkgName); 10149 if (ps != null) { 10150 if (res.origUsers != null) { 10151 for (int userHandle : res.origUsers) { 10152 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10153 userHandle, installerPackageName); 10154 } 10155 } 10156 // Also convey the prior install/uninstall state 10157 if (allUsers != null && perUserInstalled != null) { 10158 for (int i = 0; i < allUsers.length; i++) { 10159 if (DEBUG_INSTALL) { 10160 Slog.d(TAG, " user " + allUsers[i] 10161 + " => " + perUserInstalled[i]); 10162 } 10163 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10164 } 10165 // these install state changes will be persisted in the 10166 // upcoming call to mSettings.writeLPr(). 10167 } 10168 } 10169 } 10170 res.name = pkgName; 10171 res.uid = newPackage.applicationInfo.uid; 10172 res.pkg = newPackage; 10173 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10174 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10175 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10176 //to update install status 10177 mSettings.writeLPr(); 10178 } 10179 } 10180 10181 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 10182 final int installFlags = args.installFlags; 10183 String installerPackageName = args.installerPackageName; 10184 File tmpPackageFile = new File(args.getCodePath()); 10185 boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10186 boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0); 10187 boolean replace = false; 10188 final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE; 10189 // Result object to be returned 10190 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10191 10192 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10193 // Retrieve PackageSettings and parse package 10194 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10195 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10196 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 10197 PackageParser pp = new PackageParser(); 10198 pp.setSeparateProcesses(mSeparateProcesses); 10199 pp.setDisplayMetrics(mMetrics); 10200 10201 final PackageParser.Package pkg; 10202 try { 10203 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 10204 } catch (PackageParserException e) { 10205 res.setError("Failed parse during installPackageLI", e); 10206 return; 10207 } 10208 10209 // Mark that we have an install time CPU ABI override. 10210 pkg.cpuAbiOverride = args.abiOverride; 10211 10212 String pkgName = res.name = pkg.packageName; 10213 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 10214 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 10215 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 10216 return; 10217 } 10218 } 10219 10220 try { 10221 pp.collectCertificates(pkg, parseFlags); 10222 pp.collectManifestDigest(pkg); 10223 } catch (PackageParserException e) { 10224 res.setError("Failed collect during installPackageLI", e); 10225 return; 10226 } 10227 10228 /* If the installer passed in a manifest digest, compare it now. */ 10229 if (args.manifestDigest != null) { 10230 if (DEBUG_INSTALL) { 10231 final String parsedManifest = pkg.manifestDigest == null ? "null" 10232 : pkg.manifestDigest.toString(); 10233 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 10234 + parsedManifest); 10235 } 10236 10237 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 10238 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 10239 return; 10240 } 10241 } else if (DEBUG_INSTALL) { 10242 final String parsedManifest = pkg.manifestDigest == null 10243 ? "null" : pkg.manifestDigest.toString(); 10244 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 10245 } 10246 10247 // Get rid of all references to package scan path via parser. 10248 pp = null; 10249 String oldCodePath = null; 10250 boolean systemApp = false; 10251 synchronized (mPackages) { 10252 // Check whether the newly-scanned package wants to define an already-defined perm 10253 int N = pkg.permissions.size(); 10254 for (int i = N-1; i >= 0; i--) { 10255 PackageParser.Permission perm = pkg.permissions.get(i); 10256 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 10257 if (bp != null) { 10258 // If the defining package is signed with our cert, it's okay. This 10259 // also includes the "updating the same package" case, of course. 10260 // "updating same package" could also involve key-rotation. 10261 final boolean sigsOk; 10262 if (!bp.sourcePackage.equals(pkg.packageName) 10263 || !(bp.packageSetting instanceof PackageSetting) 10264 || !bp.packageSetting.keySetData.isUsingUpgradeKeySets() 10265 || ((PackageSetting) bp.packageSetting).sharedUser != null) { 10266 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 10267 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH; 10268 } else { 10269 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 10270 } 10271 if (!sigsOk) { 10272 // If the owning package is the system itself, we log but allow 10273 // install to proceed; we fail the install on all other permission 10274 // redefinitions. 10275 if (!bp.sourcePackage.equals("android")) { 10276 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 10277 + pkg.packageName + " attempting to redeclare permission " 10278 + perm.info.name + " already owned by " + bp.sourcePackage); 10279 res.origPermission = perm.info.name; 10280 res.origPackage = bp.sourcePackage; 10281 return; 10282 } else { 10283 Slog.w(TAG, "Package " + pkg.packageName 10284 + " attempting to redeclare system permission " 10285 + perm.info.name + "; ignoring new declaration"); 10286 pkg.permissions.remove(i); 10287 } 10288 } 10289 } 10290 } 10291 10292 // Check if installing already existing package 10293 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10294 String oldName = mSettings.mRenamedPackages.get(pkgName); 10295 if (pkg.mOriginalPackages != null 10296 && pkg.mOriginalPackages.contains(oldName) 10297 && mPackages.containsKey(oldName)) { 10298 // This package is derived from an original package, 10299 // and this device has been updating from that original 10300 // name. We must continue using the original name, so 10301 // rename the new package here. 10302 pkg.setPackageName(oldName); 10303 pkgName = pkg.packageName; 10304 replace = true; 10305 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 10306 + oldName + " pkgName=" + pkgName); 10307 } else if (mPackages.containsKey(pkgName)) { 10308 // This package, under its official name, already exists 10309 // on the device; we should replace it. 10310 replace = true; 10311 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 10312 } 10313 } 10314 PackageSetting ps = mSettings.mPackages.get(pkgName); 10315 if (ps != null) { 10316 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 10317 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 10318 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 10319 systemApp = (ps.pkg.applicationInfo.flags & 10320 ApplicationInfo.FLAG_SYSTEM) != 0; 10321 } 10322 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10323 } 10324 } 10325 10326 if (systemApp && onSd) { 10327 // Disable updates to system apps on sdcard 10328 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 10329 "Cannot install updates to system apps on sdcard"); 10330 return; 10331 } 10332 10333 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 10334 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 10335 return; 10336 } 10337 10338 if (replace) { 10339 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 10340 installerPackageName, res); 10341 } else { 10342 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 10343 args.user, installerPackageName, res); 10344 } 10345 synchronized (mPackages) { 10346 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10347 if (ps != null) { 10348 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10349 } 10350 } 10351 } 10352 10353 private static boolean isForwardLocked(PackageParser.Package pkg) { 10354 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10355 } 10356 10357 private static boolean isForwardLocked(ApplicationInfo info) { 10358 return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10359 } 10360 10361 private boolean isForwardLocked(PackageSetting ps) { 10362 return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10363 } 10364 10365 private static boolean isMultiArch(PackageSetting ps) { 10366 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10367 } 10368 10369 private static boolean isMultiArch(ApplicationInfo info) { 10370 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10371 } 10372 10373 private static boolean isExternal(PackageParser.Package pkg) { 10374 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10375 } 10376 10377 private static boolean isExternal(PackageSetting ps) { 10378 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10379 } 10380 10381 private static boolean isExternal(ApplicationInfo info) { 10382 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10383 } 10384 10385 private static boolean isSystemApp(PackageParser.Package pkg) { 10386 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10387 } 10388 10389 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 10390 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0; 10391 } 10392 10393 private static boolean isSystemApp(ApplicationInfo info) { 10394 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10395 } 10396 10397 private static boolean isSystemApp(PackageSetting ps) { 10398 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 10399 } 10400 10401 private static boolean isUpdatedSystemApp(PackageSetting ps) { 10402 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10403 } 10404 10405 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 10406 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10407 } 10408 10409 private static boolean isUpdatedSystemApp(ApplicationInfo info) { 10410 return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10411 } 10412 10413 private int packageFlagsToInstallFlags(PackageSetting ps) { 10414 int installFlags = 0; 10415 if (isExternal(ps)) { 10416 installFlags |= PackageManager.INSTALL_EXTERNAL; 10417 } 10418 if (isForwardLocked(ps)) { 10419 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 10420 } 10421 return installFlags; 10422 } 10423 10424 private void deleteTempPackageFiles() { 10425 final FilenameFilter filter = new FilenameFilter() { 10426 public boolean accept(File dir, String name) { 10427 return name.startsWith("vmdl") && name.endsWith(".tmp"); 10428 } 10429 }; 10430 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 10431 file.delete(); 10432 } 10433 } 10434 10435 @Override 10436 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 10437 int flags) { 10438 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 10439 flags); 10440 } 10441 10442 @Override 10443 public void deletePackage(final String packageName, 10444 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 10445 mContext.enforceCallingOrSelfPermission( 10446 android.Manifest.permission.DELETE_PACKAGES, null); 10447 final int uid = Binder.getCallingUid(); 10448 if (UserHandle.getUserId(uid) != userId) { 10449 mContext.enforceCallingPermission( 10450 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 10451 "deletePackage for user " + userId); 10452 } 10453 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 10454 try { 10455 observer.onPackageDeleted(packageName, 10456 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 10457 } catch (RemoteException re) { 10458 } 10459 return; 10460 } 10461 10462 boolean uninstallBlocked = false; 10463 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 10464 int[] users = sUserManager.getUserIds(); 10465 for (int i = 0; i < users.length; ++i) { 10466 if (getBlockUninstallForUser(packageName, users[i])) { 10467 uninstallBlocked = true; 10468 break; 10469 } 10470 } 10471 } else { 10472 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 10473 } 10474 if (uninstallBlocked) { 10475 try { 10476 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 10477 null); 10478 } catch (RemoteException re) { 10479 } 10480 return; 10481 } 10482 10483 if (DEBUG_REMOVE) { 10484 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 10485 } 10486 // Queue up an async operation since the package deletion may take a little while. 10487 mHandler.post(new Runnable() { 10488 public void run() { 10489 mHandler.removeCallbacks(this); 10490 final int returnCode = deletePackageX(packageName, userId, flags); 10491 if (observer != null) { 10492 try { 10493 observer.onPackageDeleted(packageName, returnCode, null); 10494 } catch (RemoteException e) { 10495 Log.i(TAG, "Observer no longer exists."); 10496 } //end catch 10497 } //end if 10498 } //end run 10499 }); 10500 } 10501 10502 private boolean isPackageDeviceAdmin(String packageName, int userId) { 10503 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 10504 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 10505 try { 10506 if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId) 10507 || dpm.isDeviceOwner(packageName))) { 10508 return true; 10509 } 10510 } catch (RemoteException e) { 10511 } 10512 return false; 10513 } 10514 10515 /** 10516 * This method is an internal method that could be get invoked either 10517 * to delete an installed package or to clean up a failed installation. 10518 * After deleting an installed package, a broadcast is sent to notify any 10519 * listeners that the package has been installed. For cleaning up a failed 10520 * installation, the broadcast is not necessary since the package's 10521 * installation wouldn't have sent the initial broadcast either 10522 * The key steps in deleting a package are 10523 * deleting the package information in internal structures like mPackages, 10524 * deleting the packages base directories through installd 10525 * updating mSettings to reflect current status 10526 * persisting settings for later use 10527 * sending a broadcast if necessary 10528 */ 10529 private int deletePackageX(String packageName, int userId, int flags) { 10530 final PackageRemovedInfo info = new PackageRemovedInfo(); 10531 final boolean res; 10532 10533 if (isPackageDeviceAdmin(packageName, userId)) { 10534 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 10535 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 10536 } 10537 10538 boolean removedForAllUsers = false; 10539 boolean systemUpdate = false; 10540 10541 // for the uninstall-updates case and restricted profiles, remember the per- 10542 // userhandle installed state 10543 int[] allUsers; 10544 boolean[] perUserInstalled; 10545 synchronized (mPackages) { 10546 PackageSetting ps = mSettings.mPackages.get(packageName); 10547 allUsers = sUserManager.getUserIds(); 10548 perUserInstalled = new boolean[allUsers.length]; 10549 for (int i = 0; i < allUsers.length; i++) { 10550 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10551 } 10552 } 10553 10554 synchronized (mInstallLock) { 10555 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 10556 res = deletePackageLI(packageName, 10557 (flags & PackageManager.DELETE_ALL_USERS) != 0 10558 ? UserHandle.ALL : new UserHandle(userId), 10559 true, allUsers, perUserInstalled, 10560 flags | REMOVE_CHATTY, info, true); 10561 systemUpdate = info.isRemovedPackageSystemUpdate; 10562 if (res && !systemUpdate && mPackages.get(packageName) == null) { 10563 removedForAllUsers = true; 10564 } 10565 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 10566 + " removedForAllUsers=" + removedForAllUsers); 10567 } 10568 10569 if (res) { 10570 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 10571 10572 // If the removed package was a system update, the old system package 10573 // was re-enabled; we need to broadcast this information 10574 if (systemUpdate) { 10575 Bundle extras = new Bundle(1); 10576 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 10577 ? info.removedAppId : info.uid); 10578 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10579 10580 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 10581 extras, null, null, null); 10582 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 10583 extras, null, null, null); 10584 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 10585 null, packageName, null, null); 10586 } 10587 } 10588 // Force a gc here. 10589 Runtime.getRuntime().gc(); 10590 // Delete the resources here after sending the broadcast to let 10591 // other processes clean up before deleting resources. 10592 if (info.args != null) { 10593 synchronized (mInstallLock) { 10594 info.args.doPostDeleteLI(true); 10595 } 10596 } 10597 10598 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10599 } 10600 10601 static class PackageRemovedInfo { 10602 String removedPackage; 10603 int uid = -1; 10604 int removedAppId = -1; 10605 int[] removedUsers = null; 10606 boolean isRemovedPackageSystemUpdate = false; 10607 // Clean up resources deleted packages. 10608 InstallArgs args = null; 10609 10610 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 10611 Bundle extras = new Bundle(1); 10612 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 10613 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 10614 if (replacing) { 10615 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10616 } 10617 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 10618 if (removedPackage != null) { 10619 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 10620 extras, null, null, removedUsers); 10621 if (fullRemove && !replacing) { 10622 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 10623 extras, null, null, removedUsers); 10624 } 10625 } 10626 if (removedAppId >= 0) { 10627 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 10628 removedUsers); 10629 } 10630 } 10631 } 10632 10633 /* 10634 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 10635 * flag is not set, the data directory is removed as well. 10636 * make sure this flag is set for partially installed apps. If not its meaningless to 10637 * delete a partially installed application. 10638 */ 10639 private void removePackageDataLI(PackageSetting ps, 10640 int[] allUserHandles, boolean[] perUserInstalled, 10641 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 10642 String packageName = ps.name; 10643 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 10644 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 10645 // Retrieve object to delete permissions for shared user later on 10646 final PackageSetting deletedPs; 10647 // reader 10648 synchronized (mPackages) { 10649 deletedPs = mSettings.mPackages.get(packageName); 10650 if (outInfo != null) { 10651 outInfo.removedPackage = packageName; 10652 outInfo.removedUsers = deletedPs != null 10653 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 10654 : null; 10655 } 10656 } 10657 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10658 removeDataDirsLI(packageName); 10659 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 10660 } 10661 // writer 10662 synchronized (mPackages) { 10663 if (deletedPs != null) { 10664 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10665 if (outInfo != null) { 10666 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 10667 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 10668 } 10669 if (deletedPs != null) { 10670 updatePermissionsLPw(deletedPs.name, null, 0); 10671 if (deletedPs.sharedUser != null) { 10672 // remove permissions associated with package 10673 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 10674 } 10675 } 10676 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 10677 } 10678 // make sure to preserve per-user disabled state if this removal was just 10679 // a downgrade of a system app to the factory package 10680 if (allUserHandles != null && perUserInstalled != null) { 10681 if (DEBUG_REMOVE) { 10682 Slog.d(TAG, "Propagating install state across downgrade"); 10683 } 10684 for (int i = 0; i < allUserHandles.length; i++) { 10685 if (DEBUG_REMOVE) { 10686 Slog.d(TAG, " user " + allUserHandles[i] 10687 + " => " + perUserInstalled[i]); 10688 } 10689 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10690 } 10691 } 10692 } 10693 // can downgrade to reader 10694 if (writeSettings) { 10695 // Save settings now 10696 mSettings.writeLPr(); 10697 } 10698 } 10699 if (outInfo != null) { 10700 // A user ID was deleted here. Go through all users and remove it 10701 // from KeyStore. 10702 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 10703 } 10704 } 10705 10706 static boolean locationIsPrivileged(File path) { 10707 try { 10708 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 10709 .getCanonicalPath(); 10710 return path.getCanonicalPath().startsWith(privilegedAppDir); 10711 } catch (IOException e) { 10712 Slog.e(TAG, "Unable to access code path " + path); 10713 } 10714 return false; 10715 } 10716 10717 /* 10718 * Tries to delete system package. 10719 */ 10720 private boolean deleteSystemPackageLI(PackageSetting newPs, 10721 int[] allUserHandles, boolean[] perUserInstalled, 10722 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 10723 final boolean applyUserRestrictions 10724 = (allUserHandles != null) && (perUserInstalled != null); 10725 PackageSetting disabledPs = null; 10726 // Confirm if the system package has been updated 10727 // An updated system app can be deleted. This will also have to restore 10728 // the system pkg from system partition 10729 // reader 10730 synchronized (mPackages) { 10731 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 10732 } 10733 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 10734 + " disabledPs=" + disabledPs); 10735 if (disabledPs == null) { 10736 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 10737 return false; 10738 } else if (DEBUG_REMOVE) { 10739 Slog.d(TAG, "Deleting system pkg from data partition"); 10740 } 10741 if (DEBUG_REMOVE) { 10742 if (applyUserRestrictions) { 10743 Slog.d(TAG, "Remembering install states:"); 10744 for (int i = 0; i < allUserHandles.length; i++) { 10745 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 10746 } 10747 } 10748 } 10749 // Delete the updated package 10750 outInfo.isRemovedPackageSystemUpdate = true; 10751 if (disabledPs.versionCode < newPs.versionCode) { 10752 // Delete data for downgrades 10753 flags &= ~PackageManager.DELETE_KEEP_DATA; 10754 } else { 10755 // Preserve data by setting flag 10756 flags |= PackageManager.DELETE_KEEP_DATA; 10757 } 10758 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 10759 allUserHandles, perUserInstalled, outInfo, writeSettings); 10760 if (!ret) { 10761 return false; 10762 } 10763 // writer 10764 synchronized (mPackages) { 10765 // Reinstate the old system package 10766 mSettings.enableSystemPackageLPw(newPs.name); 10767 // Remove any native libraries from the upgraded package. 10768 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 10769 } 10770 // Install the system package 10771 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 10772 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 10773 if (locationIsPrivileged(disabledPs.codePath)) { 10774 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10775 } 10776 10777 final PackageParser.Package newPkg; 10778 try { 10779 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 10780 } catch (PackageManagerException e) { 10781 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 10782 return false; 10783 } 10784 10785 // writer 10786 synchronized (mPackages) { 10787 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 10788 updatePermissionsLPw(newPkg.packageName, newPkg, 10789 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 10790 if (applyUserRestrictions) { 10791 if (DEBUG_REMOVE) { 10792 Slog.d(TAG, "Propagating install state across reinstall"); 10793 } 10794 for (int i = 0; i < allUserHandles.length; i++) { 10795 if (DEBUG_REMOVE) { 10796 Slog.d(TAG, " user " + allUserHandles[i] 10797 + " => " + perUserInstalled[i]); 10798 } 10799 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10800 } 10801 // Regardless of writeSettings we need to ensure that this restriction 10802 // state propagation is persisted 10803 mSettings.writeAllUsersPackageRestrictionsLPr(); 10804 } 10805 // can downgrade to reader here 10806 if (writeSettings) { 10807 mSettings.writeLPr(); 10808 } 10809 } 10810 return true; 10811 } 10812 10813 private boolean deleteInstalledPackageLI(PackageSetting ps, 10814 boolean deleteCodeAndResources, int flags, 10815 int[] allUserHandles, boolean[] perUserInstalled, 10816 PackageRemovedInfo outInfo, boolean writeSettings) { 10817 if (outInfo != null) { 10818 outInfo.uid = ps.appId; 10819 } 10820 10821 // Delete package data from internal structures and also remove data if flag is set 10822 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 10823 10824 // Delete application code and resources 10825 if (deleteCodeAndResources && (outInfo != null)) { 10826 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 10827 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 10828 getAppDexInstructionSets(ps)); 10829 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 10830 } 10831 return true; 10832 } 10833 10834 @Override 10835 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 10836 int userId) { 10837 mContext.enforceCallingOrSelfPermission( 10838 android.Manifest.permission.DELETE_PACKAGES, null); 10839 synchronized (mPackages) { 10840 PackageSetting ps = mSettings.mPackages.get(packageName); 10841 if (ps == null) { 10842 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 10843 return false; 10844 } 10845 if (!ps.getInstalled(userId)) { 10846 // Can't block uninstall for an app that is not installed or enabled. 10847 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 10848 return false; 10849 } 10850 ps.setBlockUninstall(blockUninstall, userId); 10851 mSettings.writePackageRestrictionsLPr(userId); 10852 } 10853 return true; 10854 } 10855 10856 @Override 10857 public boolean getBlockUninstallForUser(String packageName, int userId) { 10858 synchronized (mPackages) { 10859 PackageSetting ps = mSettings.mPackages.get(packageName); 10860 if (ps == null) { 10861 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 10862 return false; 10863 } 10864 return ps.getBlockUninstall(userId); 10865 } 10866 } 10867 10868 /* 10869 * This method handles package deletion in general 10870 */ 10871 private boolean deletePackageLI(String packageName, UserHandle user, 10872 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 10873 int flags, PackageRemovedInfo outInfo, 10874 boolean writeSettings) { 10875 if (packageName == null) { 10876 Slog.w(TAG, "Attempt to delete null packageName."); 10877 return false; 10878 } 10879 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 10880 PackageSetting ps; 10881 boolean dataOnly = false; 10882 int removeUser = -1; 10883 int appId = -1; 10884 synchronized (mPackages) { 10885 ps = mSettings.mPackages.get(packageName); 10886 if (ps == null) { 10887 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 10888 return false; 10889 } 10890 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 10891 && user.getIdentifier() != UserHandle.USER_ALL) { 10892 // The caller is asking that the package only be deleted for a single 10893 // user. To do this, we just mark its uninstalled state and delete 10894 // its data. If this is a system app, we only allow this to happen if 10895 // they have set the special DELETE_SYSTEM_APP which requests different 10896 // semantics than normal for uninstalling system apps. 10897 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 10898 ps.setUserState(user.getIdentifier(), 10899 COMPONENT_ENABLED_STATE_DEFAULT, 10900 false, //installed 10901 true, //stopped 10902 true, //notLaunched 10903 false, //hidden 10904 null, null, null, 10905 false // blockUninstall 10906 ); 10907 if (!isSystemApp(ps)) { 10908 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 10909 // Other user still have this package installed, so all 10910 // we need to do is clear this user's data and save that 10911 // it is uninstalled. 10912 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 10913 removeUser = user.getIdentifier(); 10914 appId = ps.appId; 10915 mSettings.writePackageRestrictionsLPr(removeUser); 10916 } else { 10917 // We need to set it back to 'installed' so the uninstall 10918 // broadcasts will be sent correctly. 10919 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 10920 ps.setInstalled(true, user.getIdentifier()); 10921 } 10922 } else { 10923 // This is a system app, so we assume that the 10924 // other users still have this package installed, so all 10925 // we need to do is clear this user's data and save that 10926 // it is uninstalled. 10927 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 10928 removeUser = user.getIdentifier(); 10929 appId = ps.appId; 10930 mSettings.writePackageRestrictionsLPr(removeUser); 10931 } 10932 } 10933 } 10934 10935 if (removeUser >= 0) { 10936 // From above, we determined that we are deleting this only 10937 // for a single user. Continue the work here. 10938 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 10939 if (outInfo != null) { 10940 outInfo.removedPackage = packageName; 10941 outInfo.removedAppId = appId; 10942 outInfo.removedUsers = new int[] {removeUser}; 10943 } 10944 mInstaller.clearUserData(packageName, removeUser); 10945 removeKeystoreDataIfNeeded(removeUser, appId); 10946 schedulePackageCleaning(packageName, removeUser, false); 10947 return true; 10948 } 10949 10950 if (dataOnly) { 10951 // Delete application data first 10952 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 10953 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 10954 return true; 10955 } 10956 10957 boolean ret = false; 10958 if (isSystemApp(ps)) { 10959 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 10960 // When an updated system application is deleted we delete the existing resources as well and 10961 // fall back to existing code in system partition 10962 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 10963 flags, outInfo, writeSettings); 10964 } else { 10965 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 10966 // Kill application pre-emptively especially for apps on sd. 10967 killApplication(packageName, ps.appId, "uninstall pkg"); 10968 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 10969 allUserHandles, perUserInstalled, 10970 outInfo, writeSettings); 10971 } 10972 10973 return ret; 10974 } 10975 10976 private final class ClearStorageConnection implements ServiceConnection { 10977 IMediaContainerService mContainerService; 10978 10979 @Override 10980 public void onServiceConnected(ComponentName name, IBinder service) { 10981 synchronized (this) { 10982 mContainerService = IMediaContainerService.Stub.asInterface(service); 10983 notifyAll(); 10984 } 10985 } 10986 10987 @Override 10988 public void onServiceDisconnected(ComponentName name) { 10989 } 10990 } 10991 10992 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 10993 final boolean mounted; 10994 if (Environment.isExternalStorageEmulated()) { 10995 mounted = true; 10996 } else { 10997 final String status = Environment.getExternalStorageState(); 10998 10999 mounted = status.equals(Environment.MEDIA_MOUNTED) 11000 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 11001 } 11002 11003 if (!mounted) { 11004 return; 11005 } 11006 11007 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 11008 int[] users; 11009 if (userId == UserHandle.USER_ALL) { 11010 users = sUserManager.getUserIds(); 11011 } else { 11012 users = new int[] { userId }; 11013 } 11014 final ClearStorageConnection conn = new ClearStorageConnection(); 11015 if (mContext.bindServiceAsUser( 11016 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 11017 try { 11018 for (int curUser : users) { 11019 long timeout = SystemClock.uptimeMillis() + 5000; 11020 synchronized (conn) { 11021 long now = SystemClock.uptimeMillis(); 11022 while (conn.mContainerService == null && now < timeout) { 11023 try { 11024 conn.wait(timeout - now); 11025 } catch (InterruptedException e) { 11026 } 11027 } 11028 } 11029 if (conn.mContainerService == null) { 11030 return; 11031 } 11032 11033 final UserEnvironment userEnv = new UserEnvironment(curUser); 11034 clearDirectory(conn.mContainerService, 11035 userEnv.buildExternalStorageAppCacheDirs(packageName)); 11036 if (allData) { 11037 clearDirectory(conn.mContainerService, 11038 userEnv.buildExternalStorageAppDataDirs(packageName)); 11039 clearDirectory(conn.mContainerService, 11040 userEnv.buildExternalStorageAppMediaDirs(packageName)); 11041 } 11042 } 11043 } finally { 11044 mContext.unbindService(conn); 11045 } 11046 } 11047 } 11048 11049 @Override 11050 public void clearApplicationUserData(final String packageName, 11051 final IPackageDataObserver observer, final int userId) { 11052 mContext.enforceCallingOrSelfPermission( 11053 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 11054 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data"); 11055 // Queue up an async operation since the package deletion may take a little while. 11056 mHandler.post(new Runnable() { 11057 public void run() { 11058 mHandler.removeCallbacks(this); 11059 final boolean succeeded; 11060 synchronized (mInstallLock) { 11061 succeeded = clearApplicationUserDataLI(packageName, userId); 11062 } 11063 clearExternalStorageDataSync(packageName, userId, true); 11064 if (succeeded) { 11065 // invoke DeviceStorageMonitor's update method to clear any notifications 11066 DeviceStorageMonitorInternal 11067 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 11068 if (dsm != null) { 11069 dsm.checkMemory(); 11070 } 11071 } 11072 if(observer != null) { 11073 try { 11074 observer.onRemoveCompleted(packageName, succeeded); 11075 } catch (RemoteException e) { 11076 Log.i(TAG, "Observer no longer exists."); 11077 } 11078 } //end if observer 11079 } //end run 11080 }); 11081 } 11082 11083 private boolean clearApplicationUserDataLI(String packageName, int userId) { 11084 if (packageName == null) { 11085 Slog.w(TAG, "Attempt to delete null packageName."); 11086 return false; 11087 } 11088 PackageParser.Package pkg; 11089 boolean dataOnly = false; 11090 final int appId; 11091 synchronized (mPackages) { 11092 pkg = mPackages.get(packageName); 11093 if (pkg == null) { 11094 dataOnly = true; 11095 PackageSetting ps = mSettings.mPackages.get(packageName); 11096 if ((ps == null) || (ps.pkg == null)) { 11097 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11098 return false; 11099 } 11100 pkg = ps.pkg; 11101 } 11102 if (!dataOnly) { 11103 // need to check this only for fully installed applications 11104 if (pkg == null) { 11105 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11106 return false; 11107 } 11108 final ApplicationInfo applicationInfo = pkg.applicationInfo; 11109 if (applicationInfo == null) { 11110 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11111 return false; 11112 } 11113 } 11114 if (pkg != null && pkg.applicationInfo != null) { 11115 appId = pkg.applicationInfo.uid; 11116 } else { 11117 appId = -1; 11118 } 11119 } 11120 int retCode = mInstaller.clearUserData(packageName, userId); 11121 if (retCode < 0) { 11122 Slog.w(TAG, "Couldn't remove cache files for package: " 11123 + packageName); 11124 return false; 11125 } 11126 removeKeystoreDataIfNeeded(userId, appId); 11127 11128 // Create a native library symlink only if we have native libraries 11129 // and if the native libraries are 32 bit libraries. We do not provide 11130 // this symlink for 64 bit libraries. 11131 if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null && 11132 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 11133 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 11134 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 11135 Slog.w(TAG, "Failed linking native library dir"); 11136 return false; 11137 } 11138 } 11139 11140 return true; 11141 } 11142 11143 /** 11144 * Remove entries from the keystore daemon. Will only remove it if the 11145 * {@code appId} is valid. 11146 */ 11147 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 11148 if (appId < 0) { 11149 return; 11150 } 11151 11152 final KeyStore keyStore = KeyStore.getInstance(); 11153 if (keyStore != null) { 11154 if (userId == UserHandle.USER_ALL) { 11155 for (final int individual : sUserManager.getUserIds()) { 11156 keyStore.clearUid(UserHandle.getUid(individual, appId)); 11157 } 11158 } else { 11159 keyStore.clearUid(UserHandle.getUid(userId, appId)); 11160 } 11161 } else { 11162 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 11163 } 11164 } 11165 11166 @Override 11167 public void deleteApplicationCacheFiles(final String packageName, 11168 final IPackageDataObserver observer) { 11169 mContext.enforceCallingOrSelfPermission( 11170 android.Manifest.permission.DELETE_CACHE_FILES, null); 11171 // Queue up an async operation since the package deletion may take a little while. 11172 final int userId = UserHandle.getCallingUserId(); 11173 mHandler.post(new Runnable() { 11174 public void run() { 11175 mHandler.removeCallbacks(this); 11176 final boolean succeded; 11177 synchronized (mInstallLock) { 11178 succeded = deleteApplicationCacheFilesLI(packageName, userId); 11179 } 11180 clearExternalStorageDataSync(packageName, userId, false); 11181 if(observer != null) { 11182 try { 11183 observer.onRemoveCompleted(packageName, succeded); 11184 } catch (RemoteException e) { 11185 Log.i(TAG, "Observer no longer exists."); 11186 } 11187 } //end if observer 11188 } //end run 11189 }); 11190 } 11191 11192 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 11193 if (packageName == null) { 11194 Slog.w(TAG, "Attempt to delete null packageName."); 11195 return false; 11196 } 11197 PackageParser.Package p; 11198 synchronized (mPackages) { 11199 p = mPackages.get(packageName); 11200 } 11201 if (p == null) { 11202 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11203 return false; 11204 } 11205 final ApplicationInfo applicationInfo = p.applicationInfo; 11206 if (applicationInfo == null) { 11207 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11208 return false; 11209 } 11210 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 11211 if (retCode < 0) { 11212 Slog.w(TAG, "Couldn't remove cache files for package: " 11213 + packageName + " u" + userId); 11214 return false; 11215 } 11216 return true; 11217 } 11218 11219 @Override 11220 public void getPackageSizeInfo(final String packageName, int userHandle, 11221 final IPackageStatsObserver observer) { 11222 mContext.enforceCallingOrSelfPermission( 11223 android.Manifest.permission.GET_PACKAGE_SIZE, null); 11224 if (packageName == null) { 11225 throw new IllegalArgumentException("Attempt to get size of null packageName"); 11226 } 11227 11228 PackageStats stats = new PackageStats(packageName, userHandle); 11229 11230 /* 11231 * Queue up an async operation since the package measurement may take a 11232 * little while. 11233 */ 11234 Message msg = mHandler.obtainMessage(INIT_COPY); 11235 msg.obj = new MeasureParams(stats, observer); 11236 mHandler.sendMessage(msg); 11237 } 11238 11239 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 11240 PackageStats pStats) { 11241 if (packageName == null) { 11242 Slog.w(TAG, "Attempt to get size of null packageName."); 11243 return false; 11244 } 11245 PackageParser.Package p; 11246 boolean dataOnly = false; 11247 String libDirRoot = null; 11248 String asecPath = null; 11249 PackageSetting ps = null; 11250 synchronized (mPackages) { 11251 p = mPackages.get(packageName); 11252 ps = mSettings.mPackages.get(packageName); 11253 if(p == null) { 11254 dataOnly = true; 11255 if((ps == null) || (ps.pkg == null)) { 11256 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11257 return false; 11258 } 11259 p = ps.pkg; 11260 } 11261 if (ps != null) { 11262 libDirRoot = ps.legacyNativeLibraryPathString; 11263 } 11264 if (p != null && (isExternal(p) || isForwardLocked(p))) { 11265 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 11266 if (secureContainerId != null) { 11267 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 11268 } 11269 } 11270 } 11271 String publicSrcDir = null; 11272 if(!dataOnly) { 11273 final ApplicationInfo applicationInfo = p.applicationInfo; 11274 if (applicationInfo == null) { 11275 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11276 return false; 11277 } 11278 if (isForwardLocked(p)) { 11279 publicSrcDir = applicationInfo.getBaseResourcePath(); 11280 } 11281 } 11282 // TODO: extend to measure size of split APKs 11283 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 11284 // not just the first level. 11285 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 11286 // just the primary. 11287 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 11288 int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot, 11289 publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 11290 if (res < 0) { 11291 return false; 11292 } 11293 11294 // Fix-up for forward-locked applications in ASEC containers. 11295 if (!isExternal(p)) { 11296 pStats.codeSize += pStats.externalCodeSize; 11297 pStats.externalCodeSize = 0L; 11298 } 11299 11300 return true; 11301 } 11302 11303 11304 @Override 11305 public void addPackageToPreferred(String packageName) { 11306 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 11307 } 11308 11309 @Override 11310 public void removePackageFromPreferred(String packageName) { 11311 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 11312 } 11313 11314 @Override 11315 public List<PackageInfo> getPreferredPackages(int flags) { 11316 return new ArrayList<PackageInfo>(); 11317 } 11318 11319 private int getUidTargetSdkVersionLockedLPr(int uid) { 11320 Object obj = mSettings.getUserIdLPr(uid); 11321 if (obj instanceof SharedUserSetting) { 11322 final SharedUserSetting sus = (SharedUserSetting) obj; 11323 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 11324 final Iterator<PackageSetting> it = sus.packages.iterator(); 11325 while (it.hasNext()) { 11326 final PackageSetting ps = it.next(); 11327 if (ps.pkg != null) { 11328 int v = ps.pkg.applicationInfo.targetSdkVersion; 11329 if (v < vers) vers = v; 11330 } 11331 } 11332 return vers; 11333 } else if (obj instanceof PackageSetting) { 11334 final PackageSetting ps = (PackageSetting) obj; 11335 if (ps.pkg != null) { 11336 return ps.pkg.applicationInfo.targetSdkVersion; 11337 } 11338 } 11339 return Build.VERSION_CODES.CUR_DEVELOPMENT; 11340 } 11341 11342 @Override 11343 public void addPreferredActivity(IntentFilter filter, int match, 11344 ComponentName[] set, ComponentName activity, int userId) { 11345 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11346 "Adding preferred"); 11347 } 11348 11349 private void addPreferredActivityInternal(IntentFilter filter, int match, 11350 ComponentName[] set, ComponentName activity, boolean always, int userId, 11351 String opname) { 11352 // writer 11353 int callingUid = Binder.getCallingUid(); 11354 enforceCrossUserPermission(callingUid, userId, true, "add preferred activity"); 11355 if (filter.countActions() == 0) { 11356 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11357 return; 11358 } 11359 synchronized (mPackages) { 11360 if (mContext.checkCallingOrSelfPermission( 11361 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11362 != PackageManager.PERMISSION_GRANTED) { 11363 if (getUidTargetSdkVersionLockedLPr(callingUid) 11364 < Build.VERSION_CODES.FROYO) { 11365 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 11366 + callingUid); 11367 return; 11368 } 11369 mContext.enforceCallingOrSelfPermission( 11370 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11371 } 11372 11373 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 11374 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 11375 + userId + ":"); 11376 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11377 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 11378 mSettings.writePackageRestrictionsLPr(userId); 11379 } 11380 } 11381 11382 @Override 11383 public void replacePreferredActivity(IntentFilter filter, int match, 11384 ComponentName[] set, ComponentName activity, int userId) { 11385 if (filter.countActions() != 1) { 11386 throw new IllegalArgumentException( 11387 "replacePreferredActivity expects filter to have only 1 action."); 11388 } 11389 if (filter.countDataAuthorities() != 0 11390 || filter.countDataPaths() != 0 11391 || filter.countDataSchemes() > 1 11392 || filter.countDataTypes() != 0) { 11393 throw new IllegalArgumentException( 11394 "replacePreferredActivity expects filter to have no data authorities, " + 11395 "paths, or types; and at most one scheme."); 11396 } 11397 11398 final int callingUid = Binder.getCallingUid(); 11399 enforceCrossUserPermission(callingUid, userId, true, "replace preferred activity"); 11400 synchronized (mPackages) { 11401 if (mContext.checkCallingOrSelfPermission( 11402 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11403 != PackageManager.PERMISSION_GRANTED) { 11404 if (getUidTargetSdkVersionLockedLPr(callingUid) 11405 < Build.VERSION_CODES.FROYO) { 11406 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 11407 + Binder.getCallingUid()); 11408 return; 11409 } 11410 mContext.enforceCallingOrSelfPermission( 11411 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11412 } 11413 11414 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11415 if (pir != null) { 11416 // Get all of the existing entries that exactly match this filter. 11417 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 11418 if (existing != null && existing.size() == 1) { 11419 PreferredActivity cur = existing.get(0); 11420 if (DEBUG_PREFERRED) { 11421 Slog.i(TAG, "Checking replace of preferred:"); 11422 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11423 if (!cur.mPref.mAlways) { 11424 Slog.i(TAG, " -- CUR; not mAlways!"); 11425 } else { 11426 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 11427 Slog.i(TAG, " -- CUR: mSet=" 11428 + Arrays.toString(cur.mPref.mSetComponents)); 11429 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 11430 Slog.i(TAG, " -- NEW: mMatch=" 11431 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 11432 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 11433 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 11434 } 11435 } 11436 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 11437 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 11438 && cur.mPref.sameSet(set)) { 11439 if (DEBUG_PREFERRED) { 11440 Slog.i(TAG, "Replacing with same preferred activity " 11441 + cur.mPref.mShortComponent + " for user " 11442 + userId + ":"); 11443 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11444 } else { 11445 Slog.i(TAG, "Replacing with same preferred activity " 11446 + cur.mPref.mShortComponent + " for user " 11447 + userId); 11448 } 11449 return; 11450 } 11451 } 11452 11453 if (existing != null) { 11454 if (DEBUG_PREFERRED) { 11455 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 11456 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11457 } 11458 for (int i = 0; i < existing.size(); i++) { 11459 PreferredActivity pa = existing.get(i); 11460 if (DEBUG_PREFERRED) { 11461 Slog.i(TAG, "Removing existing preferred activity " 11462 + pa.mPref.mComponent + ":"); 11463 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 11464 } 11465 pir.removeFilter(pa); 11466 } 11467 } 11468 } 11469 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11470 "Replacing preferred"); 11471 } 11472 } 11473 11474 @Override 11475 public void clearPackagePreferredActivities(String packageName) { 11476 final int uid = Binder.getCallingUid(); 11477 // writer 11478 synchronized (mPackages) { 11479 PackageParser.Package pkg = mPackages.get(packageName); 11480 if (pkg == null || pkg.applicationInfo.uid != uid) { 11481 if (mContext.checkCallingOrSelfPermission( 11482 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11483 != PackageManager.PERMISSION_GRANTED) { 11484 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11485 < Build.VERSION_CODES.FROYO) { 11486 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 11487 + Binder.getCallingUid()); 11488 return; 11489 } 11490 mContext.enforceCallingOrSelfPermission( 11491 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11492 } 11493 } 11494 11495 int user = UserHandle.getCallingUserId(); 11496 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 11497 mSettings.writePackageRestrictionsLPr(user); 11498 scheduleWriteSettingsLocked(); 11499 } 11500 } 11501 } 11502 11503 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 11504 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 11505 ArrayList<PreferredActivity> removed = null; 11506 boolean changed = false; 11507 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11508 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 11509 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11510 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 11511 continue; 11512 } 11513 Iterator<PreferredActivity> it = pir.filterIterator(); 11514 while (it.hasNext()) { 11515 PreferredActivity pa = it.next(); 11516 // Mark entry for removal only if it matches the package name 11517 // and the entry is of type "always". 11518 if (packageName == null || 11519 (pa.mPref.mComponent.getPackageName().equals(packageName) 11520 && pa.mPref.mAlways)) { 11521 if (removed == null) { 11522 removed = new ArrayList<PreferredActivity>(); 11523 } 11524 removed.add(pa); 11525 } 11526 } 11527 if (removed != null) { 11528 for (int j=0; j<removed.size(); j++) { 11529 PreferredActivity pa = removed.get(j); 11530 pir.removeFilter(pa); 11531 } 11532 changed = true; 11533 } 11534 } 11535 return changed; 11536 } 11537 11538 @Override 11539 public void resetPreferredActivities(int userId) { 11540 mContext.enforceCallingOrSelfPermission( 11541 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11542 // writer 11543 synchronized (mPackages) { 11544 int user = UserHandle.getCallingUserId(); 11545 clearPackagePreferredActivitiesLPw(null, user); 11546 mSettings.readDefaultPreferredAppsLPw(this, user); 11547 mSettings.writePackageRestrictionsLPr(user); 11548 scheduleWriteSettingsLocked(); 11549 } 11550 } 11551 11552 @Override 11553 public int getPreferredActivities(List<IntentFilter> outFilters, 11554 List<ComponentName> outActivities, String packageName) { 11555 11556 int num = 0; 11557 final int userId = UserHandle.getCallingUserId(); 11558 // reader 11559 synchronized (mPackages) { 11560 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11561 if (pir != null) { 11562 final Iterator<PreferredActivity> it = pir.filterIterator(); 11563 while (it.hasNext()) { 11564 final PreferredActivity pa = it.next(); 11565 if (packageName == null 11566 || (pa.mPref.mComponent.getPackageName().equals(packageName) 11567 && pa.mPref.mAlways)) { 11568 if (outFilters != null) { 11569 outFilters.add(new IntentFilter(pa)); 11570 } 11571 if (outActivities != null) { 11572 outActivities.add(pa.mPref.mComponent); 11573 } 11574 } 11575 } 11576 } 11577 } 11578 11579 return num; 11580 } 11581 11582 @Override 11583 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 11584 int userId) { 11585 int callingUid = Binder.getCallingUid(); 11586 if (callingUid != Process.SYSTEM_UID) { 11587 throw new SecurityException( 11588 "addPersistentPreferredActivity can only be run by the system"); 11589 } 11590 if (filter.countActions() == 0) { 11591 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11592 return; 11593 } 11594 synchronized (mPackages) { 11595 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 11596 " :"); 11597 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11598 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 11599 new PersistentPreferredActivity(filter, activity)); 11600 mSettings.writePackageRestrictionsLPr(userId); 11601 } 11602 } 11603 11604 @Override 11605 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 11606 int callingUid = Binder.getCallingUid(); 11607 if (callingUid != Process.SYSTEM_UID) { 11608 throw new SecurityException( 11609 "clearPackagePersistentPreferredActivities can only be run by the system"); 11610 } 11611 ArrayList<PersistentPreferredActivity> removed = null; 11612 boolean changed = false; 11613 synchronized (mPackages) { 11614 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 11615 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 11616 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 11617 .valueAt(i); 11618 if (userId != thisUserId) { 11619 continue; 11620 } 11621 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 11622 while (it.hasNext()) { 11623 PersistentPreferredActivity ppa = it.next(); 11624 // Mark entry for removal only if it matches the package name. 11625 if (ppa.mComponent.getPackageName().equals(packageName)) { 11626 if (removed == null) { 11627 removed = new ArrayList<PersistentPreferredActivity>(); 11628 } 11629 removed.add(ppa); 11630 } 11631 } 11632 if (removed != null) { 11633 for (int j=0; j<removed.size(); j++) { 11634 PersistentPreferredActivity ppa = removed.get(j); 11635 ppir.removeFilter(ppa); 11636 } 11637 changed = true; 11638 } 11639 } 11640 11641 if (changed) { 11642 mSettings.writePackageRestrictionsLPr(userId); 11643 } 11644 } 11645 } 11646 11647 @Override 11648 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 11649 int ownerUserId, int sourceUserId, int targetUserId, int flags) { 11650 mContext.enforceCallingOrSelfPermission( 11651 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11652 int callingUid = Binder.getCallingUid(); 11653 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11654 if (intentFilter.countActions() == 0) { 11655 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 11656 return; 11657 } 11658 synchronized (mPackages) { 11659 CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter, 11660 ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags); 11661 mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter); 11662 mSettings.writePackageRestrictionsLPr(sourceUserId); 11663 } 11664 } 11665 11666 @Override 11667 public void addCrossProfileIntentsForPackage(String packageName, 11668 int sourceUserId, int targetUserId) { 11669 mContext.enforceCallingOrSelfPermission( 11670 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11671 mSettings.addCrossProfilePackage(packageName, sourceUserId, targetUserId); 11672 mSettings.writePackageRestrictionsLPr(sourceUserId); 11673 } 11674 11675 @Override 11676 public void removeCrossProfileIntentsForPackage(String packageName, 11677 int sourceUserId, int targetUserId) { 11678 mContext.enforceCallingOrSelfPermission( 11679 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11680 mSettings.removeCrossProfilePackage(packageName, sourceUserId, targetUserId); 11681 mSettings.writePackageRestrictionsLPr(sourceUserId); 11682 } 11683 11684 @Override 11685 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage, 11686 int ownerUserId) { 11687 mContext.enforceCallingOrSelfPermission( 11688 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11689 int callingUid = Binder.getCallingUid(); 11690 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11691 int callingUserId = UserHandle.getUserId(callingUid); 11692 synchronized (mPackages) { 11693 CrossProfileIntentResolver resolver = 11694 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11695 HashSet<CrossProfileIntentFilter> set = 11696 new HashSet<CrossProfileIntentFilter>(resolver.filterSet()); 11697 for (CrossProfileIntentFilter filter : set) { 11698 if (filter.getOwnerPackage().equals(ownerPackage) 11699 && filter.getOwnerUserId() == callingUserId) { 11700 resolver.removeFilter(filter); 11701 } 11702 } 11703 mSettings.writePackageRestrictionsLPr(sourceUserId); 11704 } 11705 } 11706 11707 // Enforcing that callingUid is owning pkg on userId 11708 private void enforceOwnerRights(String pkg, int userId, int callingUid) { 11709 // The system owns everything. 11710 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 11711 return; 11712 } 11713 int callingUserId = UserHandle.getUserId(callingUid); 11714 if (callingUserId != userId) { 11715 throw new SecurityException("calling uid " + callingUid 11716 + " pretends to own " + pkg + " on user " + userId + " but belongs to user " 11717 + callingUserId); 11718 } 11719 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 11720 if (pi == null) { 11721 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 11722 + callingUserId); 11723 } 11724 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 11725 throw new SecurityException("Calling uid " + callingUid 11726 + " does not own package " + pkg); 11727 } 11728 } 11729 11730 @Override 11731 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 11732 Intent intent = new Intent(Intent.ACTION_MAIN); 11733 intent.addCategory(Intent.CATEGORY_HOME); 11734 11735 final int callingUserId = UserHandle.getCallingUserId(); 11736 List<ResolveInfo> list = queryIntentActivities(intent, null, 11737 PackageManager.GET_META_DATA, callingUserId); 11738 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 11739 true, false, false, callingUserId); 11740 11741 allHomeCandidates.clear(); 11742 if (list != null) { 11743 for (ResolveInfo ri : list) { 11744 allHomeCandidates.add(ri); 11745 } 11746 } 11747 return (preferred == null || preferred.activityInfo == null) 11748 ? null 11749 : new ComponentName(preferred.activityInfo.packageName, 11750 preferred.activityInfo.name); 11751 } 11752 11753 @Override 11754 public void setApplicationEnabledSetting(String appPackageName, 11755 int newState, int flags, int userId, String callingPackage) { 11756 if (!sUserManager.exists(userId)) return; 11757 if (callingPackage == null) { 11758 callingPackage = Integer.toString(Binder.getCallingUid()); 11759 } 11760 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 11761 } 11762 11763 @Override 11764 public void setComponentEnabledSetting(ComponentName componentName, 11765 int newState, int flags, int userId) { 11766 if (!sUserManager.exists(userId)) return; 11767 setEnabledSetting(componentName.getPackageName(), 11768 componentName.getClassName(), newState, flags, userId, null); 11769 } 11770 11771 private void setEnabledSetting(final String packageName, String className, int newState, 11772 final int flags, int userId, String callingPackage) { 11773 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 11774 || newState == COMPONENT_ENABLED_STATE_ENABLED 11775 || newState == COMPONENT_ENABLED_STATE_DISABLED 11776 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 11777 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 11778 throw new IllegalArgumentException("Invalid new component state: " 11779 + newState); 11780 } 11781 PackageSetting pkgSetting; 11782 final int uid = Binder.getCallingUid(); 11783 final int permission = mContext.checkCallingOrSelfPermission( 11784 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11785 enforceCrossUserPermission(uid, userId, false, "set enabled"); 11786 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11787 boolean sendNow = false; 11788 boolean isApp = (className == null); 11789 String componentName = isApp ? packageName : className; 11790 int packageUid = -1; 11791 ArrayList<String> components; 11792 11793 // writer 11794 synchronized (mPackages) { 11795 pkgSetting = mSettings.mPackages.get(packageName); 11796 if (pkgSetting == null) { 11797 if (className == null) { 11798 throw new IllegalArgumentException( 11799 "Unknown package: " + packageName); 11800 } 11801 throw new IllegalArgumentException( 11802 "Unknown component: " + packageName 11803 + "/" + className); 11804 } 11805 // Allow root and verify that userId is not being specified by a different user 11806 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 11807 throw new SecurityException( 11808 "Permission Denial: attempt to change component state from pid=" 11809 + Binder.getCallingPid() 11810 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 11811 } 11812 if (className == null) { 11813 // We're dealing with an application/package level state change 11814 if (pkgSetting.getEnabled(userId) == newState) { 11815 // Nothing to do 11816 return; 11817 } 11818 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 11819 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 11820 // Don't care about who enables an app. 11821 callingPackage = null; 11822 } 11823 pkgSetting.setEnabled(newState, userId, callingPackage); 11824 // pkgSetting.pkg.mSetEnabled = newState; 11825 } else { 11826 // We're dealing with a component level state change 11827 // First, verify that this is a valid class name. 11828 PackageParser.Package pkg = pkgSetting.pkg; 11829 if (pkg == null || !pkg.hasComponentClassName(className)) { 11830 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 11831 throw new IllegalArgumentException("Component class " + className 11832 + " does not exist in " + packageName); 11833 } else { 11834 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 11835 + className + " does not exist in " + packageName); 11836 } 11837 } 11838 switch (newState) { 11839 case COMPONENT_ENABLED_STATE_ENABLED: 11840 if (!pkgSetting.enableComponentLPw(className, userId)) { 11841 return; 11842 } 11843 break; 11844 case COMPONENT_ENABLED_STATE_DISABLED: 11845 if (!pkgSetting.disableComponentLPw(className, userId)) { 11846 return; 11847 } 11848 break; 11849 case COMPONENT_ENABLED_STATE_DEFAULT: 11850 if (!pkgSetting.restoreComponentLPw(className, userId)) { 11851 return; 11852 } 11853 break; 11854 default: 11855 Slog.e(TAG, "Invalid new component state: " + newState); 11856 return; 11857 } 11858 } 11859 mSettings.writePackageRestrictionsLPr(userId); 11860 components = mPendingBroadcasts.get(userId, packageName); 11861 final boolean newPackage = components == null; 11862 if (newPackage) { 11863 components = new ArrayList<String>(); 11864 } 11865 if (!components.contains(componentName)) { 11866 components.add(componentName); 11867 } 11868 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 11869 sendNow = true; 11870 // Purge entry from pending broadcast list if another one exists already 11871 // since we are sending one right away. 11872 mPendingBroadcasts.remove(userId, packageName); 11873 } else { 11874 if (newPackage) { 11875 mPendingBroadcasts.put(userId, packageName, components); 11876 } 11877 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 11878 // Schedule a message 11879 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 11880 } 11881 } 11882 } 11883 11884 long callingId = Binder.clearCallingIdentity(); 11885 try { 11886 if (sendNow) { 11887 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 11888 sendPackageChangedBroadcast(packageName, 11889 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 11890 } 11891 } finally { 11892 Binder.restoreCallingIdentity(callingId); 11893 } 11894 } 11895 11896 private void sendPackageChangedBroadcast(String packageName, 11897 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 11898 if (DEBUG_INSTALL) 11899 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 11900 + componentNames); 11901 Bundle extras = new Bundle(4); 11902 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 11903 String nameList[] = new String[componentNames.size()]; 11904 componentNames.toArray(nameList); 11905 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 11906 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 11907 extras.putInt(Intent.EXTRA_UID, packageUid); 11908 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 11909 new int[] {UserHandle.getUserId(packageUid)}); 11910 } 11911 11912 @Override 11913 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 11914 if (!sUserManager.exists(userId)) return; 11915 final int uid = Binder.getCallingUid(); 11916 final int permission = mContext.checkCallingOrSelfPermission( 11917 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11918 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11919 enforceCrossUserPermission(uid, userId, true, "stop package"); 11920 // writer 11921 synchronized (mPackages) { 11922 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 11923 uid, userId)) { 11924 scheduleWritePackageRestrictionsLocked(userId); 11925 } 11926 } 11927 } 11928 11929 @Override 11930 public String getInstallerPackageName(String packageName) { 11931 // reader 11932 synchronized (mPackages) { 11933 return mSettings.getInstallerPackageNameLPr(packageName); 11934 } 11935 } 11936 11937 @Override 11938 public int getApplicationEnabledSetting(String packageName, int userId) { 11939 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11940 int uid = Binder.getCallingUid(); 11941 enforceCrossUserPermission(uid, userId, false, "get enabled"); 11942 // reader 11943 synchronized (mPackages) { 11944 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 11945 } 11946 } 11947 11948 @Override 11949 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 11950 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11951 int uid = Binder.getCallingUid(); 11952 enforceCrossUserPermission(uid, userId, false, "get component enabled"); 11953 // reader 11954 synchronized (mPackages) { 11955 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 11956 } 11957 } 11958 11959 @Override 11960 public void enterSafeMode() { 11961 enforceSystemOrRoot("Only the system can request entering safe mode"); 11962 11963 if (!mSystemReady) { 11964 mSafeMode = true; 11965 } 11966 } 11967 11968 @Override 11969 public void systemReady() { 11970 mSystemReady = true; 11971 11972 // Read the compatibilty setting when the system is ready. 11973 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 11974 mContext.getContentResolver(), 11975 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 11976 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 11977 if (DEBUG_SETTINGS) { 11978 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 11979 } 11980 11981 synchronized (mPackages) { 11982 // Verify that all of the preferred activity components actually 11983 // exist. It is possible for applications to be updated and at 11984 // that point remove a previously declared activity component that 11985 // had been set as a preferred activity. We try to clean this up 11986 // the next time we encounter that preferred activity, but it is 11987 // possible for the user flow to never be able to return to that 11988 // situation so here we do a sanity check to make sure we haven't 11989 // left any junk around. 11990 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 11991 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11992 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11993 removed.clear(); 11994 for (PreferredActivity pa : pir.filterSet()) { 11995 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 11996 removed.add(pa); 11997 } 11998 } 11999 if (removed.size() > 0) { 12000 for (int r=0; r<removed.size(); r++) { 12001 PreferredActivity pa = removed.get(r); 12002 Slog.w(TAG, "Removing dangling preferred activity: " 12003 + pa.mPref.mComponent); 12004 pir.removeFilter(pa); 12005 } 12006 mSettings.writePackageRestrictionsLPr( 12007 mSettings.mPreferredActivities.keyAt(i)); 12008 } 12009 } 12010 } 12011 sUserManager.systemReady(); 12012 12013 // Kick off any messages waiting for system ready 12014 if (mPostSystemReadyMessages != null) { 12015 for (Message msg : mPostSystemReadyMessages) { 12016 msg.sendToTarget(); 12017 } 12018 mPostSystemReadyMessages = null; 12019 } 12020 } 12021 12022 @Override 12023 public boolean isSafeMode() { 12024 return mSafeMode; 12025 } 12026 12027 @Override 12028 public boolean hasSystemUidErrors() { 12029 return mHasSystemUidErrors; 12030 } 12031 12032 static String arrayToString(int[] array) { 12033 StringBuffer buf = new StringBuffer(128); 12034 buf.append('['); 12035 if (array != null) { 12036 for (int i=0; i<array.length; i++) { 12037 if (i > 0) buf.append(", "); 12038 buf.append(array[i]); 12039 } 12040 } 12041 buf.append(']'); 12042 return buf.toString(); 12043 } 12044 12045 static class DumpState { 12046 public static final int DUMP_LIBS = 1 << 0; 12047 public static final int DUMP_FEATURES = 1 << 1; 12048 public static final int DUMP_RESOLVERS = 1 << 2; 12049 public static final int DUMP_PERMISSIONS = 1 << 3; 12050 public static final int DUMP_PACKAGES = 1 << 4; 12051 public static final int DUMP_SHARED_USERS = 1 << 5; 12052 public static final int DUMP_MESSAGES = 1 << 6; 12053 public static final int DUMP_PROVIDERS = 1 << 7; 12054 public static final int DUMP_VERIFIERS = 1 << 8; 12055 public static final int DUMP_PREFERRED = 1 << 9; 12056 public static final int DUMP_PREFERRED_XML = 1 << 10; 12057 public static final int DUMP_KEYSETS = 1 << 11; 12058 public static final int DUMP_VERSION = 1 << 12; 12059 public static final int DUMP_INSTALLS = 1 << 13; 12060 12061 public static final int OPTION_SHOW_FILTERS = 1 << 0; 12062 12063 private int mTypes; 12064 12065 private int mOptions; 12066 12067 private boolean mTitlePrinted; 12068 12069 private SharedUserSetting mSharedUser; 12070 12071 public boolean isDumping(int type) { 12072 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 12073 return true; 12074 } 12075 12076 return (mTypes & type) != 0; 12077 } 12078 12079 public void setDump(int type) { 12080 mTypes |= type; 12081 } 12082 12083 public boolean isOptionEnabled(int option) { 12084 return (mOptions & option) != 0; 12085 } 12086 12087 public void setOptionEnabled(int option) { 12088 mOptions |= option; 12089 } 12090 12091 public boolean onTitlePrinted() { 12092 final boolean printed = mTitlePrinted; 12093 mTitlePrinted = true; 12094 return printed; 12095 } 12096 12097 public boolean getTitlePrinted() { 12098 return mTitlePrinted; 12099 } 12100 12101 public void setTitlePrinted(boolean enabled) { 12102 mTitlePrinted = enabled; 12103 } 12104 12105 public SharedUserSetting getSharedUser() { 12106 return mSharedUser; 12107 } 12108 12109 public void setSharedUser(SharedUserSetting user) { 12110 mSharedUser = user; 12111 } 12112 } 12113 12114 @Override 12115 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 12116 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 12117 != PackageManager.PERMISSION_GRANTED) { 12118 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 12119 + Binder.getCallingPid() 12120 + ", uid=" + Binder.getCallingUid() 12121 + " without permission " 12122 + android.Manifest.permission.DUMP); 12123 return; 12124 } 12125 12126 DumpState dumpState = new DumpState(); 12127 boolean fullPreferred = false; 12128 boolean checkin = false; 12129 12130 String packageName = null; 12131 12132 int opti = 0; 12133 while (opti < args.length) { 12134 String opt = args[opti]; 12135 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 12136 break; 12137 } 12138 opti++; 12139 if ("-a".equals(opt)) { 12140 // Right now we only know how to print all. 12141 } else if ("-h".equals(opt)) { 12142 pw.println("Package manager dump options:"); 12143 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 12144 pw.println(" --checkin: dump for a checkin"); 12145 pw.println(" -f: print details of intent filters"); 12146 pw.println(" -h: print this help"); 12147 pw.println(" cmd may be one of:"); 12148 pw.println(" l[ibraries]: list known shared libraries"); 12149 pw.println(" f[ibraries]: list device features"); 12150 pw.println(" k[eysets]: print known keysets"); 12151 pw.println(" r[esolvers]: dump intent resolvers"); 12152 pw.println(" perm[issions]: dump permissions"); 12153 pw.println(" pref[erred]: print preferred package settings"); 12154 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 12155 pw.println(" prov[iders]: dump content providers"); 12156 pw.println(" p[ackages]: dump installed packages"); 12157 pw.println(" s[hared-users]: dump shared user IDs"); 12158 pw.println(" m[essages]: print collected runtime messages"); 12159 pw.println(" v[erifiers]: print package verifier info"); 12160 pw.println(" version: print database version info"); 12161 pw.println(" write: write current settings now"); 12162 pw.println(" <package.name>: info about given package"); 12163 pw.println(" installs: details about install sessions"); 12164 return; 12165 } else if ("--checkin".equals(opt)) { 12166 checkin = true; 12167 } else if ("-f".equals(opt)) { 12168 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12169 } else { 12170 pw.println("Unknown argument: " + opt + "; use -h for help"); 12171 } 12172 } 12173 12174 // Is the caller requesting to dump a particular piece of data? 12175 if (opti < args.length) { 12176 String cmd = args[opti]; 12177 opti++; 12178 // Is this a package name? 12179 if ("android".equals(cmd) || cmd.contains(".")) { 12180 packageName = cmd; 12181 // When dumping a single package, we always dump all of its 12182 // filter information since the amount of data will be reasonable. 12183 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12184 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 12185 dumpState.setDump(DumpState.DUMP_LIBS); 12186 } else if ("f".equals(cmd) || "features".equals(cmd)) { 12187 dumpState.setDump(DumpState.DUMP_FEATURES); 12188 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 12189 dumpState.setDump(DumpState.DUMP_RESOLVERS); 12190 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 12191 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 12192 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 12193 dumpState.setDump(DumpState.DUMP_PREFERRED); 12194 } else if ("preferred-xml".equals(cmd)) { 12195 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 12196 if (opti < args.length && "--full".equals(args[opti])) { 12197 fullPreferred = true; 12198 opti++; 12199 } 12200 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 12201 dumpState.setDump(DumpState.DUMP_PACKAGES); 12202 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 12203 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 12204 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 12205 dumpState.setDump(DumpState.DUMP_PROVIDERS); 12206 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 12207 dumpState.setDump(DumpState.DUMP_MESSAGES); 12208 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 12209 dumpState.setDump(DumpState.DUMP_VERIFIERS); 12210 } else if ("version".equals(cmd)) { 12211 dumpState.setDump(DumpState.DUMP_VERSION); 12212 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 12213 dumpState.setDump(DumpState.DUMP_KEYSETS); 12214 } else if ("write".equals(cmd)) { 12215 synchronized (mPackages) { 12216 mSettings.writeLPr(); 12217 pw.println("Settings written."); 12218 return; 12219 } 12220 } else if ("installs".equals(cmd)) { 12221 dumpState.setDump(DumpState.DUMP_INSTALLS); 12222 } 12223 } 12224 12225 if (checkin) { 12226 pw.println("vers,1"); 12227 } 12228 12229 // reader 12230 synchronized (mPackages) { 12231 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 12232 if (!checkin) { 12233 if (dumpState.onTitlePrinted()) 12234 pw.println(); 12235 pw.println("Database versions:"); 12236 pw.print(" SDK Version:"); 12237 pw.print(" internal="); 12238 pw.print(mSettings.mInternalSdkPlatform); 12239 pw.print(" external="); 12240 pw.println(mSettings.mExternalSdkPlatform); 12241 pw.print(" DB Version:"); 12242 pw.print(" internal="); 12243 pw.print(mSettings.mInternalDatabaseVersion); 12244 pw.print(" external="); 12245 pw.println(mSettings.mExternalDatabaseVersion); 12246 } 12247 } 12248 12249 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 12250 if (!checkin) { 12251 if (dumpState.onTitlePrinted()) 12252 pw.println(); 12253 pw.println("Verifiers:"); 12254 pw.print(" Required: "); 12255 pw.print(mRequiredVerifierPackage); 12256 pw.print(" (uid="); 12257 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 12258 pw.println(")"); 12259 } else if (mRequiredVerifierPackage != null) { 12260 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 12261 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 12262 } 12263 } 12264 12265 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 12266 boolean printedHeader = false; 12267 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 12268 while (it.hasNext()) { 12269 String name = it.next(); 12270 SharedLibraryEntry ent = mSharedLibraries.get(name); 12271 if (!checkin) { 12272 if (!printedHeader) { 12273 if (dumpState.onTitlePrinted()) 12274 pw.println(); 12275 pw.println("Libraries:"); 12276 printedHeader = true; 12277 } 12278 pw.print(" "); 12279 } else { 12280 pw.print("lib,"); 12281 } 12282 pw.print(name); 12283 if (!checkin) { 12284 pw.print(" -> "); 12285 } 12286 if (ent.path != null) { 12287 if (!checkin) { 12288 pw.print("(jar) "); 12289 pw.print(ent.path); 12290 } else { 12291 pw.print(",jar,"); 12292 pw.print(ent.path); 12293 } 12294 } else { 12295 if (!checkin) { 12296 pw.print("(apk) "); 12297 pw.print(ent.apk); 12298 } else { 12299 pw.print(",apk,"); 12300 pw.print(ent.apk); 12301 } 12302 } 12303 pw.println(); 12304 } 12305 } 12306 12307 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 12308 if (dumpState.onTitlePrinted()) 12309 pw.println(); 12310 if (!checkin) { 12311 pw.println("Features:"); 12312 } 12313 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 12314 while (it.hasNext()) { 12315 String name = it.next(); 12316 if (!checkin) { 12317 pw.print(" "); 12318 } else { 12319 pw.print("feat,"); 12320 } 12321 pw.println(name); 12322 } 12323 } 12324 12325 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 12326 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 12327 : "Activity Resolver Table:", " ", packageName, 12328 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12329 dumpState.setTitlePrinted(true); 12330 } 12331 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 12332 : "Receiver Resolver Table:", " ", packageName, 12333 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12334 dumpState.setTitlePrinted(true); 12335 } 12336 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 12337 : "Service Resolver Table:", " ", packageName, 12338 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12339 dumpState.setTitlePrinted(true); 12340 } 12341 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 12342 : "Provider Resolver Table:", " ", packageName, 12343 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12344 dumpState.setTitlePrinted(true); 12345 } 12346 } 12347 12348 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 12349 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12350 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12351 int user = mSettings.mPreferredActivities.keyAt(i); 12352 if (pir.dump(pw, 12353 dumpState.getTitlePrinted() 12354 ? "\nPreferred Activities User " + user + ":" 12355 : "Preferred Activities User " + user + ":", " ", 12356 packageName, true)) { 12357 dumpState.setTitlePrinted(true); 12358 } 12359 } 12360 } 12361 12362 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 12363 pw.flush(); 12364 FileOutputStream fout = new FileOutputStream(fd); 12365 BufferedOutputStream str = new BufferedOutputStream(fout); 12366 XmlSerializer serializer = new FastXmlSerializer(); 12367 try { 12368 serializer.setOutput(str, "utf-8"); 12369 serializer.startDocument(null, true); 12370 serializer.setFeature( 12371 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 12372 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 12373 serializer.endDocument(); 12374 serializer.flush(); 12375 } catch (IllegalArgumentException e) { 12376 pw.println("Failed writing: " + e); 12377 } catch (IllegalStateException e) { 12378 pw.println("Failed writing: " + e); 12379 } catch (IOException e) { 12380 pw.println("Failed writing: " + e); 12381 } 12382 } 12383 12384 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 12385 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 12386 if (packageName == null) { 12387 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 12388 if (iperm == 0) { 12389 if (dumpState.onTitlePrinted()) 12390 pw.println(); 12391 pw.println("AppOp Permissions:"); 12392 } 12393 pw.print(" AppOp Permission "); 12394 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 12395 pw.println(":"); 12396 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 12397 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 12398 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 12399 } 12400 } 12401 } 12402 } 12403 12404 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 12405 boolean printedSomething = false; 12406 for (PackageParser.Provider p : mProviders.mProviders.values()) { 12407 if (packageName != null && !packageName.equals(p.info.packageName)) { 12408 continue; 12409 } 12410 if (!printedSomething) { 12411 if (dumpState.onTitlePrinted()) 12412 pw.println(); 12413 pw.println("Registered ContentProviders:"); 12414 printedSomething = true; 12415 } 12416 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 12417 pw.print(" "); pw.println(p.toString()); 12418 } 12419 printedSomething = false; 12420 for (Map.Entry<String, PackageParser.Provider> entry : 12421 mProvidersByAuthority.entrySet()) { 12422 PackageParser.Provider p = entry.getValue(); 12423 if (packageName != null && !packageName.equals(p.info.packageName)) { 12424 continue; 12425 } 12426 if (!printedSomething) { 12427 if (dumpState.onTitlePrinted()) 12428 pw.println(); 12429 pw.println("ContentProvider Authorities:"); 12430 printedSomething = true; 12431 } 12432 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 12433 pw.print(" "); pw.println(p.toString()); 12434 if (p.info != null && p.info.applicationInfo != null) { 12435 final String appInfo = p.info.applicationInfo.toString(); 12436 pw.print(" applicationInfo="); pw.println(appInfo); 12437 } 12438 } 12439 } 12440 12441 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 12442 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 12443 } 12444 12445 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 12446 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 12447 } 12448 12449 if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 12450 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState); 12451 } 12452 12453 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS)) { 12454 if (dumpState.onTitlePrinted()) pw.println(); 12455 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 12456 } 12457 12458 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 12459 if (dumpState.onTitlePrinted()) pw.println(); 12460 mSettings.dumpReadMessagesLPr(pw, dumpState); 12461 12462 pw.println(); 12463 pw.println("Package warning messages:"); 12464 final File fname = getSettingsProblemFile(); 12465 FileInputStream in = null; 12466 try { 12467 in = new FileInputStream(fname); 12468 final int avail = in.available(); 12469 final byte[] data = new byte[avail]; 12470 in.read(data); 12471 pw.print(new String(data)); 12472 } catch (FileNotFoundException e) { 12473 } catch (IOException e) { 12474 } finally { 12475 if (in != null) { 12476 try { 12477 in.close(); 12478 } catch (IOException e) { 12479 } 12480 } 12481 } 12482 } 12483 } 12484 } 12485 12486 // ------- apps on sdcard specific code ------- 12487 static final boolean DEBUG_SD_INSTALL = false; 12488 12489 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 12490 12491 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 12492 12493 private boolean mMediaMounted = false; 12494 12495 static String getEncryptKey() { 12496 try { 12497 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 12498 SD_ENCRYPTION_KEYSTORE_NAME); 12499 if (sdEncKey == null) { 12500 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 12501 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 12502 if (sdEncKey == null) { 12503 Slog.e(TAG, "Failed to create encryption keys"); 12504 return null; 12505 } 12506 } 12507 return sdEncKey; 12508 } catch (NoSuchAlgorithmException nsae) { 12509 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 12510 return null; 12511 } catch (IOException ioe) { 12512 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 12513 return null; 12514 } 12515 } 12516 12517 /* 12518 * Update media status on PackageManager. 12519 */ 12520 @Override 12521 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 12522 int callingUid = Binder.getCallingUid(); 12523 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 12524 throw new SecurityException("Media status can only be updated by the system"); 12525 } 12526 // reader; this apparently protects mMediaMounted, but should probably 12527 // be a different lock in that case. 12528 synchronized (mPackages) { 12529 Log.i(TAG, "Updating external media status from " 12530 + (mMediaMounted ? "mounted" : "unmounted") + " to " 12531 + (mediaStatus ? "mounted" : "unmounted")); 12532 if (DEBUG_SD_INSTALL) 12533 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 12534 + ", mMediaMounted=" + mMediaMounted); 12535 if (mediaStatus == mMediaMounted) { 12536 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 12537 : 0, -1); 12538 mHandler.sendMessage(msg); 12539 return; 12540 } 12541 mMediaMounted = mediaStatus; 12542 } 12543 // Queue up an async operation since the package installation may take a 12544 // little while. 12545 mHandler.post(new Runnable() { 12546 public void run() { 12547 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 12548 } 12549 }); 12550 } 12551 12552 /** 12553 * Called by MountService when the initial ASECs to scan are available. 12554 * Should block until all the ASEC containers are finished being scanned. 12555 */ 12556 public void scanAvailableAsecs() { 12557 updateExternalMediaStatusInner(true, false, false); 12558 if (mShouldRestoreconData) { 12559 SELinuxMMAC.setRestoreconDone(); 12560 mShouldRestoreconData = false; 12561 } 12562 } 12563 12564 /* 12565 * Collect information of applications on external media, map them against 12566 * existing containers and update information based on current mount status. 12567 * Please note that we always have to report status if reportStatus has been 12568 * set to true especially when unloading packages. 12569 */ 12570 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 12571 boolean externalStorage) { 12572 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 12573 int[] uidArr = EmptyArray.INT; 12574 12575 final String[] list = PackageHelper.getSecureContainerList(); 12576 if (ArrayUtils.isEmpty(list)) { 12577 Log.i(TAG, "No secure containers found"); 12578 } else { 12579 // Process list of secure containers and categorize them 12580 // as active or stale based on their package internal state. 12581 12582 // reader 12583 synchronized (mPackages) { 12584 for (String cid : list) { 12585 // Leave stages untouched for now; installer service owns them 12586 if (PackageInstallerService.isStageName(cid)) continue; 12587 12588 if (DEBUG_SD_INSTALL) 12589 Log.i(TAG, "Processing container " + cid); 12590 String pkgName = getAsecPackageName(cid); 12591 if (pkgName == null) { 12592 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 12593 continue; 12594 } 12595 if (DEBUG_SD_INSTALL) 12596 Log.i(TAG, "Looking for pkg : " + pkgName); 12597 12598 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12599 if (ps == null) { 12600 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 12601 continue; 12602 } 12603 12604 /* 12605 * Skip packages that are not external if we're unmounting 12606 * external storage. 12607 */ 12608 if (externalStorage && !isMounted && !isExternal(ps)) { 12609 continue; 12610 } 12611 12612 final AsecInstallArgs args = new AsecInstallArgs(cid, 12613 getAppDexInstructionSets(ps), isForwardLocked(ps)); 12614 // The package status is changed only if the code path 12615 // matches between settings and the container id. 12616 if (ps.codePathString != null 12617 && ps.codePathString.startsWith(args.getCodePath())) { 12618 if (DEBUG_SD_INSTALL) { 12619 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 12620 + " at code path: " + ps.codePathString); 12621 } 12622 12623 // We do have a valid package installed on sdcard 12624 processCids.put(args, ps.codePathString); 12625 final int uid = ps.appId; 12626 if (uid != -1) { 12627 uidArr = ArrayUtils.appendInt(uidArr, uid); 12628 } 12629 } else { 12630 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 12631 + ps.codePathString); 12632 } 12633 } 12634 } 12635 12636 Arrays.sort(uidArr); 12637 } 12638 12639 // Process packages with valid entries. 12640 if (isMounted) { 12641 if (DEBUG_SD_INSTALL) 12642 Log.i(TAG, "Loading packages"); 12643 loadMediaPackages(processCids, uidArr); 12644 startCleaningPackages(); 12645 mInstallerService.onSecureContainersAvailable(); 12646 } else { 12647 if (DEBUG_SD_INSTALL) 12648 Log.i(TAG, "Unloading packages"); 12649 unloadMediaPackages(processCids, uidArr, reportStatus); 12650 } 12651 } 12652 12653 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 12654 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 12655 int size = pkgList.size(); 12656 if (size > 0) { 12657 // Send broadcasts here 12658 Bundle extras = new Bundle(); 12659 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 12660 .toArray(new String[size])); 12661 if (uidArr != null) { 12662 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 12663 } 12664 if (replacing) { 12665 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 12666 } 12667 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 12668 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 12669 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 12670 } 12671 } 12672 12673 /* 12674 * Look at potentially valid container ids from processCids If package 12675 * information doesn't match the one on record or package scanning fails, 12676 * the cid is added to list of removeCids. We currently don't delete stale 12677 * containers. 12678 */ 12679 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 12680 ArrayList<String> pkgList = new ArrayList<String>(); 12681 Set<AsecInstallArgs> keys = processCids.keySet(); 12682 12683 for (AsecInstallArgs args : keys) { 12684 String codePath = processCids.get(args); 12685 if (DEBUG_SD_INSTALL) 12686 Log.i(TAG, "Loading container : " + args.cid); 12687 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12688 try { 12689 // Make sure there are no container errors first. 12690 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 12691 Slog.e(TAG, "Failed to mount cid : " + args.cid 12692 + " when installing from sdcard"); 12693 continue; 12694 } 12695 // Check code path here. 12696 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 12697 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 12698 + " does not match one in settings " + codePath); 12699 continue; 12700 } 12701 // Parse package 12702 int parseFlags = mDefParseFlags; 12703 if (args.isExternal()) { 12704 parseFlags |= PackageParser.PARSE_ON_SDCARD; 12705 } 12706 if (args.isFwdLocked()) { 12707 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 12708 } 12709 12710 synchronized (mInstallLock) { 12711 PackageParser.Package pkg = null; 12712 try { 12713 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 12714 } catch (PackageManagerException e) { 12715 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 12716 } 12717 // Scan the package 12718 if (pkg != null) { 12719 /* 12720 * TODO why is the lock being held? doPostInstall is 12721 * called in other places without the lock. This needs 12722 * to be straightened out. 12723 */ 12724 // writer 12725 synchronized (mPackages) { 12726 retCode = PackageManager.INSTALL_SUCCEEDED; 12727 pkgList.add(pkg.packageName); 12728 // Post process args 12729 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 12730 pkg.applicationInfo.uid); 12731 } 12732 } else { 12733 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 12734 } 12735 } 12736 12737 } finally { 12738 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 12739 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 12740 } 12741 } 12742 } 12743 // writer 12744 synchronized (mPackages) { 12745 // If the platform SDK has changed since the last time we booted, 12746 // we need to re-grant app permission to catch any new ones that 12747 // appear. This is really a hack, and means that apps can in some 12748 // cases get permissions that the user didn't initially explicitly 12749 // allow... it would be nice to have some better way to handle 12750 // this situation. 12751 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 12752 if (regrantPermissions) 12753 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 12754 + mSdkVersion + "; regranting permissions for external storage"); 12755 mSettings.mExternalSdkPlatform = mSdkVersion; 12756 12757 // Make sure group IDs have been assigned, and any permission 12758 // changes in other apps are accounted for 12759 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 12760 | (regrantPermissions 12761 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 12762 : 0)); 12763 12764 mSettings.updateExternalDatabaseVersion(); 12765 12766 // can downgrade to reader 12767 // Persist settings 12768 mSettings.writeLPr(); 12769 } 12770 // Send a broadcast to let everyone know we are done processing 12771 if (pkgList.size() > 0) { 12772 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12773 } 12774 } 12775 12776 /* 12777 * Utility method to unload a list of specified containers 12778 */ 12779 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 12780 // Just unmount all valid containers. 12781 for (AsecInstallArgs arg : cidArgs) { 12782 synchronized (mInstallLock) { 12783 arg.doPostDeleteLI(false); 12784 } 12785 } 12786 } 12787 12788 /* 12789 * Unload packages mounted on external media. This involves deleting package 12790 * data from internal structures, sending broadcasts about diabled packages, 12791 * gc'ing to free up references, unmounting all secure containers 12792 * corresponding to packages on external media, and posting a 12793 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 12794 * that we always have to post this message if status has been requested no 12795 * matter what. 12796 */ 12797 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 12798 final boolean reportStatus) { 12799 if (DEBUG_SD_INSTALL) 12800 Log.i(TAG, "unloading media packages"); 12801 ArrayList<String> pkgList = new ArrayList<String>(); 12802 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 12803 final Set<AsecInstallArgs> keys = processCids.keySet(); 12804 for (AsecInstallArgs args : keys) { 12805 String pkgName = args.getPackageName(); 12806 if (DEBUG_SD_INSTALL) 12807 Log.i(TAG, "Trying to unload pkg : " + pkgName); 12808 // Delete package internally 12809 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 12810 synchronized (mInstallLock) { 12811 boolean res = deletePackageLI(pkgName, null, false, null, null, 12812 PackageManager.DELETE_KEEP_DATA, outInfo, false); 12813 if (res) { 12814 pkgList.add(pkgName); 12815 } else { 12816 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 12817 failedList.add(args); 12818 } 12819 } 12820 } 12821 12822 // reader 12823 synchronized (mPackages) { 12824 // We didn't update the settings after removing each package; 12825 // write them now for all packages. 12826 mSettings.writeLPr(); 12827 } 12828 12829 // We have to absolutely send UPDATED_MEDIA_STATUS only 12830 // after confirming that all the receivers processed the ordered 12831 // broadcast when packages get disabled, force a gc to clean things up. 12832 // and unload all the containers. 12833 if (pkgList.size() > 0) { 12834 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 12835 new IIntentReceiver.Stub() { 12836 public void performReceive(Intent intent, int resultCode, String data, 12837 Bundle extras, boolean ordered, boolean sticky, 12838 int sendingUser) throws RemoteException { 12839 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 12840 reportStatus ? 1 : 0, 1, keys); 12841 mHandler.sendMessage(msg); 12842 } 12843 }); 12844 } else { 12845 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 12846 keys); 12847 mHandler.sendMessage(msg); 12848 } 12849 } 12850 12851 /** Binder call */ 12852 @Override 12853 public void movePackage(final String packageName, final IPackageMoveObserver observer, 12854 final int flags) { 12855 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 12856 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 12857 int returnCode = PackageManager.MOVE_SUCCEEDED; 12858 int currInstallFlags = 0; 12859 int newInstallFlags = 0; 12860 12861 File codeFile = null; 12862 String installerPackageName = null; 12863 String packageAbiOverride = null; 12864 12865 // reader 12866 synchronized (mPackages) { 12867 final PackageParser.Package pkg = mPackages.get(packageName); 12868 final PackageSetting ps = mSettings.mPackages.get(packageName); 12869 if (pkg == null || ps == null) { 12870 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12871 } else { 12872 // Disable moving fwd locked apps and system packages 12873 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 12874 Slog.w(TAG, "Cannot move system application"); 12875 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 12876 } else if (pkg.mOperationPending) { 12877 Slog.w(TAG, "Attempt to move package which has pending operations"); 12878 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 12879 } else { 12880 // Find install location first 12881 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 12882 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 12883 Slog.w(TAG, "Ambigous flags specified for move location."); 12884 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12885 } else { 12886 newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 12887 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 12888 currInstallFlags = isExternal(pkg) 12889 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 12890 12891 if (newInstallFlags == currInstallFlags) { 12892 Slog.w(TAG, "No move required. Trying to move to same location"); 12893 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12894 } else { 12895 if (isForwardLocked(pkg)) { 12896 currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12897 newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12898 } 12899 } 12900 } 12901 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12902 pkg.mOperationPending = true; 12903 } 12904 } 12905 12906 codeFile = new File(pkg.codePath); 12907 installerPackageName = ps.installerPackageName; 12908 packageAbiOverride = ps.cpuAbiOverrideString; 12909 } 12910 } 12911 12912 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 12913 try { 12914 observer.packageMoved(packageName, returnCode); 12915 } catch (RemoteException ignored) { 12916 } 12917 return; 12918 } 12919 12920 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 12921 @Override 12922 public void onUserActionRequired(Intent intent) throws RemoteException { 12923 throw new IllegalStateException(); 12924 } 12925 12926 @Override 12927 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 12928 Bundle extras) throws RemoteException { 12929 Slog.d(TAG, "Install result for move: " 12930 + PackageManager.installStatusToString(returnCode, msg)); 12931 12932 // We usually have a new package now after the install, but if 12933 // we failed we need to clear the pending flag on the original 12934 // package object. 12935 synchronized (mPackages) { 12936 final PackageParser.Package pkg = mPackages.get(packageName); 12937 if (pkg != null) { 12938 pkg.mOperationPending = false; 12939 } 12940 } 12941 12942 final int status = PackageManager.installStatusToPublicStatus(returnCode); 12943 switch (status) { 12944 case PackageInstaller.STATUS_SUCCESS: 12945 observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED); 12946 break; 12947 case PackageInstaller.STATUS_FAILURE_STORAGE: 12948 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 12949 break; 12950 default: 12951 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR); 12952 break; 12953 } 12954 } 12955 }; 12956 12957 // Treat a move like reinstalling an existing app, which ensures that we 12958 // process everythign uniformly, like unpacking native libraries. 12959 newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 12960 12961 final Message msg = mHandler.obtainMessage(INIT_COPY); 12962 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 12963 msg.obj = new InstallParams(origin, installObserver, newInstallFlags, 12964 installerPackageName, null, user, packageAbiOverride); 12965 mHandler.sendMessage(msg); 12966 } 12967 12968 @Override 12969 public boolean setInstallLocation(int loc) { 12970 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 12971 null); 12972 if (getInstallLocation() == loc) { 12973 return true; 12974 } 12975 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 12976 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 12977 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 12978 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 12979 return true; 12980 } 12981 return false; 12982 } 12983 12984 @Override 12985 public int getInstallLocation() { 12986 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12987 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 12988 PackageHelper.APP_INSTALL_AUTO); 12989 } 12990 12991 /** Called by UserManagerService */ 12992 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 12993 mDirtyUsers.remove(userHandle); 12994 mSettings.removeUserLPw(userHandle); 12995 mPendingBroadcasts.remove(userHandle); 12996 if (mInstaller != null) { 12997 // Technically, we shouldn't be doing this with the package lock 12998 // held. However, this is very rare, and there is already so much 12999 // other disk I/O going on, that we'll let it slide for now. 13000 mInstaller.removeUserDataDirs(userHandle); 13001 } 13002 mUserNeedsBadging.delete(userHandle); 13003 removeUnusedPackagesLILPw(userManager, userHandle); 13004 } 13005 13006 /** 13007 * We're removing userHandle and would like to remove any downloaded packages 13008 * that are no longer in use by any other user. 13009 * @param userHandle the user being removed 13010 */ 13011 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 13012 final boolean DEBUG_CLEAN_APKS = false; 13013 int [] users = userManager.getUserIdsLPr(); 13014 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 13015 while (psit.hasNext()) { 13016 PackageSetting ps = psit.next(); 13017 if (ps.pkg == null) { 13018 continue; 13019 } 13020 final String packageName = ps.pkg.packageName; 13021 // Skip over if system app 13022 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 13023 continue; 13024 } 13025 if (DEBUG_CLEAN_APKS) { 13026 Slog.i(TAG, "Checking package " + packageName); 13027 } 13028 boolean keep = false; 13029 for (int i = 0; i < users.length; i++) { 13030 if (users[i] != userHandle && ps.getInstalled(users[i])) { 13031 keep = true; 13032 if (DEBUG_CLEAN_APKS) { 13033 Slog.i(TAG, " Keeping package " + packageName + " for user " 13034 + users[i]); 13035 } 13036 break; 13037 } 13038 } 13039 if (!keep) { 13040 if (DEBUG_CLEAN_APKS) { 13041 Slog.i(TAG, " Removing package " + packageName); 13042 } 13043 mHandler.post(new Runnable() { 13044 public void run() { 13045 deletePackageX(packageName, userHandle, 0); 13046 } //end run 13047 }); 13048 } 13049 } 13050 } 13051 13052 /** Called by UserManagerService */ 13053 void createNewUserLILPw(int userHandle, File path) { 13054 if (mInstaller != null) { 13055 mInstaller.createUserConfig(userHandle); 13056 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 13057 } 13058 } 13059 13060 @Override 13061 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 13062 mContext.enforceCallingOrSelfPermission( 13063 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13064 "Only package verification agents can read the verifier device identity"); 13065 13066 synchronized (mPackages) { 13067 return mSettings.getVerifierDeviceIdentityLPw(); 13068 } 13069 } 13070 13071 @Override 13072 public void setPermissionEnforced(String permission, boolean enforced) { 13073 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 13074 if (READ_EXTERNAL_STORAGE.equals(permission)) { 13075 synchronized (mPackages) { 13076 if (mSettings.mReadExternalStorageEnforced == null 13077 || mSettings.mReadExternalStorageEnforced != enforced) { 13078 mSettings.mReadExternalStorageEnforced = enforced; 13079 mSettings.writeLPr(); 13080 } 13081 } 13082 // kill any non-foreground processes so we restart them and 13083 // grant/revoke the GID. 13084 final IActivityManager am = ActivityManagerNative.getDefault(); 13085 if (am != null) { 13086 final long token = Binder.clearCallingIdentity(); 13087 try { 13088 am.killProcessesBelowForeground("setPermissionEnforcement"); 13089 } catch (RemoteException e) { 13090 } finally { 13091 Binder.restoreCallingIdentity(token); 13092 } 13093 } 13094 } else { 13095 throw new IllegalArgumentException("No selective enforcement for " + permission); 13096 } 13097 } 13098 13099 @Override 13100 @Deprecated 13101 public boolean isPermissionEnforced(String permission) { 13102 return true; 13103 } 13104 13105 @Override 13106 public boolean isStorageLow() { 13107 final long token = Binder.clearCallingIdentity(); 13108 try { 13109 final DeviceStorageMonitorInternal 13110 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13111 if (dsm != null) { 13112 return dsm.isMemoryLow(); 13113 } else { 13114 return false; 13115 } 13116 } finally { 13117 Binder.restoreCallingIdentity(token); 13118 } 13119 } 13120 13121 @Override 13122 public IPackageInstaller getPackageInstaller() { 13123 return mInstallerService; 13124 } 13125 13126 private boolean userNeedsBadging(int userId) { 13127 int index = mUserNeedsBadging.indexOfKey(userId); 13128 if (index < 0) { 13129 final UserInfo userInfo; 13130 final long token = Binder.clearCallingIdentity(); 13131 try { 13132 userInfo = sUserManager.getUserInfo(userId); 13133 } finally { 13134 Binder.restoreCallingIdentity(token); 13135 } 13136 final boolean b; 13137 if (userInfo != null && userInfo.isManagedProfile()) { 13138 b = true; 13139 } else { 13140 b = false; 13141 } 13142 mUserNeedsBadging.put(userId, b); 13143 return b; 13144 } 13145 return mUserNeedsBadging.valueAt(index); 13146 } 13147 13148 @Override 13149 public KeySet getKeySetByAlias(String packageName, String alias) { 13150 if (packageName == null || alias == null) { 13151 return null; 13152 } 13153 synchronized(mPackages) { 13154 final PackageParser.Package pkg = mPackages.get(packageName); 13155 if (pkg == null) { 13156 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13157 throw new IllegalArgumentException("Unknown package: " + packageName); 13158 } 13159 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13160 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 13161 } 13162 } 13163 13164 @Override 13165 public KeySet getSigningKeySet(String packageName) { 13166 if (packageName == null) { 13167 return null; 13168 } 13169 synchronized(mPackages) { 13170 final PackageParser.Package pkg = mPackages.get(packageName); 13171 if (pkg == null) { 13172 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13173 throw new IllegalArgumentException("Unknown package: " + packageName); 13174 } 13175 if (pkg.applicationInfo.uid != Binder.getCallingUid() 13176 && Process.SYSTEM_UID != Binder.getCallingUid()) { 13177 throw new SecurityException("May not access signing KeySet of other apps."); 13178 } 13179 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13180 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 13181 } 13182 } 13183 13184 @Override 13185 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 13186 if (packageName == null || ks == null) { 13187 return false; 13188 } 13189 synchronized(mPackages) { 13190 final PackageParser.Package pkg = mPackages.get(packageName); 13191 if (pkg == null) { 13192 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13193 throw new IllegalArgumentException("Unknown package: " + packageName); 13194 } 13195 IBinder ksh = ks.getToken(); 13196 if (ksh instanceof KeySetHandle) { 13197 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13198 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 13199 } 13200 return false; 13201 } 13202 } 13203 13204 @Override 13205 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 13206 if (packageName == null || ks == null) { 13207 return false; 13208 } 13209 synchronized(mPackages) { 13210 final PackageParser.Package pkg = mPackages.get(packageName); 13211 if (pkg == null) { 13212 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13213 throw new IllegalArgumentException("Unknown package: " + packageName); 13214 } 13215 IBinder ksh = ks.getToken(); 13216 if (ksh instanceof KeySetHandle) { 13217 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13218 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 13219 } 13220 return false; 13221 } 13222 } 13223} 13224