PackageManagerService.java revision 20e0c50f601e5930a246d4556118423a49c12ca1
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 android.system.OsConstants.S_IRGRP; 52import static android.system.OsConstants.S_IROTH; 53import static android.system.OsConstants.S_IRWXU; 54import static android.system.OsConstants.S_IXGRP; 55import static android.system.OsConstants.S_IXOTH; 56import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 57import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 58import static com.android.internal.util.ArrayUtils.appendInt; 59import static com.android.internal.util.ArrayUtils.removeInt; 60 61import android.util.ArrayMap; 62 63import com.android.internal.R; 64import com.android.internal.app.IMediaContainerService; 65import com.android.internal.app.ResolverActivity; 66import com.android.internal.content.NativeLibraryHelper; 67import com.android.internal.content.PackageHelper; 68import com.android.internal.os.IParcelFileDescriptorFactory; 69import com.android.internal.util.ArrayUtils; 70import com.android.internal.util.FastPrintWriter; 71import com.android.internal.util.FastXmlSerializer; 72import com.android.internal.util.IndentingPrintWriter; 73import com.android.internal.util.Preconditions; 74import com.android.server.EventLogTags; 75import com.android.server.IntentResolver; 76import com.android.server.LocalServices; 77import com.android.server.ServiceThread; 78import com.android.server.SystemConfig; 79import com.android.server.Watchdog; 80import com.android.server.pm.Settings.DatabaseVersion; 81import com.android.server.storage.DeviceStorageMonitorInternal; 82 83import org.xmlpull.v1.XmlSerializer; 84 85import android.app.ActivityManager; 86import android.app.ActivityManagerNative; 87import android.app.IActivityManager; 88import android.app.admin.IDevicePolicyManager; 89import android.app.backup.IBackupManager; 90import android.content.BroadcastReceiver; 91import android.content.ComponentName; 92import android.content.Context; 93import android.content.IIntentReceiver; 94import android.content.Intent; 95import android.content.IntentFilter; 96import android.content.IntentSender; 97import android.content.IntentSender.SendIntentException; 98import android.content.ServiceConnection; 99import android.content.pm.ActivityInfo; 100import android.content.pm.ApplicationInfo; 101import android.content.pm.FeatureInfo; 102import android.content.pm.IPackageDataObserver; 103import android.content.pm.IPackageDeleteObserver; 104import android.content.pm.IPackageInstallObserver2; 105import android.content.pm.IPackageInstaller; 106import android.content.pm.IPackageManager; 107import android.content.pm.IPackageMoveObserver; 108import android.content.pm.IPackageStatsObserver; 109import android.content.pm.InstallSessionParams; 110import android.content.pm.InstrumentationInfo; 111import android.content.pm.ManifestDigest; 112import android.content.pm.PackageCleanItem; 113import android.content.pm.PackageInfo; 114import android.content.pm.PackageInfoLite; 115import android.content.pm.PackageManager; 116import android.content.pm.PackageParser.ActivityIntentInfo; 117import android.content.pm.PackageParser.PackageLite; 118import android.content.pm.PackageParser.PackageParserException; 119import android.content.pm.PackageParser; 120import android.content.pm.PackageStats; 121import android.content.pm.PackageUserState; 122import android.content.pm.ParceledListSlice; 123import android.content.pm.PermissionGroupInfo; 124import android.content.pm.PermissionInfo; 125import android.content.pm.ProviderInfo; 126import android.content.pm.ResolveInfo; 127import android.content.pm.ServiceInfo; 128import android.content.pm.Signature; 129import android.content.pm.UserInfo; 130import android.content.pm.VerificationParams; 131import android.content.pm.VerifierDeviceIdentity; 132import android.content.pm.VerifierInfo; 133import android.content.res.Resources; 134import android.hardware.display.DisplayManager; 135import android.net.Uri; 136import android.os.Binder; 137import android.os.Build; 138import android.os.Bundle; 139import android.os.Environment; 140import android.os.Environment.UserEnvironment; 141import android.os.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; 212 213/** 214 * Keep track of all those .apks everywhere. 215 * 216 * This is very central to the platform's security; please run the unit 217 * tests whenever making modifications here: 218 * 219mmm frameworks/base/tests/AndroidTests 220adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 221adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 222 * 223 * {@hide} 224 */ 225public class PackageManagerService extends IPackageManager.Stub { 226 static final String TAG = "PackageManager"; 227 static final boolean DEBUG_SETTINGS = false; 228 static final boolean DEBUG_PREFERRED = false; 229 static final boolean DEBUG_UPGRADE = false; 230 private static final boolean DEBUG_INSTALL = false; 231 private static final boolean DEBUG_REMOVE = false; 232 private static final boolean DEBUG_BROADCASTS = false; 233 private static final boolean DEBUG_SHOW_INFO = false; 234 private static final boolean DEBUG_PACKAGE_INFO = false; 235 private static final boolean DEBUG_INTENT_MATCHING = false; 236 private static final boolean DEBUG_PACKAGE_SCANNING = false; 237 private static final boolean DEBUG_VERIFY = false; 238 private static final boolean DEBUG_DEXOPT = false; 239 private static final boolean DEBUG_ABI_SELECTION = false; 240 241 private static final int RADIO_UID = Process.PHONE_UID; 242 private static final int LOG_UID = Process.LOG_UID; 243 private static final int NFC_UID = Process.NFC_UID; 244 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 245 private static final int SHELL_UID = Process.SHELL_UID; 246 247 // Cap the size of permission trees that 3rd party apps can define 248 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 249 250 // Suffix used during package installation when copying/moving 251 // package apks to install directory. 252 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 253 254 static final int SCAN_MONITOR = 1<<0; 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 266 static final int REMOVE_CHATTY = 1<<16; 267 268 /** 269 * Timeout (in milliseconds) after which the watchdog should declare that 270 * our handler thread is wedged. The usual default for such things is one 271 * minute but we sometimes do very lengthy I/O operations on this thread, 272 * such as installing multi-gigabyte applications, so ours needs to be longer. 273 */ 274 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 275 276 /** 277 * Whether verification is enabled by default. 278 */ 279 private static final boolean DEFAULT_VERIFY_ENABLE = true; 280 281 /** 282 * The default maximum time to wait for the verification agent to return in 283 * milliseconds. 284 */ 285 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 286 287 /** 288 * The default response for package verification timeout. 289 * 290 * This can be either PackageManager.VERIFICATION_ALLOW or 291 * PackageManager.VERIFICATION_REJECT. 292 */ 293 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 294 295 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 296 297 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 298 DEFAULT_CONTAINER_PACKAGE, 299 "com.android.defcontainer.DefaultContainerService"); 300 301 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 302 303 private static final String LIB_DIR_NAME = "lib"; 304 private static final String LIB64_DIR_NAME = "lib64"; 305 306 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 307 308 static final String mTempContainerPrefix = "smdl2tmp"; 309 310 private static String sPreferredInstructionSet; 311 312 final ServiceThread mHandlerThread; 313 314 private static final String IDMAP_PREFIX = "/data/resource-cache/"; 315 private static final String IDMAP_SUFFIX = "@idmap"; 316 317 final PackageHandler mHandler; 318 319 final int mSdkVersion = Build.VERSION.SDK_INT; 320 321 final Context mContext; 322 final boolean mFactoryTest; 323 final boolean mOnlyCore; 324 final DisplayMetrics mMetrics; 325 final int mDefParseFlags; 326 final String[] mSeparateProcesses; 327 328 // This is where all application persistent data goes. 329 final File mAppDataDir; 330 331 // This is where all application persistent data goes for secondary users. 332 final File mUserAppDataDir; 333 334 /** The location for ASEC container files on internal storage. */ 335 final String mAsecInternalPath; 336 337 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 338 // LOCK HELD. Can be called with mInstallLock held. 339 final Installer mInstaller; 340 341 /** Directory where installed third-party apps stored */ 342 final File mAppInstallDir; 343 344 /** 345 * Directory to which applications installed internally have their 346 * 32 bit native libraries copied. 347 */ 348 private File mAppLib32InstallDir; 349 350 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 351 // apps. 352 final File mDrmAppPrivateInstallDir; 353 354 // ---------------------------------------------------------------- 355 356 // Lock for state used when installing and doing other long running 357 // operations. Methods that must be called with this lock held have 358 // the suffix "LI". 359 final Object mInstallLock = new Object(); 360 361 // These are the directories in the 3rd party applications installed dir 362 // that we have currently loaded packages from. Keys are the application's 363 // installed zip file (absolute codePath), and values are Package. 364 final HashMap<String, PackageParser.Package> mAppDirs = 365 new HashMap<String, PackageParser.Package>(); 366 367 // ---------------------------------------------------------------- 368 369 // Keys are String (package name), values are Package. This also serves 370 // as the lock for the global state. Methods that must be called with 371 // this lock held have the prefix "LP". 372 final HashMap<String, PackageParser.Package> mPackages = 373 new HashMap<String, PackageParser.Package>(); 374 375 // Tracks available target package names -> overlay package paths. 376 final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays = 377 new HashMap<String, HashMap<String, PackageParser.Package>>(); 378 379 final Settings mSettings; 380 boolean mRestoredSettings; 381 382 // System configuration read by SystemConfig. 383 final int[] mGlobalGids; 384 final SparseArray<HashSet<String>> mSystemPermissions; 385 final HashMap<String, FeatureInfo> mAvailableFeatures; 386 387 // If mac_permissions.xml was found for seinfo labeling. 388 boolean mFoundPolicyFile; 389 390 // If a recursive restorecon of /data/data/<pkg> is needed. 391 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 392 393 public static final class SharedLibraryEntry { 394 public final String path; 395 public final String apk; 396 397 SharedLibraryEntry(String _path, String _apk) { 398 path = _path; 399 apk = _apk; 400 } 401 } 402 403 // Currently known shared libraries. 404 final HashMap<String, SharedLibraryEntry> mSharedLibraries = 405 new HashMap<String, SharedLibraryEntry>(); 406 407 // All available activities, for your resolving pleasure. 408 final ActivityIntentResolver mActivities = 409 new ActivityIntentResolver(); 410 411 // All available receivers, for your resolving pleasure. 412 final ActivityIntentResolver mReceivers = 413 new ActivityIntentResolver(); 414 415 // All available services, for your resolving pleasure. 416 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 417 418 // All available providers, for your resolving pleasure. 419 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 420 421 // Mapping from provider base names (first directory in content URI codePath) 422 // to the provider information. 423 final HashMap<String, PackageParser.Provider> mProvidersByAuthority = 424 new HashMap<String, PackageParser.Provider>(); 425 426 // Mapping from instrumentation class names to info about them. 427 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 428 new HashMap<ComponentName, PackageParser.Instrumentation>(); 429 430 // Mapping from permission names to info about them. 431 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups = 432 new HashMap<String, PackageParser.PermissionGroup>(); 433 434 // Packages whose data we have transfered into another package, thus 435 // should no longer exist. 436 final HashSet<String> mTransferedPackages = new HashSet<String>(); 437 438 // Broadcast actions that are only available to the system. 439 final HashSet<String> mProtectedBroadcasts = new HashSet<String>(); 440 441 /** List of packages waiting for verification. */ 442 final SparseArray<PackageVerificationState> mPendingVerification 443 = new SparseArray<PackageVerificationState>(); 444 445 /** Set of packages associated with each app op permission. */ 446 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 447 448 final PackageInstallerService mInstallerService; 449 450 HashSet<PackageParser.Package> mDeferredDexOpt = null; 451 452 // Cache of users who need badging. 453 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 454 455 /** Token for keys in mPendingVerification. */ 456 private int mPendingVerificationToken = 0; 457 458 boolean mSystemReady; 459 boolean mSafeMode; 460 boolean mHasSystemUidErrors; 461 462 ApplicationInfo mAndroidApplication; 463 final ActivityInfo mResolveActivity = new ActivityInfo(); 464 final ResolveInfo mResolveInfo = new ResolveInfo(); 465 ComponentName mResolveComponentName; 466 PackageParser.Package mPlatformPackage; 467 ComponentName mCustomResolverComponentName; 468 469 boolean mResolverReplaced = false; 470 471 // Set of pending broadcasts for aggregating enable/disable of components. 472 static class PendingPackageBroadcasts { 473 // for each user id, a map of <package name -> components within that package> 474 final SparseArray<HashMap<String, ArrayList<String>>> mUidMap; 475 476 public PendingPackageBroadcasts() { 477 mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2); 478 } 479 480 public ArrayList<String> get(int userId, String packageName) { 481 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 482 return packages.get(packageName); 483 } 484 485 public void put(int userId, String packageName, ArrayList<String> components) { 486 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 487 packages.put(packageName, components); 488 } 489 490 public void remove(int userId, String packageName) { 491 HashMap<String, ArrayList<String>> packages = mUidMap.get(userId); 492 if (packages != null) { 493 packages.remove(packageName); 494 } 495 } 496 497 public void remove(int userId) { 498 mUidMap.remove(userId); 499 } 500 501 public int userIdCount() { 502 return mUidMap.size(); 503 } 504 505 public int userIdAt(int n) { 506 return mUidMap.keyAt(n); 507 } 508 509 public HashMap<String, ArrayList<String>> packagesForUserId(int userId) { 510 return mUidMap.get(userId); 511 } 512 513 public int size() { 514 // total number of pending broadcast entries across all userIds 515 int num = 0; 516 for (int i = 0; i< mUidMap.size(); i++) { 517 num += mUidMap.valueAt(i).size(); 518 } 519 return num; 520 } 521 522 public void clear() { 523 mUidMap.clear(); 524 } 525 526 private HashMap<String, ArrayList<String>> getOrAllocate(int userId) { 527 HashMap<String, ArrayList<String>> map = mUidMap.get(userId); 528 if (map == null) { 529 map = new HashMap<String, ArrayList<String>>(); 530 mUidMap.put(userId, map); 531 } 532 return map; 533 } 534 } 535 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 536 537 // Service Connection to remote media container service to copy 538 // package uri's from external media onto secure containers 539 // or internal storage. 540 private IMediaContainerService mContainerService = null; 541 542 static final int SEND_PENDING_BROADCAST = 1; 543 static final int MCS_BOUND = 3; 544 static final int END_COPY = 4; 545 static final int INIT_COPY = 5; 546 static final int MCS_UNBIND = 6; 547 static final int START_CLEANING_PACKAGE = 7; 548 static final int FIND_INSTALL_LOC = 8; 549 static final int POST_INSTALL = 9; 550 static final int MCS_RECONNECT = 10; 551 static final int MCS_GIVE_UP = 11; 552 static final int UPDATED_MEDIA_STATUS = 12; 553 static final int WRITE_SETTINGS = 13; 554 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 555 static final int PACKAGE_VERIFIED = 15; 556 static final int CHECK_PENDING_VERIFICATION = 16; 557 558 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 559 560 // Delay time in millisecs 561 static final int BROADCAST_DELAY = 10 * 1000; 562 563 static UserManagerService sUserManager; 564 565 // Stores a list of users whose package restrictions file needs to be updated 566 private HashSet<Integer> mDirtyUsers = new HashSet<Integer>(); 567 568 final private DefaultContainerConnection mDefContainerConn = 569 new DefaultContainerConnection(); 570 class DefaultContainerConnection implements ServiceConnection { 571 public void onServiceConnected(ComponentName name, IBinder service) { 572 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 573 IMediaContainerService imcs = 574 IMediaContainerService.Stub.asInterface(service); 575 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 576 } 577 578 public void onServiceDisconnected(ComponentName name) { 579 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 580 } 581 }; 582 583 // Recordkeeping of restore-after-install operations that are currently in flight 584 // between the Package Manager and the Backup Manager 585 class PostInstallData { 586 public InstallArgs args; 587 public PackageInstalledInfo res; 588 589 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 590 args = _a; 591 res = _r; 592 } 593 }; 594 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 595 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 596 597 private final String mRequiredVerifierPackage; 598 599 private final PackageUsage mPackageUsage = new PackageUsage(); 600 601 private class PackageUsage { 602 private static final int WRITE_INTERVAL 603 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 604 605 private final Object mFileLock = new Object(); 606 private final AtomicLong mLastWritten = new AtomicLong(0); 607 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 608 609 private boolean mIsHistoricalPackageUsageAvailable = true; 610 611 boolean isHistoricalPackageUsageAvailable() { 612 return mIsHistoricalPackageUsageAvailable; 613 } 614 615 void write(boolean force) { 616 if (force) { 617 writeInternal(); 618 return; 619 } 620 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 621 && !DEBUG_DEXOPT) { 622 return; 623 } 624 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 625 new Thread("PackageUsage_DiskWriter") { 626 @Override 627 public void run() { 628 try { 629 writeInternal(); 630 } finally { 631 mBackgroundWriteRunning.set(false); 632 } 633 } 634 }.start(); 635 } 636 } 637 638 private void writeInternal() { 639 synchronized (mPackages) { 640 synchronized (mFileLock) { 641 AtomicFile file = getFile(); 642 FileOutputStream f = null; 643 try { 644 f = file.startWrite(); 645 BufferedOutputStream out = new BufferedOutputStream(f); 646 FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID); 647 StringBuilder sb = new StringBuilder(); 648 for (PackageParser.Package pkg : mPackages.values()) { 649 if (pkg.mLastPackageUsageTimeInMills == 0) { 650 continue; 651 } 652 sb.setLength(0); 653 sb.append(pkg.packageName); 654 sb.append(' '); 655 sb.append((long)pkg.mLastPackageUsageTimeInMills); 656 sb.append('\n'); 657 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 658 } 659 out.flush(); 660 file.finishWrite(f); 661 } catch (IOException e) { 662 if (f != null) { 663 file.failWrite(f); 664 } 665 Log.e(TAG, "Failed to write package usage times", e); 666 } 667 } 668 } 669 mLastWritten.set(SystemClock.elapsedRealtime()); 670 } 671 672 void readLP() { 673 synchronized (mFileLock) { 674 AtomicFile file = getFile(); 675 BufferedInputStream in = null; 676 try { 677 in = new BufferedInputStream(file.openRead()); 678 StringBuffer sb = new StringBuffer(); 679 while (true) { 680 String packageName = readToken(in, sb, ' '); 681 if (packageName == null) { 682 break; 683 } 684 String timeInMillisString = readToken(in, sb, '\n'); 685 if (timeInMillisString == null) { 686 throw new IOException("Failed to find last usage time for package " 687 + packageName); 688 } 689 PackageParser.Package pkg = mPackages.get(packageName); 690 if (pkg == null) { 691 continue; 692 } 693 long timeInMillis; 694 try { 695 timeInMillis = Long.parseLong(timeInMillisString.toString()); 696 } catch (NumberFormatException e) { 697 throw new IOException("Failed to parse " + timeInMillisString 698 + " as a long.", e); 699 } 700 pkg.mLastPackageUsageTimeInMills = timeInMillis; 701 } 702 } catch (FileNotFoundException expected) { 703 mIsHistoricalPackageUsageAvailable = false; 704 } catch (IOException e) { 705 Log.w(TAG, "Failed to read package usage times", e); 706 } finally { 707 IoUtils.closeQuietly(in); 708 } 709 } 710 mLastWritten.set(SystemClock.elapsedRealtime()); 711 } 712 713 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 714 throws IOException { 715 sb.setLength(0); 716 while (true) { 717 int ch = in.read(); 718 if (ch == -1) { 719 if (sb.length() == 0) { 720 return null; 721 } 722 throw new IOException("Unexpected EOF"); 723 } 724 if (ch == endOfToken) { 725 return sb.toString(); 726 } 727 sb.append((char)ch); 728 } 729 } 730 731 private AtomicFile getFile() { 732 File dataDir = Environment.getDataDirectory(); 733 File systemDir = new File(dataDir, "system"); 734 File fname = new File(systemDir, "package-usage.list"); 735 return new AtomicFile(fname); 736 } 737 } 738 739 class PackageHandler extends Handler { 740 private boolean mBound = false; 741 final ArrayList<HandlerParams> mPendingInstalls = 742 new ArrayList<HandlerParams>(); 743 744 private boolean connectToService() { 745 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 746 " DefaultContainerService"); 747 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 748 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 749 if (mContext.bindServiceAsUser(service, mDefContainerConn, 750 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 751 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 752 mBound = true; 753 return true; 754 } 755 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 756 return false; 757 } 758 759 private void disconnectService() { 760 mContainerService = null; 761 mBound = false; 762 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 763 mContext.unbindService(mDefContainerConn); 764 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 765 } 766 767 PackageHandler(Looper looper) { 768 super(looper); 769 } 770 771 public void handleMessage(Message msg) { 772 try { 773 doHandleMessage(msg); 774 } finally { 775 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 776 } 777 } 778 779 void doHandleMessage(Message msg) { 780 switch (msg.what) { 781 case INIT_COPY: { 782 HandlerParams params = (HandlerParams) msg.obj; 783 int idx = mPendingInstalls.size(); 784 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 785 // If a bind was already initiated we dont really 786 // need to do anything. The pending install 787 // will be processed later on. 788 if (!mBound) { 789 // If this is the only one pending we might 790 // have to bind to the service again. 791 if (!connectToService()) { 792 Slog.e(TAG, "Failed to bind to media container service"); 793 params.serviceError(); 794 return; 795 } else { 796 // Once we bind to the service, the first 797 // pending request will be processed. 798 mPendingInstalls.add(idx, params); 799 } 800 } else { 801 mPendingInstalls.add(idx, params); 802 // Already bound to the service. Just make 803 // sure we trigger off processing the first request. 804 if (idx == 0) { 805 mHandler.sendEmptyMessage(MCS_BOUND); 806 } 807 } 808 break; 809 } 810 case MCS_BOUND: { 811 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 812 if (msg.obj != null) { 813 mContainerService = (IMediaContainerService) msg.obj; 814 } 815 if (mContainerService == null) { 816 // Something seriously wrong. Bail out 817 Slog.e(TAG, "Cannot bind to media container service"); 818 for (HandlerParams params : mPendingInstalls) { 819 // Indicate service bind error 820 params.serviceError(); 821 } 822 mPendingInstalls.clear(); 823 } else if (mPendingInstalls.size() > 0) { 824 HandlerParams params = mPendingInstalls.get(0); 825 if (params != null) { 826 if (params.startCopy()) { 827 // We are done... look for more work or to 828 // go idle. 829 if (DEBUG_SD_INSTALL) Log.i(TAG, 830 "Checking for more work or unbind..."); 831 // Delete pending install 832 if (mPendingInstalls.size() > 0) { 833 mPendingInstalls.remove(0); 834 } 835 if (mPendingInstalls.size() == 0) { 836 if (mBound) { 837 if (DEBUG_SD_INSTALL) Log.i(TAG, 838 "Posting delayed MCS_UNBIND"); 839 removeMessages(MCS_UNBIND); 840 Message ubmsg = obtainMessage(MCS_UNBIND); 841 // Unbind after a little delay, to avoid 842 // continual thrashing. 843 sendMessageDelayed(ubmsg, 10000); 844 } 845 } else { 846 // There are more pending requests in queue. 847 // Just post MCS_BOUND message to trigger processing 848 // of next pending install. 849 if (DEBUG_SD_INSTALL) Log.i(TAG, 850 "Posting MCS_BOUND for next work"); 851 mHandler.sendEmptyMessage(MCS_BOUND); 852 } 853 } 854 } 855 } else { 856 // Should never happen ideally. 857 Slog.w(TAG, "Empty queue"); 858 } 859 break; 860 } 861 case MCS_RECONNECT: { 862 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 863 if (mPendingInstalls.size() > 0) { 864 if (mBound) { 865 disconnectService(); 866 } 867 if (!connectToService()) { 868 Slog.e(TAG, "Failed to bind to media container service"); 869 for (HandlerParams params : mPendingInstalls) { 870 // Indicate service bind error 871 params.serviceError(); 872 } 873 mPendingInstalls.clear(); 874 } 875 } 876 break; 877 } 878 case MCS_UNBIND: { 879 // If there is no actual work left, then time to unbind. 880 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 881 882 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 883 if (mBound) { 884 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 885 886 disconnectService(); 887 } 888 } else if (mPendingInstalls.size() > 0) { 889 // There are more pending requests in queue. 890 // Just post MCS_BOUND message to trigger processing 891 // of next pending install. 892 mHandler.sendEmptyMessage(MCS_BOUND); 893 } 894 895 break; 896 } 897 case MCS_GIVE_UP: { 898 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 899 mPendingInstalls.remove(0); 900 break; 901 } 902 case SEND_PENDING_BROADCAST: { 903 String packages[]; 904 ArrayList<String> components[]; 905 int size = 0; 906 int uids[]; 907 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 908 synchronized (mPackages) { 909 if (mPendingBroadcasts == null) { 910 return; 911 } 912 size = mPendingBroadcasts.size(); 913 if (size <= 0) { 914 // Nothing to be done. Just return 915 return; 916 } 917 packages = new String[size]; 918 components = new ArrayList[size]; 919 uids = new int[size]; 920 int i = 0; // filling out the above arrays 921 922 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 923 int packageUserId = mPendingBroadcasts.userIdAt(n); 924 Iterator<Map.Entry<String, ArrayList<String>>> it 925 = mPendingBroadcasts.packagesForUserId(packageUserId) 926 .entrySet().iterator(); 927 while (it.hasNext() && i < size) { 928 Map.Entry<String, ArrayList<String>> ent = it.next(); 929 packages[i] = ent.getKey(); 930 components[i] = ent.getValue(); 931 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 932 uids[i] = (ps != null) 933 ? UserHandle.getUid(packageUserId, ps.appId) 934 : -1; 935 i++; 936 } 937 } 938 size = i; 939 mPendingBroadcasts.clear(); 940 } 941 // Send broadcasts 942 for (int i = 0; i < size; i++) { 943 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 944 } 945 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 946 break; 947 } 948 case START_CLEANING_PACKAGE: { 949 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 950 final String packageName = (String)msg.obj; 951 final int userId = msg.arg1; 952 final boolean andCode = msg.arg2 != 0; 953 synchronized (mPackages) { 954 if (userId == UserHandle.USER_ALL) { 955 int[] users = sUserManager.getUserIds(); 956 for (int user : users) { 957 mSettings.addPackageToCleanLPw( 958 new PackageCleanItem(user, packageName, andCode)); 959 } 960 } else { 961 mSettings.addPackageToCleanLPw( 962 new PackageCleanItem(userId, packageName, andCode)); 963 } 964 } 965 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 966 startCleaningPackages(); 967 } break; 968 case POST_INSTALL: { 969 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 970 PostInstallData data = mRunningInstalls.get(msg.arg1); 971 mRunningInstalls.delete(msg.arg1); 972 boolean deleteOld = false; 973 974 if (data != null) { 975 InstallArgs args = data.args; 976 PackageInstalledInfo res = data.res; 977 978 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 979 res.removedInfo.sendBroadcast(false, true, false); 980 Bundle extras = new Bundle(1); 981 extras.putInt(Intent.EXTRA_UID, res.uid); 982 // Determine the set of users who are adding this 983 // package for the first time vs. those who are seeing 984 // an update. 985 int[] firstUsers; 986 int[] updateUsers = new int[0]; 987 if (res.origUsers == null || res.origUsers.length == 0) { 988 firstUsers = res.newUsers; 989 } else { 990 firstUsers = new int[0]; 991 for (int i=0; i<res.newUsers.length; i++) { 992 int user = res.newUsers[i]; 993 boolean isNew = true; 994 for (int j=0; j<res.origUsers.length; j++) { 995 if (res.origUsers[j] == user) { 996 isNew = false; 997 break; 998 } 999 } 1000 if (isNew) { 1001 int[] newFirst = new int[firstUsers.length+1]; 1002 System.arraycopy(firstUsers, 0, newFirst, 0, 1003 firstUsers.length); 1004 newFirst[firstUsers.length] = user; 1005 firstUsers = newFirst; 1006 } else { 1007 int[] newUpdate = new int[updateUsers.length+1]; 1008 System.arraycopy(updateUsers, 0, newUpdate, 0, 1009 updateUsers.length); 1010 newUpdate[updateUsers.length] = user; 1011 updateUsers = newUpdate; 1012 } 1013 } 1014 } 1015 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1016 res.pkg.applicationInfo.packageName, 1017 extras, null, null, firstUsers); 1018 final boolean update = res.removedInfo.removedPackage != null; 1019 if (update) { 1020 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1021 } 1022 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1023 res.pkg.applicationInfo.packageName, 1024 extras, null, null, updateUsers); 1025 if (update) { 1026 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1027 res.pkg.applicationInfo.packageName, 1028 extras, null, null, updateUsers); 1029 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1030 null, null, 1031 res.pkg.applicationInfo.packageName, null, updateUsers); 1032 1033 // treat asec-hosted packages like removable media on upgrade 1034 if (isForwardLocked(res.pkg) || isExternal(res.pkg)) { 1035 if (DEBUG_INSTALL) { 1036 Slog.i(TAG, "upgrading pkg " + res.pkg 1037 + " is ASEC-hosted -> AVAILABLE"); 1038 } 1039 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1040 ArrayList<String> pkgList = new ArrayList<String>(1); 1041 pkgList.add(res.pkg.applicationInfo.packageName); 1042 sendResourcesChangedBroadcast(true, true, 1043 pkgList,uidArray, null); 1044 } 1045 } 1046 if (res.removedInfo.args != null) { 1047 // Remove the replaced package's older resources safely now 1048 deleteOld = true; 1049 } 1050 1051 // Log current value of "unknown sources" setting 1052 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1053 getUnknownSourcesSettings()); 1054 } 1055 // Force a gc to clear up things 1056 Runtime.getRuntime().gc(); 1057 // We delete after a gc for applications on sdcard. 1058 if (deleteOld) { 1059 synchronized (mInstallLock) { 1060 res.removedInfo.args.doPostDeleteLI(true); 1061 } 1062 } 1063 if (args.observer != null) { 1064 try { 1065 Bundle extras = extrasForInstallResult(res); 1066 args.observer.packageInstalled(res.name, extras, res.returnCode, 1067 res.returnMsg); 1068 } catch (RemoteException e) { 1069 Slog.i(TAG, "Observer no longer exists."); 1070 } 1071 } 1072 } else { 1073 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1074 } 1075 } break; 1076 case UPDATED_MEDIA_STATUS: { 1077 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1078 boolean reportStatus = msg.arg1 == 1; 1079 boolean doGc = msg.arg2 == 1; 1080 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1081 if (doGc) { 1082 // Force a gc to clear up stale containers. 1083 Runtime.getRuntime().gc(); 1084 } 1085 if (msg.obj != null) { 1086 @SuppressWarnings("unchecked") 1087 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1088 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1089 // Unload containers 1090 unloadAllContainers(args); 1091 } 1092 if (reportStatus) { 1093 try { 1094 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1095 PackageHelper.getMountService().finishMediaUpdate(); 1096 } catch (RemoteException e) { 1097 Log.e(TAG, "MountService not running?"); 1098 } 1099 } 1100 } break; 1101 case WRITE_SETTINGS: { 1102 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1103 synchronized (mPackages) { 1104 removeMessages(WRITE_SETTINGS); 1105 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1106 mSettings.writeLPr(); 1107 mDirtyUsers.clear(); 1108 } 1109 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1110 } break; 1111 case WRITE_PACKAGE_RESTRICTIONS: { 1112 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1113 synchronized (mPackages) { 1114 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1115 for (int userId : mDirtyUsers) { 1116 mSettings.writePackageRestrictionsLPr(userId); 1117 } 1118 mDirtyUsers.clear(); 1119 } 1120 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1121 } break; 1122 case CHECK_PENDING_VERIFICATION: { 1123 final int verificationId = msg.arg1; 1124 final PackageVerificationState state = mPendingVerification.get(verificationId); 1125 1126 if ((state != null) && !state.timeoutExtended()) { 1127 final InstallArgs args = state.getInstallArgs(); 1128 final Uri originUri = Uri.fromFile(args.originFile); 1129 1130 Slog.i(TAG, "Verification timed out for " + originUri); 1131 mPendingVerification.remove(verificationId); 1132 1133 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1134 1135 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1136 Slog.i(TAG, "Continuing with installation of " + originUri); 1137 state.setVerifierResponse(Binder.getCallingUid(), 1138 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1139 broadcastPackageVerified(verificationId, originUri, 1140 PackageManager.VERIFICATION_ALLOW, 1141 state.getInstallArgs().getUser()); 1142 try { 1143 ret = args.copyApk(mContainerService, true); 1144 } catch (RemoteException e) { 1145 Slog.e(TAG, "Could not contact the ContainerService"); 1146 } 1147 } else { 1148 broadcastPackageVerified(verificationId, originUri, 1149 PackageManager.VERIFICATION_REJECT, 1150 state.getInstallArgs().getUser()); 1151 } 1152 1153 processPendingInstall(args, ret); 1154 mHandler.sendEmptyMessage(MCS_UNBIND); 1155 } 1156 break; 1157 } 1158 case PACKAGE_VERIFIED: { 1159 final int verificationId = msg.arg1; 1160 1161 final PackageVerificationState state = mPendingVerification.get(verificationId); 1162 if (state == null) { 1163 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1164 break; 1165 } 1166 1167 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1168 1169 state.setVerifierResponse(response.callerUid, response.code); 1170 1171 if (state.isVerificationComplete()) { 1172 mPendingVerification.remove(verificationId); 1173 1174 final InstallArgs args = state.getInstallArgs(); 1175 final Uri originUri = Uri.fromFile(args.originFile); 1176 1177 int ret; 1178 if (state.isInstallAllowed()) { 1179 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1180 broadcastPackageVerified(verificationId, originUri, 1181 response.code, state.getInstallArgs().getUser()); 1182 try { 1183 ret = args.copyApk(mContainerService, true); 1184 } catch (RemoteException e) { 1185 Slog.e(TAG, "Could not contact the ContainerService"); 1186 } 1187 } else { 1188 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1189 } 1190 1191 processPendingInstall(args, ret); 1192 1193 mHandler.sendEmptyMessage(MCS_UNBIND); 1194 } 1195 1196 break; 1197 } 1198 } 1199 } 1200 } 1201 1202 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1203 Bundle extras = null; 1204 switch (res.returnCode) { 1205 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1206 extras = new Bundle(); 1207 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1208 res.origPermission); 1209 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1210 res.origPackage); 1211 break; 1212 } 1213 } 1214 return extras; 1215 } 1216 1217 void scheduleWriteSettingsLocked() { 1218 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1219 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1220 } 1221 } 1222 1223 void scheduleWritePackageRestrictionsLocked(int userId) { 1224 if (!sUserManager.exists(userId)) return; 1225 mDirtyUsers.add(userId); 1226 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1227 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1228 } 1229 } 1230 1231 public static final PackageManagerService main(Context context, Installer installer, 1232 boolean factoryTest, boolean onlyCore) { 1233 PackageManagerService m = new PackageManagerService(context, installer, 1234 factoryTest, onlyCore); 1235 ServiceManager.addService("package", m); 1236 return m; 1237 } 1238 1239 static String[] splitString(String str, char sep) { 1240 int count = 1; 1241 int i = 0; 1242 while ((i=str.indexOf(sep, i)) >= 0) { 1243 count++; 1244 i++; 1245 } 1246 1247 String[] res = new String[count]; 1248 i=0; 1249 count = 0; 1250 int lastI=0; 1251 while ((i=str.indexOf(sep, i)) >= 0) { 1252 res[count] = str.substring(lastI, i); 1253 count++; 1254 i++; 1255 lastI = i; 1256 } 1257 res[count] = str.substring(lastI, str.length()); 1258 return res; 1259 } 1260 1261 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1262 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1263 Context.DISPLAY_SERVICE); 1264 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1265 } 1266 1267 public PackageManagerService(Context context, Installer installer, 1268 boolean factoryTest, boolean onlyCore) { 1269 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1270 SystemClock.uptimeMillis()); 1271 1272 if (mSdkVersion <= 0) { 1273 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1274 } 1275 1276 mContext = context; 1277 mFactoryTest = factoryTest; 1278 mOnlyCore = onlyCore; 1279 mMetrics = new DisplayMetrics(); 1280 mSettings = new Settings(context); 1281 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1282 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1283 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1284 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1285 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1286 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1287 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1288 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1289 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1290 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1291 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1292 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1293 1294 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1295 if (separateProcesses != null && separateProcesses.length() > 0) { 1296 if ("*".equals(separateProcesses)) { 1297 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1298 mSeparateProcesses = null; 1299 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1300 } else { 1301 mDefParseFlags = 0; 1302 mSeparateProcesses = separateProcesses.split(","); 1303 Slog.w(TAG, "Running with debug.separate_processes: " 1304 + separateProcesses); 1305 } 1306 } else { 1307 mDefParseFlags = 0; 1308 mSeparateProcesses = null; 1309 } 1310 1311 mInstaller = installer; 1312 1313 getDefaultDisplayMetrics(context, mMetrics); 1314 1315 SystemConfig systemConfig = SystemConfig.getInstance(); 1316 mGlobalGids = systemConfig.getGlobalGids(); 1317 mSystemPermissions = systemConfig.getSystemPermissions(); 1318 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1319 1320 synchronized (mInstallLock) { 1321 // writer 1322 synchronized (mPackages) { 1323 mHandlerThread = new ServiceThread(TAG, 1324 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1325 mHandlerThread.start(); 1326 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1327 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1328 1329 File dataDir = Environment.getDataDirectory(); 1330 mAppDataDir = new File(dataDir, "data"); 1331 mAppInstallDir = new File(dataDir, "app"); 1332 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1333 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1334 mUserAppDataDir = new File(dataDir, "user"); 1335 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1336 1337 sUserManager = new UserManagerService(context, this, 1338 mInstallLock, mPackages); 1339 1340 // Propagate permission configuration in to package manager. 1341 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1342 = systemConfig.getPermissions(); 1343 for (int i=0; i<permConfig.size(); i++) { 1344 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1345 BasePermission bp = mSettings.mPermissions.get(perm.name); 1346 if (bp == null) { 1347 bp = new BasePermission(perm.name, null, BasePermission.TYPE_BUILTIN); 1348 mSettings.mPermissions.put(perm.name, bp); 1349 } 1350 if (perm.gids != null) { 1351 bp.gids = appendInts(bp.gids, perm.gids); 1352 } 1353 } 1354 1355 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1356 for (int i=0; i<libConfig.size(); i++) { 1357 mSharedLibraries.put(libConfig.keyAt(i), 1358 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1359 } 1360 1361 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1362 1363 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1364 mSdkVersion, mOnlyCore); 1365 1366 String customResolverActivity = Resources.getSystem().getString( 1367 R.string.config_customResolverActivity); 1368 if (TextUtils.isEmpty(customResolverActivity)) { 1369 customResolverActivity = null; 1370 } else { 1371 mCustomResolverComponentName = ComponentName.unflattenFromString( 1372 customResolverActivity); 1373 } 1374 1375 long startTime = SystemClock.uptimeMillis(); 1376 1377 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1378 startTime); 1379 1380 // Set flag to monitor and not change apk file paths when 1381 // scanning install directories. 1382 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1383 1384 final HashSet<String> alreadyDexOpted = new HashSet<String>(); 1385 1386 /** 1387 * Add everything in the in the boot class path to the 1388 * list of process files because dexopt will have been run 1389 * if necessary during zygote startup. 1390 */ 1391 String bootClassPath = System.getProperty("java.boot.class.path"); 1392 if (bootClassPath != null) { 1393 String[] paths = splitString(bootClassPath, ':'); 1394 for (int i=0; i<paths.length; i++) { 1395 alreadyDexOpted.add(paths[i]); 1396 } 1397 } else { 1398 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1399 } 1400 1401 boolean didDexOptLibraryOrTool = false; 1402 1403 final List<String> instructionSets = getAllInstructionSets(); 1404 1405 /** 1406 * Ensure all external libraries have had dexopt run on them. 1407 */ 1408 if (mSharedLibraries.size() > 0) { 1409 // NOTE: For now, we're compiling these system "shared libraries" 1410 // (and framework jars) into all available architectures. It's possible 1411 // to compile them only when we come across an app that uses them (there's 1412 // already logic for that in scanPackageLI) but that adds some complexity. 1413 for (String instructionSet : instructionSets) { 1414 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1415 final String lib = libEntry.path; 1416 if (lib == null) { 1417 continue; 1418 } 1419 1420 try { 1421 if (DexFile.isDexOptNeededInternal(lib, null, instructionSet, false)) { 1422 alreadyDexOpted.add(lib); 1423 1424 // The list of "shared libraries" we have at this point is 1425 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, instructionSet); 1426 didDexOptLibraryOrTool = true; 1427 } 1428 } catch (FileNotFoundException e) { 1429 Slog.w(TAG, "Library not found: " + lib); 1430 } catch (IOException e) { 1431 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1432 + e.getMessage()); 1433 } 1434 } 1435 } 1436 } 1437 1438 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1439 1440 // Gross hack for now: we know this file doesn't contain any 1441 // code, so don't dexopt it to avoid the resulting log spew. 1442 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1443 1444 // Gross hack for now: we know this file is only part of 1445 // the boot class path for art, so don't dexopt it to 1446 // avoid the resulting log spew. 1447 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1448 1449 /** 1450 * And there are a number of commands implemented in Java, which 1451 * we currently need to do the dexopt on so that they can be 1452 * run from a non-root shell. 1453 */ 1454 String[] frameworkFiles = frameworkDir.list(); 1455 if (frameworkFiles != null) { 1456 // TODO: We could compile these only for the most preferred ABI. We should 1457 // first double check that the dex files for these commands are not referenced 1458 // by other system apps. 1459 for (String instructionSet : instructionSets) { 1460 for (int i=0; i<frameworkFiles.length; i++) { 1461 File libPath = new File(frameworkDir, frameworkFiles[i]); 1462 String path = libPath.getPath(); 1463 // Skip the file if we already did it. 1464 if (alreadyDexOpted.contains(path)) { 1465 continue; 1466 } 1467 // Skip the file if it is not a type we want to dexopt. 1468 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1469 continue; 1470 } 1471 try { 1472 if (DexFile.isDexOptNeededInternal(path, null, instructionSet, false)) { 1473 mInstaller.dexopt(path, Process.SYSTEM_UID, true, instructionSet); 1474 didDexOptLibraryOrTool = true; 1475 } 1476 } catch (FileNotFoundException e) { 1477 Slog.w(TAG, "Jar not found: " + path); 1478 } catch (IOException e) { 1479 Slog.w(TAG, "Exception reading jar: " + path, e); 1480 } 1481 } 1482 } 1483 } 1484 1485 if (didDexOptLibraryOrTool) { 1486 // If we dexopted a library or tool, then something on the system has 1487 // changed. Consider this significant, and wipe away all other 1488 // existing dexopt files to ensure we don't leave any dangling around. 1489 // 1490 // TODO: This should be revisited because it isn't as good an indicator 1491 // as it used to be. It used to include the boot classpath but at some point 1492 // DexFile.isDexOptNeeded started returning false for the boot 1493 // class path files in all cases. It is very possible in a 1494 // small maintenance release update that the library and tool 1495 // jars may be unchanged but APK could be removed resulting in 1496 // unused dalvik-cache files. 1497 for (String instructionSet : instructionSets) { 1498 mInstaller.pruneDexCache(instructionSet); 1499 } 1500 1501 // Additionally, delete all dex files from the root directory 1502 // since there shouldn't be any there anyway, unless we're upgrading 1503 // from an older OS version or a build that contained the "old" style 1504 // flat scheme. 1505 mInstaller.pruneDexCache("."); 1506 } 1507 1508 // Collect vendor overlay packages. 1509 // (Do this before scanning any apps.) 1510 // For security and version matching reason, only consider 1511 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1512 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1513 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1514 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode | SCAN_TRUSTED_OVERLAY, 0); 1515 1516 // Find base frameworks (resource packages without code). 1517 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1518 | PackageParser.PARSE_IS_SYSTEM_DIR 1519 | PackageParser.PARSE_IS_PRIVILEGED, 1520 scanMode | SCAN_NO_DEX, 0); 1521 1522 // Collected privileged system packages. 1523 File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1524 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1525 | PackageParser.PARSE_IS_SYSTEM_DIR 1526 | PackageParser.PARSE_IS_PRIVILEGED, scanMode, 0); 1527 1528 // Collect ordinary system packages. 1529 File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1530 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1531 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1532 1533 // Collect all vendor packages. 1534 File vendorAppDir = new File("/vendor/app"); 1535 try { 1536 vendorAppDir = vendorAppDir.getCanonicalFile(); 1537 } catch (IOException e) { 1538 // failed to look up canonical path, continue with original one 1539 } 1540 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1541 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1542 1543 // Collect all OEM packages. 1544 File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1545 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1546 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1547 1548 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1549 mInstaller.moveFiles(); 1550 1551 // Prune any system packages that no longer exist. 1552 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1553 if (!mOnlyCore) { 1554 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1555 while (psit.hasNext()) { 1556 PackageSetting ps = psit.next(); 1557 1558 /* 1559 * If this is not a system app, it can't be a 1560 * disable system app. 1561 */ 1562 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1563 continue; 1564 } 1565 1566 /* 1567 * If the package is scanned, it's not erased. 1568 */ 1569 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1570 if (scannedPkg != null) { 1571 /* 1572 * If the system app is both scanned and in the 1573 * disabled packages list, then it must have been 1574 * added via OTA. Remove it from the currently 1575 * scanned package so the previously user-installed 1576 * application can be scanned. 1577 */ 1578 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1579 Slog.i(TAG, "Expecting better updatd system app for " + ps.name 1580 + "; removing system app"); 1581 removePackageLI(ps, true); 1582 } 1583 1584 continue; 1585 } 1586 1587 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1588 psit.remove(); 1589 String msg = "System package " + ps.name 1590 + " no longer exists; wiping its data"; 1591 reportSettingsProblem(Log.WARN, msg); 1592 removeDataDirsLI(ps.name); 1593 } else { 1594 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1595 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1596 possiblyDeletedUpdatedSystemApps.add(ps.name); 1597 } 1598 } 1599 } 1600 } 1601 1602 //look for any incomplete package installations 1603 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1604 //clean up list 1605 for(int i = 0; i < deletePkgsList.size(); i++) { 1606 //clean up here 1607 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1608 } 1609 //delete tmp files 1610 deleteTempPackageFiles(); 1611 1612 // Remove any shared userIDs that have no associated packages 1613 mSettings.pruneSharedUsersLPw(); 1614 1615 if (!mOnlyCore) { 1616 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 1617 SystemClock.uptimeMillis()); 1618 scanDirLI(mAppInstallDir, 0, scanMode, 0); 1619 1620 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 1621 scanMode, 0); 1622 1623 /** 1624 * Remove disable package settings for any updated system 1625 * apps that were removed via an OTA. If they're not a 1626 * previously-updated app, remove them completely. 1627 * Otherwise, just revoke their system-level permissions. 1628 */ 1629 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 1630 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 1631 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 1632 1633 String msg; 1634 if (deletedPkg == null) { 1635 msg = "Updated system package " + deletedAppName 1636 + " no longer exists; wiping its data"; 1637 removeDataDirsLI(deletedAppName); 1638 } else { 1639 msg = "Updated system app + " + deletedAppName 1640 + " no longer present; removing system privileges for " 1641 + deletedAppName; 1642 1643 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 1644 1645 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 1646 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 1647 } 1648 reportSettingsProblem(Log.WARN, msg); 1649 } 1650 } 1651 1652 // Now that we know all of the shared libraries, update all clients to have 1653 // the correct library paths. 1654 updateAllSharedLibrariesLPw(); 1655 1656 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 1657 // NOTE: We ignore potential failures here during a system scan (like 1658 // the rest of the commands above) because there's precious little we 1659 // can do about it. A settings error is reported, though. 1660 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 1661 false /* force dexopt */, false /* defer dexopt */); 1662 } 1663 1664 // Now that we know all the packages we are keeping, 1665 // read and update their last usage times. 1666 mPackageUsage.readLP(); 1667 1668 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 1669 SystemClock.uptimeMillis()); 1670 Slog.i(TAG, "Time to scan packages: " 1671 + ((SystemClock.uptimeMillis()-startTime)/1000f) 1672 + " seconds"); 1673 1674 // If the platform SDK has changed since the last time we booted, 1675 // we need to re-grant app permission to catch any new ones that 1676 // appear. This is really a hack, and means that apps can in some 1677 // cases get permissions that the user didn't initially explicitly 1678 // allow... it would be nice to have some better way to handle 1679 // this situation. 1680 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 1681 != mSdkVersion; 1682 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 1683 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 1684 + "; regranting permissions for internal storage"); 1685 mSettings.mInternalSdkPlatform = mSdkVersion; 1686 1687 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 1688 | (regrantPermissions 1689 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 1690 : 0)); 1691 1692 // If this is the first boot, and it is a normal boot, then 1693 // we need to initialize the default preferred apps. 1694 if (!mRestoredSettings && !onlyCore) { 1695 mSettings.readDefaultPreferredAppsLPw(this, 0); 1696 } 1697 1698 // If this is first boot after an OTA, and a normal boot, then 1699 // we need to clear code cache directories. 1700 if (!Build.FINGERPRINT.equals(mSettings.mFingerprint) && !onlyCore) { 1701 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 1702 for (String pkgName : mSettings.mPackages.keySet()) { 1703 deleteCodeCacheDirsLI(pkgName); 1704 } 1705 mSettings.mFingerprint = Build.FINGERPRINT; 1706 } 1707 1708 // All the changes are done during package scanning. 1709 mSettings.updateInternalDatabaseVersion(); 1710 1711 // can downgrade to reader 1712 mSettings.writeLPr(); 1713 1714 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 1715 SystemClock.uptimeMillis()); 1716 1717 1718 mRequiredVerifierPackage = getRequiredVerifierLPr(); 1719 } // synchronized (mPackages) 1720 } // synchronized (mInstallLock) 1721 1722 mInstallerService = new PackageInstallerService(context, this, mAppInstallDir); 1723 1724 // Now after opening every single application zip, make sure they 1725 // are all flushed. Not really needed, but keeps things nice and 1726 // tidy. 1727 Runtime.getRuntime().gc(); 1728 } 1729 1730 @Override 1731 public boolean isFirstBoot() { 1732 return !mRestoredSettings; 1733 } 1734 1735 @Override 1736 public boolean isOnlyCoreApps() { 1737 return mOnlyCore; 1738 } 1739 1740 private String getRequiredVerifierLPr() { 1741 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 1742 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 1743 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 1744 1745 String requiredVerifier = null; 1746 1747 final int N = receivers.size(); 1748 for (int i = 0; i < N; i++) { 1749 final ResolveInfo info = receivers.get(i); 1750 1751 if (info.activityInfo == null) { 1752 continue; 1753 } 1754 1755 final String packageName = info.activityInfo.packageName; 1756 1757 final PackageSetting ps = mSettings.mPackages.get(packageName); 1758 if (ps == null) { 1759 continue; 1760 } 1761 1762 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1763 if (!gp.grantedPermissions 1764 .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) { 1765 continue; 1766 } 1767 1768 if (requiredVerifier != null) { 1769 throw new RuntimeException("There can be only one required verifier"); 1770 } 1771 1772 requiredVerifier = packageName; 1773 } 1774 1775 return requiredVerifier; 1776 } 1777 1778 @Override 1779 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 1780 throws RemoteException { 1781 try { 1782 return super.onTransact(code, data, reply, flags); 1783 } catch (RuntimeException e) { 1784 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 1785 Slog.wtf(TAG, "Package Manager Crash", e); 1786 } 1787 throw e; 1788 } 1789 } 1790 1791 void cleanupInstallFailedPackage(PackageSetting ps) { 1792 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name); 1793 removeDataDirsLI(ps.name); 1794 1795 // TODO: try cleaning up codePath directory contents first, since it 1796 // might be a cluster 1797 1798 if (ps.codePath != null) { 1799 if (!ps.codePath.delete()) { 1800 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath); 1801 } 1802 } 1803 if (ps.resourcePath != null) { 1804 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) { 1805 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath); 1806 } 1807 } 1808 mSettings.removePackageLPw(ps.name); 1809 } 1810 1811 static int[] appendInts(int[] cur, int[] add) { 1812 if (add == null) return cur; 1813 if (cur == null) return add; 1814 final int N = add.length; 1815 for (int i=0; i<N; i++) { 1816 cur = appendInt(cur, add[i]); 1817 } 1818 return cur; 1819 } 1820 1821 static int[] removeInts(int[] cur, int[] rem) { 1822 if (rem == null) return cur; 1823 if (cur == null) return cur; 1824 final int N = rem.length; 1825 for (int i=0; i<N; i++) { 1826 cur = removeInt(cur, rem[i]); 1827 } 1828 return cur; 1829 } 1830 1831 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 1832 if (!sUserManager.exists(userId)) return null; 1833 final PackageSetting ps = (PackageSetting) p.mExtras; 1834 if (ps == null) { 1835 return null; 1836 } 1837 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1838 final PackageUserState state = ps.readUserState(userId); 1839 return PackageParser.generatePackageInfo(p, gp.gids, flags, 1840 ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions, 1841 state, userId); 1842 } 1843 1844 @Override 1845 public boolean isPackageAvailable(String packageName, int userId) { 1846 if (!sUserManager.exists(userId)) return false; 1847 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available"); 1848 synchronized (mPackages) { 1849 PackageParser.Package p = mPackages.get(packageName); 1850 if (p != null) { 1851 final PackageSetting ps = (PackageSetting) p.mExtras; 1852 if (ps != null) { 1853 final PackageUserState state = ps.readUserState(userId); 1854 if (state != null) { 1855 return PackageParser.isAvailable(state); 1856 } 1857 } 1858 } 1859 } 1860 return false; 1861 } 1862 1863 @Override 1864 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 1865 if (!sUserManager.exists(userId)) return null; 1866 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info"); 1867 // reader 1868 synchronized (mPackages) { 1869 PackageParser.Package p = mPackages.get(packageName); 1870 if (DEBUG_PACKAGE_INFO) 1871 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 1872 if (p != null) { 1873 return generatePackageInfo(p, flags, userId); 1874 } 1875 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 1876 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 1877 } 1878 } 1879 return null; 1880 } 1881 1882 @Override 1883 public String[] currentToCanonicalPackageNames(String[] names) { 1884 String[] out = new String[names.length]; 1885 // reader 1886 synchronized (mPackages) { 1887 for (int i=names.length-1; i>=0; i--) { 1888 PackageSetting ps = mSettings.mPackages.get(names[i]); 1889 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 1890 } 1891 } 1892 return out; 1893 } 1894 1895 @Override 1896 public String[] canonicalToCurrentPackageNames(String[] names) { 1897 String[] out = new String[names.length]; 1898 // reader 1899 synchronized (mPackages) { 1900 for (int i=names.length-1; i>=0; i--) { 1901 String cur = mSettings.mRenamedPackages.get(names[i]); 1902 out[i] = cur != null ? cur : names[i]; 1903 } 1904 } 1905 return out; 1906 } 1907 1908 @Override 1909 public int getPackageUid(String packageName, int userId) { 1910 if (!sUserManager.exists(userId)) return -1; 1911 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid"); 1912 // reader 1913 synchronized (mPackages) { 1914 PackageParser.Package p = mPackages.get(packageName); 1915 if(p != null) { 1916 return UserHandle.getUid(userId, p.applicationInfo.uid); 1917 } 1918 PackageSetting ps = mSettings.mPackages.get(packageName); 1919 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 1920 return -1; 1921 } 1922 p = ps.pkg; 1923 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 1924 } 1925 } 1926 1927 @Override 1928 public int[] getPackageGids(String packageName) { 1929 // reader 1930 synchronized (mPackages) { 1931 PackageParser.Package p = mPackages.get(packageName); 1932 if (DEBUG_PACKAGE_INFO) 1933 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 1934 if (p != null) { 1935 final PackageSetting ps = (PackageSetting)p.mExtras; 1936 return ps.getGids(); 1937 } 1938 } 1939 // stupid thing to indicate an error. 1940 return new int[0]; 1941 } 1942 1943 static final PermissionInfo generatePermissionInfo( 1944 BasePermission bp, int flags) { 1945 if (bp.perm != null) { 1946 return PackageParser.generatePermissionInfo(bp.perm, flags); 1947 } 1948 PermissionInfo pi = new PermissionInfo(); 1949 pi.name = bp.name; 1950 pi.packageName = bp.sourcePackage; 1951 pi.nonLocalizedLabel = bp.name; 1952 pi.protectionLevel = bp.protectionLevel; 1953 return pi; 1954 } 1955 1956 @Override 1957 public PermissionInfo getPermissionInfo(String name, int flags) { 1958 // reader 1959 synchronized (mPackages) { 1960 final BasePermission p = mSettings.mPermissions.get(name); 1961 if (p != null) { 1962 return generatePermissionInfo(p, flags); 1963 } 1964 return null; 1965 } 1966 } 1967 1968 @Override 1969 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 1970 // reader 1971 synchronized (mPackages) { 1972 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 1973 for (BasePermission p : mSettings.mPermissions.values()) { 1974 if (group == null) { 1975 if (p.perm == null || p.perm.info.group == null) { 1976 out.add(generatePermissionInfo(p, flags)); 1977 } 1978 } else { 1979 if (p.perm != null && group.equals(p.perm.info.group)) { 1980 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 1981 } 1982 } 1983 } 1984 1985 if (out.size() > 0) { 1986 return out; 1987 } 1988 return mPermissionGroups.containsKey(group) ? out : null; 1989 } 1990 } 1991 1992 @Override 1993 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 1994 // reader 1995 synchronized (mPackages) { 1996 return PackageParser.generatePermissionGroupInfo( 1997 mPermissionGroups.get(name), flags); 1998 } 1999 } 2000 2001 @Override 2002 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2003 // reader 2004 synchronized (mPackages) { 2005 final int N = mPermissionGroups.size(); 2006 ArrayList<PermissionGroupInfo> out 2007 = new ArrayList<PermissionGroupInfo>(N); 2008 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2009 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2010 } 2011 return out; 2012 } 2013 } 2014 2015 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2016 int userId) { 2017 if (!sUserManager.exists(userId)) return null; 2018 PackageSetting ps = mSettings.mPackages.get(packageName); 2019 if (ps != null) { 2020 if (ps.pkg == null) { 2021 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2022 flags, userId); 2023 if (pInfo != null) { 2024 return pInfo.applicationInfo; 2025 } 2026 return null; 2027 } 2028 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2029 ps.readUserState(userId), userId); 2030 } 2031 return null; 2032 } 2033 2034 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2035 int userId) { 2036 if (!sUserManager.exists(userId)) return null; 2037 PackageSetting ps = mSettings.mPackages.get(packageName); 2038 if (ps != null) { 2039 PackageParser.Package pkg = ps.pkg; 2040 if (pkg == null) { 2041 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2042 return null; 2043 } 2044 // Only data remains, so we aren't worried about code paths 2045 pkg = new PackageParser.Package(packageName); 2046 pkg.applicationInfo.packageName = packageName; 2047 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2048 pkg.applicationInfo.dataDir = 2049 getDataPathForPackage(packageName, 0).getPath(); 2050 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2051 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2052 } 2053 return generatePackageInfo(pkg, flags, userId); 2054 } 2055 return null; 2056 } 2057 2058 @Override 2059 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2060 if (!sUserManager.exists(userId)) return null; 2061 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info"); 2062 // writer 2063 synchronized (mPackages) { 2064 PackageParser.Package p = mPackages.get(packageName); 2065 if (DEBUG_PACKAGE_INFO) Log.v( 2066 TAG, "getApplicationInfo " + packageName 2067 + ": " + p); 2068 if (p != null) { 2069 PackageSetting ps = mSettings.mPackages.get(packageName); 2070 if (ps == null) return null; 2071 // Note: isEnabledLP() does not apply here - always return info 2072 return PackageParser.generateApplicationInfo( 2073 p, flags, ps.readUserState(userId), userId); 2074 } 2075 if ("android".equals(packageName)||"system".equals(packageName)) { 2076 return mAndroidApplication; 2077 } 2078 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2079 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2080 } 2081 } 2082 return null; 2083 } 2084 2085 2086 @Override 2087 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2088 mContext.enforceCallingOrSelfPermission( 2089 android.Manifest.permission.CLEAR_APP_CACHE, null); 2090 // Queue up an async operation since clearing cache may take a little while. 2091 mHandler.post(new Runnable() { 2092 public void run() { 2093 mHandler.removeCallbacks(this); 2094 int retCode = -1; 2095 synchronized (mInstallLock) { 2096 retCode = mInstaller.freeCache(freeStorageSize); 2097 if (retCode < 0) { 2098 Slog.w(TAG, "Couldn't clear application caches"); 2099 } 2100 } 2101 if (observer != null) { 2102 try { 2103 observer.onRemoveCompleted(null, (retCode >= 0)); 2104 } catch (RemoteException e) { 2105 Slog.w(TAG, "RemoveException when invoking call back"); 2106 } 2107 } 2108 } 2109 }); 2110 } 2111 2112 @Override 2113 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2114 mContext.enforceCallingOrSelfPermission( 2115 android.Manifest.permission.CLEAR_APP_CACHE, null); 2116 // Queue up an async operation since clearing cache may take a little while. 2117 mHandler.post(new Runnable() { 2118 public void run() { 2119 mHandler.removeCallbacks(this); 2120 int retCode = -1; 2121 synchronized (mInstallLock) { 2122 retCode = mInstaller.freeCache(freeStorageSize); 2123 if (retCode < 0) { 2124 Slog.w(TAG, "Couldn't clear application caches"); 2125 } 2126 } 2127 if(pi != null) { 2128 try { 2129 // Callback via pending intent 2130 int code = (retCode >= 0) ? 1 : 0; 2131 pi.sendIntent(null, code, null, 2132 null, null); 2133 } catch (SendIntentException e1) { 2134 Slog.i(TAG, "Failed to send pending intent"); 2135 } 2136 } 2137 } 2138 }); 2139 } 2140 2141 void freeStorage(long freeStorageSize) throws IOException { 2142 synchronized (mInstallLock) { 2143 if (mInstaller.freeCache(freeStorageSize) < 0) { 2144 throw new IOException("Failed to free enough space"); 2145 } 2146 } 2147 } 2148 2149 @Override 2150 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2151 if (!sUserManager.exists(userId)) return null; 2152 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info"); 2153 synchronized (mPackages) { 2154 PackageParser.Activity a = mActivities.mActivities.get(component); 2155 2156 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2157 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2158 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2159 if (ps == null) return null; 2160 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2161 userId); 2162 } 2163 if (mResolveComponentName.equals(component)) { 2164 return mResolveActivity; 2165 } 2166 } 2167 return null; 2168 } 2169 2170 @Override 2171 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2172 String resolvedType) { 2173 synchronized (mPackages) { 2174 PackageParser.Activity a = mActivities.mActivities.get(component); 2175 if (a == null) { 2176 return false; 2177 } 2178 for (int i=0; i<a.intents.size(); i++) { 2179 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2180 intent.getData(), intent.getCategories(), TAG) >= 0) { 2181 return true; 2182 } 2183 } 2184 return false; 2185 } 2186 } 2187 2188 @Override 2189 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2190 if (!sUserManager.exists(userId)) return null; 2191 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info"); 2192 synchronized (mPackages) { 2193 PackageParser.Activity a = mReceivers.mActivities.get(component); 2194 if (DEBUG_PACKAGE_INFO) Log.v( 2195 TAG, "getReceiverInfo " + component + ": " + a); 2196 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2197 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2198 if (ps == null) return null; 2199 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2200 userId); 2201 } 2202 } 2203 return null; 2204 } 2205 2206 @Override 2207 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2208 if (!sUserManager.exists(userId)) return null; 2209 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info"); 2210 synchronized (mPackages) { 2211 PackageParser.Service s = mServices.mServices.get(component); 2212 if (DEBUG_PACKAGE_INFO) Log.v( 2213 TAG, "getServiceInfo " + component + ": " + s); 2214 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2215 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2216 if (ps == null) return null; 2217 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2218 userId); 2219 } 2220 } 2221 return null; 2222 } 2223 2224 @Override 2225 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2226 if (!sUserManager.exists(userId)) return null; 2227 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info"); 2228 synchronized (mPackages) { 2229 PackageParser.Provider p = mProviders.mProviders.get(component); 2230 if (DEBUG_PACKAGE_INFO) Log.v( 2231 TAG, "getProviderInfo " + component + ": " + p); 2232 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2233 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2234 if (ps == null) return null; 2235 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2236 userId); 2237 } 2238 } 2239 return null; 2240 } 2241 2242 @Override 2243 public String[] getSystemSharedLibraryNames() { 2244 Set<String> libSet; 2245 synchronized (mPackages) { 2246 libSet = mSharedLibraries.keySet(); 2247 int size = libSet.size(); 2248 if (size > 0) { 2249 String[] libs = new String[size]; 2250 libSet.toArray(libs); 2251 return libs; 2252 } 2253 } 2254 return null; 2255 } 2256 2257 @Override 2258 public FeatureInfo[] getSystemAvailableFeatures() { 2259 Collection<FeatureInfo> featSet; 2260 synchronized (mPackages) { 2261 featSet = mAvailableFeatures.values(); 2262 int size = featSet.size(); 2263 if (size > 0) { 2264 FeatureInfo[] features = new FeatureInfo[size+1]; 2265 featSet.toArray(features); 2266 FeatureInfo fi = new FeatureInfo(); 2267 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2268 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2269 features[size] = fi; 2270 return features; 2271 } 2272 } 2273 return null; 2274 } 2275 2276 @Override 2277 public boolean hasSystemFeature(String name) { 2278 synchronized (mPackages) { 2279 return mAvailableFeatures.containsKey(name); 2280 } 2281 } 2282 2283 private void checkValidCaller(int uid, int userId) { 2284 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2285 return; 2286 2287 throw new SecurityException("Caller uid=" + uid 2288 + " is not privileged to communicate with user=" + userId); 2289 } 2290 2291 @Override 2292 public int checkPermission(String permName, String pkgName) { 2293 synchronized (mPackages) { 2294 PackageParser.Package p = mPackages.get(pkgName); 2295 if (p != null && p.mExtras != null) { 2296 PackageSetting ps = (PackageSetting)p.mExtras; 2297 if (ps.sharedUser != null) { 2298 if (ps.sharedUser.grantedPermissions.contains(permName)) { 2299 return PackageManager.PERMISSION_GRANTED; 2300 } 2301 } else if (ps.grantedPermissions.contains(permName)) { 2302 return PackageManager.PERMISSION_GRANTED; 2303 } 2304 } 2305 } 2306 return PackageManager.PERMISSION_DENIED; 2307 } 2308 2309 @Override 2310 public int checkUidPermission(String permName, int uid) { 2311 synchronized (mPackages) { 2312 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2313 if (obj != null) { 2314 GrantedPermissions gp = (GrantedPermissions)obj; 2315 if (gp.grantedPermissions.contains(permName)) { 2316 return PackageManager.PERMISSION_GRANTED; 2317 } 2318 } else { 2319 HashSet<String> perms = mSystemPermissions.get(uid); 2320 if (perms != null && perms.contains(permName)) { 2321 return PackageManager.PERMISSION_GRANTED; 2322 } 2323 } 2324 } 2325 return PackageManager.PERMISSION_DENIED; 2326 } 2327 2328 /** 2329 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2330 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2331 * @param message the message to log on security exception 2332 */ 2333 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2334 String message) { 2335 if (userId < 0) { 2336 throw new IllegalArgumentException("Invalid userId " + userId); 2337 } 2338 if (userId == UserHandle.getUserId(callingUid)) return; 2339 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2340 if (requireFullPermission) { 2341 mContext.enforceCallingOrSelfPermission( 2342 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2343 } else { 2344 try { 2345 mContext.enforceCallingOrSelfPermission( 2346 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2347 } catch (SecurityException se) { 2348 mContext.enforceCallingOrSelfPermission( 2349 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2350 } 2351 } 2352 } 2353 } 2354 2355 private BasePermission findPermissionTreeLP(String permName) { 2356 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2357 if (permName.startsWith(bp.name) && 2358 permName.length() > bp.name.length() && 2359 permName.charAt(bp.name.length()) == '.') { 2360 return bp; 2361 } 2362 } 2363 return null; 2364 } 2365 2366 private BasePermission checkPermissionTreeLP(String permName) { 2367 if (permName != null) { 2368 BasePermission bp = findPermissionTreeLP(permName); 2369 if (bp != null) { 2370 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2371 return bp; 2372 } 2373 throw new SecurityException("Calling uid " 2374 + Binder.getCallingUid() 2375 + " is not allowed to add to permission tree " 2376 + bp.name + " owned by uid " + bp.uid); 2377 } 2378 } 2379 throw new SecurityException("No permission tree found for " + permName); 2380 } 2381 2382 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2383 if (s1 == null) { 2384 return s2 == null; 2385 } 2386 if (s2 == null) { 2387 return false; 2388 } 2389 if (s1.getClass() != s2.getClass()) { 2390 return false; 2391 } 2392 return s1.equals(s2); 2393 } 2394 2395 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2396 if (pi1.icon != pi2.icon) return false; 2397 if (pi1.logo != pi2.logo) return false; 2398 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2399 if (!compareStrings(pi1.name, pi2.name)) return false; 2400 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2401 // We'll take care of setting this one. 2402 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2403 // These are not currently stored in settings. 2404 //if (!compareStrings(pi1.group, pi2.group)) return false; 2405 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2406 //if (pi1.labelRes != pi2.labelRes) return false; 2407 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2408 return true; 2409 } 2410 2411 int permissionInfoFootprint(PermissionInfo info) { 2412 int size = info.name.length(); 2413 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2414 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2415 return size; 2416 } 2417 2418 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2419 int size = 0; 2420 for (BasePermission perm : mSettings.mPermissions.values()) { 2421 if (perm.uid == tree.uid) { 2422 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2423 } 2424 } 2425 return size; 2426 } 2427 2428 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2429 // We calculate the max size of permissions defined by this uid and throw 2430 // if that plus the size of 'info' would exceed our stated maximum. 2431 if (tree.uid != Process.SYSTEM_UID) { 2432 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2433 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2434 throw new SecurityException("Permission tree size cap exceeded"); 2435 } 2436 } 2437 } 2438 2439 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2440 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2441 throw new SecurityException("Label must be specified in permission"); 2442 } 2443 BasePermission tree = checkPermissionTreeLP(info.name); 2444 BasePermission bp = mSettings.mPermissions.get(info.name); 2445 boolean added = bp == null; 2446 boolean changed = true; 2447 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2448 if (added) { 2449 enforcePermissionCapLocked(info, tree); 2450 bp = new BasePermission(info.name, tree.sourcePackage, 2451 BasePermission.TYPE_DYNAMIC); 2452 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2453 throw new SecurityException( 2454 "Not allowed to modify non-dynamic permission " 2455 + info.name); 2456 } else { 2457 if (bp.protectionLevel == fixedLevel 2458 && bp.perm.owner.equals(tree.perm.owner) 2459 && bp.uid == tree.uid 2460 && comparePermissionInfos(bp.perm.info, info)) { 2461 changed = false; 2462 } 2463 } 2464 bp.protectionLevel = fixedLevel; 2465 info = new PermissionInfo(info); 2466 info.protectionLevel = fixedLevel; 2467 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 2468 bp.perm.info.packageName = tree.perm.info.packageName; 2469 bp.uid = tree.uid; 2470 if (added) { 2471 mSettings.mPermissions.put(info.name, bp); 2472 } 2473 if (changed) { 2474 if (!async) { 2475 mSettings.writeLPr(); 2476 } else { 2477 scheduleWriteSettingsLocked(); 2478 } 2479 } 2480 return added; 2481 } 2482 2483 @Override 2484 public boolean addPermission(PermissionInfo info) { 2485 synchronized (mPackages) { 2486 return addPermissionLocked(info, false); 2487 } 2488 } 2489 2490 @Override 2491 public boolean addPermissionAsync(PermissionInfo info) { 2492 synchronized (mPackages) { 2493 return addPermissionLocked(info, true); 2494 } 2495 } 2496 2497 @Override 2498 public void removePermission(String name) { 2499 synchronized (mPackages) { 2500 checkPermissionTreeLP(name); 2501 BasePermission bp = mSettings.mPermissions.get(name); 2502 if (bp != null) { 2503 if (bp.type != BasePermission.TYPE_DYNAMIC) { 2504 throw new SecurityException( 2505 "Not allowed to modify non-dynamic permission " 2506 + name); 2507 } 2508 mSettings.mPermissions.remove(name); 2509 mSettings.writeLPr(); 2510 } 2511 } 2512 } 2513 2514 private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) { 2515 int index = pkg.requestedPermissions.indexOf(bp.name); 2516 if (index == -1) { 2517 throw new SecurityException("Package " + pkg.packageName 2518 + " has not requested permission " + bp.name); 2519 } 2520 boolean isNormal = 2521 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2522 == PermissionInfo.PROTECTION_NORMAL); 2523 boolean isDangerous = 2524 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2525 == PermissionInfo.PROTECTION_DANGEROUS); 2526 boolean isDevelopment = 2527 ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0); 2528 2529 if (!isNormal && !isDangerous && !isDevelopment) { 2530 throw new SecurityException("Permission " + bp.name 2531 + " is not a changeable permission type"); 2532 } 2533 2534 if (isNormal || isDangerous) { 2535 if (pkg.requestedPermissionsRequired.get(index)) { 2536 throw new SecurityException("Can't change " + bp.name 2537 + ". It is required by the application"); 2538 } 2539 } 2540 } 2541 2542 @Override 2543 public void grantPermission(String packageName, String permissionName) { 2544 mContext.enforceCallingOrSelfPermission( 2545 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2546 synchronized (mPackages) { 2547 final PackageParser.Package pkg = mPackages.get(packageName); 2548 if (pkg == null) { 2549 throw new IllegalArgumentException("Unknown package: " + packageName); 2550 } 2551 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2552 if (bp == null) { 2553 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2554 } 2555 2556 checkGrantRevokePermissions(pkg, bp); 2557 2558 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2559 if (ps == null) { 2560 return; 2561 } 2562 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2563 if (gp.grantedPermissions.add(permissionName)) { 2564 if (ps.haveGids) { 2565 gp.gids = appendInts(gp.gids, bp.gids); 2566 } 2567 mSettings.writeLPr(); 2568 } 2569 } 2570 } 2571 2572 @Override 2573 public void revokePermission(String packageName, String permissionName) { 2574 int changedAppId = -1; 2575 2576 synchronized (mPackages) { 2577 final PackageParser.Package pkg = mPackages.get(packageName); 2578 if (pkg == null) { 2579 throw new IllegalArgumentException("Unknown package: " + packageName); 2580 } 2581 if (pkg.applicationInfo.uid != Binder.getCallingUid()) { 2582 mContext.enforceCallingOrSelfPermission( 2583 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2584 } 2585 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2586 if (bp == null) { 2587 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2588 } 2589 2590 checkGrantRevokePermissions(pkg, bp); 2591 2592 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2593 if (ps == null) { 2594 return; 2595 } 2596 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2597 if (gp.grantedPermissions.remove(permissionName)) { 2598 gp.grantedPermissions.remove(permissionName); 2599 if (ps.haveGids) { 2600 gp.gids = removeInts(gp.gids, bp.gids); 2601 } 2602 mSettings.writeLPr(); 2603 changedAppId = ps.appId; 2604 } 2605 } 2606 2607 if (changedAppId >= 0) { 2608 // We changed the perm on someone, kill its processes. 2609 IActivityManager am = ActivityManagerNative.getDefault(); 2610 if (am != null) { 2611 final int callingUserId = UserHandle.getCallingUserId(); 2612 final long ident = Binder.clearCallingIdentity(); 2613 try { 2614 //XXX we should only revoke for the calling user's app permissions, 2615 // but for now we impact all users. 2616 //am.killUid(UserHandle.getUid(callingUserId, changedAppId), 2617 // "revoke " + permissionName); 2618 int[] users = sUserManager.getUserIds(); 2619 for (int user : users) { 2620 am.killUid(UserHandle.getUid(user, changedAppId), 2621 "revoke " + permissionName); 2622 } 2623 } catch (RemoteException e) { 2624 } finally { 2625 Binder.restoreCallingIdentity(ident); 2626 } 2627 } 2628 } 2629 } 2630 2631 @Override 2632 public boolean isProtectedBroadcast(String actionName) { 2633 synchronized (mPackages) { 2634 return mProtectedBroadcasts.contains(actionName); 2635 } 2636 } 2637 2638 @Override 2639 public int checkSignatures(String pkg1, String pkg2) { 2640 synchronized (mPackages) { 2641 final PackageParser.Package p1 = mPackages.get(pkg1); 2642 final PackageParser.Package p2 = mPackages.get(pkg2); 2643 if (p1 == null || p1.mExtras == null 2644 || p2 == null || p2.mExtras == null) { 2645 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2646 } 2647 return compareSignatures(p1.mSignatures, p2.mSignatures); 2648 } 2649 } 2650 2651 @Override 2652 public int checkUidSignatures(int uid1, int uid2) { 2653 // Map to base uids. 2654 uid1 = UserHandle.getAppId(uid1); 2655 uid2 = UserHandle.getAppId(uid2); 2656 // reader 2657 synchronized (mPackages) { 2658 Signature[] s1; 2659 Signature[] s2; 2660 Object obj = mSettings.getUserIdLPr(uid1); 2661 if (obj != null) { 2662 if (obj instanceof SharedUserSetting) { 2663 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 2664 } else if (obj instanceof PackageSetting) { 2665 s1 = ((PackageSetting)obj).signatures.mSignatures; 2666 } else { 2667 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2668 } 2669 } else { 2670 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2671 } 2672 obj = mSettings.getUserIdLPr(uid2); 2673 if (obj != null) { 2674 if (obj instanceof SharedUserSetting) { 2675 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 2676 } else if (obj instanceof PackageSetting) { 2677 s2 = ((PackageSetting)obj).signatures.mSignatures; 2678 } else { 2679 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2680 } 2681 } else { 2682 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2683 } 2684 return compareSignatures(s1, s2); 2685 } 2686 } 2687 2688 /** 2689 * Compares two sets of signatures. Returns: 2690 * <br /> 2691 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 2692 * <br /> 2693 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 2694 * <br /> 2695 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 2696 * <br /> 2697 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 2698 * <br /> 2699 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 2700 */ 2701 static int compareSignatures(Signature[] s1, Signature[] s2) { 2702 if (s1 == null) { 2703 return s2 == null 2704 ? PackageManager.SIGNATURE_NEITHER_SIGNED 2705 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 2706 } 2707 2708 if (s2 == null) { 2709 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 2710 } 2711 2712 if (s1.length != s2.length) { 2713 return PackageManager.SIGNATURE_NO_MATCH; 2714 } 2715 2716 // Since both signature sets are of size 1, we can compare without HashSets. 2717 if (s1.length == 1) { 2718 return s1[0].equals(s2[0]) ? 2719 PackageManager.SIGNATURE_MATCH : 2720 PackageManager.SIGNATURE_NO_MATCH; 2721 } 2722 2723 HashSet<Signature> set1 = new HashSet<Signature>(); 2724 for (Signature sig : s1) { 2725 set1.add(sig); 2726 } 2727 HashSet<Signature> set2 = new HashSet<Signature>(); 2728 for (Signature sig : s2) { 2729 set2.add(sig); 2730 } 2731 // Make sure s2 contains all signatures in s1. 2732 if (set1.equals(set2)) { 2733 return PackageManager.SIGNATURE_MATCH; 2734 } 2735 return PackageManager.SIGNATURE_NO_MATCH; 2736 } 2737 2738 /** 2739 * If the database version for this type of package (internal storage or 2740 * external storage) is less than the version where package signatures 2741 * were updated, return true. 2742 */ 2743 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2744 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 2745 DatabaseVersion.SIGNATURE_END_ENTITY)) 2746 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 2747 DatabaseVersion.SIGNATURE_END_ENTITY)); 2748 } 2749 2750 /** 2751 * Used for backward compatibility to make sure any packages with 2752 * certificate chains get upgraded to the new style. {@code existingSigs} 2753 * will be in the old format (since they were stored on disk from before the 2754 * system upgrade) and {@code scannedSigs} will be in the newer format. 2755 */ 2756 private int compareSignaturesCompat(PackageSignatures existingSigs, 2757 PackageParser.Package scannedPkg) { 2758 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 2759 return PackageManager.SIGNATURE_NO_MATCH; 2760 } 2761 2762 HashSet<Signature> existingSet = new HashSet<Signature>(); 2763 for (Signature sig : existingSigs.mSignatures) { 2764 existingSet.add(sig); 2765 } 2766 HashSet<Signature> scannedCompatSet = new HashSet<Signature>(); 2767 for (Signature sig : scannedPkg.mSignatures) { 2768 try { 2769 Signature[] chainSignatures = sig.getChainSignatures(); 2770 for (Signature chainSig : chainSignatures) { 2771 scannedCompatSet.add(chainSig); 2772 } 2773 } catch (CertificateEncodingException e) { 2774 scannedCompatSet.add(sig); 2775 } 2776 } 2777 /* 2778 * Make sure the expanded scanned set contains all signatures in the 2779 * existing one. 2780 */ 2781 if (scannedCompatSet.equals(existingSet)) { 2782 // Migrate the old signatures to the new scheme. 2783 existingSigs.assignSignatures(scannedPkg.mSignatures); 2784 // The new KeySets will be re-added later in the scanning process. 2785 synchronized (mPackages) { 2786 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 2787 } 2788 return PackageManager.SIGNATURE_MATCH; 2789 } 2790 return PackageManager.SIGNATURE_NO_MATCH; 2791 } 2792 2793 @Override 2794 public String[] getPackagesForUid(int uid) { 2795 uid = UserHandle.getAppId(uid); 2796 // reader 2797 synchronized (mPackages) { 2798 Object obj = mSettings.getUserIdLPr(uid); 2799 if (obj instanceof SharedUserSetting) { 2800 final SharedUserSetting sus = (SharedUserSetting) obj; 2801 final int N = sus.packages.size(); 2802 final String[] res = new String[N]; 2803 final Iterator<PackageSetting> it = sus.packages.iterator(); 2804 int i = 0; 2805 while (it.hasNext()) { 2806 res[i++] = it.next().name; 2807 } 2808 return res; 2809 } else if (obj instanceof PackageSetting) { 2810 final PackageSetting ps = (PackageSetting) obj; 2811 return new String[] { ps.name }; 2812 } 2813 } 2814 return null; 2815 } 2816 2817 @Override 2818 public String getNameForUid(int uid) { 2819 // reader 2820 synchronized (mPackages) { 2821 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2822 if (obj instanceof SharedUserSetting) { 2823 final SharedUserSetting sus = (SharedUserSetting) obj; 2824 return sus.name + ":" + sus.userId; 2825 } else if (obj instanceof PackageSetting) { 2826 final PackageSetting ps = (PackageSetting) obj; 2827 return ps.name; 2828 } 2829 } 2830 return null; 2831 } 2832 2833 @Override 2834 public int getUidForSharedUser(String sharedUserName) { 2835 if(sharedUserName == null) { 2836 return -1; 2837 } 2838 // reader 2839 synchronized (mPackages) { 2840 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false); 2841 if (suid == null) { 2842 return -1; 2843 } 2844 return suid.userId; 2845 } 2846 } 2847 2848 @Override 2849 public int getFlagsForUid(int uid) { 2850 synchronized (mPackages) { 2851 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2852 if (obj instanceof SharedUserSetting) { 2853 final SharedUserSetting sus = (SharedUserSetting) obj; 2854 return sus.pkgFlags; 2855 } else if (obj instanceof PackageSetting) { 2856 final PackageSetting ps = (PackageSetting) obj; 2857 return ps.pkgFlags; 2858 } 2859 } 2860 return 0; 2861 } 2862 2863 @Override 2864 public String[] getAppOpPermissionPackages(String permissionName) { 2865 synchronized (mPackages) { 2866 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 2867 if (pkgs == null) { 2868 return null; 2869 } 2870 return pkgs.toArray(new String[pkgs.size()]); 2871 } 2872 } 2873 2874 @Override 2875 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 2876 int flags, int userId) { 2877 if (!sUserManager.exists(userId)) return null; 2878 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent"); 2879 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2880 return chooseBestActivity(intent, resolvedType, flags, query, userId); 2881 } 2882 2883 @Override 2884 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 2885 IntentFilter filter, int match, ComponentName activity) { 2886 final int userId = UserHandle.getCallingUserId(); 2887 if (DEBUG_PREFERRED) { 2888 Log.v(TAG, "setLastChosenActivity intent=" + intent 2889 + " resolvedType=" + resolvedType 2890 + " flags=" + flags 2891 + " filter=" + filter 2892 + " match=" + match 2893 + " activity=" + activity); 2894 filter.dump(new PrintStreamPrinter(System.out), " "); 2895 } 2896 intent.setComponent(null); 2897 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2898 // Find any earlier preferred or last chosen entries and nuke them 2899 findPreferredActivity(intent, resolvedType, 2900 flags, query, 0, false, true, false, userId); 2901 // Add the new activity as the last chosen for this filter 2902 addPreferredActivityInternal(filter, match, null, activity, false, userId); 2903 } 2904 2905 @Override 2906 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 2907 final int userId = UserHandle.getCallingUserId(); 2908 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 2909 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2910 return findPreferredActivity(intent, resolvedType, flags, query, 0, 2911 false, false, false, userId); 2912 } 2913 2914 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 2915 int flags, List<ResolveInfo> query, int userId) { 2916 if (query != null) { 2917 final int N = query.size(); 2918 if (N == 1) { 2919 return query.get(0); 2920 } else if (N > 1) { 2921 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 2922 // If there is more than one activity with the same priority, 2923 // then let the user decide between them. 2924 ResolveInfo r0 = query.get(0); 2925 ResolveInfo r1 = query.get(1); 2926 if (DEBUG_INTENT_MATCHING || debug) { 2927 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 2928 + r1.activityInfo.name + "=" + r1.priority); 2929 } 2930 // If the first activity has a higher priority, or a different 2931 // default, then it is always desireable to pick it. 2932 if (r0.priority != r1.priority 2933 || r0.preferredOrder != r1.preferredOrder 2934 || r0.isDefault != r1.isDefault) { 2935 return query.get(0); 2936 } 2937 // If we have saved a preference for a preferred activity for 2938 // this Intent, use that. 2939 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 2940 flags, query, r0.priority, true, false, debug, userId); 2941 if (ri != null) { 2942 return ri; 2943 } 2944 if (userId != 0) { 2945 ri = new ResolveInfo(mResolveInfo); 2946 ri.activityInfo = new ActivityInfo(ri.activityInfo); 2947 ri.activityInfo.applicationInfo = new ApplicationInfo( 2948 ri.activityInfo.applicationInfo); 2949 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 2950 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 2951 return ri; 2952 } 2953 return mResolveInfo; 2954 } 2955 } 2956 return null; 2957 } 2958 2959 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 2960 int flags, List<ResolveInfo> query, boolean debug, int userId) { 2961 final int N = query.size(); 2962 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 2963 .get(userId); 2964 // Get the list of persistent preferred activities that handle the intent 2965 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 2966 List<PersistentPreferredActivity> pprefs = ppir != null 2967 ? ppir.queryIntent(intent, resolvedType, 2968 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 2969 : null; 2970 if (pprefs != null && pprefs.size() > 0) { 2971 final int M = pprefs.size(); 2972 for (int i=0; i<M; i++) { 2973 final PersistentPreferredActivity ppa = pprefs.get(i); 2974 if (DEBUG_PREFERRED || debug) { 2975 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 2976 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 2977 + "\n component=" + ppa.mComponent); 2978 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 2979 } 2980 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 2981 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 2982 if (DEBUG_PREFERRED || debug) { 2983 Slog.v(TAG, "Found persistent preferred activity:"); 2984 if (ai != null) { 2985 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 2986 } else { 2987 Slog.v(TAG, " null"); 2988 } 2989 } 2990 if (ai == null) { 2991 // This previously registered persistent preferred activity 2992 // component is no longer known. Ignore it and do NOT remove it. 2993 continue; 2994 } 2995 for (int j=0; j<N; j++) { 2996 final ResolveInfo ri = query.get(j); 2997 if (!ri.activityInfo.applicationInfo.packageName 2998 .equals(ai.applicationInfo.packageName)) { 2999 continue; 3000 } 3001 if (!ri.activityInfo.name.equals(ai.name)) { 3002 continue; 3003 } 3004 // Found a persistent preference that can handle the intent. 3005 if (DEBUG_PREFERRED || debug) { 3006 Slog.v(TAG, "Returning persistent preferred activity: " + 3007 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3008 } 3009 return ri; 3010 } 3011 } 3012 } 3013 return null; 3014 } 3015 3016 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3017 List<ResolveInfo> query, int priority, boolean always, 3018 boolean removeMatches, boolean debug, int userId) { 3019 if (!sUserManager.exists(userId)) return null; 3020 // writer 3021 synchronized (mPackages) { 3022 if (intent.getSelector() != null) { 3023 intent = intent.getSelector(); 3024 } 3025 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3026 3027 // Try to find a matching persistent preferred activity. 3028 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3029 debug, userId); 3030 3031 // If a persistent preferred activity matched, use it. 3032 if (pri != null) { 3033 return pri; 3034 } 3035 3036 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3037 // Get the list of preferred activities that handle the intent 3038 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3039 List<PreferredActivity> prefs = pir != null 3040 ? pir.queryIntent(intent, resolvedType, 3041 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3042 : null; 3043 if (prefs != null && prefs.size() > 0) { 3044 // First figure out how good the original match set is. 3045 // We will only allow preferred activities that came 3046 // from the same match quality. 3047 int match = 0; 3048 3049 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3050 3051 final int N = query.size(); 3052 for (int j=0; j<N; j++) { 3053 final ResolveInfo ri = query.get(j); 3054 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3055 + ": 0x" + Integer.toHexString(match)); 3056 if (ri.match > match) { 3057 match = ri.match; 3058 } 3059 } 3060 3061 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3062 + Integer.toHexString(match)); 3063 3064 match &= IntentFilter.MATCH_CATEGORY_MASK; 3065 final int M = prefs.size(); 3066 for (int i=0; i<M; i++) { 3067 final PreferredActivity pa = prefs.get(i); 3068 if (DEBUG_PREFERRED || debug) { 3069 Slog.v(TAG, "Checking PreferredActivity ds=" 3070 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3071 + "\n component=" + pa.mPref.mComponent); 3072 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3073 } 3074 if (pa.mPref.mMatch != match) { 3075 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3076 + Integer.toHexString(pa.mPref.mMatch)); 3077 continue; 3078 } 3079 // If it's not an "always" type preferred activity and that's what we're 3080 // looking for, skip it. 3081 if (always && !pa.mPref.mAlways) { 3082 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3083 continue; 3084 } 3085 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3086 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3087 if (DEBUG_PREFERRED || debug) { 3088 Slog.v(TAG, "Found preferred activity:"); 3089 if (ai != null) { 3090 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3091 } else { 3092 Slog.v(TAG, " null"); 3093 } 3094 } 3095 if (ai == null) { 3096 // This previously registered preferred activity 3097 // component is no longer known. Most likely an update 3098 // to the app was installed and in the new version this 3099 // component no longer exists. Clean it up by removing 3100 // it from the preferred activities list, and skip it. 3101 Slog.w(TAG, "Removing dangling preferred activity: " 3102 + pa.mPref.mComponent); 3103 pir.removeFilter(pa); 3104 continue; 3105 } 3106 for (int j=0; j<N; j++) { 3107 final ResolveInfo ri = query.get(j); 3108 if (!ri.activityInfo.applicationInfo.packageName 3109 .equals(ai.applicationInfo.packageName)) { 3110 continue; 3111 } 3112 if (!ri.activityInfo.name.equals(ai.name)) { 3113 continue; 3114 } 3115 3116 if (removeMatches) { 3117 pir.removeFilter(pa); 3118 if (DEBUG_PREFERRED) { 3119 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3120 } 3121 break; 3122 } 3123 3124 // Okay we found a previously set preferred or last chosen app. 3125 // If the result set is different from when this 3126 // was created, we need to clear it and re-ask the 3127 // user their preference, if we're looking for an "always" type entry. 3128 if (always && !pa.mPref.sameSet(query, priority)) { 3129 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3130 + intent + " type " + resolvedType); 3131 if (DEBUG_PREFERRED) { 3132 Slog.v(TAG, "Removing preferred activity since set changed " 3133 + pa.mPref.mComponent); 3134 } 3135 pir.removeFilter(pa); 3136 // Re-add the filter as a "last chosen" entry (!always) 3137 PreferredActivity lastChosen = new PreferredActivity( 3138 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3139 pir.addFilter(lastChosen); 3140 mSettings.writePackageRestrictionsLPr(userId); 3141 return null; 3142 } 3143 3144 // Yay! Either the set matched or we're looking for the last chosen 3145 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3146 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3147 mSettings.writePackageRestrictionsLPr(userId); 3148 return ri; 3149 } 3150 } 3151 } 3152 mSettings.writePackageRestrictionsLPr(userId); 3153 } 3154 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3155 return null; 3156 } 3157 3158 /* 3159 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3160 */ 3161 @Override 3162 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3163 int targetUserId) { 3164 mContext.enforceCallingOrSelfPermission( 3165 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3166 List<CrossProfileIntentFilter> matches = 3167 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3168 if (matches != null) { 3169 int size = matches.size(); 3170 for (int i = 0; i < size; i++) { 3171 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3172 } 3173 } 3174 3175 ArrayList<String> packageNames = null; 3176 SparseArray<ArrayList<String>> fromSource = 3177 mSettings.mCrossProfilePackageInfo.get(sourceUserId); 3178 if (fromSource != null) { 3179 packageNames = fromSource.get(targetUserId); 3180 } 3181 if (packageNames.contains(intent.getPackage())) { 3182 return true; 3183 } 3184 // We need the package name, so we try to resolve with the loosest flags possible 3185 List<ResolveInfo> resolveInfos = mActivities.queryIntent( 3186 intent, resolvedType, PackageManager.GET_UNINSTALLED_PACKAGES, targetUserId); 3187 int count = resolveInfos.size(); 3188 for (int i = 0; i < count; i++) { 3189 ResolveInfo resolveInfo = resolveInfos.get(i); 3190 if (packageNames.contains(resolveInfo.activityInfo.packageName)) { 3191 return true; 3192 } 3193 } 3194 return false; 3195 } 3196 3197 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3198 String resolvedType, int userId) { 3199 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3200 if (resolver != null) { 3201 return resolver.queryIntent(intent, resolvedType, false, userId); 3202 } 3203 return null; 3204 } 3205 3206 @Override 3207 public List<ResolveInfo> queryIntentActivities(Intent intent, 3208 String resolvedType, int flags, int userId) { 3209 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3210 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities"); 3211 ComponentName comp = intent.getComponent(); 3212 if (comp == null) { 3213 if (intent.getSelector() != null) { 3214 intent = intent.getSelector(); 3215 comp = intent.getComponent(); 3216 } 3217 } 3218 3219 if (comp != null) { 3220 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3221 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3222 if (ai != null) { 3223 final ResolveInfo ri = new ResolveInfo(); 3224 ri.activityInfo = ai; 3225 list.add(ri); 3226 } 3227 return list; 3228 } 3229 3230 // reader 3231 synchronized (mPackages) { 3232 final String pkgName = intent.getPackage(); 3233 boolean queryCrossProfile = (flags & PackageManager.NO_CROSS_PROFILE) == 0; 3234 if (pkgName == null) { 3235 ResolveInfo resolveInfo = null; 3236 if (queryCrossProfile) { 3237 // Check if the intent needs to be forwarded to another user for this package 3238 ArrayList<ResolveInfo> crossProfileResult = 3239 queryIntentActivitiesCrossProfilePackage( 3240 intent, resolvedType, flags, userId); 3241 if (!crossProfileResult.isEmpty()) { 3242 // Skip the current profile 3243 return crossProfileResult; 3244 } 3245 List<CrossProfileIntentFilter> matchingFilters = 3246 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3247 // Check for results that need to skip the current profile. 3248 resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3249 resolvedType, flags, userId); 3250 if (resolveInfo != null) { 3251 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3252 result.add(resolveInfo); 3253 return result; 3254 } 3255 // Check for cross profile results. 3256 resolveInfo = queryCrossProfileIntents( 3257 matchingFilters, intent, resolvedType, flags, userId); 3258 } 3259 // Check for results in the current profile. 3260 List<ResolveInfo> result = mActivities.queryIntent( 3261 intent, resolvedType, flags, userId); 3262 if (resolveInfo != null) { 3263 result.add(resolveInfo); 3264 } 3265 return result; 3266 } 3267 final PackageParser.Package pkg = mPackages.get(pkgName); 3268 if (pkg != null) { 3269 if (queryCrossProfile) { 3270 ArrayList<ResolveInfo> crossProfileResult = 3271 queryIntentActivitiesCrossProfilePackage( 3272 intent, resolvedType, flags, userId, pkg, pkgName); 3273 if (!crossProfileResult.isEmpty()) { 3274 // Skip the current profile 3275 return crossProfileResult; 3276 } 3277 } 3278 return mActivities.queryIntentForPackage(intent, resolvedType, flags, 3279 pkg.activities, userId); 3280 } 3281 return new ArrayList<ResolveInfo>(); 3282 } 3283 } 3284 3285 private ResolveInfo querySkipCurrentProfileIntents( 3286 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3287 int flags, int sourceUserId) { 3288 if (matchingFilters != null) { 3289 int size = matchingFilters.size(); 3290 for (int i = 0; i < size; i ++) { 3291 CrossProfileIntentFilter filter = matchingFilters.get(i); 3292 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 3293 // Checking if there are activities in the target user that can handle the 3294 // intent. 3295 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3296 flags, sourceUserId); 3297 if (resolveInfo != null) { 3298 return resolveInfo; 3299 } 3300 } 3301 } 3302 } 3303 return null; 3304 } 3305 3306 private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage( 3307 Intent intent, String resolvedType, int flags, int userId) { 3308 ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>(); 3309 SparseArray<ArrayList<String>> sourceForwardingInfo = 3310 mSettings.mCrossProfilePackageInfo.get(userId); 3311 if (sourceForwardingInfo != null) { 3312 int NI = sourceForwardingInfo.size(); 3313 for (int i = 0; i < NI; i++) { 3314 int targetUserId = sourceForwardingInfo.keyAt(i); 3315 ArrayList<String> packageNames = sourceForwardingInfo.valueAt(i); 3316 List<ResolveInfo> resolveInfos = mActivities.queryIntent( 3317 intent, resolvedType, flags, targetUserId); 3318 int NJ = resolveInfos.size(); 3319 for (int j = 0; j < NJ; j++) { 3320 ResolveInfo resolveInfo = resolveInfos.get(j); 3321 if (packageNames.contains(resolveInfo.activityInfo.packageName)) { 3322 matchingResolveInfos.add(createForwardingResolveInfo( 3323 resolveInfo.filter, userId, targetUserId)); 3324 } 3325 } 3326 } 3327 } 3328 return matchingResolveInfos; 3329 } 3330 3331 private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage( 3332 Intent intent, String resolvedType, int flags, int userId, PackageParser.Package pkg, 3333 String packageName) { 3334 ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>(); 3335 SparseArray<ArrayList<String>> sourceForwardingInfo = 3336 mSettings.mCrossProfilePackageInfo.get(userId); 3337 if (sourceForwardingInfo != null) { 3338 int NI = sourceForwardingInfo.size(); 3339 for (int i = 0; i < NI; i++) { 3340 int targetUserId = sourceForwardingInfo.keyAt(i); 3341 if (sourceForwardingInfo.valueAt(i).contains(packageName)) { 3342 List<ResolveInfo> resolveInfos = mActivities.queryIntentForPackage( 3343 intent, resolvedType, flags, pkg.activities, targetUserId); 3344 int NJ = resolveInfos.size(); 3345 for (int j = 0; j < NJ; j++) { 3346 ResolveInfo resolveInfo = resolveInfos.get(j); 3347 matchingResolveInfos.add(createForwardingResolveInfo( 3348 resolveInfo.filter, userId, targetUserId)); 3349 } 3350 } 3351 } 3352 } 3353 return matchingResolveInfos; 3354 } 3355 3356 // Return matching ResolveInfo if any for skip current profile intent filters. 3357 private ResolveInfo queryCrossProfileIntents( 3358 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3359 int flags, int sourceUserId) { 3360 if (matchingFilters != null) { 3361 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 3362 // match the same intent. For performance reasons, it is better not to 3363 // run queryIntent twice for the same userId 3364 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 3365 int size = matchingFilters.size(); 3366 for (int i = 0; i < size; i++) { 3367 CrossProfileIntentFilter filter = matchingFilters.get(i); 3368 int targetUserId = filter.getTargetUserId(); 3369 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 3370 && !alreadyTriedUserIds.get(targetUserId)) { 3371 // Checking if there are activities in the target user that can handle the 3372 // intent. 3373 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3374 flags, sourceUserId); 3375 if (resolveInfo != null) return resolveInfo; 3376 alreadyTriedUserIds.put(targetUserId, true); 3377 } 3378 } 3379 } 3380 return null; 3381 } 3382 3383 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 3384 String resolvedType, int flags, int sourceUserId) { 3385 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 3386 resolvedType, flags, filter.getTargetUserId()); 3387 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 3388 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 3389 } 3390 return null; 3391 } 3392 3393 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 3394 int sourceUserId, int targetUserId) { 3395 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 3396 String className; 3397 if (targetUserId == UserHandle.USER_OWNER) { 3398 className = FORWARD_INTENT_TO_USER_OWNER; 3399 } else { 3400 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 3401 } 3402 ComponentName forwardingActivityComponentName = new ComponentName( 3403 mAndroidApplication.packageName, className); 3404 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 3405 sourceUserId); 3406 if (targetUserId == UserHandle.USER_OWNER) { 3407 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 3408 forwardingResolveInfo.noResourceId = true; 3409 } 3410 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 3411 forwardingResolveInfo.priority = 0; 3412 forwardingResolveInfo.preferredOrder = 0; 3413 forwardingResolveInfo.match = 0; 3414 forwardingResolveInfo.isDefault = true; 3415 forwardingResolveInfo.filter = filter; 3416 forwardingResolveInfo.targetUserId = targetUserId; 3417 return forwardingResolveInfo; 3418 } 3419 3420 @Override 3421 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 3422 Intent[] specifics, String[] specificTypes, Intent intent, 3423 String resolvedType, int flags, int userId) { 3424 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3425 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 3426 "query intent activity options"); 3427 final String resultsAction = intent.getAction(); 3428 3429 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 3430 | PackageManager.GET_RESOLVED_FILTER, userId); 3431 3432 if (DEBUG_INTENT_MATCHING) { 3433 Log.v(TAG, "Query " + intent + ": " + results); 3434 } 3435 3436 int specificsPos = 0; 3437 int N; 3438 3439 // todo: note that the algorithm used here is O(N^2). This 3440 // isn't a problem in our current environment, but if we start running 3441 // into situations where we have more than 5 or 10 matches then this 3442 // should probably be changed to something smarter... 3443 3444 // First we go through and resolve each of the specific items 3445 // that were supplied, taking care of removing any corresponding 3446 // duplicate items in the generic resolve list. 3447 if (specifics != null) { 3448 for (int i=0; i<specifics.length; i++) { 3449 final Intent sintent = specifics[i]; 3450 if (sintent == null) { 3451 continue; 3452 } 3453 3454 if (DEBUG_INTENT_MATCHING) { 3455 Log.v(TAG, "Specific #" + i + ": " + sintent); 3456 } 3457 3458 String action = sintent.getAction(); 3459 if (resultsAction != null && resultsAction.equals(action)) { 3460 // If this action was explicitly requested, then don't 3461 // remove things that have it. 3462 action = null; 3463 } 3464 3465 ResolveInfo ri = null; 3466 ActivityInfo ai = null; 3467 3468 ComponentName comp = sintent.getComponent(); 3469 if (comp == null) { 3470 ri = resolveIntent( 3471 sintent, 3472 specificTypes != null ? specificTypes[i] : null, 3473 flags, userId); 3474 if (ri == null) { 3475 continue; 3476 } 3477 if (ri == mResolveInfo) { 3478 // ACK! Must do something better with this. 3479 } 3480 ai = ri.activityInfo; 3481 comp = new ComponentName(ai.applicationInfo.packageName, 3482 ai.name); 3483 } else { 3484 ai = getActivityInfo(comp, flags, userId); 3485 if (ai == null) { 3486 continue; 3487 } 3488 } 3489 3490 // Look for any generic query activities that are duplicates 3491 // of this specific one, and remove them from the results. 3492 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 3493 N = results.size(); 3494 int j; 3495 for (j=specificsPos; j<N; j++) { 3496 ResolveInfo sri = results.get(j); 3497 if ((sri.activityInfo.name.equals(comp.getClassName()) 3498 && sri.activityInfo.applicationInfo.packageName.equals( 3499 comp.getPackageName())) 3500 || (action != null && sri.filter.matchAction(action))) { 3501 results.remove(j); 3502 if (DEBUG_INTENT_MATCHING) Log.v( 3503 TAG, "Removing duplicate item from " + j 3504 + " due to specific " + specificsPos); 3505 if (ri == null) { 3506 ri = sri; 3507 } 3508 j--; 3509 N--; 3510 } 3511 } 3512 3513 // Add this specific item to its proper place. 3514 if (ri == null) { 3515 ri = new ResolveInfo(); 3516 ri.activityInfo = ai; 3517 } 3518 results.add(specificsPos, ri); 3519 ri.specificIndex = i; 3520 specificsPos++; 3521 } 3522 } 3523 3524 // Now we go through the remaining generic results and remove any 3525 // duplicate actions that are found here. 3526 N = results.size(); 3527 for (int i=specificsPos; i<N-1; i++) { 3528 final ResolveInfo rii = results.get(i); 3529 if (rii.filter == null) { 3530 continue; 3531 } 3532 3533 // Iterate over all of the actions of this result's intent 3534 // filter... typically this should be just one. 3535 final Iterator<String> it = rii.filter.actionsIterator(); 3536 if (it == null) { 3537 continue; 3538 } 3539 while (it.hasNext()) { 3540 final String action = it.next(); 3541 if (resultsAction != null && resultsAction.equals(action)) { 3542 // If this action was explicitly requested, then don't 3543 // remove things that have it. 3544 continue; 3545 } 3546 for (int j=i+1; j<N; j++) { 3547 final ResolveInfo rij = results.get(j); 3548 if (rij.filter != null && rij.filter.hasAction(action)) { 3549 results.remove(j); 3550 if (DEBUG_INTENT_MATCHING) Log.v( 3551 TAG, "Removing duplicate item from " + j 3552 + " due to action " + action + " at " + i); 3553 j--; 3554 N--; 3555 } 3556 } 3557 } 3558 3559 // If the caller didn't request filter information, drop it now 3560 // so we don't have to marshall/unmarshall it. 3561 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3562 rii.filter = null; 3563 } 3564 } 3565 3566 // Filter out the caller activity if so requested. 3567 if (caller != null) { 3568 N = results.size(); 3569 for (int i=0; i<N; i++) { 3570 ActivityInfo ainfo = results.get(i).activityInfo; 3571 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 3572 && caller.getClassName().equals(ainfo.name)) { 3573 results.remove(i); 3574 break; 3575 } 3576 } 3577 } 3578 3579 // If the caller didn't request filter information, 3580 // drop them now so we don't have to 3581 // marshall/unmarshall it. 3582 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3583 N = results.size(); 3584 for (int i=0; i<N; i++) { 3585 results.get(i).filter = null; 3586 } 3587 } 3588 3589 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 3590 return results; 3591 } 3592 3593 @Override 3594 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 3595 int userId) { 3596 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3597 ComponentName comp = intent.getComponent(); 3598 if (comp == null) { 3599 if (intent.getSelector() != null) { 3600 intent = intent.getSelector(); 3601 comp = intent.getComponent(); 3602 } 3603 } 3604 if (comp != null) { 3605 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3606 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 3607 if (ai != null) { 3608 ResolveInfo ri = new ResolveInfo(); 3609 ri.activityInfo = ai; 3610 list.add(ri); 3611 } 3612 return list; 3613 } 3614 3615 // reader 3616 synchronized (mPackages) { 3617 String pkgName = intent.getPackage(); 3618 if (pkgName == null) { 3619 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 3620 } 3621 final PackageParser.Package pkg = mPackages.get(pkgName); 3622 if (pkg != null) { 3623 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 3624 userId); 3625 } 3626 return null; 3627 } 3628 } 3629 3630 @Override 3631 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 3632 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 3633 if (!sUserManager.exists(userId)) return null; 3634 if (query != null) { 3635 if (query.size() >= 1) { 3636 // If there is more than one service with the same priority, 3637 // just arbitrarily pick the first one. 3638 return query.get(0); 3639 } 3640 } 3641 return null; 3642 } 3643 3644 @Override 3645 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 3646 int userId) { 3647 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3648 ComponentName comp = intent.getComponent(); 3649 if (comp == null) { 3650 if (intent.getSelector() != null) { 3651 intent = intent.getSelector(); 3652 comp = intent.getComponent(); 3653 } 3654 } 3655 if (comp != null) { 3656 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3657 final ServiceInfo si = getServiceInfo(comp, flags, userId); 3658 if (si != null) { 3659 final ResolveInfo ri = new ResolveInfo(); 3660 ri.serviceInfo = si; 3661 list.add(ri); 3662 } 3663 return list; 3664 } 3665 3666 // reader 3667 synchronized (mPackages) { 3668 String pkgName = intent.getPackage(); 3669 if (pkgName == null) { 3670 return mServices.queryIntent(intent, resolvedType, flags, userId); 3671 } 3672 final PackageParser.Package pkg = mPackages.get(pkgName); 3673 if (pkg != null) { 3674 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 3675 userId); 3676 } 3677 return null; 3678 } 3679 } 3680 3681 @Override 3682 public List<ResolveInfo> queryIntentContentProviders( 3683 Intent intent, String resolvedType, int flags, int userId) { 3684 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3685 ComponentName comp = intent.getComponent(); 3686 if (comp == null) { 3687 if (intent.getSelector() != null) { 3688 intent = intent.getSelector(); 3689 comp = intent.getComponent(); 3690 } 3691 } 3692 if (comp != null) { 3693 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3694 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 3695 if (pi != null) { 3696 final ResolveInfo ri = new ResolveInfo(); 3697 ri.providerInfo = pi; 3698 list.add(ri); 3699 } 3700 return list; 3701 } 3702 3703 // reader 3704 synchronized (mPackages) { 3705 String pkgName = intent.getPackage(); 3706 if (pkgName == null) { 3707 return mProviders.queryIntent(intent, resolvedType, flags, userId); 3708 } 3709 final PackageParser.Package pkg = mPackages.get(pkgName); 3710 if (pkg != null) { 3711 return mProviders.queryIntentForPackage( 3712 intent, resolvedType, flags, pkg.providers, userId); 3713 } 3714 return null; 3715 } 3716 } 3717 3718 @Override 3719 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 3720 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3721 3722 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages"); 3723 3724 // writer 3725 synchronized (mPackages) { 3726 ArrayList<PackageInfo> list; 3727 if (listUninstalled) { 3728 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 3729 for (PackageSetting ps : mSettings.mPackages.values()) { 3730 PackageInfo pi; 3731 if (ps.pkg != null) { 3732 pi = generatePackageInfo(ps.pkg, flags, userId); 3733 } else { 3734 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3735 } 3736 if (pi != null) { 3737 list.add(pi); 3738 } 3739 } 3740 } else { 3741 list = new ArrayList<PackageInfo>(mPackages.size()); 3742 for (PackageParser.Package p : mPackages.values()) { 3743 PackageInfo pi = generatePackageInfo(p, flags, userId); 3744 if (pi != null) { 3745 list.add(pi); 3746 } 3747 } 3748 } 3749 3750 return new ParceledListSlice<PackageInfo>(list); 3751 } 3752 } 3753 3754 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 3755 String[] permissions, boolean[] tmp, int flags, int userId) { 3756 int numMatch = 0; 3757 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 3758 for (int i=0; i<permissions.length; i++) { 3759 if (gp.grantedPermissions.contains(permissions[i])) { 3760 tmp[i] = true; 3761 numMatch++; 3762 } else { 3763 tmp[i] = false; 3764 } 3765 } 3766 if (numMatch == 0) { 3767 return; 3768 } 3769 PackageInfo pi; 3770 if (ps.pkg != null) { 3771 pi = generatePackageInfo(ps.pkg, flags, userId); 3772 } else { 3773 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3774 } 3775 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 3776 if (numMatch == permissions.length) { 3777 pi.requestedPermissions = permissions; 3778 } else { 3779 pi.requestedPermissions = new String[numMatch]; 3780 numMatch = 0; 3781 for (int i=0; i<permissions.length; i++) { 3782 if (tmp[i]) { 3783 pi.requestedPermissions[numMatch] = permissions[i]; 3784 numMatch++; 3785 } 3786 } 3787 } 3788 } 3789 list.add(pi); 3790 } 3791 3792 @Override 3793 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 3794 String[] permissions, int flags, int userId) { 3795 if (!sUserManager.exists(userId)) return null; 3796 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3797 3798 // writer 3799 synchronized (mPackages) { 3800 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 3801 boolean[] tmpBools = new boolean[permissions.length]; 3802 if (listUninstalled) { 3803 for (PackageSetting ps : mSettings.mPackages.values()) { 3804 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 3805 } 3806 } else { 3807 for (PackageParser.Package pkg : mPackages.values()) { 3808 PackageSetting ps = (PackageSetting)pkg.mExtras; 3809 if (ps != null) { 3810 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 3811 userId); 3812 } 3813 } 3814 } 3815 3816 return new ParceledListSlice<PackageInfo>(list); 3817 } 3818 } 3819 3820 @Override 3821 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 3822 if (!sUserManager.exists(userId)) return null; 3823 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3824 3825 // writer 3826 synchronized (mPackages) { 3827 ArrayList<ApplicationInfo> list; 3828 if (listUninstalled) { 3829 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 3830 for (PackageSetting ps : mSettings.mPackages.values()) { 3831 ApplicationInfo ai; 3832 if (ps.pkg != null) { 3833 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3834 ps.readUserState(userId), userId); 3835 } else { 3836 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 3837 } 3838 if (ai != null) { 3839 list.add(ai); 3840 } 3841 } 3842 } else { 3843 list = new ArrayList<ApplicationInfo>(mPackages.size()); 3844 for (PackageParser.Package p : mPackages.values()) { 3845 if (p.mExtras != null) { 3846 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3847 ((PackageSetting)p.mExtras).readUserState(userId), userId); 3848 if (ai != null) { 3849 list.add(ai); 3850 } 3851 } 3852 } 3853 } 3854 3855 return new ParceledListSlice<ApplicationInfo>(list); 3856 } 3857 } 3858 3859 public List<ApplicationInfo> getPersistentApplications(int flags) { 3860 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 3861 3862 // reader 3863 synchronized (mPackages) { 3864 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 3865 final int userId = UserHandle.getCallingUserId(); 3866 while (i.hasNext()) { 3867 final PackageParser.Package p = i.next(); 3868 if (p.applicationInfo != null 3869 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 3870 && (!mSafeMode || isSystemApp(p))) { 3871 PackageSetting ps = mSettings.mPackages.get(p.packageName); 3872 if (ps != null) { 3873 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3874 ps.readUserState(userId), userId); 3875 if (ai != null) { 3876 finalList.add(ai); 3877 } 3878 } 3879 } 3880 } 3881 } 3882 3883 return finalList; 3884 } 3885 3886 @Override 3887 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 3888 if (!sUserManager.exists(userId)) return null; 3889 // reader 3890 synchronized (mPackages) { 3891 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 3892 PackageSetting ps = provider != null 3893 ? mSettings.mPackages.get(provider.owner.packageName) 3894 : null; 3895 return ps != null 3896 && mSettings.isEnabledLPr(provider.info, flags, userId) 3897 && (!mSafeMode || (provider.info.applicationInfo.flags 3898 &ApplicationInfo.FLAG_SYSTEM) != 0) 3899 ? PackageParser.generateProviderInfo(provider, flags, 3900 ps.readUserState(userId), userId) 3901 : null; 3902 } 3903 } 3904 3905 /** 3906 * @deprecated 3907 */ 3908 @Deprecated 3909 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 3910 // reader 3911 synchronized (mPackages) { 3912 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 3913 .entrySet().iterator(); 3914 final int userId = UserHandle.getCallingUserId(); 3915 while (i.hasNext()) { 3916 Map.Entry<String, PackageParser.Provider> entry = i.next(); 3917 PackageParser.Provider p = entry.getValue(); 3918 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3919 3920 if (ps != null && p.syncable 3921 && (!mSafeMode || (p.info.applicationInfo.flags 3922 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 3923 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 3924 ps.readUserState(userId), userId); 3925 if (info != null) { 3926 outNames.add(entry.getKey()); 3927 outInfo.add(info); 3928 } 3929 } 3930 } 3931 } 3932 } 3933 3934 @Override 3935 public List<ProviderInfo> queryContentProviders(String processName, 3936 int uid, int flags) { 3937 ArrayList<ProviderInfo> finalList = null; 3938 // reader 3939 synchronized (mPackages) { 3940 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 3941 final int userId = processName != null ? 3942 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 3943 while (i.hasNext()) { 3944 final PackageParser.Provider p = i.next(); 3945 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3946 if (ps != null && p.info.authority != null 3947 && (processName == null 3948 || (p.info.processName.equals(processName) 3949 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 3950 && mSettings.isEnabledLPr(p.info, flags, userId) 3951 && (!mSafeMode 3952 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 3953 if (finalList == null) { 3954 finalList = new ArrayList<ProviderInfo>(3); 3955 } 3956 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 3957 ps.readUserState(userId), userId); 3958 if (info != null) { 3959 finalList.add(info); 3960 } 3961 } 3962 } 3963 } 3964 3965 if (finalList != null) { 3966 Collections.sort(finalList, mProviderInitOrderSorter); 3967 } 3968 3969 return finalList; 3970 } 3971 3972 @Override 3973 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 3974 int flags) { 3975 // reader 3976 synchronized (mPackages) { 3977 final PackageParser.Instrumentation i = mInstrumentation.get(name); 3978 return PackageParser.generateInstrumentationInfo(i, flags); 3979 } 3980 } 3981 3982 @Override 3983 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 3984 int flags) { 3985 ArrayList<InstrumentationInfo> finalList = 3986 new ArrayList<InstrumentationInfo>(); 3987 3988 // reader 3989 synchronized (mPackages) { 3990 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 3991 while (i.hasNext()) { 3992 final PackageParser.Instrumentation p = i.next(); 3993 if (targetPackage == null 3994 || targetPackage.equals(p.info.targetPackage)) { 3995 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 3996 flags); 3997 if (ii != null) { 3998 finalList.add(ii); 3999 } 4000 } 4001 } 4002 } 4003 4004 return finalList; 4005 } 4006 4007 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4008 HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4009 if (overlays == null) { 4010 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4011 return; 4012 } 4013 for (PackageParser.Package opkg : overlays.values()) { 4014 // Not much to do if idmap fails: we already logged the error 4015 // and we certainly don't want to abort installation of pkg simply 4016 // because an overlay didn't fit properly. For these reasons, 4017 // ignore the return value of createIdmapForPackagePairLI. 4018 createIdmapForPackagePairLI(pkg, opkg); 4019 } 4020 } 4021 4022 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4023 PackageParser.Package opkg) { 4024 if (!opkg.mTrustedOverlay) { 4025 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4026 opkg.baseCodePath + ": overlay not trusted"); 4027 return false; 4028 } 4029 HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4030 if (overlaySet == null) { 4031 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4032 opkg.baseCodePath + " but target package has no known overlays"); 4033 return false; 4034 } 4035 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4036 // TODO: generate idmap for split APKs 4037 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4038 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4039 + opkg.baseCodePath); 4040 return false; 4041 } 4042 PackageParser.Package[] overlayArray = 4043 overlaySet.values().toArray(new PackageParser.Package[0]); 4044 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4045 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4046 return p1.mOverlayPriority - p2.mOverlayPriority; 4047 } 4048 }; 4049 Arrays.sort(overlayArray, cmp); 4050 4051 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4052 int i = 0; 4053 for (PackageParser.Package p : overlayArray) { 4054 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4055 } 4056 return true; 4057 } 4058 4059 private void scanDirLI(File dir, int flags, int scanMode, long currentTime) { 4060 final File[] files = dir.listFiles(); 4061 if (ArrayUtils.isEmpty(files)) { 4062 Log.d(TAG, "No files in app dir " + dir); 4063 return; 4064 } 4065 4066 if (DEBUG_PACKAGE_SCANNING) { 4067 Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode 4068 + " flags=0x" + Integer.toHexString(flags)); 4069 } 4070 4071 for (File file : files) { 4072 final boolean isPackage = isApkFile(file) || file.isDirectory(); 4073 if (!isPackage) { 4074 // Ignore entries which are not apk's 4075 continue; 4076 } 4077 try { 4078 scanPackageLI(file, flags | PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, 4079 null, null); 4080 } catch (PackageManagerException e) { 4081 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4082 4083 // Don't mess around with apps in system partition. 4084 if ((flags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4085 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4086 // Delete the apk 4087 Slog.w(TAG, "Cleaning up failed install of " + file); 4088 file.delete(); 4089 } 4090 } 4091 } 4092 } 4093 4094 private static File getSettingsProblemFile() { 4095 File dataDir = Environment.getDataDirectory(); 4096 File systemDir = new File(dataDir, "system"); 4097 File fname = new File(systemDir, "uiderrors.txt"); 4098 return fname; 4099 } 4100 4101 static void reportSettingsProblem(int priority, String msg) { 4102 try { 4103 File fname = getSettingsProblemFile(); 4104 FileOutputStream out = new FileOutputStream(fname, true); 4105 PrintWriter pw = new FastPrintWriter(out); 4106 SimpleDateFormat formatter = new SimpleDateFormat(); 4107 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4108 pw.println(dateString + ": " + msg); 4109 pw.close(); 4110 FileUtils.setPermissions( 4111 fname.toString(), 4112 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4113 -1, -1); 4114 } catch (java.io.IOException e) { 4115 } 4116 Slog.println(priority, TAG, msg); 4117 } 4118 4119 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 4120 PackageParser.Package pkg, File srcFile, int parseFlags) 4121 throws PackageManagerException { 4122 if (ps != null 4123 && ps.codePath.equals(srcFile) 4124 && ps.timeStamp == srcFile.lastModified() 4125 && !isCompatSignatureUpdateNeeded(pkg)) { 4126 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4127 if (ps.signatures.mSignatures != null 4128 && ps.signatures.mSignatures.length != 0 4129 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4130 // Optimization: reuse the existing cached certificates 4131 // if the package appears to be unchanged. 4132 pkg.mSignatures = ps.signatures.mSignatures; 4133 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4134 synchronized (mPackages) { 4135 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 4136 } 4137 return; 4138 } 4139 4140 Slog.w(TAG, "PackageSetting for " + ps.name 4141 + " is missing signatures. Collecting certs again to recover them."); 4142 } else { 4143 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4144 } 4145 4146 try { 4147 pp.collectCertificates(pkg, parseFlags); 4148 pp.collectManifestDigest(pkg); 4149 } catch (PackageParserException e) { 4150 throw new PackageManagerException(e.error, "Failed to collect certificates for " 4151 + pkg.packageName + ": " + e.getMessage()); 4152 } 4153 } 4154 4155 /* 4156 * Scan a package and return the newly parsed package. 4157 * Returns null in case of errors and the error code is stored in mLastScanError 4158 */ 4159 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanMode, 4160 long currentTime, UserHandle user, String abiOverride) throws PackageManagerException { 4161 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4162 parseFlags |= mDefParseFlags; 4163 PackageParser pp = new PackageParser(); 4164 pp.setSeparateProcesses(mSeparateProcesses); 4165 pp.setOnlyCoreApps(mOnlyCore); 4166 pp.setDisplayMetrics(mMetrics); 4167 4168 if ((scanMode & SCAN_TRUSTED_OVERLAY) != 0) { 4169 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4170 } 4171 4172 final PackageParser.Package pkg; 4173 try { 4174 pkg = pp.parsePackage(scanFile, parseFlags); 4175 } catch (PackageParserException e) { 4176 throw new PackageManagerException(e.error, 4177 "Failed to scan " + scanFile + ": " + e.getMessage()); 4178 } 4179 4180 PackageSetting ps = null; 4181 PackageSetting updatedPkg; 4182 // reader 4183 synchronized (mPackages) { 4184 // Look to see if we already know about this package. 4185 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4186 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4187 // This package has been renamed to its original name. Let's 4188 // use that. 4189 ps = mSettings.peekPackageLPr(oldName); 4190 } 4191 // If there was no original package, see one for the real package name. 4192 if (ps == null) { 4193 ps = mSettings.peekPackageLPr(pkg.packageName); 4194 } 4195 // Check to see if this package could be hiding/updating a system 4196 // package. Must look for it either under the original or real 4197 // package name depending on our state. 4198 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4199 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4200 } 4201 boolean updatedPkgBetter = false; 4202 // First check if this is a system package that may involve an update 4203 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4204 if (ps != null && !ps.codePath.equals(scanFile)) { 4205 // The path has changed from what was last scanned... check the 4206 // version of the new path against what we have stored to determine 4207 // what to do. 4208 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4209 if (pkg.mVersionCode < ps.versionCode) { 4210 // The system package has been updated and the code path does not match 4211 // Ignore entry. Skip it. 4212 Log.i(TAG, "Package " + ps.name + " at " + scanFile 4213 + " ignored: updated version " + ps.versionCode 4214 + " better than this " + pkg.mVersionCode); 4215 if (!updatedPkg.codePath.equals(scanFile)) { 4216 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4217 + ps.name + " changing from " + updatedPkg.codePathString 4218 + " to " + scanFile); 4219 updatedPkg.codePath = scanFile; 4220 updatedPkg.codePathString = scanFile.toString(); 4221 // This is the point at which we know that the system-disk APK 4222 // for this package has moved during a reboot (e.g. due to an OTA), 4223 // so we need to reevaluate it for privilege policy. 4224 if (locationIsPrivileged(scanFile)) { 4225 updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED; 4226 } 4227 } 4228 updatedPkg.pkg = pkg; 4229 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 4230 } else { 4231 // The current app on the system partition is better than 4232 // what we have updated to on the data partition; switch 4233 // back to the system partition version. 4234 // At this point, its safely assumed that package installation for 4235 // apps in system partition will go through. If not there won't be a working 4236 // version of the app 4237 // writer 4238 synchronized (mPackages) { 4239 // Just remove the loaded entries from package lists. 4240 mPackages.remove(ps.name); 4241 } 4242 Slog.w(TAG, "Package " + ps.name + " at " + scanFile 4243 + "reverting from " + ps.codePathString 4244 + ": new version " + pkg.mVersionCode 4245 + " better than installed " + ps.versionCode); 4246 4247 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4248 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4249 getAppDexInstructionSets(ps), isMultiArch(ps)); 4250 synchronized (mInstallLock) { 4251 args.cleanUpResourcesLI(); 4252 } 4253 synchronized (mPackages) { 4254 mSettings.enableSystemPackageLPw(ps.name); 4255 } 4256 updatedPkgBetter = true; 4257 } 4258 } 4259 } 4260 4261 if (updatedPkg != null) { 4262 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4263 // initially 4264 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4265 4266 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4267 // flag set initially 4268 if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) { 4269 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4270 } 4271 } 4272 4273 // Verify certificates against what was last scanned 4274 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 4275 4276 /* 4277 * A new system app appeared, but we already had a non-system one of the 4278 * same name installed earlier. 4279 */ 4280 boolean shouldHideSystemApp = false; 4281 if (updatedPkg == null && ps != null 4282 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4283 /* 4284 * Check to make sure the signatures match first. If they don't, 4285 * wipe the installed application and its data. 4286 */ 4287 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4288 != PackageManager.SIGNATURE_MATCH) { 4289 if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!"); 4290 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4291 ps = null; 4292 } else { 4293 /* 4294 * If the newly-added system app is an older version than the 4295 * already installed version, hide it. It will be scanned later 4296 * and re-added like an update. 4297 */ 4298 if (pkg.mVersionCode < ps.versionCode) { 4299 shouldHideSystemApp = true; 4300 } else { 4301 /* 4302 * The newly found system app is a newer version that the 4303 * one previously installed. Simply remove the 4304 * already-installed application and replace it with our own 4305 * while keeping the application data. 4306 */ 4307 Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from " 4308 + ps.codePathString + ": new version " + pkg.mVersionCode 4309 + " better than installed " + ps.versionCode); 4310 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4311 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4312 getAppDexInstructionSets(ps), isMultiArch(ps)); 4313 synchronized (mInstallLock) { 4314 args.cleanUpResourcesLI(); 4315 } 4316 } 4317 } 4318 } 4319 4320 // The apk is forward locked (not public) if its code and resources 4321 // are kept in different files. (except for app in either system or 4322 // vendor path). 4323 // TODO grab this value from PackageSettings 4324 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4325 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4326 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 4327 } 4328 } 4329 4330 // TODO: extend to support forward-locked splits 4331 String resourcePath = null; 4332 String baseResourcePath = null; 4333 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 4334 if (ps != null && ps.resourcePathString != null) { 4335 resourcePath = ps.resourcePathString; 4336 baseResourcePath = ps.resourcePathString; 4337 } else { 4338 // Should not happen at all. Just log an error. 4339 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 4340 } 4341 } else { 4342 resourcePath = pkg.codePath; 4343 baseResourcePath = pkg.baseCodePath; 4344 } 4345 4346 // Set application objects path explicitly. 4347 pkg.applicationInfo.setCodePath(pkg.codePath); 4348 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 4349 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 4350 pkg.applicationInfo.setResourcePath(resourcePath); 4351 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 4352 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 4353 4354 // Note that we invoke the following method only if we are about to unpack an application 4355 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode 4356 | SCAN_UPDATE_SIGNATURE, currentTime, user, abiOverride); 4357 4358 /* 4359 * If the system app should be overridden by a previously installed 4360 * data, hide the system app now and let the /data/app scan pick it up 4361 * again. 4362 */ 4363 if (shouldHideSystemApp) { 4364 synchronized (mPackages) { 4365 /* 4366 * We have to grant systems permissions before we hide, because 4367 * grantPermissions will assume the package update is trying to 4368 * expand its permissions. 4369 */ 4370 grantPermissionsLPw(pkg, true); 4371 mSettings.disableSystemPackageLPw(pkg.packageName); 4372 } 4373 } 4374 4375 return scannedPkg; 4376 } 4377 4378 private static String fixProcessName(String defProcessName, 4379 String processName, int uid) { 4380 if (processName == null) { 4381 return defProcessName; 4382 } 4383 return processName; 4384 } 4385 4386 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 4387 throws PackageManagerException { 4388 if (pkgSetting.signatures.mSignatures != null) { 4389 // Already existing package. Make sure signatures match 4390 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 4391 == PackageManager.SIGNATURE_MATCH; 4392 if (!match) { 4393 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 4394 == PackageManager.SIGNATURE_MATCH; 4395 } 4396 if (!match) { 4397 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 4398 + pkg.packageName + " signatures do not match the " 4399 + "previously installed version; ignoring!"); 4400 } 4401 } 4402 4403 // Check for shared user signatures 4404 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 4405 // Already existing package. Make sure signatures match 4406 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4407 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 4408 if (!match) { 4409 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 4410 == PackageManager.SIGNATURE_MATCH; 4411 } 4412 if (!match) { 4413 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 4414 "Package " + pkg.packageName 4415 + " has no signatures that match those in shared user " 4416 + pkgSetting.sharedUser.name + "; ignoring!"); 4417 } 4418 } 4419 } 4420 4421 /** 4422 * Enforces that only the system UID or root's UID can call a method exposed 4423 * via Binder. 4424 * 4425 * @param message used as message if SecurityException is thrown 4426 * @throws SecurityException if the caller is not system or root 4427 */ 4428 private static final void enforceSystemOrRoot(String message) { 4429 final int uid = Binder.getCallingUid(); 4430 if (uid != Process.SYSTEM_UID && uid != 0) { 4431 throw new SecurityException(message); 4432 } 4433 } 4434 4435 @Override 4436 public void performBootDexOpt() { 4437 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4438 4439 final HashSet<PackageParser.Package> pkgs; 4440 synchronized (mPackages) { 4441 pkgs = mDeferredDexOpt; 4442 mDeferredDexOpt = null; 4443 } 4444 4445 if (pkgs != null) { 4446 // Filter out packages that aren't recently used. 4447 // 4448 // The exception is first boot of a non-eng device, which 4449 // should do a full dexopt. 4450 boolean eng = "eng".equals(SystemProperties.get("ro.build.type")); 4451 if (eng || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 4452 // TODO: add a property to control this? 4453 long dexOptLRUThresholdInMinutes; 4454 if (eng) { 4455 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 4456 } else { 4457 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 4458 } 4459 long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 4460 4461 int total = pkgs.size(); 4462 int skipped = 0; 4463 long now = System.currentTimeMillis(); 4464 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 4465 PackageParser.Package pkg = i.next(); 4466 long then = pkg.mLastPackageUsageTimeInMills; 4467 if (then + dexOptLRUThresholdInMills < now) { 4468 if (DEBUG_DEXOPT) { 4469 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 4470 ((then == 0) ? "never" : new Date(then))); 4471 } 4472 i.remove(); 4473 skipped++; 4474 } 4475 } 4476 if (DEBUG_DEXOPT) { 4477 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 4478 } 4479 } 4480 4481 int i = 0; 4482 for (PackageParser.Package pkg : pkgs) { 4483 i++; 4484 if (DEBUG_DEXOPT) { 4485 Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size() 4486 + ": " + pkg.packageName); 4487 } 4488 if (!isFirstBoot()) { 4489 try { 4490 ActivityManagerNative.getDefault().showBootMessage( 4491 mContext.getResources().getString( 4492 R.string.android_upgrading_apk, 4493 i, pkgs.size()), true); 4494 } catch (RemoteException e) { 4495 } 4496 } 4497 PackageParser.Package p = pkg; 4498 synchronized (mInstallLock) { 4499 performDexOptLI(p, null /* instruction sets */, false /* force dex */, false /* defer */, 4500 true /* include dependencies */); 4501 } 4502 } 4503 } 4504 } 4505 4506 @Override 4507 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 4508 return performDexOpt(packageName, instructionSet, true); 4509 } 4510 4511 private static String getPrimaryInstructionSet(ApplicationInfo info) { 4512 if (info.primaryCpuAbi == null) { 4513 return getPreferredInstructionSet(); 4514 } 4515 4516 return VMRuntime.getInstructionSet(info.primaryCpuAbi); 4517 } 4518 4519 public boolean performDexOpt(String packageName, String instructionSet, boolean updateUsage) { 4520 PackageParser.Package p; 4521 final String targetInstructionSet; 4522 synchronized (mPackages) { 4523 p = mPackages.get(packageName); 4524 if (p == null) { 4525 return false; 4526 } 4527 if (updateUsage) { 4528 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 4529 } 4530 mPackageUsage.write(false); 4531 4532 targetInstructionSet = instructionSet != null ? instructionSet : 4533 getPrimaryInstructionSet(p.applicationInfo); 4534 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 4535 return false; 4536 } 4537 } 4538 4539 synchronized (mInstallLock) { 4540 final String[] instructionSets = new String[] { targetInstructionSet }; 4541 return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */, 4542 true /* include dependencies */) == DEX_OPT_PERFORMED; 4543 } 4544 } 4545 4546 public HashSet<String> getPackagesThatNeedDexOpt() { 4547 HashSet<String> pkgs = null; 4548 synchronized (mPackages) { 4549 for (PackageParser.Package p : mPackages.values()) { 4550 if (DEBUG_DEXOPT) { 4551 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 4552 } 4553 if (!p.mDexOptPerformed.isEmpty()) { 4554 continue; 4555 } 4556 if (pkgs == null) { 4557 pkgs = new HashSet<String>(); 4558 } 4559 pkgs.add(p.packageName); 4560 } 4561 } 4562 return pkgs; 4563 } 4564 4565 public void shutdown() { 4566 mPackageUsage.write(true); 4567 } 4568 4569 private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets, 4570 boolean forceDex, boolean defer, HashSet<String> done) { 4571 for (int i=0; i<libs.size(); i++) { 4572 PackageParser.Package libPkg; 4573 String libName; 4574 synchronized (mPackages) { 4575 libName = libs.get(i); 4576 SharedLibraryEntry lib = mSharedLibraries.get(libName); 4577 if (lib != null && lib.apk != null) { 4578 libPkg = mPackages.get(lib.apk); 4579 } else { 4580 libPkg = null; 4581 } 4582 } 4583 if (libPkg != null && !done.contains(libName)) { 4584 performDexOptLI(libPkg, instructionSets, forceDex, defer, done); 4585 } 4586 } 4587 } 4588 4589 static final int DEX_OPT_SKIPPED = 0; 4590 static final int DEX_OPT_PERFORMED = 1; 4591 static final int DEX_OPT_DEFERRED = 2; 4592 static final int DEX_OPT_FAILED = -1; 4593 4594 private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets, 4595 boolean forceDex, boolean defer, HashSet<String> done) { 4596 final String[] instructionSets = targetInstructionSets != null ? 4597 targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo); 4598 4599 if (done != null) { 4600 done.add(pkg.packageName); 4601 if (pkg.usesLibraries != null) { 4602 performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done); 4603 } 4604 if (pkg.usesOptionalLibraries != null) { 4605 performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done); 4606 } 4607 } 4608 4609 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) { 4610 return DEX_OPT_SKIPPED; 4611 } 4612 4613 final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly(); 4614 boolean performedDexOpt = false; 4615 // There are three basic cases here: 4616 // 1.) we need to dexopt, either because we are forced or it is needed 4617 // 2.) we are defering a needed dexopt 4618 // 3.) we are skipping an unneeded dexopt 4619 for (String path : paths) { 4620 for (String instructionSet : instructionSets) { 4621 if (!forceDex && pkg.mDexOptPerformed.contains(instructionSet)) { 4622 continue; 4623 } 4624 4625 try { 4626 final boolean isDexOptNeeded = DexFile.isDexOptNeededInternal(path, 4627 pkg.packageName, instructionSet, defer); 4628 if (forceDex || (!defer && isDexOptNeeded)) { 4629 Log.i(TAG, "Running dexopt on: " + path + " pkg=" 4630 + pkg.applicationInfo.packageName + " isa=" + instructionSet); 4631 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4632 final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg), 4633 pkg.packageName, instructionSet); 4634 4635 if (ret < 0) { 4636 // Don't bother running dexopt again if we failed, it will probably 4637 // just result in an error again. Also, don't bother dexopting for other 4638 // paths & ISAs. 4639 return DEX_OPT_FAILED; 4640 } else { 4641 performedDexOpt = true; 4642 pkg.mDexOptPerformed.add(instructionSet); 4643 } 4644 } 4645 4646 // We're deciding to defer a needed dexopt. Don't bother dexopting for other 4647 // paths and instruction sets. We'll deal with them all together when we process 4648 // our list of deferred dexopts. 4649 if (defer && isDexOptNeeded) { 4650 if (mDeferredDexOpt == null) { 4651 mDeferredDexOpt = new HashSet<PackageParser.Package>(); 4652 } 4653 mDeferredDexOpt.add(pkg); 4654 return DEX_OPT_DEFERRED; 4655 } 4656 } catch (FileNotFoundException e) { 4657 Slog.w(TAG, "Apk not found for dexopt: " + path); 4658 return DEX_OPT_FAILED; 4659 } catch (IOException e) { 4660 Slog.w(TAG, "IOException reading apk: " + path, e); 4661 return DEX_OPT_FAILED; 4662 } catch (StaleDexCacheError e) { 4663 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e); 4664 return DEX_OPT_FAILED; 4665 } catch (Exception e) { 4666 Slog.w(TAG, "Exception when doing dexopt : ", e); 4667 return DEX_OPT_FAILED; 4668 } 4669 } 4670 } 4671 4672 // If we've gotten here, we're sure that no error occurred and that we haven't 4673 // deferred dex-opt. We've either dex-opted one more paths or instruction sets or 4674 // we've skipped all of them because they are up to date. In both cases this 4675 // package doesn't need dexopt any longer. 4676 return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED; 4677 } 4678 4679 private static String[] getAppDexInstructionSets(ApplicationInfo info) { 4680 if (info.primaryCpuAbi != null) { 4681 if (info.secondaryCpuAbi != null) { 4682 return new String[] { 4683 VMRuntime.getInstructionSet(info.primaryCpuAbi), 4684 VMRuntime.getInstructionSet(info.secondaryCpuAbi) }; 4685 } else { 4686 return new String[] { 4687 VMRuntime.getInstructionSet(info.primaryCpuAbi) }; 4688 } 4689 } 4690 4691 return new String[] { getPreferredInstructionSet() }; 4692 } 4693 4694 private static String[] getAppDexInstructionSets(PackageSetting ps) { 4695 if (ps.primaryCpuAbiString != null) { 4696 if (ps.secondaryCpuAbiString != null) { 4697 return new String[] { 4698 VMRuntime.getInstructionSet(ps.primaryCpuAbiString), 4699 VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) }; 4700 } else { 4701 return new String[] { 4702 VMRuntime.getInstructionSet(ps.primaryCpuAbiString) }; 4703 } 4704 } 4705 4706 return new String[] { getPreferredInstructionSet() }; 4707 } 4708 4709 private static String getPreferredInstructionSet() { 4710 if (sPreferredInstructionSet == null) { 4711 sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]); 4712 } 4713 4714 return sPreferredInstructionSet; 4715 } 4716 4717 private static List<String> getAllInstructionSets() { 4718 final String[] allAbis = Build.SUPPORTED_ABIS; 4719 final List<String> allInstructionSets = new ArrayList<String>(allAbis.length); 4720 4721 for (String abi : allAbis) { 4722 final String instructionSet = VMRuntime.getInstructionSet(abi); 4723 if (!allInstructionSets.contains(instructionSet)) { 4724 allInstructionSets.add(instructionSet); 4725 } 4726 } 4727 4728 return allInstructionSets; 4729 } 4730 4731 @Override 4732 public void forceDexOpt(String packageName) { 4733 enforceSystemOrRoot("forceDexOpt"); 4734 4735 PackageParser.Package pkg; 4736 synchronized (mPackages) { 4737 pkg = mPackages.get(packageName); 4738 if (pkg == null) { 4739 throw new IllegalArgumentException("Missing package: " + packageName); 4740 } 4741 } 4742 4743 synchronized (mInstallLock) { 4744 final String[] instructionSets = new String[] { 4745 getPrimaryInstructionSet(pkg.applicationInfo) }; 4746 final int res = performDexOptLI(pkg, instructionSets, true, false, true); 4747 if (res != DEX_OPT_PERFORMED) { 4748 throw new IllegalStateException("Failed to dexopt: " + res); 4749 } 4750 } 4751 } 4752 4753 private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets, 4754 boolean forceDex, boolean defer, boolean inclDependencies) { 4755 HashSet<String> done; 4756 if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) { 4757 done = new HashSet<String>(); 4758 done.add(pkg.packageName); 4759 } else { 4760 done = null; 4761 } 4762 return performDexOptLI(pkg, instructionSets, forceDex, defer, done); 4763 } 4764 4765 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 4766 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 4767 Slog.w(TAG, "Unable to update from " + oldPkg.name 4768 + " to " + newPkg.packageName 4769 + ": old package not in system partition"); 4770 return false; 4771 } else if (mPackages.get(oldPkg.name) != null) { 4772 Slog.w(TAG, "Unable to update from " + oldPkg.name 4773 + " to " + newPkg.packageName 4774 + ": old package still exists"); 4775 return false; 4776 } 4777 return true; 4778 } 4779 4780 File getDataPathForUser(int userId) { 4781 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId); 4782 } 4783 4784 private File getDataPathForPackage(String packageName, int userId) { 4785 /* 4786 * Until we fully support multiple users, return the directory we 4787 * previously would have. The PackageManagerTests will need to be 4788 * revised when this is changed back.. 4789 */ 4790 if (userId == 0) { 4791 return new File(mAppDataDir, packageName); 4792 } else { 4793 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 4794 + File.separator + packageName); 4795 } 4796 } 4797 4798 private int createDataDirsLI(String packageName, int uid, String seinfo) { 4799 int[] users = sUserManager.getUserIds(); 4800 int res = mInstaller.install(packageName, uid, uid, seinfo); 4801 if (res < 0) { 4802 return res; 4803 } 4804 for (int user : users) { 4805 if (user != 0) { 4806 res = mInstaller.createUserData(packageName, 4807 UserHandle.getUid(user, uid), user, seinfo); 4808 if (res < 0) { 4809 return res; 4810 } 4811 } 4812 } 4813 return res; 4814 } 4815 4816 private int removeDataDirsLI(String packageName) { 4817 int[] users = sUserManager.getUserIds(); 4818 int res = 0; 4819 for (int user : users) { 4820 int resInner = mInstaller.remove(packageName, user); 4821 if (resInner < 0) { 4822 res = resInner; 4823 } 4824 } 4825 4826 return res; 4827 } 4828 4829 private int deleteCodeCacheDirsLI(String packageName) { 4830 int[] users = sUserManager.getUserIds(); 4831 int res = 0; 4832 for (int user : users) { 4833 int resInner = mInstaller.deleteCodeCacheFiles(packageName, user); 4834 if (resInner < 0) { 4835 res = resInner; 4836 } 4837 } 4838 return res; 4839 } 4840 4841 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 4842 PackageParser.Package changingLib) { 4843 if (file.path != null) { 4844 usesLibraryFiles.add(file.path); 4845 return; 4846 } 4847 PackageParser.Package p = mPackages.get(file.apk); 4848 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 4849 // If we are doing this while in the middle of updating a library apk, 4850 // then we need to make sure to use that new apk for determining the 4851 // dependencies here. (We haven't yet finished committing the new apk 4852 // to the package manager state.) 4853 if (p == null || p.packageName.equals(changingLib.packageName)) { 4854 p = changingLib; 4855 } 4856 } 4857 if (p != null) { 4858 usesLibraryFiles.addAll(p.getAllCodePaths()); 4859 } 4860 } 4861 4862 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 4863 PackageParser.Package changingLib) throws PackageManagerException { 4864 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 4865 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 4866 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 4867 for (int i=0; i<N; i++) { 4868 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 4869 if (file == null) { 4870 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 4871 "Package " + pkg.packageName + " requires unavailable shared library " 4872 + pkg.usesLibraries.get(i) + "; failing!"); 4873 } 4874 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4875 } 4876 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 4877 for (int i=0; i<N; i++) { 4878 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 4879 if (file == null) { 4880 Slog.w(TAG, "Package " + pkg.packageName 4881 + " desires unavailable shared library " 4882 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 4883 } else { 4884 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4885 } 4886 } 4887 N = usesLibraryFiles.size(); 4888 if (N > 0) { 4889 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 4890 } else { 4891 pkg.usesLibraryFiles = null; 4892 } 4893 } 4894 } 4895 4896 private static boolean hasString(List<String> list, List<String> which) { 4897 if (list == null) { 4898 return false; 4899 } 4900 for (int i=list.size()-1; i>=0; i--) { 4901 for (int j=which.size()-1; j>=0; j--) { 4902 if (which.get(j).equals(list.get(i))) { 4903 return true; 4904 } 4905 } 4906 } 4907 return false; 4908 } 4909 4910 private void updateAllSharedLibrariesLPw() { 4911 for (PackageParser.Package pkg : mPackages.values()) { 4912 try { 4913 updateSharedLibrariesLPw(pkg, null); 4914 } catch (PackageManagerException e) { 4915 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 4916 } 4917 } 4918 } 4919 4920 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 4921 PackageParser.Package changingPkg) { 4922 ArrayList<PackageParser.Package> res = null; 4923 for (PackageParser.Package pkg : mPackages.values()) { 4924 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 4925 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 4926 if (res == null) { 4927 res = new ArrayList<PackageParser.Package>(); 4928 } 4929 res.add(pkg); 4930 try { 4931 updateSharedLibrariesLPw(pkg, changingPkg); 4932 } catch (PackageManagerException e) { 4933 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 4934 } 4935 } 4936 } 4937 return res; 4938 } 4939 4940 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 4941 int scanMode, long currentTime, UserHandle user, String abiOverride) 4942 throws PackageManagerException { 4943 final File scanFile = new File(pkg.codePath); 4944 if (pkg.applicationInfo.getCodePath() == null || 4945 pkg.applicationInfo.getResourcePath() == null) { 4946 // Bail out. The resource and code paths haven't been set. 4947 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 4948 "Code and resource paths haven't been set correctly"); 4949 } 4950 4951 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4952 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 4953 } 4954 4955 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 4956 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED; 4957 } 4958 4959 if (mCustomResolverComponentName != null && 4960 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 4961 setUpCustomResolverActivity(pkg); 4962 } 4963 4964 if (pkg.packageName.equals("android")) { 4965 synchronized (mPackages) { 4966 if (mAndroidApplication != null) { 4967 Slog.w(TAG, "*************************************************"); 4968 Slog.w(TAG, "Core android package being redefined. Skipping."); 4969 Slog.w(TAG, " file=" + scanFile); 4970 Slog.w(TAG, "*************************************************"); 4971 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 4972 "Core android package being redefined. Skipping."); 4973 } 4974 4975 // Set up information for our fall-back user intent resolution activity. 4976 mPlatformPackage = pkg; 4977 pkg.mVersionCode = mSdkVersion; 4978 mAndroidApplication = pkg.applicationInfo; 4979 4980 if (!mResolverReplaced) { 4981 mResolveActivity.applicationInfo = mAndroidApplication; 4982 mResolveActivity.name = ResolverActivity.class.getName(); 4983 mResolveActivity.packageName = mAndroidApplication.packageName; 4984 mResolveActivity.processName = "system:ui"; 4985 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 4986 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 4987 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 4988 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 4989 mResolveActivity.exported = true; 4990 mResolveActivity.enabled = true; 4991 mResolveInfo.activityInfo = mResolveActivity; 4992 mResolveInfo.priority = 0; 4993 mResolveInfo.preferredOrder = 0; 4994 mResolveInfo.match = 0; 4995 mResolveComponentName = new ComponentName( 4996 mAndroidApplication.packageName, mResolveActivity.name); 4997 } 4998 } 4999 } 5000 5001 if (DEBUG_PACKAGE_SCANNING) { 5002 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5003 Log.d(TAG, "Scanning package " + pkg.packageName); 5004 } 5005 5006 if (mPackages.containsKey(pkg.packageName) 5007 || mSharedLibraries.containsKey(pkg.packageName)) { 5008 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5009 "Application package " + pkg.packageName 5010 + " already installed. Skipping duplicate."); 5011 } 5012 5013 // Initialize package source and resource directories 5014 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5015 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5016 5017 SharedUserSetting suid = null; 5018 PackageSetting pkgSetting = null; 5019 5020 if (!isSystemApp(pkg)) { 5021 // Only system apps can use these features. 5022 pkg.mOriginalPackages = null; 5023 pkg.mRealPackage = null; 5024 pkg.mAdoptPermissions = null; 5025 } 5026 5027 // writer 5028 synchronized (mPackages) { 5029 if (pkg.mSharedUserId != null) { 5030 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true); 5031 if (suid == null) { 5032 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5033 "Creating application package " + pkg.packageName 5034 + " for shared user failed"); 5035 } 5036 if (DEBUG_PACKAGE_SCANNING) { 5037 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5038 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5039 + "): packages=" + suid.packages); 5040 } 5041 } 5042 5043 // Check if we are renaming from an original package name. 5044 PackageSetting origPackage = null; 5045 String realName = null; 5046 if (pkg.mOriginalPackages != null) { 5047 // This package may need to be renamed to a previously 5048 // installed name. Let's check on that... 5049 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5050 if (pkg.mOriginalPackages.contains(renamed)) { 5051 // This package had originally been installed as the 5052 // original name, and we have already taken care of 5053 // transitioning to the new one. Just update the new 5054 // one to continue using the old name. 5055 realName = pkg.mRealPackage; 5056 if (!pkg.packageName.equals(renamed)) { 5057 // Callers into this function may have already taken 5058 // care of renaming the package; only do it here if 5059 // it is not already done. 5060 pkg.setPackageName(renamed); 5061 } 5062 5063 } else { 5064 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5065 if ((origPackage = mSettings.peekPackageLPr( 5066 pkg.mOriginalPackages.get(i))) != null) { 5067 // We do have the package already installed under its 5068 // original name... should we use it? 5069 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5070 // New package is not compatible with original. 5071 origPackage = null; 5072 continue; 5073 } else if (origPackage.sharedUser != null) { 5074 // Make sure uid is compatible between packages. 5075 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5076 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5077 + " to " + pkg.packageName + ": old uid " 5078 + origPackage.sharedUser.name 5079 + " differs from " + pkg.mSharedUserId); 5080 origPackage = null; 5081 continue; 5082 } 5083 } else { 5084 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5085 + pkg.packageName + " to old name " + origPackage.name); 5086 } 5087 break; 5088 } 5089 } 5090 } 5091 } 5092 5093 if (mTransferedPackages.contains(pkg.packageName)) { 5094 Slog.w(TAG, "Package " + pkg.packageName 5095 + " was transferred to another, but its .apk remains"); 5096 } 5097 5098 // Just create the setting, don't add it yet. For already existing packages 5099 // the PkgSetting exists already and doesn't have to be created. 5100 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5101 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 5102 pkg.applicationInfo.primaryCpuAbi, 5103 pkg.applicationInfo.secondaryCpuAbi, 5104 pkg.applicationInfo.flags, user, false); 5105 if (pkgSetting == null) { 5106 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5107 "Creating application package " + pkg.packageName + " failed"); 5108 } 5109 5110 if (pkgSetting.origPackage != null) { 5111 // If we are first transitioning from an original package, 5112 // fix up the new package's name now. We need to do this after 5113 // looking up the package under its new name, so getPackageLP 5114 // can take care of fiddling things correctly. 5115 pkg.setPackageName(origPackage.name); 5116 5117 // File a report about this. 5118 String msg = "New package " + pkgSetting.realName 5119 + " renamed to replace old package " + pkgSetting.name; 5120 reportSettingsProblem(Log.WARN, msg); 5121 5122 // Make a note of it. 5123 mTransferedPackages.add(origPackage.name); 5124 5125 // No longer need to retain this. 5126 pkgSetting.origPackage = null; 5127 } 5128 5129 if (realName != null) { 5130 // Make a note of it. 5131 mTransferedPackages.add(pkg.packageName); 5132 } 5133 5134 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5135 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5136 } 5137 5138 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5139 // Check all shared libraries and map to their actual file path. 5140 // We only do this here for apps not on a system dir, because those 5141 // are the only ones that can fail an install due to this. We 5142 // will take care of the system apps by updating all of their 5143 // library paths after the scan is done. 5144 updateSharedLibrariesLPw(pkg, null); 5145 } 5146 5147 if (mFoundPolicyFile) { 5148 SELinuxMMAC.assignSeinfoValue(pkg); 5149 } 5150 5151 pkg.applicationInfo.uid = pkgSetting.appId; 5152 pkg.mExtras = pkgSetting; 5153 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5154 try { 5155 verifySignaturesLP(pkgSetting, pkg); 5156 } catch (PackageManagerException e) { 5157 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5158 throw e; 5159 } 5160 // The signature has changed, but this package is in the system 5161 // image... let's recover! 5162 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5163 // However... if this package is part of a shared user, but it 5164 // doesn't match the signature of the shared user, let's fail. 5165 // What this means is that you can't change the signatures 5166 // associated with an overall shared user, which doesn't seem all 5167 // that unreasonable. 5168 if (pkgSetting.sharedUser != null) { 5169 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5170 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5171 throw new PackageManagerException( 5172 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 5173 "Signature mismatch for shared user : " 5174 + pkgSetting.sharedUser); 5175 } 5176 } 5177 // File a report about this. 5178 String msg = "System package " + pkg.packageName 5179 + " signature changed; retaining data."; 5180 reportSettingsProblem(Log.WARN, msg); 5181 } 5182 } else { 5183 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 5184 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5185 + pkg.packageName + " upgrade keys do not match the " 5186 + "previously installed version"); 5187 } else { 5188 // signatures may have changed as result of upgrade 5189 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5190 } 5191 } 5192 // Verify that this new package doesn't have any content providers 5193 // that conflict with existing packages. Only do this if the 5194 // package isn't already installed, since we don't want to break 5195 // things that are installed. 5196 if ((scanMode&SCAN_NEW_INSTALL) != 0) { 5197 final int N = pkg.providers.size(); 5198 int i; 5199 for (i=0; i<N; i++) { 5200 PackageParser.Provider p = pkg.providers.get(i); 5201 if (p.info.authority != null) { 5202 String names[] = p.info.authority.split(";"); 5203 for (int j = 0; j < names.length; j++) { 5204 if (mProvidersByAuthority.containsKey(names[j])) { 5205 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5206 final String otherPackageName = 5207 ((other != null && other.getComponentName() != null) ? 5208 other.getComponentName().getPackageName() : "?"); 5209 throw new PackageManagerException( 5210 INSTALL_FAILED_CONFLICTING_PROVIDER, 5211 "Can't install because provider name " + names[j] 5212 + " (in package " + pkg.applicationInfo.packageName 5213 + ") is already used by " + otherPackageName); 5214 } 5215 } 5216 } 5217 } 5218 } 5219 5220 if (pkg.mAdoptPermissions != null) { 5221 // This package wants to adopt ownership of permissions from 5222 // another package. 5223 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 5224 final String origName = pkg.mAdoptPermissions.get(i); 5225 final PackageSetting orig = mSettings.peekPackageLPr(origName); 5226 if (orig != null) { 5227 if (verifyPackageUpdateLPr(orig, pkg)) { 5228 Slog.i(TAG, "Adopting permissions from " + origName + " to " 5229 + pkg.packageName); 5230 mSettings.transferPermissionsLPw(origName, pkg.packageName); 5231 } 5232 } 5233 } 5234 } 5235 } 5236 5237 final String pkgName = pkg.packageName; 5238 5239 final long scanFileTime = scanFile.lastModified(); 5240 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0; 5241 pkg.applicationInfo.processName = fixProcessName( 5242 pkg.applicationInfo.packageName, 5243 pkg.applicationInfo.processName, 5244 pkg.applicationInfo.uid); 5245 5246 File dataPath; 5247 if (mPlatformPackage == pkg) { 5248 // The system package is special. 5249 dataPath = new File (Environment.getDataDirectory(), "system"); 5250 pkg.applicationInfo.dataDir = dataPath.getPath(); 5251 5252 } else { 5253 // This is a normal package, need to make its data directory. 5254 dataPath = getDataPathForPackage(pkg.packageName, 0); 5255 5256 boolean uidError = false; 5257 5258 if (dataPath.exists()) { 5259 int currentUid = 0; 5260 try { 5261 StructStat stat = Os.stat(dataPath.getPath()); 5262 currentUid = stat.st_uid; 5263 } catch (ErrnoException e) { 5264 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 5265 } 5266 5267 // If we have mismatched owners for the data path, we have a problem. 5268 if (currentUid != pkg.applicationInfo.uid) { 5269 boolean recovered = false; 5270 if (currentUid == 0) { 5271 // The directory somehow became owned by root. Wow. 5272 // This is probably because the system was stopped while 5273 // installd was in the middle of messing with its libs 5274 // directory. Ask installd to fix that. 5275 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 5276 pkg.applicationInfo.uid); 5277 if (ret >= 0) { 5278 recovered = true; 5279 String msg = "Package " + pkg.packageName 5280 + " unexpectedly changed to uid 0; recovered to " + 5281 + pkg.applicationInfo.uid; 5282 reportSettingsProblem(Log.WARN, msg); 5283 } 5284 } 5285 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5286 || (scanMode&SCAN_BOOTING) != 0)) { 5287 // If this is a system app, we can at least delete its 5288 // current data so the application will still work. 5289 int ret = removeDataDirsLI(pkgName); 5290 if (ret >= 0) { 5291 // TODO: Kill the processes first 5292 // Old data gone! 5293 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5294 ? "System package " : "Third party package "; 5295 String msg = prefix + pkg.packageName 5296 + " has changed from uid: " 5297 + currentUid + " to " 5298 + pkg.applicationInfo.uid + "; old data erased"; 5299 reportSettingsProblem(Log.WARN, msg); 5300 recovered = true; 5301 5302 // And now re-install the app. 5303 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5304 pkg.applicationInfo.seinfo); 5305 if (ret == -1) { 5306 // Ack should not happen! 5307 msg = prefix + pkg.packageName 5308 + " could not have data directory re-created after delete."; 5309 reportSettingsProblem(Log.WARN, msg); 5310 throw new PackageManagerException( 5311 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 5312 } 5313 } 5314 if (!recovered) { 5315 mHasSystemUidErrors = true; 5316 } 5317 } else if (!recovered) { 5318 // If we allow this install to proceed, we will be broken. 5319 // Abort, abort! 5320 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 5321 "scanPackageLI"); 5322 } 5323 if (!recovered) { 5324 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 5325 + pkg.applicationInfo.uid + "/fs_" 5326 + currentUid; 5327 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 5328 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 5329 String msg = "Package " + pkg.packageName 5330 + " has mismatched uid: " 5331 + currentUid + " on disk, " 5332 + pkg.applicationInfo.uid + " in settings"; 5333 // writer 5334 synchronized (mPackages) { 5335 mSettings.mReadMessages.append(msg); 5336 mSettings.mReadMessages.append('\n'); 5337 uidError = true; 5338 if (!pkgSetting.uidError) { 5339 reportSettingsProblem(Log.ERROR, msg); 5340 } 5341 } 5342 } 5343 } 5344 pkg.applicationInfo.dataDir = dataPath.getPath(); 5345 if (mShouldRestoreconData) { 5346 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 5347 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 5348 pkg.applicationInfo.uid); 5349 } 5350 } else { 5351 if (DEBUG_PACKAGE_SCANNING) { 5352 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5353 Log.v(TAG, "Want this data dir: " + dataPath); 5354 } 5355 //invoke installer to do the actual installation 5356 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5357 pkg.applicationInfo.seinfo); 5358 if (ret < 0) { 5359 // Error from installer 5360 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5361 "Unable to create data dirs [errorCode=" + ret + "]"); 5362 } 5363 5364 if (dataPath.exists()) { 5365 pkg.applicationInfo.dataDir = dataPath.getPath(); 5366 } else { 5367 Slog.w(TAG, "Unable to create data directory: " + dataPath); 5368 pkg.applicationInfo.dataDir = null; 5369 } 5370 } 5371 5372 pkgSetting.uidError = uidError; 5373 } 5374 5375 final String path = scanFile.getPath(); 5376 final String codePath = pkg.applicationInfo.getCodePath(); 5377 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 5378 // For the case where we had previously uninstalled an update, get rid 5379 // of any native binaries we might have unpackaged. Note that this assumes 5380 // that system app updates were not installed via ASEC. 5381 // 5382 // TODO(multiArch): Is this cleanup really necessary ? 5383 NativeLibraryHelper.removeNativeBinariesFromDirLI( 5384 new File(codePath, LIB_DIR_NAME), false /* delete dirs */); 5385 setBundledAppAbisAndRoots(pkg, pkgSetting); 5386 5387 // If we haven't found any native libraries for the app, check if it has 5388 // renderscript code. We'll need to force the app to 32 bit if it has 5389 // renderscript bitcode. 5390 if (pkg.applicationInfo.primaryCpuAbi == null 5391 && pkg.applicationInfo.secondaryCpuAbi == null 5392 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5393 NativeLibraryHelper.Handle handle = null; 5394 try { 5395 handle = NativeLibraryHelper.Handle.create(scanFile); 5396 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5397 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 5398 } 5399 } catch (IOException ioe) { 5400 Slog.w(TAG, "Error scanning system app : " + ioe); 5401 } finally { 5402 IoUtils.closeQuietly(handle); 5403 } 5404 } 5405 5406 setNativeLibraryPaths(pkg); 5407 } else { 5408 // TODO: We can probably be smarter about this stuff. For installed apps, 5409 // we can calculate this information at install time once and for all. For 5410 // system apps, we can probably assume that this information doesn't change 5411 // after the first boot scan. As things stand, we do lots of unnecessary work. 5412 5413 // Give ourselves some initial paths; we'll come back for another 5414 // pass once we've determined ABI below. 5415 setNativeLibraryPaths(pkg); 5416 5417 final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg); 5418 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 5419 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 5420 5421 NativeLibraryHelper.Handle handle = null; 5422 try { 5423 handle = NativeLibraryHelper.Handle.create(scanFile); 5424 // TODO(multiArch): This can be null for apps that didn't go through the 5425 // usual installation process. We can calculate it again, like we 5426 // do during install time. 5427 // 5428 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 5429 // unnecessary. 5430 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 5431 5432 // Null out the abis so that they can be recalculated. 5433 pkg.applicationInfo.primaryCpuAbi = null; 5434 pkg.applicationInfo.secondaryCpuAbi = null; 5435 if (isMultiArch(pkg.applicationInfo)) { 5436 // Warn if we've set an abiOverride for multi-lib packages.. 5437 // By definition, we need to copy both 32 and 64 bit libraries for 5438 // such packages. 5439 if (abiOverride != null) { 5440 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 5441 } 5442 5443 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 5444 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 5445 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 5446 if (isAsec) { 5447 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 5448 } else { 5449 abi32 = copyNativeLibrariesForInternalApp(handle, 5450 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, useIsaSpecificSubdirs); 5451 } 5452 } 5453 5454 maybeThrowExceptionForMultiArchCopy( 5455 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 5456 5457 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5458 if (isAsec) { 5459 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 5460 } else { 5461 abi64 = copyNativeLibrariesForInternalApp(handle, 5462 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, useIsaSpecificSubdirs); 5463 } 5464 } 5465 5466 maybeThrowExceptionForMultiArchCopy( 5467 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 5468 5469 if (abi64 >= 0) { 5470 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 5471 } 5472 5473 if (abi32 >= 0) { 5474 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 5475 if (abi64 >= 0) { 5476 pkg.applicationInfo.secondaryCpuAbi = abi; 5477 } else { 5478 pkg.applicationInfo.primaryCpuAbi = abi; 5479 } 5480 } 5481 } else { 5482 String[] abiList = (abiOverride != null) ? 5483 new String[] { abiOverride } : Build.SUPPORTED_ABIS; 5484 5485 // Enable gross and lame hacks for apps that are built with old 5486 // SDK tools. We must scan their APKs for renderscript bitcode and 5487 // not launch them if it's present. Don't bother checking on devices 5488 // that don't have 64 bit support. 5489 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && abiOverride == null && 5490 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5491 abiList = Build.SUPPORTED_32_BIT_ABIS; 5492 } 5493 5494 final int copyRet; 5495 if (isAsec) { 5496 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 5497 } else { 5498 copyRet = copyNativeLibrariesForInternalApp(handle, nativeLibraryRoot, abiList, 5499 useIsaSpecificSubdirs); 5500 } 5501 5502 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5503 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5504 "Error unpackaging native libs for app, errorCode=" + copyRet); 5505 } 5506 5507 if (copyRet >= 0) { 5508 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 5509 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && abiOverride != null) { 5510 pkg.applicationInfo.primaryCpuAbi = abiOverride; 5511 } 5512 } 5513 } catch (IOException ioe) { 5514 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 5515 } finally { 5516 IoUtils.closeQuietly(handle); 5517 } 5518 5519 // Now that we've calculated the ABIs and determined if it's an internal app, 5520 // we will go ahead and populate the nativeLibraryPath. 5521 setNativeLibraryPaths(pkg); 5522 5523 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 5524 final int[] userIds = sUserManager.getUserIds(); 5525 synchronized (mInstallLock) { 5526 // Create a native library symlink only if we have native libraries 5527 // and if the native libraries are 32 bit libraries. We do not provide 5528 // this symlink for 64 bit libraries. 5529 if (pkg.applicationInfo.primaryCpuAbi != null && 5530 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 5531 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 5532 for (int userId : userIds) { 5533 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 5534 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5535 "Failed linking native library dir (user=" + userId + ")"); 5536 } 5537 } 5538 } 5539 } 5540 } 5541 5542 // This is a special case for the "system" package, where the ABI is 5543 // dictated by the zygote configuration (and init.rc). We should keep track 5544 // of this ABI so that we can deal with "normal" applications that run under 5545 // the same UID correctly. 5546 if (mPlatformPackage == pkg) { 5547 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 5548 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 5549 } 5550 5551 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 5552 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 5553 5554 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 5555 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 5556 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 5557 5558 // Push the derived path down into PackageSettings so we know what to 5559 // clean up at uninstall time. 5560 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 5561 5562 if (DEBUG_ABI_SELECTION) { 5563 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 5564 " primary=" + pkg.applicationInfo.primaryCpuAbi + 5565 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 5566 } 5567 5568 if ((scanMode&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 5569 // We don't do this here during boot because we can do it all 5570 // at once after scanning all existing packages. 5571 // 5572 // We also do this *before* we perform dexopt on this package, so that 5573 // we can avoid redundant dexopts, and also to make sure we've got the 5574 // code and package path correct. 5575 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 5576 pkg, forceDex, (scanMode & SCAN_DEFER_DEX) != 0); 5577 } 5578 5579 if ((scanMode&SCAN_NO_DEX) == 0) { 5580 if (performDexOptLI(pkg, null /* instruction sets */, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5581 == DEX_OPT_FAILED) { 5582 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5583 removeDataDirsLI(pkg.packageName); 5584 } 5585 5586 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 5587 } 5588 } 5589 5590 if (mFactoryTest && pkg.requestedPermissions.contains( 5591 android.Manifest.permission.FACTORY_TEST)) { 5592 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 5593 } 5594 5595 ArrayList<PackageParser.Package> clientLibPkgs = null; 5596 5597 // writer 5598 synchronized (mPackages) { 5599 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5600 // Only system apps can add new shared libraries. 5601 if (pkg.libraryNames != null) { 5602 for (int i=0; i<pkg.libraryNames.size(); i++) { 5603 String name = pkg.libraryNames.get(i); 5604 boolean allowed = false; 5605 if (isUpdatedSystemApp(pkg)) { 5606 // New library entries can only be added through the 5607 // system image. This is important to get rid of a lot 5608 // of nasty edge cases: for example if we allowed a non- 5609 // system update of the app to add a library, then uninstalling 5610 // the update would make the library go away, and assumptions 5611 // we made such as through app install filtering would now 5612 // have allowed apps on the device which aren't compatible 5613 // with it. Better to just have the restriction here, be 5614 // conservative, and create many fewer cases that can negatively 5615 // impact the user experience. 5616 final PackageSetting sysPs = mSettings 5617 .getDisabledSystemPkgLPr(pkg.packageName); 5618 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 5619 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 5620 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 5621 allowed = true; 5622 allowed = true; 5623 break; 5624 } 5625 } 5626 } 5627 } else { 5628 allowed = true; 5629 } 5630 if (allowed) { 5631 if (!mSharedLibraries.containsKey(name)) { 5632 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 5633 } else if (!name.equals(pkg.packageName)) { 5634 Slog.w(TAG, "Package " + pkg.packageName + " library " 5635 + name + " already exists; skipping"); 5636 } 5637 } else { 5638 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 5639 + name + " that is not declared on system image; skipping"); 5640 } 5641 } 5642 if ((scanMode&SCAN_BOOTING) == 0) { 5643 // If we are not booting, we need to update any applications 5644 // that are clients of our shared library. If we are booting, 5645 // this will all be done once the scan is complete. 5646 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 5647 } 5648 } 5649 } 5650 } 5651 5652 // We also need to dexopt any apps that are dependent on this library. Note that 5653 // if these fail, we should abort the install since installing the library will 5654 // result in some apps being broken. 5655 if (clientLibPkgs != null) { 5656 if ((scanMode&SCAN_NO_DEX) == 0) { 5657 for (int i=0; i<clientLibPkgs.size(); i++) { 5658 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5659 if (performDexOptLI(clientPkg, null /* instruction sets */, 5660 forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5661 == DEX_OPT_FAILED) { 5662 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5663 removeDataDirsLI(pkg.packageName); 5664 } 5665 5666 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 5667 "scanPackageLI failed to dexopt clientLibPkgs"); 5668 } 5669 } 5670 } 5671 } 5672 5673 // Request the ActivityManager to kill the process(only for existing packages) 5674 // so that we do not end up in a confused state while the user is still using the older 5675 // version of the application while the new one gets installed. 5676 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 5677 // If the package lives in an asec, tell everyone that the container is going 5678 // away so they can clean up any references to its resources (which would prevent 5679 // vold from being able to unmount the asec) 5680 if (isForwardLocked(pkg) || isExternal(pkg)) { 5681 if (DEBUG_INSTALL) { 5682 Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE"); 5683 } 5684 final int[] uidArray = new int[] { pkg.applicationInfo.uid }; 5685 final ArrayList<String> pkgList = new ArrayList<String>(1); 5686 pkgList.add(pkg.applicationInfo.packageName); 5687 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 5688 } 5689 5690 // Post the request that it be killed now that the going-away broadcast is en route 5691 killApplication(pkg.applicationInfo.packageName, 5692 pkg.applicationInfo.uid, "update pkg"); 5693 } 5694 5695 // Also need to kill any apps that are dependent on the library. 5696 if (clientLibPkgs != null) { 5697 for (int i=0; i<clientLibPkgs.size(); i++) { 5698 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5699 killApplication(clientPkg.applicationInfo.packageName, 5700 clientPkg.applicationInfo.uid, "update lib"); 5701 } 5702 } 5703 5704 // writer 5705 synchronized (mPackages) { 5706 // We don't expect installation to fail beyond this point, 5707 if ((scanMode&SCAN_MONITOR) != 0) { 5708 mAppDirs.put(pkg.codePath, pkg); 5709 } 5710 // Add the new setting to mSettings 5711 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 5712 // Add the new setting to mPackages 5713 mPackages.put(pkg.applicationInfo.packageName, pkg); 5714 // Make sure we don't accidentally delete its data. 5715 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 5716 while (iter.hasNext()) { 5717 PackageCleanItem item = iter.next(); 5718 if (pkgName.equals(item.packageName)) { 5719 iter.remove(); 5720 } 5721 } 5722 5723 // Take care of first install / last update times. 5724 if (currentTime != 0) { 5725 if (pkgSetting.firstInstallTime == 0) { 5726 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 5727 } else if ((scanMode&SCAN_UPDATE_TIME) != 0) { 5728 pkgSetting.lastUpdateTime = currentTime; 5729 } 5730 } else if (pkgSetting.firstInstallTime == 0) { 5731 // We need *something*. Take time time stamp of the file. 5732 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 5733 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 5734 if (scanFileTime != pkgSetting.timeStamp) { 5735 // A package on the system image has changed; consider this 5736 // to be an update. 5737 pkgSetting.lastUpdateTime = scanFileTime; 5738 } 5739 } 5740 5741 // Add the package's KeySets to the global KeySetManagerService 5742 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5743 try { 5744 // Old KeySetData no longer valid. 5745 ksms.removeAppKeySetDataLPw(pkg.packageName); 5746 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 5747 if (pkg.mKeySetMapping != null) { 5748 for (Map.Entry<String, ArraySet<PublicKey>> entry : 5749 pkg.mKeySetMapping.entrySet()) { 5750 if (entry.getValue() != null) { 5751 ksms.addDefinedKeySetToPackageLPw(pkg.packageName, 5752 entry.getValue(), entry.getKey()); 5753 } 5754 } 5755 if (pkg.mUpgradeKeySets != null) { 5756 for (String upgradeAlias : pkg.mUpgradeKeySets) { 5757 ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias); 5758 } 5759 } 5760 } 5761 } catch (NullPointerException e) { 5762 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 5763 } catch (IllegalArgumentException e) { 5764 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 5765 } 5766 5767 int N = pkg.providers.size(); 5768 StringBuilder r = null; 5769 int i; 5770 for (i=0; i<N; i++) { 5771 PackageParser.Provider p = pkg.providers.get(i); 5772 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 5773 p.info.processName, pkg.applicationInfo.uid); 5774 mProviders.addProvider(p); 5775 p.syncable = p.info.isSyncable; 5776 if (p.info.authority != null) { 5777 String names[] = p.info.authority.split(";"); 5778 p.info.authority = null; 5779 for (int j = 0; j < names.length; j++) { 5780 if (j == 1 && p.syncable) { 5781 // We only want the first authority for a provider to possibly be 5782 // syncable, so if we already added this provider using a different 5783 // authority clear the syncable flag. We copy the provider before 5784 // changing it because the mProviders object contains a reference 5785 // to a provider that we don't want to change. 5786 // Only do this for the second authority since the resulting provider 5787 // object can be the same for all future authorities for this provider. 5788 p = new PackageParser.Provider(p); 5789 p.syncable = false; 5790 } 5791 if (!mProvidersByAuthority.containsKey(names[j])) { 5792 mProvidersByAuthority.put(names[j], p); 5793 if (p.info.authority == null) { 5794 p.info.authority = names[j]; 5795 } else { 5796 p.info.authority = p.info.authority + ";" + names[j]; 5797 } 5798 if (DEBUG_PACKAGE_SCANNING) { 5799 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5800 Log.d(TAG, "Registered content provider: " + names[j] 5801 + ", className = " + p.info.name + ", isSyncable = " 5802 + p.info.isSyncable); 5803 } 5804 } else { 5805 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5806 Slog.w(TAG, "Skipping provider name " + names[j] + 5807 " (in package " + pkg.applicationInfo.packageName + 5808 "): name already used by " 5809 + ((other != null && other.getComponentName() != null) 5810 ? other.getComponentName().getPackageName() : "?")); 5811 } 5812 } 5813 } 5814 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5815 if (r == null) { 5816 r = new StringBuilder(256); 5817 } else { 5818 r.append(' '); 5819 } 5820 r.append(p.info.name); 5821 } 5822 } 5823 if (r != null) { 5824 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 5825 } 5826 5827 N = pkg.services.size(); 5828 r = null; 5829 for (i=0; i<N; i++) { 5830 PackageParser.Service s = pkg.services.get(i); 5831 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 5832 s.info.processName, pkg.applicationInfo.uid); 5833 mServices.addService(s); 5834 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5835 if (r == null) { 5836 r = new StringBuilder(256); 5837 } else { 5838 r.append(' '); 5839 } 5840 r.append(s.info.name); 5841 } 5842 } 5843 if (r != null) { 5844 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 5845 } 5846 5847 N = pkg.receivers.size(); 5848 r = null; 5849 for (i=0; i<N; i++) { 5850 PackageParser.Activity a = pkg.receivers.get(i); 5851 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5852 a.info.processName, pkg.applicationInfo.uid); 5853 mReceivers.addActivity(a, "receiver"); 5854 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5855 if (r == null) { 5856 r = new StringBuilder(256); 5857 } else { 5858 r.append(' '); 5859 } 5860 r.append(a.info.name); 5861 } 5862 } 5863 if (r != null) { 5864 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 5865 } 5866 5867 N = pkg.activities.size(); 5868 r = null; 5869 for (i=0; i<N; i++) { 5870 PackageParser.Activity a = pkg.activities.get(i); 5871 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5872 a.info.processName, pkg.applicationInfo.uid); 5873 mActivities.addActivity(a, "activity"); 5874 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5875 if (r == null) { 5876 r = new StringBuilder(256); 5877 } else { 5878 r.append(' '); 5879 } 5880 r.append(a.info.name); 5881 } 5882 } 5883 if (r != null) { 5884 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 5885 } 5886 5887 N = pkg.permissionGroups.size(); 5888 r = null; 5889 for (i=0; i<N; i++) { 5890 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 5891 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 5892 if (cur == null) { 5893 mPermissionGroups.put(pg.info.name, pg); 5894 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5895 if (r == null) { 5896 r = new StringBuilder(256); 5897 } else { 5898 r.append(' '); 5899 } 5900 r.append(pg.info.name); 5901 } 5902 } else { 5903 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 5904 + pg.info.packageName + " ignored: original from " 5905 + cur.info.packageName); 5906 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5907 if (r == null) { 5908 r = new StringBuilder(256); 5909 } else { 5910 r.append(' '); 5911 } 5912 r.append("DUP:"); 5913 r.append(pg.info.name); 5914 } 5915 } 5916 } 5917 if (r != null) { 5918 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 5919 } 5920 5921 N = pkg.permissions.size(); 5922 r = null; 5923 for (i=0; i<N; i++) { 5924 PackageParser.Permission p = pkg.permissions.get(i); 5925 HashMap<String, BasePermission> permissionMap = 5926 p.tree ? mSettings.mPermissionTrees 5927 : mSettings.mPermissions; 5928 p.group = mPermissionGroups.get(p.info.group); 5929 if (p.info.group == null || p.group != null) { 5930 BasePermission bp = permissionMap.get(p.info.name); 5931 if (bp == null) { 5932 bp = new BasePermission(p.info.name, p.info.packageName, 5933 BasePermission.TYPE_NORMAL); 5934 permissionMap.put(p.info.name, bp); 5935 } 5936 if (bp.perm == null) { 5937 if (bp.sourcePackage != null 5938 && !bp.sourcePackage.equals(p.info.packageName)) { 5939 // If this is a permission that was formerly defined by a non-system 5940 // app, but is now defined by a system app (following an upgrade), 5941 // discard the previous declaration and consider the system's to be 5942 // canonical. 5943 if (isSystemApp(p.owner)) { 5944 String msg = "New decl " + p.owner + " of permission " 5945 + p.info.name + " is system"; 5946 reportSettingsProblem(Log.WARN, msg); 5947 bp.sourcePackage = null; 5948 } 5949 } 5950 if (bp.sourcePackage == null 5951 || bp.sourcePackage.equals(p.info.packageName)) { 5952 BasePermission tree = findPermissionTreeLP(p.info.name); 5953 if (tree == null 5954 || tree.sourcePackage.equals(p.info.packageName)) { 5955 bp.packageSetting = pkgSetting; 5956 bp.perm = p; 5957 bp.uid = pkg.applicationInfo.uid; 5958 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5959 if (r == null) { 5960 r = new StringBuilder(256); 5961 } else { 5962 r.append(' '); 5963 } 5964 r.append(p.info.name); 5965 } 5966 } else { 5967 Slog.w(TAG, "Permission " + p.info.name + " from package " 5968 + p.info.packageName + " ignored: base tree " 5969 + tree.name + " is from package " 5970 + tree.sourcePackage); 5971 } 5972 } else { 5973 Slog.w(TAG, "Permission " + p.info.name + " from package " 5974 + p.info.packageName + " ignored: original from " 5975 + bp.sourcePackage); 5976 } 5977 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5978 if (r == null) { 5979 r = new StringBuilder(256); 5980 } else { 5981 r.append(' '); 5982 } 5983 r.append("DUP:"); 5984 r.append(p.info.name); 5985 } 5986 if (bp.perm == p) { 5987 bp.protectionLevel = p.info.protectionLevel; 5988 } 5989 } else { 5990 Slog.w(TAG, "Permission " + p.info.name + " from package " 5991 + p.info.packageName + " ignored: no group " 5992 + p.group); 5993 } 5994 } 5995 if (r != null) { 5996 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 5997 } 5998 5999 N = pkg.instrumentation.size(); 6000 r = null; 6001 for (i=0; i<N; i++) { 6002 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6003 a.info.packageName = pkg.applicationInfo.packageName; 6004 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6005 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6006 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6007 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6008 a.info.dataDir = pkg.applicationInfo.dataDir; 6009 6010 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6011 // need other information about the application, like the ABI and what not ? 6012 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6013 mInstrumentation.put(a.getComponentName(), a); 6014 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6015 if (r == null) { 6016 r = new StringBuilder(256); 6017 } else { 6018 r.append(' '); 6019 } 6020 r.append(a.info.name); 6021 } 6022 } 6023 if (r != null) { 6024 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6025 } 6026 6027 if (pkg.protectedBroadcasts != null) { 6028 N = pkg.protectedBroadcasts.size(); 6029 for (i=0; i<N; i++) { 6030 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6031 } 6032 } 6033 6034 pkgSetting.setTimeStamp(scanFileTime); 6035 6036 // Create idmap files for pairs of (packages, overlay packages). 6037 // Note: "android", ie framework-res.apk, is handled by native layers. 6038 if (pkg.mOverlayTarget != null) { 6039 // This is an overlay package. 6040 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6041 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6042 mOverlays.put(pkg.mOverlayTarget, 6043 new HashMap<String, PackageParser.Package>()); 6044 } 6045 HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6046 map.put(pkg.packageName, pkg); 6047 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6048 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6049 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6050 "scanPackageLI failed to createIdmap"); 6051 } 6052 } 6053 } else if (mOverlays.containsKey(pkg.packageName) && 6054 !pkg.packageName.equals("android")) { 6055 // This is a regular package, with one or more known overlay packages. 6056 createIdmapsForPackageLI(pkg); 6057 } 6058 } 6059 6060 return pkg; 6061 } 6062 6063 /** 6064 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6065 * i.e, so that all packages can be run inside a single process if required. 6066 * 6067 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6068 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6069 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6070 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6071 * updating a package that belongs to a shared user. 6072 * 6073 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6074 * adds unnecessary complexity. 6075 */ 6076 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6077 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6078 String requiredInstructionSet = null; 6079 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6080 requiredInstructionSet = VMRuntime.getInstructionSet( 6081 scannedPackage.applicationInfo.primaryCpuAbi); 6082 } 6083 6084 PackageSetting requirer = null; 6085 for (PackageSetting ps : packagesForUser) { 6086 // If packagesForUser contains scannedPackage, we skip it. This will happen 6087 // when scannedPackage is an update of an existing package. Without this check, 6088 // we will never be able to change the ABI of any package belonging to a shared 6089 // user, even if it's compatible with other packages. 6090 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6091 if (ps.primaryCpuAbiString == null) { 6092 continue; 6093 } 6094 6095 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6096 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6097 // We have a mismatch between instruction sets (say arm vs arm64) warn about 6098 // this but there's not much we can do. 6099 String errorMessage = "Instruction set mismatch, " 6100 + ((requirer == null) ? "[caller]" : requirer) 6101 + " requires " + requiredInstructionSet + " whereas " + ps 6102 + " requires " + instructionSet; 6103 Slog.w(TAG, errorMessage); 6104 } 6105 6106 if (requiredInstructionSet == null) { 6107 requiredInstructionSet = instructionSet; 6108 requirer = ps; 6109 } 6110 } 6111 } 6112 6113 if (requiredInstructionSet != null) { 6114 String adjustedAbi; 6115 if (requirer != null) { 6116 // requirer != null implies that either scannedPackage was null or that scannedPackage 6117 // did not require an ABI, in which case we have to adjust scannedPackage to match 6118 // the ABI of the set (which is the same as requirer's ABI) 6119 adjustedAbi = requirer.primaryCpuAbiString; 6120 if (scannedPackage != null) { 6121 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6122 } 6123 } else { 6124 // requirer == null implies that we're updating all ABIs in the set to 6125 // match scannedPackage. 6126 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6127 } 6128 6129 for (PackageSetting ps : packagesForUser) { 6130 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6131 if (ps.primaryCpuAbiString != null) { 6132 continue; 6133 } 6134 6135 ps.primaryCpuAbiString = adjustedAbi; 6136 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6137 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6138 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6139 6140 if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt, 6141 deferDexOpt, true) == DEX_OPT_FAILED) { 6142 ps.primaryCpuAbiString = null; 6143 ps.pkg.applicationInfo.primaryCpuAbi = null; 6144 return; 6145 } else { 6146 mInstaller.rmdex(ps.codePathString, getPreferredInstructionSet()); 6147 } 6148 } 6149 } 6150 } 6151 } 6152 } 6153 6154 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6155 synchronized (mPackages) { 6156 mResolverReplaced = true; 6157 // Set up information for custom user intent resolution activity. 6158 mResolveActivity.applicationInfo = pkg.applicationInfo; 6159 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6160 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6161 mResolveActivity.processName = null; 6162 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6163 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6164 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6165 mResolveActivity.theme = 0; 6166 mResolveActivity.exported = true; 6167 mResolveActivity.enabled = true; 6168 mResolveInfo.activityInfo = mResolveActivity; 6169 mResolveInfo.priority = 0; 6170 mResolveInfo.preferredOrder = 0; 6171 mResolveInfo.match = 0; 6172 mResolveComponentName = mCustomResolverComponentName; 6173 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6174 mResolveComponentName); 6175 } 6176 } 6177 6178 private static String calculateApkRoot(final String codePathString) { 6179 final File codePath = new File(codePathString); 6180 final File codeRoot; 6181 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6182 codeRoot = Environment.getRootDirectory(); 6183 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6184 codeRoot = Environment.getOemDirectory(); 6185 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6186 codeRoot = Environment.getVendorDirectory(); 6187 } else { 6188 // Unrecognized code path; take its top real segment as the apk root: 6189 // e.g. /something/app/blah.apk => /something 6190 try { 6191 File f = codePath.getCanonicalFile(); 6192 File parent = f.getParentFile(); // non-null because codePath is a file 6193 File tmp; 6194 while ((tmp = parent.getParentFile()) != null) { 6195 f = parent; 6196 parent = tmp; 6197 } 6198 codeRoot = f; 6199 Slog.w(TAG, "Unrecognized code path " 6200 + codePath + " - using " + codeRoot); 6201 } catch (IOException e) { 6202 // Can't canonicalize the code path -- shenanigans? 6203 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6204 return Environment.getRootDirectory().getPath(); 6205 } 6206 } 6207 return codeRoot.getPath(); 6208 } 6209 6210 /** 6211 * Derive and set the location of native libraries for the given package, 6212 * which varies depending on where and how the package was installed. 6213 */ 6214 private void setNativeLibraryPaths(PackageParser.Package pkg) { 6215 final ApplicationInfo info = pkg.applicationInfo; 6216 final String codePath = pkg.codePath; 6217 final File codeFile = new File(codePath); 6218 // If "/system/lib64/apkname" exists, assume that is the per-package 6219 // native library directory to use; otherwise use "/system/lib/apkname". 6220 final String apkRoot = calculateApkRoot(info.sourceDir); 6221 6222 final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info); 6223 final boolean asecApp = isForwardLocked(info) || isExternal(info); 6224 6225 6226 info.nativeLibraryRootDir = null; 6227 info.nativeLibraryRootRequiresIsa = false; 6228 info.nativeLibraryDir = null; 6229 info.secondaryNativeLibraryDir = null; 6230 6231 if (isApkFile(codeFile)) { 6232 // Monolithic install 6233 if (bundledApp) { 6234 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 6235 getPrimaryInstructionSet(info)); 6236 6237 // This is a bundled system app so choose the path based on the ABI. 6238 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 6239 // is just the default path. 6240 final String apkName = deriveCodePathName(codePath); 6241 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 6242 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 6243 apkName).getAbsolutePath(); 6244 6245 if (info.secondaryCpuAbi != null) { 6246 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 6247 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 6248 secondaryLibDir, apkName).getAbsolutePath(); 6249 } 6250 } else if (asecApp) { 6251 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 6252 .getAbsolutePath(); 6253 } else { 6254 final String apkName = deriveCodePathName(codePath); 6255 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 6256 .getAbsolutePath(); 6257 } 6258 6259 info.nativeLibraryRootRequiresIsa = false; 6260 info.nativeLibraryDir = info.nativeLibraryRootDir; 6261 } else { 6262 // Cluster install 6263 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 6264 info.nativeLibraryRootRequiresIsa = true; 6265 6266 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 6267 getPrimaryInstructionSet(info)).getAbsolutePath(); 6268 6269 if (info.secondaryCpuAbi != null) { 6270 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 6271 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 6272 } 6273 } 6274 } 6275 6276 /** 6277 * Calculate the abis and roots for a bundled app. These can uniquely 6278 * be determined from the contents of the system partition, i.e whether 6279 * it contains 64 or 32 bit shared libraries etc. We do not validate any 6280 * of this information, and instead assume that the system was built 6281 * sensibly. 6282 */ 6283 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 6284 PackageSetting pkgSetting) { 6285 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 6286 6287 // If "/system/lib64/apkname" exists, assume that is the per-package 6288 // native library directory to use; otherwise use "/system/lib/apkname". 6289 final String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir); 6290 setBundledAppAbi(pkg, apkRoot, apkName); 6291 // pkgSetting might be null during rescan following uninstall of updates 6292 // to a bundled app, so accommodate that possibility. The settings in 6293 // that case will be established later from the parsed package. 6294 // 6295 // If the settings aren't null, sync them up with what we've just derived. 6296 // note that apkRoot isn't stored in the package settings. 6297 if (pkgSetting != null) { 6298 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6299 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6300 } 6301 } 6302 6303 /** 6304 * Deduces the ABI of a bundled app and sets the relevant fields on the 6305 * parsed pkg object. 6306 * 6307 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 6308 * under which system libraries are installed. 6309 * @param apkName the name of the installed package. 6310 */ 6311 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 6312 final File codeFile = new File(pkg.codePath); 6313 6314 final boolean has64BitLibs; 6315 final boolean has32BitLibs; 6316 if (isApkFile(codeFile)) { 6317 // Monolithic install 6318 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 6319 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 6320 } else { 6321 // Cluster install 6322 final File rootDir = new File(codeFile, LIB_DIR_NAME); 6323 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 6324 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 6325 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 6326 has64BitLibs = (new File(rootDir, isa)).exists(); 6327 } else { 6328 has64BitLibs = false; 6329 } 6330 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 6331 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 6332 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 6333 has32BitLibs = (new File(rootDir, isa)).exists(); 6334 } else { 6335 has32BitLibs = false; 6336 } 6337 } 6338 6339 if (has64BitLibs && !has32BitLibs) { 6340 // The package has 64 bit libs, but not 32 bit libs. Its primary 6341 // ABI should be 64 bit. We can safely assume here that the bundled 6342 // native libraries correspond to the most preferred ABI in the list. 6343 6344 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6345 pkg.applicationInfo.secondaryCpuAbi = null; 6346 } else if (has32BitLibs && !has64BitLibs) { 6347 // The package has 32 bit libs but not 64 bit libs. Its primary 6348 // ABI should be 32 bit. 6349 6350 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6351 pkg.applicationInfo.secondaryCpuAbi = null; 6352 } else if (has32BitLibs && has64BitLibs) { 6353 // The application has both 64 and 32 bit bundled libraries. We check 6354 // here that the app declares multiArch support, and warn if it doesn't. 6355 // 6356 // We will be lenient here and record both ABIs. The primary will be the 6357 // ABI that's higher on the list, i.e, a device that's configured to prefer 6358 // 64 bit apps will see a 64 bit primary ABI, 6359 6360 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 6361 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 6362 } 6363 6364 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 6365 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6366 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6367 } else { 6368 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6369 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6370 } 6371 } else { 6372 pkg.applicationInfo.primaryCpuAbi = null; 6373 pkg.applicationInfo.secondaryCpuAbi = null; 6374 } 6375 } 6376 6377 private static void createNativeLibrarySubdir(File path) throws IOException { 6378 if (!path.isDirectory()) { 6379 path.delete(); 6380 6381 if (!path.mkdir()) { 6382 throw new IOException("Cannot create " + path.getPath()); 6383 } 6384 6385 try { 6386 Os.chmod(path.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); 6387 } catch (ErrnoException e) { 6388 throw new IOException("Cannot chmod native library directory " 6389 + path.getPath(), e); 6390 } 6391 } else if (!SELinux.restorecon(path)) { 6392 throw new IOException("Cannot set SELinux context for " + path.getPath()); 6393 } 6394 } 6395 6396 private static int copyNativeLibrariesForInternalApp(NativeLibraryHelper.Handle handle, 6397 final File nativeLibraryRoot, String[] abiList, boolean useIsaSubdir) throws IOException { 6398 createNativeLibrarySubdir(nativeLibraryRoot); 6399 6400 /* 6401 * If this is an internal application or our nativeLibraryPath points to 6402 * the app-lib directory, unpack the libraries if necessary. 6403 */ 6404 int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList); 6405 if (abi >= 0) { 6406 /* 6407 * If we have a matching instruction set, construct a subdir under the native 6408 * library root that corresponds to this instruction set. 6409 */ 6410 final String instructionSet = VMRuntime.getInstructionSet(abiList[abi]); 6411 final File subDir; 6412 if (useIsaSubdir) { 6413 final File isaSubdir = new File(nativeLibraryRoot, instructionSet); 6414 createNativeLibrarySubdir(isaSubdir); 6415 subDir = isaSubdir; 6416 } else { 6417 subDir = nativeLibraryRoot; 6418 } 6419 6420 int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle, subDir, abiList[abi]); 6421 if (copyRet != PackageManager.INSTALL_SUCCEEDED) { 6422 return copyRet; 6423 } 6424 } 6425 6426 return abi; 6427 } 6428 6429 private void killApplication(String pkgName, int appId, String reason) { 6430 // Request the ActivityManager to kill the process(only for existing packages) 6431 // so that we do not end up in a confused state while the user is still using the older 6432 // version of the application while the new one gets installed. 6433 IActivityManager am = ActivityManagerNative.getDefault(); 6434 if (am != null) { 6435 try { 6436 am.killApplicationWithAppId(pkgName, appId, reason); 6437 } catch (RemoteException e) { 6438 } 6439 } 6440 } 6441 6442 void removePackageLI(PackageSetting ps, boolean chatty) { 6443 if (DEBUG_INSTALL) { 6444 if (chatty) 6445 Log.d(TAG, "Removing package " + ps.name); 6446 } 6447 6448 // writer 6449 synchronized (mPackages) { 6450 mPackages.remove(ps.name); 6451 if (ps.codePathString != null) { 6452 mAppDirs.remove(ps.codePathString); 6453 } 6454 6455 final PackageParser.Package pkg = ps.pkg; 6456 if (pkg != null) { 6457 cleanPackageDataStructuresLILPw(pkg, chatty); 6458 } 6459 } 6460 } 6461 6462 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 6463 if (DEBUG_INSTALL) { 6464 if (chatty) 6465 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 6466 } 6467 6468 // writer 6469 synchronized (mPackages) { 6470 mPackages.remove(pkg.applicationInfo.packageName); 6471 if (pkg.codePath != null) { 6472 mAppDirs.remove(pkg.codePath); 6473 } 6474 cleanPackageDataStructuresLILPw(pkg, chatty); 6475 } 6476 } 6477 6478 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 6479 int N = pkg.providers.size(); 6480 StringBuilder r = null; 6481 int i; 6482 for (i=0; i<N; i++) { 6483 PackageParser.Provider p = pkg.providers.get(i); 6484 mProviders.removeProvider(p); 6485 if (p.info.authority == null) { 6486 6487 /* There was another ContentProvider with this authority when 6488 * this app was installed so this authority is null, 6489 * Ignore it as we don't have to unregister the provider. 6490 */ 6491 continue; 6492 } 6493 String names[] = p.info.authority.split(";"); 6494 for (int j = 0; j < names.length; j++) { 6495 if (mProvidersByAuthority.get(names[j]) == p) { 6496 mProvidersByAuthority.remove(names[j]); 6497 if (DEBUG_REMOVE) { 6498 if (chatty) 6499 Log.d(TAG, "Unregistered content provider: " + names[j] 6500 + ", className = " + p.info.name + ", isSyncable = " 6501 + p.info.isSyncable); 6502 } 6503 } 6504 } 6505 if (DEBUG_REMOVE && chatty) { 6506 if (r == null) { 6507 r = new StringBuilder(256); 6508 } else { 6509 r.append(' '); 6510 } 6511 r.append(p.info.name); 6512 } 6513 } 6514 if (r != null) { 6515 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 6516 } 6517 6518 N = pkg.services.size(); 6519 r = null; 6520 for (i=0; i<N; i++) { 6521 PackageParser.Service s = pkg.services.get(i); 6522 mServices.removeService(s); 6523 if (chatty) { 6524 if (r == null) { 6525 r = new StringBuilder(256); 6526 } else { 6527 r.append(' '); 6528 } 6529 r.append(s.info.name); 6530 } 6531 } 6532 if (r != null) { 6533 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 6534 } 6535 6536 N = pkg.receivers.size(); 6537 r = null; 6538 for (i=0; i<N; i++) { 6539 PackageParser.Activity a = pkg.receivers.get(i); 6540 mReceivers.removeActivity(a, "receiver"); 6541 if (DEBUG_REMOVE && chatty) { 6542 if (r == null) { 6543 r = new StringBuilder(256); 6544 } else { 6545 r.append(' '); 6546 } 6547 r.append(a.info.name); 6548 } 6549 } 6550 if (r != null) { 6551 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 6552 } 6553 6554 N = pkg.activities.size(); 6555 r = null; 6556 for (i=0; i<N; i++) { 6557 PackageParser.Activity a = pkg.activities.get(i); 6558 mActivities.removeActivity(a, "activity"); 6559 if (DEBUG_REMOVE && chatty) { 6560 if (r == null) { 6561 r = new StringBuilder(256); 6562 } else { 6563 r.append(' '); 6564 } 6565 r.append(a.info.name); 6566 } 6567 } 6568 if (r != null) { 6569 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 6570 } 6571 6572 N = pkg.permissions.size(); 6573 r = null; 6574 for (i=0; i<N; i++) { 6575 PackageParser.Permission p = pkg.permissions.get(i); 6576 BasePermission bp = mSettings.mPermissions.get(p.info.name); 6577 if (bp == null) { 6578 bp = mSettings.mPermissionTrees.get(p.info.name); 6579 } 6580 if (bp != null && bp.perm == p) { 6581 bp.perm = null; 6582 if (DEBUG_REMOVE && chatty) { 6583 if (r == null) { 6584 r = new StringBuilder(256); 6585 } else { 6586 r.append(' '); 6587 } 6588 r.append(p.info.name); 6589 } 6590 } 6591 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6592 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 6593 if (appOpPerms != null) { 6594 appOpPerms.remove(pkg.packageName); 6595 } 6596 } 6597 } 6598 if (r != null) { 6599 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6600 } 6601 6602 N = pkg.requestedPermissions.size(); 6603 r = null; 6604 for (i=0; i<N; i++) { 6605 String perm = pkg.requestedPermissions.get(i); 6606 BasePermission bp = mSettings.mPermissions.get(perm); 6607 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6608 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 6609 if (appOpPerms != null) { 6610 appOpPerms.remove(pkg.packageName); 6611 if (appOpPerms.isEmpty()) { 6612 mAppOpPermissionPackages.remove(perm); 6613 } 6614 } 6615 } 6616 } 6617 if (r != null) { 6618 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6619 } 6620 6621 N = pkg.instrumentation.size(); 6622 r = null; 6623 for (i=0; i<N; i++) { 6624 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6625 mInstrumentation.remove(a.getComponentName()); 6626 if (DEBUG_REMOVE && chatty) { 6627 if (r == null) { 6628 r = new StringBuilder(256); 6629 } else { 6630 r.append(' '); 6631 } 6632 r.append(a.info.name); 6633 } 6634 } 6635 if (r != null) { 6636 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 6637 } 6638 6639 r = null; 6640 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6641 // Only system apps can hold shared libraries. 6642 if (pkg.libraryNames != null) { 6643 for (i=0; i<pkg.libraryNames.size(); i++) { 6644 String name = pkg.libraryNames.get(i); 6645 SharedLibraryEntry cur = mSharedLibraries.get(name); 6646 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 6647 mSharedLibraries.remove(name); 6648 if (DEBUG_REMOVE && chatty) { 6649 if (r == null) { 6650 r = new StringBuilder(256); 6651 } else { 6652 r.append(' '); 6653 } 6654 r.append(name); 6655 } 6656 } 6657 } 6658 } 6659 } 6660 if (r != null) { 6661 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 6662 } 6663 } 6664 6665 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 6666 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 6667 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 6668 return true; 6669 } 6670 } 6671 return false; 6672 } 6673 6674 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 6675 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 6676 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 6677 6678 private void updatePermissionsLPw(String changingPkg, 6679 PackageParser.Package pkgInfo, int flags) { 6680 // Make sure there are no dangling permission trees. 6681 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 6682 while (it.hasNext()) { 6683 final BasePermission bp = it.next(); 6684 if (bp.packageSetting == null) { 6685 // We may not yet have parsed the package, so just see if 6686 // we still know about its settings. 6687 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6688 } 6689 if (bp.packageSetting == null) { 6690 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 6691 + " from package " + bp.sourcePackage); 6692 it.remove(); 6693 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6694 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6695 Slog.i(TAG, "Removing old permission tree: " + bp.name 6696 + " from package " + bp.sourcePackage); 6697 flags |= UPDATE_PERMISSIONS_ALL; 6698 it.remove(); 6699 } 6700 } 6701 } 6702 6703 // Make sure all dynamic permissions have been assigned to a package, 6704 // and make sure there are no dangling permissions. 6705 it = mSettings.mPermissions.values().iterator(); 6706 while (it.hasNext()) { 6707 final BasePermission bp = it.next(); 6708 if (bp.type == BasePermission.TYPE_DYNAMIC) { 6709 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 6710 + bp.name + " pkg=" + bp.sourcePackage 6711 + " info=" + bp.pendingInfo); 6712 if (bp.packageSetting == null && bp.pendingInfo != null) { 6713 final BasePermission tree = findPermissionTreeLP(bp.name); 6714 if (tree != null && tree.perm != null) { 6715 bp.packageSetting = tree.packageSetting; 6716 bp.perm = new PackageParser.Permission(tree.perm.owner, 6717 new PermissionInfo(bp.pendingInfo)); 6718 bp.perm.info.packageName = tree.perm.info.packageName; 6719 bp.perm.info.name = bp.name; 6720 bp.uid = tree.uid; 6721 } 6722 } 6723 } 6724 if (bp.packageSetting == null) { 6725 // We may not yet have parsed the package, so just see if 6726 // we still know about its settings. 6727 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6728 } 6729 if (bp.packageSetting == null) { 6730 Slog.w(TAG, "Removing dangling permission: " + bp.name 6731 + " from package " + bp.sourcePackage); 6732 it.remove(); 6733 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6734 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6735 Slog.i(TAG, "Removing old permission: " + bp.name 6736 + " from package " + bp.sourcePackage); 6737 flags |= UPDATE_PERMISSIONS_ALL; 6738 it.remove(); 6739 } 6740 } 6741 } 6742 6743 // Now update the permissions for all packages, in particular 6744 // replace the granted permissions of the system packages. 6745 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 6746 for (PackageParser.Package pkg : mPackages.values()) { 6747 if (pkg != pkgInfo) { 6748 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0); 6749 } 6750 } 6751 } 6752 6753 if (pkgInfo != null) { 6754 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0); 6755 } 6756 } 6757 6758 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) { 6759 final PackageSetting ps = (PackageSetting) pkg.mExtras; 6760 if (ps == null) { 6761 return; 6762 } 6763 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 6764 HashSet<String> origPermissions = gp.grantedPermissions; 6765 boolean changedPermission = false; 6766 6767 if (replace) { 6768 ps.permissionsFixed = false; 6769 if (gp == ps) { 6770 origPermissions = new HashSet<String>(gp.grantedPermissions); 6771 gp.grantedPermissions.clear(); 6772 gp.gids = mGlobalGids; 6773 } 6774 } 6775 6776 if (gp.gids == null) { 6777 gp.gids = mGlobalGids; 6778 } 6779 6780 final int N = pkg.requestedPermissions.size(); 6781 for (int i=0; i<N; i++) { 6782 final String name = pkg.requestedPermissions.get(i); 6783 final boolean required = pkg.requestedPermissionsRequired.get(i); 6784 final BasePermission bp = mSettings.mPermissions.get(name); 6785 if (DEBUG_INSTALL) { 6786 if (gp != ps) { 6787 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 6788 } 6789 } 6790 6791 if (bp == null || bp.packageSetting == null) { 6792 Slog.w(TAG, "Unknown permission " + name 6793 + " in package " + pkg.packageName); 6794 continue; 6795 } 6796 6797 final String perm = bp.name; 6798 boolean allowed; 6799 boolean allowedSig = false; 6800 if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6801 // Keep track of app op permissions. 6802 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 6803 if (pkgs == null) { 6804 pkgs = new ArraySet<>(); 6805 mAppOpPermissionPackages.put(bp.name, pkgs); 6806 } 6807 pkgs.add(pkg.packageName); 6808 } 6809 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 6810 if (level == PermissionInfo.PROTECTION_NORMAL 6811 || level == PermissionInfo.PROTECTION_DANGEROUS) { 6812 // We grant a normal or dangerous permission if any of the following 6813 // are true: 6814 // 1) The permission is required 6815 // 2) The permission is optional, but was granted in the past 6816 // 3) The permission is optional, but was requested by an 6817 // app in /system (not /data) 6818 // 6819 // Otherwise, reject the permission. 6820 allowed = (required || origPermissions.contains(perm) 6821 || (isSystemApp(ps) && !isUpdatedSystemApp(ps))); 6822 } else if (bp.packageSetting == null) { 6823 // This permission is invalid; skip it. 6824 allowed = false; 6825 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 6826 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions); 6827 if (allowed) { 6828 allowedSig = true; 6829 } 6830 } else { 6831 allowed = false; 6832 } 6833 if (DEBUG_INSTALL) { 6834 if (gp != ps) { 6835 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 6836 } 6837 } 6838 if (allowed) { 6839 if (!isSystemApp(ps) && ps.permissionsFixed) { 6840 // If this is an existing, non-system package, then 6841 // we can't add any new permissions to it. 6842 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 6843 // Except... if this is a permission that was added 6844 // to the platform (note: need to only do this when 6845 // updating the platform). 6846 allowed = isNewPlatformPermissionForPackage(perm, pkg); 6847 } 6848 } 6849 if (allowed) { 6850 if (!gp.grantedPermissions.contains(perm)) { 6851 changedPermission = true; 6852 gp.grantedPermissions.add(perm); 6853 gp.gids = appendInts(gp.gids, bp.gids); 6854 } else if (!ps.haveGids) { 6855 gp.gids = appendInts(gp.gids, bp.gids); 6856 } 6857 } else { 6858 Slog.w(TAG, "Not granting permission " + perm 6859 + " to package " + pkg.packageName 6860 + " because it was previously installed without"); 6861 } 6862 } else { 6863 if (gp.grantedPermissions.remove(perm)) { 6864 changedPermission = true; 6865 gp.gids = removeInts(gp.gids, bp.gids); 6866 Slog.i(TAG, "Un-granting permission " + perm 6867 + " from package " + pkg.packageName 6868 + " (protectionLevel=" + bp.protectionLevel 6869 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6870 + ")"); 6871 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 6872 // Don't print warning for app op permissions, since it is fine for them 6873 // not to be granted, there is a UI for the user to decide. 6874 Slog.w(TAG, "Not granting permission " + perm 6875 + " to package " + pkg.packageName 6876 + " (protectionLevel=" + bp.protectionLevel 6877 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6878 + ")"); 6879 } 6880 } 6881 } 6882 6883 if ((changedPermission || replace) && !ps.permissionsFixed && 6884 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 6885 // This is the first that we have heard about this package, so the 6886 // permissions we have now selected are fixed until explicitly 6887 // changed. 6888 ps.permissionsFixed = true; 6889 } 6890 ps.haveGids = true; 6891 } 6892 6893 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 6894 boolean allowed = false; 6895 final int NP = PackageParser.NEW_PERMISSIONS.length; 6896 for (int ip=0; ip<NP; ip++) { 6897 final PackageParser.NewPermissionInfo npi 6898 = PackageParser.NEW_PERMISSIONS[ip]; 6899 if (npi.name.equals(perm) 6900 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 6901 allowed = true; 6902 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 6903 + pkg.packageName); 6904 break; 6905 } 6906 } 6907 return allowed; 6908 } 6909 6910 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 6911 BasePermission bp, HashSet<String> origPermissions) { 6912 boolean allowed; 6913 allowed = (compareSignatures( 6914 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 6915 == PackageManager.SIGNATURE_MATCH) 6916 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 6917 == PackageManager.SIGNATURE_MATCH); 6918 if (!allowed && (bp.protectionLevel 6919 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 6920 if (isSystemApp(pkg)) { 6921 // For updated system applications, a system permission 6922 // is granted only if it had been defined by the original application. 6923 if (isUpdatedSystemApp(pkg)) { 6924 final PackageSetting sysPs = mSettings 6925 .getDisabledSystemPkgLPr(pkg.packageName); 6926 final GrantedPermissions origGp = sysPs.sharedUser != null 6927 ? sysPs.sharedUser : sysPs; 6928 6929 if (origGp.grantedPermissions.contains(perm)) { 6930 // If the original was granted this permission, we take 6931 // that grant decision as read and propagate it to the 6932 // update. 6933 allowed = true; 6934 } else { 6935 // The system apk may have been updated with an older 6936 // version of the one on the data partition, but which 6937 // granted a new system permission that it didn't have 6938 // before. In this case we do want to allow the app to 6939 // now get the new permission if the ancestral apk is 6940 // privileged to get it. 6941 if (sysPs.pkg != null && sysPs.isPrivileged()) { 6942 for (int j=0; 6943 j<sysPs.pkg.requestedPermissions.size(); j++) { 6944 if (perm.equals( 6945 sysPs.pkg.requestedPermissions.get(j))) { 6946 allowed = true; 6947 break; 6948 } 6949 } 6950 } 6951 } 6952 } else { 6953 allowed = isPrivilegedApp(pkg); 6954 } 6955 } 6956 } 6957 if (!allowed && (bp.protectionLevel 6958 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 6959 // For development permissions, a development permission 6960 // is granted only if it was already granted. 6961 allowed = origPermissions.contains(perm); 6962 } 6963 return allowed; 6964 } 6965 6966 final class ActivityIntentResolver 6967 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 6968 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 6969 boolean defaultOnly, int userId) { 6970 if (!sUserManager.exists(userId)) return null; 6971 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 6972 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 6973 } 6974 6975 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 6976 int userId) { 6977 if (!sUserManager.exists(userId)) return null; 6978 mFlags = flags; 6979 return super.queryIntent(intent, resolvedType, 6980 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 6981 } 6982 6983 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 6984 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 6985 if (!sUserManager.exists(userId)) return null; 6986 if (packageActivities == null) { 6987 return null; 6988 } 6989 mFlags = flags; 6990 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 6991 final int N = packageActivities.size(); 6992 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 6993 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 6994 6995 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 6996 for (int i = 0; i < N; ++i) { 6997 intentFilters = packageActivities.get(i).intents; 6998 if (intentFilters != null && intentFilters.size() > 0) { 6999 PackageParser.ActivityIntentInfo[] array = 7000 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 7001 intentFilters.toArray(array); 7002 listCut.add(array); 7003 } 7004 } 7005 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7006 } 7007 7008 public final void addActivity(PackageParser.Activity a, String type) { 7009 final boolean systemApp = isSystemApp(a.info.applicationInfo); 7010 mActivities.put(a.getComponentName(), a); 7011 if (DEBUG_SHOW_INFO) 7012 Log.v( 7013 TAG, " " + type + " " + 7014 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 7015 if (DEBUG_SHOW_INFO) 7016 Log.v(TAG, " Class=" + a.info.name); 7017 final int NI = a.intents.size(); 7018 for (int j=0; j<NI; j++) { 7019 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7020 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 7021 intent.setPriority(0); 7022 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 7023 + a.className + " with priority > 0, forcing to 0"); 7024 } 7025 if (DEBUG_SHOW_INFO) { 7026 Log.v(TAG, " IntentFilter:"); 7027 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7028 } 7029 if (!intent.debugCheck()) { 7030 Log.w(TAG, "==> For Activity " + a.info.name); 7031 } 7032 addFilter(intent); 7033 } 7034 } 7035 7036 public final void removeActivity(PackageParser.Activity a, String type) { 7037 mActivities.remove(a.getComponentName()); 7038 if (DEBUG_SHOW_INFO) { 7039 Log.v(TAG, " " + type + " " 7040 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 7041 : a.info.name) + ":"); 7042 Log.v(TAG, " Class=" + a.info.name); 7043 } 7044 final int NI = a.intents.size(); 7045 for (int j=0; j<NI; j++) { 7046 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7047 if (DEBUG_SHOW_INFO) { 7048 Log.v(TAG, " IntentFilter:"); 7049 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7050 } 7051 removeFilter(intent); 7052 } 7053 } 7054 7055 @Override 7056 protected boolean allowFilterResult( 7057 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 7058 ActivityInfo filterAi = filter.activity.info; 7059 for (int i=dest.size()-1; i>=0; i--) { 7060 ActivityInfo destAi = dest.get(i).activityInfo; 7061 if (destAi.name == filterAi.name 7062 && destAi.packageName == filterAi.packageName) { 7063 return false; 7064 } 7065 } 7066 return true; 7067 } 7068 7069 @Override 7070 protected ActivityIntentInfo[] newArray(int size) { 7071 return new ActivityIntentInfo[size]; 7072 } 7073 7074 @Override 7075 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 7076 if (!sUserManager.exists(userId)) return true; 7077 PackageParser.Package p = filter.activity.owner; 7078 if (p != null) { 7079 PackageSetting ps = (PackageSetting)p.mExtras; 7080 if (ps != null) { 7081 // System apps are never considered stopped for purposes of 7082 // filtering, because there may be no way for the user to 7083 // actually re-launch them. 7084 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 7085 && ps.getStopped(userId); 7086 } 7087 } 7088 return false; 7089 } 7090 7091 @Override 7092 protected boolean isPackageForFilter(String packageName, 7093 PackageParser.ActivityIntentInfo info) { 7094 return packageName.equals(info.activity.owner.packageName); 7095 } 7096 7097 @Override 7098 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7099 int match, int userId) { 7100 if (!sUserManager.exists(userId)) return null; 7101 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7102 return null; 7103 } 7104 final PackageParser.Activity activity = info.activity; 7105 if (mSafeMode && (activity.info.applicationInfo.flags 7106 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7107 return null; 7108 } 7109 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7110 if (ps == null) { 7111 return null; 7112 } 7113 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7114 ps.readUserState(userId), userId); 7115 if (ai == null) { 7116 return null; 7117 } 7118 final ResolveInfo res = new ResolveInfo(); 7119 res.activityInfo = ai; 7120 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7121 res.filter = info; 7122 } 7123 res.priority = info.getPriority(); 7124 res.preferredOrder = activity.owner.mPreferredOrder; 7125 //System.out.println("Result: " + res.activityInfo.className + 7126 // " = " + res.priority); 7127 res.match = match; 7128 res.isDefault = info.hasDefault; 7129 res.labelRes = info.labelRes; 7130 res.nonLocalizedLabel = info.nonLocalizedLabel; 7131 if (userNeedsBadging(userId)) { 7132 res.noResourceId = true; 7133 } else { 7134 res.icon = info.icon; 7135 } 7136 res.system = isSystemApp(res.activityInfo.applicationInfo); 7137 return res; 7138 } 7139 7140 @Override 7141 protected void sortResults(List<ResolveInfo> results) { 7142 Collections.sort(results, mResolvePrioritySorter); 7143 } 7144 7145 @Override 7146 protected void dumpFilter(PrintWriter out, String prefix, 7147 PackageParser.ActivityIntentInfo filter) { 7148 out.print(prefix); out.print( 7149 Integer.toHexString(System.identityHashCode(filter.activity))); 7150 out.print(' '); 7151 filter.activity.printComponentShortName(out); 7152 out.print(" filter "); 7153 out.println(Integer.toHexString(System.identityHashCode(filter))); 7154 } 7155 7156// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7157// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7158// final List<ResolveInfo> retList = Lists.newArrayList(); 7159// while (i.hasNext()) { 7160// final ResolveInfo resolveInfo = i.next(); 7161// if (isEnabledLP(resolveInfo.activityInfo)) { 7162// retList.add(resolveInfo); 7163// } 7164// } 7165// return retList; 7166// } 7167 7168 // Keys are String (activity class name), values are Activity. 7169 private final HashMap<ComponentName, PackageParser.Activity> mActivities 7170 = new HashMap<ComponentName, PackageParser.Activity>(); 7171 private int mFlags; 7172 } 7173 7174 private final class ServiceIntentResolver 7175 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 7176 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7177 boolean defaultOnly, int userId) { 7178 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7179 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7180 } 7181 7182 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7183 int userId) { 7184 if (!sUserManager.exists(userId)) return null; 7185 mFlags = flags; 7186 return super.queryIntent(intent, resolvedType, 7187 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7188 } 7189 7190 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7191 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 7192 if (!sUserManager.exists(userId)) return null; 7193 if (packageServices == null) { 7194 return null; 7195 } 7196 mFlags = flags; 7197 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7198 final int N = packageServices.size(); 7199 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 7200 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 7201 7202 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 7203 for (int i = 0; i < N; ++i) { 7204 intentFilters = packageServices.get(i).intents; 7205 if (intentFilters != null && intentFilters.size() > 0) { 7206 PackageParser.ServiceIntentInfo[] array = 7207 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 7208 intentFilters.toArray(array); 7209 listCut.add(array); 7210 } 7211 } 7212 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7213 } 7214 7215 public final void addService(PackageParser.Service s) { 7216 mServices.put(s.getComponentName(), s); 7217 if (DEBUG_SHOW_INFO) { 7218 Log.v(TAG, " " 7219 + (s.info.nonLocalizedLabel != null 7220 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7221 Log.v(TAG, " Class=" + s.info.name); 7222 } 7223 final int NI = s.intents.size(); 7224 int j; 7225 for (j=0; j<NI; j++) { 7226 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7227 if (DEBUG_SHOW_INFO) { 7228 Log.v(TAG, " IntentFilter:"); 7229 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7230 } 7231 if (!intent.debugCheck()) { 7232 Log.w(TAG, "==> For Service " + s.info.name); 7233 } 7234 addFilter(intent); 7235 } 7236 } 7237 7238 public final void removeService(PackageParser.Service s) { 7239 mServices.remove(s.getComponentName()); 7240 if (DEBUG_SHOW_INFO) { 7241 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 7242 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7243 Log.v(TAG, " Class=" + s.info.name); 7244 } 7245 final int NI = s.intents.size(); 7246 int j; 7247 for (j=0; j<NI; j++) { 7248 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7249 if (DEBUG_SHOW_INFO) { 7250 Log.v(TAG, " IntentFilter:"); 7251 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7252 } 7253 removeFilter(intent); 7254 } 7255 } 7256 7257 @Override 7258 protected boolean allowFilterResult( 7259 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 7260 ServiceInfo filterSi = filter.service.info; 7261 for (int i=dest.size()-1; i>=0; i--) { 7262 ServiceInfo destAi = dest.get(i).serviceInfo; 7263 if (destAi.name == filterSi.name 7264 && destAi.packageName == filterSi.packageName) { 7265 return false; 7266 } 7267 } 7268 return true; 7269 } 7270 7271 @Override 7272 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 7273 return new PackageParser.ServiceIntentInfo[size]; 7274 } 7275 7276 @Override 7277 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 7278 if (!sUserManager.exists(userId)) return true; 7279 PackageParser.Package p = filter.service.owner; 7280 if (p != null) { 7281 PackageSetting ps = (PackageSetting)p.mExtras; 7282 if (ps != null) { 7283 // System apps are never considered stopped for purposes of 7284 // filtering, because there may be no way for the user to 7285 // actually re-launch them. 7286 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7287 && ps.getStopped(userId); 7288 } 7289 } 7290 return false; 7291 } 7292 7293 @Override 7294 protected boolean isPackageForFilter(String packageName, 7295 PackageParser.ServiceIntentInfo info) { 7296 return packageName.equals(info.service.owner.packageName); 7297 } 7298 7299 @Override 7300 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 7301 int match, int userId) { 7302 if (!sUserManager.exists(userId)) return null; 7303 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 7304 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 7305 return null; 7306 } 7307 final PackageParser.Service service = info.service; 7308 if (mSafeMode && (service.info.applicationInfo.flags 7309 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7310 return null; 7311 } 7312 PackageSetting ps = (PackageSetting) service.owner.mExtras; 7313 if (ps == null) { 7314 return null; 7315 } 7316 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 7317 ps.readUserState(userId), userId); 7318 if (si == null) { 7319 return null; 7320 } 7321 final ResolveInfo res = new ResolveInfo(); 7322 res.serviceInfo = si; 7323 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7324 res.filter = filter; 7325 } 7326 res.priority = info.getPriority(); 7327 res.preferredOrder = service.owner.mPreferredOrder; 7328 //System.out.println("Result: " + res.activityInfo.className + 7329 // " = " + res.priority); 7330 res.match = match; 7331 res.isDefault = info.hasDefault; 7332 res.labelRes = info.labelRes; 7333 res.nonLocalizedLabel = info.nonLocalizedLabel; 7334 res.icon = info.icon; 7335 res.system = isSystemApp(res.serviceInfo.applicationInfo); 7336 return res; 7337 } 7338 7339 @Override 7340 protected void sortResults(List<ResolveInfo> results) { 7341 Collections.sort(results, mResolvePrioritySorter); 7342 } 7343 7344 @Override 7345 protected void dumpFilter(PrintWriter out, String prefix, 7346 PackageParser.ServiceIntentInfo filter) { 7347 out.print(prefix); out.print( 7348 Integer.toHexString(System.identityHashCode(filter.service))); 7349 out.print(' '); 7350 filter.service.printComponentShortName(out); 7351 out.print(" filter "); 7352 out.println(Integer.toHexString(System.identityHashCode(filter))); 7353 } 7354 7355// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7356// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7357// final List<ResolveInfo> retList = Lists.newArrayList(); 7358// while (i.hasNext()) { 7359// final ResolveInfo resolveInfo = (ResolveInfo) i; 7360// if (isEnabledLP(resolveInfo.serviceInfo)) { 7361// retList.add(resolveInfo); 7362// } 7363// } 7364// return retList; 7365// } 7366 7367 // Keys are String (activity class name), values are Activity. 7368 private final HashMap<ComponentName, PackageParser.Service> mServices 7369 = new HashMap<ComponentName, PackageParser.Service>(); 7370 private int mFlags; 7371 }; 7372 7373 private final class ProviderIntentResolver 7374 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 7375 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7376 boolean defaultOnly, int userId) { 7377 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7378 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7379 } 7380 7381 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7382 int userId) { 7383 if (!sUserManager.exists(userId)) 7384 return null; 7385 mFlags = flags; 7386 return super.queryIntent(intent, resolvedType, 7387 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7388 } 7389 7390 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7391 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 7392 if (!sUserManager.exists(userId)) 7393 return null; 7394 if (packageProviders == null) { 7395 return null; 7396 } 7397 mFlags = flags; 7398 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 7399 final int N = packageProviders.size(); 7400 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 7401 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 7402 7403 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 7404 for (int i = 0; i < N; ++i) { 7405 intentFilters = packageProviders.get(i).intents; 7406 if (intentFilters != null && intentFilters.size() > 0) { 7407 PackageParser.ProviderIntentInfo[] array = 7408 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 7409 intentFilters.toArray(array); 7410 listCut.add(array); 7411 } 7412 } 7413 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7414 } 7415 7416 public final void addProvider(PackageParser.Provider p) { 7417 if (mProviders.containsKey(p.getComponentName())) { 7418 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 7419 return; 7420 } 7421 7422 mProviders.put(p.getComponentName(), p); 7423 if (DEBUG_SHOW_INFO) { 7424 Log.v(TAG, " " 7425 + (p.info.nonLocalizedLabel != null 7426 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7427 Log.v(TAG, " Class=" + p.info.name); 7428 } 7429 final int NI = p.intents.size(); 7430 int j; 7431 for (j = 0; j < NI; j++) { 7432 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7433 if (DEBUG_SHOW_INFO) { 7434 Log.v(TAG, " IntentFilter:"); 7435 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7436 } 7437 if (!intent.debugCheck()) { 7438 Log.w(TAG, "==> For Provider " + p.info.name); 7439 } 7440 addFilter(intent); 7441 } 7442 } 7443 7444 public final void removeProvider(PackageParser.Provider p) { 7445 mProviders.remove(p.getComponentName()); 7446 if (DEBUG_SHOW_INFO) { 7447 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 7448 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7449 Log.v(TAG, " Class=" + p.info.name); 7450 } 7451 final int NI = p.intents.size(); 7452 int j; 7453 for (j = 0; j < NI; j++) { 7454 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7455 if (DEBUG_SHOW_INFO) { 7456 Log.v(TAG, " IntentFilter:"); 7457 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7458 } 7459 removeFilter(intent); 7460 } 7461 } 7462 7463 @Override 7464 protected boolean allowFilterResult( 7465 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 7466 ProviderInfo filterPi = filter.provider.info; 7467 for (int i = dest.size() - 1; i >= 0; i--) { 7468 ProviderInfo destPi = dest.get(i).providerInfo; 7469 if (destPi.name == filterPi.name 7470 && destPi.packageName == filterPi.packageName) { 7471 return false; 7472 } 7473 } 7474 return true; 7475 } 7476 7477 @Override 7478 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 7479 return new PackageParser.ProviderIntentInfo[size]; 7480 } 7481 7482 @Override 7483 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 7484 if (!sUserManager.exists(userId)) 7485 return true; 7486 PackageParser.Package p = filter.provider.owner; 7487 if (p != null) { 7488 PackageSetting ps = (PackageSetting) p.mExtras; 7489 if (ps != null) { 7490 // System apps are never considered stopped for purposes of 7491 // filtering, because there may be no way for the user to 7492 // actually re-launch them. 7493 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7494 && ps.getStopped(userId); 7495 } 7496 } 7497 return false; 7498 } 7499 7500 @Override 7501 protected boolean isPackageForFilter(String packageName, 7502 PackageParser.ProviderIntentInfo info) { 7503 return packageName.equals(info.provider.owner.packageName); 7504 } 7505 7506 @Override 7507 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 7508 int match, int userId) { 7509 if (!sUserManager.exists(userId)) 7510 return null; 7511 final PackageParser.ProviderIntentInfo info = filter; 7512 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 7513 return null; 7514 } 7515 final PackageParser.Provider provider = info.provider; 7516 if (mSafeMode && (provider.info.applicationInfo.flags 7517 & ApplicationInfo.FLAG_SYSTEM) == 0) { 7518 return null; 7519 } 7520 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 7521 if (ps == null) { 7522 return null; 7523 } 7524 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 7525 ps.readUserState(userId), userId); 7526 if (pi == null) { 7527 return null; 7528 } 7529 final ResolveInfo res = new ResolveInfo(); 7530 res.providerInfo = pi; 7531 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 7532 res.filter = filter; 7533 } 7534 res.priority = info.getPriority(); 7535 res.preferredOrder = provider.owner.mPreferredOrder; 7536 res.match = match; 7537 res.isDefault = info.hasDefault; 7538 res.labelRes = info.labelRes; 7539 res.nonLocalizedLabel = info.nonLocalizedLabel; 7540 res.icon = info.icon; 7541 res.system = isSystemApp(res.providerInfo.applicationInfo); 7542 return res; 7543 } 7544 7545 @Override 7546 protected void sortResults(List<ResolveInfo> results) { 7547 Collections.sort(results, mResolvePrioritySorter); 7548 } 7549 7550 @Override 7551 protected void dumpFilter(PrintWriter out, String prefix, 7552 PackageParser.ProviderIntentInfo filter) { 7553 out.print(prefix); 7554 out.print( 7555 Integer.toHexString(System.identityHashCode(filter.provider))); 7556 out.print(' '); 7557 filter.provider.printComponentShortName(out); 7558 out.print(" filter "); 7559 out.println(Integer.toHexString(System.identityHashCode(filter))); 7560 } 7561 7562 private final HashMap<ComponentName, PackageParser.Provider> mProviders 7563 = new HashMap<ComponentName, PackageParser.Provider>(); 7564 private int mFlags; 7565 }; 7566 7567 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 7568 new Comparator<ResolveInfo>() { 7569 public int compare(ResolveInfo r1, ResolveInfo r2) { 7570 int v1 = r1.priority; 7571 int v2 = r2.priority; 7572 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 7573 if (v1 != v2) { 7574 return (v1 > v2) ? -1 : 1; 7575 } 7576 v1 = r1.preferredOrder; 7577 v2 = r2.preferredOrder; 7578 if (v1 != v2) { 7579 return (v1 > v2) ? -1 : 1; 7580 } 7581 if (r1.isDefault != r2.isDefault) { 7582 return r1.isDefault ? -1 : 1; 7583 } 7584 v1 = r1.match; 7585 v2 = r2.match; 7586 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 7587 if (v1 != v2) { 7588 return (v1 > v2) ? -1 : 1; 7589 } 7590 if (r1.system != r2.system) { 7591 return r1.system ? -1 : 1; 7592 } 7593 return 0; 7594 } 7595 }; 7596 7597 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 7598 new Comparator<ProviderInfo>() { 7599 public int compare(ProviderInfo p1, ProviderInfo p2) { 7600 final int v1 = p1.initOrder; 7601 final int v2 = p2.initOrder; 7602 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 7603 } 7604 }; 7605 7606 static final void sendPackageBroadcast(String action, String pkg, 7607 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 7608 int[] userIds) { 7609 IActivityManager am = ActivityManagerNative.getDefault(); 7610 if (am != null) { 7611 try { 7612 if (userIds == null) { 7613 userIds = am.getRunningUserIds(); 7614 } 7615 for (int id : userIds) { 7616 final Intent intent = new Intent(action, 7617 pkg != null ? Uri.fromParts("package", pkg, null) : null); 7618 if (extras != null) { 7619 intent.putExtras(extras); 7620 } 7621 if (targetPkg != null) { 7622 intent.setPackage(targetPkg); 7623 } 7624 // Modify the UID when posting to other users 7625 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 7626 if (uid > 0 && UserHandle.getUserId(uid) != id) { 7627 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 7628 intent.putExtra(Intent.EXTRA_UID, uid); 7629 } 7630 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 7631 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 7632 if (DEBUG_BROADCASTS) { 7633 RuntimeException here = new RuntimeException("here"); 7634 here.fillInStackTrace(); 7635 Slog.d(TAG, "Sending to user " + id + ": " 7636 + intent.toShortString(false, true, false, false) 7637 + " " + intent.getExtras(), here); 7638 } 7639 am.broadcastIntent(null, intent, null, finishedReceiver, 7640 0, null, null, null, android.app.AppOpsManager.OP_NONE, 7641 finishedReceiver != null, false, id); 7642 } 7643 } catch (RemoteException ex) { 7644 } 7645 } 7646 } 7647 7648 /** 7649 * Check if the external storage media is available. This is true if there 7650 * is a mounted external storage medium or if the external storage is 7651 * emulated. 7652 */ 7653 private boolean isExternalMediaAvailable() { 7654 return mMediaMounted || Environment.isExternalStorageEmulated(); 7655 } 7656 7657 @Override 7658 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 7659 // writer 7660 synchronized (mPackages) { 7661 if (!isExternalMediaAvailable()) { 7662 // If the external storage is no longer mounted at this point, 7663 // the caller may not have been able to delete all of this 7664 // packages files and can not delete any more. Bail. 7665 return null; 7666 } 7667 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 7668 if (lastPackage != null) { 7669 pkgs.remove(lastPackage); 7670 } 7671 if (pkgs.size() > 0) { 7672 return pkgs.get(0); 7673 } 7674 } 7675 return null; 7676 } 7677 7678 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 7679 if (false) { 7680 RuntimeException here = new RuntimeException("here"); 7681 here.fillInStackTrace(); 7682 Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId 7683 + " andCode=" + andCode, here); 7684 } 7685 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, 7686 userId, andCode ? 1 : 0, packageName)); 7687 } 7688 7689 void startCleaningPackages() { 7690 // reader 7691 synchronized (mPackages) { 7692 if (!isExternalMediaAvailable()) { 7693 return; 7694 } 7695 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 7696 return; 7697 } 7698 } 7699 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 7700 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 7701 IActivityManager am = ActivityManagerNative.getDefault(); 7702 if (am != null) { 7703 try { 7704 am.startService(null, intent, null, UserHandle.USER_OWNER); 7705 } catch (RemoteException e) { 7706 } 7707 } 7708 } 7709 7710 @Override 7711 public void installPackage(String originPath, IPackageInstallObserver2 observer, int flags, 7712 String installerPackageName, VerificationParams verificationParams, 7713 String packageAbiOverride) { 7714 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7715 null); 7716 7717 final File originFile = new File(originPath); 7718 final int uid = Binder.getCallingUid(); 7719 if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) { 7720 try { 7721 if (observer != null) { 7722 observer.packageInstalled("", null, INSTALL_FAILED_USER_RESTRICTED, null); 7723 } 7724 } catch (RemoteException re) { 7725 } 7726 return; 7727 } 7728 7729 UserHandle user; 7730 if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) { 7731 user = UserHandle.ALL; 7732 } else { 7733 user = new UserHandle(UserHandle.getUserId(uid)); 7734 } 7735 7736 final int filteredFlags; 7737 if (uid == Process.SHELL_UID || uid == 0) { 7738 if (DEBUG_INSTALL) { 7739 Slog.v(TAG, "Install from ADB"); 7740 } 7741 filteredFlags = flags | PackageManager.INSTALL_FROM_ADB; 7742 } else { 7743 filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB; 7744 } 7745 7746 verificationParams.setInstallerUid(uid); 7747 7748 final Message msg = mHandler.obtainMessage(INIT_COPY); 7749 msg.obj = new InstallParams(originFile, false, observer, filteredFlags, 7750 installerPackageName, verificationParams, user, packageAbiOverride); 7751 mHandler.sendMessage(msg); 7752 } 7753 7754 void installStage(String packageName, File stageDir, IPackageInstallObserver2 observer, 7755 InstallSessionParams params, String installerPackageName, int installerUid, 7756 UserHandle user) { 7757 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 7758 params.referrerUri, installerUid, null); 7759 7760 final Message msg = mHandler.obtainMessage(INIT_COPY); 7761 msg.obj = new InstallParams(stageDir, true, observer, params.installFlags, 7762 installerPackageName, verifParams, user, params.abiOverride); 7763 mHandler.sendMessage(msg); 7764 } 7765 7766 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 7767 Bundle extras = new Bundle(1); 7768 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 7769 7770 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 7771 packageName, extras, null, null, new int[] {userId}); 7772 try { 7773 IActivityManager am = ActivityManagerNative.getDefault(); 7774 final boolean isSystem = 7775 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 7776 if (isSystem && am.isUserRunning(userId, false)) { 7777 // The just-installed/enabled app is bundled on the system, so presumed 7778 // to be able to run automatically without needing an explicit launch. 7779 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 7780 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 7781 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 7782 .setPackage(packageName); 7783 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 7784 android.app.AppOpsManager.OP_NONE, false, false, userId); 7785 } 7786 } catch (RemoteException e) { 7787 // shouldn't happen 7788 Slog.w(TAG, "Unable to bootstrap installed package", e); 7789 } 7790 } 7791 7792 @Override 7793 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 7794 int userId) { 7795 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7796 PackageSetting pkgSetting; 7797 final int uid = Binder.getCallingUid(); 7798 if (UserHandle.getUserId(uid) != userId) { 7799 mContext.enforceCallingOrSelfPermission( 7800 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 7801 "setApplicationHiddenSetting for user " + userId); 7802 } 7803 7804 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 7805 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 7806 return false; 7807 } 7808 7809 long callingId = Binder.clearCallingIdentity(); 7810 try { 7811 boolean sendAdded = false; 7812 boolean sendRemoved = false; 7813 // writer 7814 synchronized (mPackages) { 7815 pkgSetting = mSettings.mPackages.get(packageName); 7816 if (pkgSetting == null) { 7817 return false; 7818 } 7819 if (pkgSetting.getHidden(userId) != hidden) { 7820 pkgSetting.setHidden(hidden, userId); 7821 mSettings.writePackageRestrictionsLPr(userId); 7822 if (hidden) { 7823 sendRemoved = true; 7824 } else { 7825 sendAdded = true; 7826 } 7827 } 7828 } 7829 if (sendAdded) { 7830 sendPackageAddedForUser(packageName, pkgSetting, userId); 7831 return true; 7832 } 7833 if (sendRemoved) { 7834 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 7835 "hiding pkg"); 7836 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 7837 } 7838 } finally { 7839 Binder.restoreCallingIdentity(callingId); 7840 } 7841 return false; 7842 } 7843 7844 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 7845 int userId) { 7846 final PackageRemovedInfo info = new PackageRemovedInfo(); 7847 info.removedPackage = packageName; 7848 info.removedUsers = new int[] {userId}; 7849 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 7850 info.sendBroadcast(false, false, false); 7851 } 7852 7853 /** 7854 * Returns true if application is not found or there was an error. Otherwise it returns 7855 * the hidden state of the package for the given user. 7856 */ 7857 @Override 7858 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 7859 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7860 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 7861 "getApplicationHidden for user " + userId); 7862 PackageSetting pkgSetting; 7863 long callingId = Binder.clearCallingIdentity(); 7864 try { 7865 // writer 7866 synchronized (mPackages) { 7867 pkgSetting = mSettings.mPackages.get(packageName); 7868 if (pkgSetting == null) { 7869 return true; 7870 } 7871 return pkgSetting.getHidden(userId); 7872 } 7873 } finally { 7874 Binder.restoreCallingIdentity(callingId); 7875 } 7876 } 7877 7878 /** 7879 * @hide 7880 */ 7881 @Override 7882 public int installExistingPackageAsUser(String packageName, int userId) { 7883 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7884 null); 7885 PackageSetting pkgSetting; 7886 final int uid = Binder.getCallingUid(); 7887 enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId); 7888 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 7889 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 7890 } 7891 7892 long callingId = Binder.clearCallingIdentity(); 7893 try { 7894 boolean sendAdded = false; 7895 Bundle extras = new Bundle(1); 7896 7897 // writer 7898 synchronized (mPackages) { 7899 pkgSetting = mSettings.mPackages.get(packageName); 7900 if (pkgSetting == null) { 7901 return PackageManager.INSTALL_FAILED_INVALID_URI; 7902 } 7903 if (!pkgSetting.getInstalled(userId)) { 7904 pkgSetting.setInstalled(true, userId); 7905 pkgSetting.setHidden(false, userId); 7906 mSettings.writePackageRestrictionsLPr(userId); 7907 sendAdded = true; 7908 } 7909 } 7910 7911 if (sendAdded) { 7912 sendPackageAddedForUser(packageName, pkgSetting, userId); 7913 } 7914 } finally { 7915 Binder.restoreCallingIdentity(callingId); 7916 } 7917 7918 return PackageManager.INSTALL_SUCCEEDED; 7919 } 7920 7921 boolean isUserRestricted(int userId, String restrictionKey) { 7922 Bundle restrictions = sUserManager.getUserRestrictions(userId); 7923 if (restrictions.getBoolean(restrictionKey, false)) { 7924 Log.w(TAG, "User is restricted: " + restrictionKey); 7925 return true; 7926 } 7927 return false; 7928 } 7929 7930 @Override 7931 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 7932 mContext.enforceCallingOrSelfPermission( 7933 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7934 "Only package verification agents can verify applications"); 7935 7936 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7937 final PackageVerificationResponse response = new PackageVerificationResponse( 7938 verificationCode, Binder.getCallingUid()); 7939 msg.arg1 = id; 7940 msg.obj = response; 7941 mHandler.sendMessage(msg); 7942 } 7943 7944 @Override 7945 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 7946 long millisecondsToDelay) { 7947 mContext.enforceCallingOrSelfPermission( 7948 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7949 "Only package verification agents can extend verification timeouts"); 7950 7951 final PackageVerificationState state = mPendingVerification.get(id); 7952 final PackageVerificationResponse response = new PackageVerificationResponse( 7953 verificationCodeAtTimeout, Binder.getCallingUid()); 7954 7955 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 7956 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 7957 } 7958 if (millisecondsToDelay < 0) { 7959 millisecondsToDelay = 0; 7960 } 7961 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 7962 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 7963 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 7964 } 7965 7966 if ((state != null) && !state.timeoutExtended()) { 7967 state.extendTimeout(); 7968 7969 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7970 msg.arg1 = id; 7971 msg.obj = response; 7972 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 7973 } 7974 } 7975 7976 private void broadcastPackageVerified(int verificationId, Uri packageUri, 7977 int verificationCode, UserHandle user) { 7978 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 7979 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 7980 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 7981 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 7982 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 7983 7984 mContext.sendBroadcastAsUser(intent, user, 7985 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 7986 } 7987 7988 private ComponentName matchComponentForVerifier(String packageName, 7989 List<ResolveInfo> receivers) { 7990 ActivityInfo targetReceiver = null; 7991 7992 final int NR = receivers.size(); 7993 for (int i = 0; i < NR; i++) { 7994 final ResolveInfo info = receivers.get(i); 7995 if (info.activityInfo == null) { 7996 continue; 7997 } 7998 7999 if (packageName.equals(info.activityInfo.packageName)) { 8000 targetReceiver = info.activityInfo; 8001 break; 8002 } 8003 } 8004 8005 if (targetReceiver == null) { 8006 return null; 8007 } 8008 8009 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8010 } 8011 8012 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8013 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8014 if (pkgInfo.verifiers.length == 0) { 8015 return null; 8016 } 8017 8018 final int N = pkgInfo.verifiers.length; 8019 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8020 for (int i = 0; i < N; i++) { 8021 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8022 8023 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8024 receivers); 8025 if (comp == null) { 8026 continue; 8027 } 8028 8029 final int verifierUid = getUidForVerifier(verifierInfo); 8030 if (verifierUid == -1) { 8031 continue; 8032 } 8033 8034 if (DEBUG_VERIFY) { 8035 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8036 + " with the correct signature"); 8037 } 8038 sufficientVerifiers.add(comp); 8039 verificationState.addSufficientVerifier(verifierUid); 8040 } 8041 8042 return sufficientVerifiers; 8043 } 8044 8045 private int getUidForVerifier(VerifierInfo verifierInfo) { 8046 synchronized (mPackages) { 8047 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8048 if (pkg == null) { 8049 return -1; 8050 } else if (pkg.mSignatures.length != 1) { 8051 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8052 + " has more than one signature; ignoring"); 8053 return -1; 8054 } 8055 8056 /* 8057 * If the public key of the package's signature does not match 8058 * our expected public key, then this is a different package and 8059 * we should skip. 8060 */ 8061 8062 final byte[] expectedPublicKey; 8063 try { 8064 final Signature verifierSig = pkg.mSignatures[0]; 8065 final PublicKey publicKey = verifierSig.getPublicKey(); 8066 expectedPublicKey = publicKey.getEncoded(); 8067 } catch (CertificateException e) { 8068 return -1; 8069 } 8070 8071 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8072 8073 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8074 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8075 + " does not have the expected public key; ignoring"); 8076 return -1; 8077 } 8078 8079 return pkg.applicationInfo.uid; 8080 } 8081 } 8082 8083 @Override 8084 public void finishPackageInstall(int token) { 8085 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8086 8087 if (DEBUG_INSTALL) { 8088 Slog.v(TAG, "BM finishing package install for " + token); 8089 } 8090 8091 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8092 mHandler.sendMessage(msg); 8093 } 8094 8095 /** 8096 * Get the verification agent timeout. 8097 * 8098 * @return verification timeout in milliseconds 8099 */ 8100 private long getVerificationTimeout() { 8101 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8102 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8103 DEFAULT_VERIFICATION_TIMEOUT); 8104 } 8105 8106 /** 8107 * Get the default verification agent response code. 8108 * 8109 * @return default verification response code 8110 */ 8111 private int getDefaultVerificationResponse() { 8112 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8113 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8114 DEFAULT_VERIFICATION_RESPONSE); 8115 } 8116 8117 /** 8118 * Check whether or not package verification has been enabled. 8119 * 8120 * @return true if verification should be performed 8121 */ 8122 private boolean isVerificationEnabled(int userId, int flags) { 8123 if (!DEFAULT_VERIFY_ENABLE) { 8124 return false; 8125 } 8126 8127 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 8128 8129 // Check if installing from ADB 8130 if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) { 8131 // Do not run verification in a test harness environment 8132 if (ActivityManager.isRunningInTestHarness()) { 8133 return false; 8134 } 8135 if (ensureVerifyAppsEnabled) { 8136 return true; 8137 } 8138 // Check if the developer does not want package verification for ADB installs 8139 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8140 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8141 return false; 8142 } 8143 } 8144 8145 if (ensureVerifyAppsEnabled) { 8146 return true; 8147 } 8148 8149 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8150 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8151 } 8152 8153 /** 8154 * Get the "allow unknown sources" setting. 8155 * 8156 * @return the current "allow unknown sources" setting 8157 */ 8158 private int getUnknownSourcesSettings() { 8159 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8160 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 8161 -1); 8162 } 8163 8164 @Override 8165 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 8166 final int uid = Binder.getCallingUid(); 8167 // writer 8168 synchronized (mPackages) { 8169 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 8170 if (targetPackageSetting == null) { 8171 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 8172 } 8173 8174 PackageSetting installerPackageSetting; 8175 if (installerPackageName != null) { 8176 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 8177 if (installerPackageSetting == null) { 8178 throw new IllegalArgumentException("Unknown installer package: " 8179 + installerPackageName); 8180 } 8181 } else { 8182 installerPackageSetting = null; 8183 } 8184 8185 Signature[] callerSignature; 8186 Object obj = mSettings.getUserIdLPr(uid); 8187 if (obj != null) { 8188 if (obj instanceof SharedUserSetting) { 8189 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 8190 } else if (obj instanceof PackageSetting) { 8191 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 8192 } else { 8193 throw new SecurityException("Bad object " + obj + " for uid " + uid); 8194 } 8195 } else { 8196 throw new SecurityException("Unknown calling uid " + uid); 8197 } 8198 8199 // Verify: can't set installerPackageName to a package that is 8200 // not signed with the same cert as the caller. 8201 if (installerPackageSetting != null) { 8202 if (compareSignatures(callerSignature, 8203 installerPackageSetting.signatures.mSignatures) 8204 != PackageManager.SIGNATURE_MATCH) { 8205 throw new SecurityException( 8206 "Caller does not have same cert as new installer package " 8207 + installerPackageName); 8208 } 8209 } 8210 8211 // Verify: if target already has an installer package, it must 8212 // be signed with the same cert as the caller. 8213 if (targetPackageSetting.installerPackageName != null) { 8214 PackageSetting setting = mSettings.mPackages.get( 8215 targetPackageSetting.installerPackageName); 8216 // If the currently set package isn't valid, then it's always 8217 // okay to change it. 8218 if (setting != null) { 8219 if (compareSignatures(callerSignature, 8220 setting.signatures.mSignatures) 8221 != PackageManager.SIGNATURE_MATCH) { 8222 throw new SecurityException( 8223 "Caller does not have same cert as old installer package " 8224 + targetPackageSetting.installerPackageName); 8225 } 8226 } 8227 } 8228 8229 // Okay! 8230 targetPackageSetting.installerPackageName = installerPackageName; 8231 scheduleWriteSettingsLocked(); 8232 } 8233 } 8234 8235 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 8236 // Queue up an async operation since the package installation may take a little while. 8237 mHandler.post(new Runnable() { 8238 public void run() { 8239 mHandler.removeCallbacks(this); 8240 // Result object to be returned 8241 PackageInstalledInfo res = new PackageInstalledInfo(); 8242 res.returnCode = currentStatus; 8243 res.uid = -1; 8244 res.pkg = null; 8245 res.removedInfo = new PackageRemovedInfo(); 8246 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 8247 args.doPreInstall(res.returnCode); 8248 synchronized (mInstallLock) { 8249 installPackageLI(args, true, res); 8250 } 8251 args.doPostInstall(res.returnCode, res.uid); 8252 } 8253 8254 // A restore should be performed at this point if (a) the install 8255 // succeeded, (b) the operation is not an update, and (c) the new 8256 // package has a backupAgent defined. 8257 final boolean update = res.removedInfo.removedPackage != null; 8258 boolean doRestore = (!update 8259 && res.pkg != null 8260 && res.pkg.applicationInfo.backupAgentName != null); 8261 8262 // Set up the post-install work request bookkeeping. This will be used 8263 // and cleaned up by the post-install event handling regardless of whether 8264 // there's a restore pass performed. Token values are >= 1. 8265 int token; 8266 if (mNextInstallToken < 0) mNextInstallToken = 1; 8267 token = mNextInstallToken++; 8268 8269 PostInstallData data = new PostInstallData(args, res); 8270 mRunningInstalls.put(token, data); 8271 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 8272 8273 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 8274 // Pass responsibility to the Backup Manager. It will perform a 8275 // restore if appropriate, then pass responsibility back to the 8276 // Package Manager to run the post-install observer callbacks 8277 // and broadcasts. 8278 IBackupManager bm = IBackupManager.Stub.asInterface( 8279 ServiceManager.getService(Context.BACKUP_SERVICE)); 8280 if (bm != null) { 8281 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 8282 + " to BM for possible restore"); 8283 try { 8284 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 8285 } catch (RemoteException e) { 8286 // can't happen; the backup manager is local 8287 } catch (Exception e) { 8288 Slog.e(TAG, "Exception trying to enqueue restore", e); 8289 doRestore = false; 8290 } 8291 } else { 8292 Slog.e(TAG, "Backup Manager not found!"); 8293 doRestore = false; 8294 } 8295 } 8296 8297 if (!doRestore) { 8298 // No restore possible, or the Backup Manager was mysteriously not 8299 // available -- just fire the post-install work request directly. 8300 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 8301 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8302 mHandler.sendMessage(msg); 8303 } 8304 } 8305 }); 8306 } 8307 8308 private abstract class HandlerParams { 8309 private static final int MAX_RETRIES = 4; 8310 8311 /** 8312 * Number of times startCopy() has been attempted and had a non-fatal 8313 * error. 8314 */ 8315 private int mRetries = 0; 8316 8317 /** User handle for the user requesting the information or installation. */ 8318 private final UserHandle mUser; 8319 8320 HandlerParams(UserHandle user) { 8321 mUser = user; 8322 } 8323 8324 UserHandle getUser() { 8325 return mUser; 8326 } 8327 8328 final boolean startCopy() { 8329 boolean res; 8330 try { 8331 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 8332 8333 if (++mRetries > MAX_RETRIES) { 8334 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 8335 mHandler.sendEmptyMessage(MCS_GIVE_UP); 8336 handleServiceError(); 8337 return false; 8338 } else { 8339 handleStartCopy(); 8340 res = true; 8341 } 8342 } catch (RemoteException e) { 8343 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 8344 mHandler.sendEmptyMessage(MCS_RECONNECT); 8345 res = false; 8346 } 8347 handleReturnCode(); 8348 return res; 8349 } 8350 8351 final void serviceError() { 8352 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 8353 handleServiceError(); 8354 handleReturnCode(); 8355 } 8356 8357 abstract void handleStartCopy() throws RemoteException; 8358 abstract void handleServiceError(); 8359 abstract void handleReturnCode(); 8360 } 8361 8362 class MeasureParams extends HandlerParams { 8363 private final PackageStats mStats; 8364 private boolean mSuccess; 8365 8366 private final IPackageStatsObserver mObserver; 8367 8368 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 8369 super(new UserHandle(stats.userHandle)); 8370 mObserver = observer; 8371 mStats = stats; 8372 } 8373 8374 @Override 8375 public String toString() { 8376 return "MeasureParams{" 8377 + Integer.toHexString(System.identityHashCode(this)) 8378 + " " + mStats.packageName + "}"; 8379 } 8380 8381 @Override 8382 void handleStartCopy() throws RemoteException { 8383 synchronized (mInstallLock) { 8384 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 8385 } 8386 8387 if (mSuccess) { 8388 final boolean mounted; 8389 if (Environment.isExternalStorageEmulated()) { 8390 mounted = true; 8391 } else { 8392 final String status = Environment.getExternalStorageState(); 8393 mounted = (Environment.MEDIA_MOUNTED.equals(status) 8394 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 8395 } 8396 8397 if (mounted) { 8398 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 8399 8400 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 8401 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 8402 8403 mStats.externalDataSize = calculateDirectorySize(mContainerService, 8404 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 8405 8406 // Always subtract cache size, since it's a subdirectory 8407 mStats.externalDataSize -= mStats.externalCacheSize; 8408 8409 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 8410 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 8411 8412 mStats.externalObbSize = calculateDirectorySize(mContainerService, 8413 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 8414 } 8415 } 8416 } 8417 8418 @Override 8419 void handleReturnCode() { 8420 if (mObserver != null) { 8421 try { 8422 mObserver.onGetStatsCompleted(mStats, mSuccess); 8423 } catch (RemoteException e) { 8424 Slog.i(TAG, "Observer no longer exists."); 8425 } 8426 } 8427 } 8428 8429 @Override 8430 void handleServiceError() { 8431 Slog.e(TAG, "Could not measure application " + mStats.packageName 8432 + " external storage"); 8433 } 8434 } 8435 8436 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 8437 throws RemoteException { 8438 long result = 0; 8439 for (File path : paths) { 8440 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 8441 } 8442 return result; 8443 } 8444 8445 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 8446 for (File path : paths) { 8447 try { 8448 mcs.clearDirectory(path.getAbsolutePath()); 8449 } catch (RemoteException e) { 8450 } 8451 } 8452 } 8453 8454 class InstallParams extends HandlerParams { 8455 /** 8456 * Location where install is coming from, before it has been 8457 * copied/renamed into place. This could be a single monolithic APK 8458 * file, or a cluster directory. This location may be untrusted. 8459 */ 8460 final File originFile; 8461 8462 /** 8463 * Flag indicating that {@link #originFile} has already been staged, 8464 * meaning downstream users don't need to defensively copy the contents. 8465 */ 8466 boolean originStaged; 8467 8468 final IPackageInstallObserver2 observer; 8469 int flags; 8470 final String installerPackageName; 8471 final VerificationParams verificationParams; 8472 private InstallArgs mArgs; 8473 private int mRet; 8474 final String packageAbiOverride; 8475 boolean multiArch; 8476 8477 InstallParams(File originFile, boolean originStaged, IPackageInstallObserver2 observer, 8478 int flags, String installerPackageName, VerificationParams verificationParams, 8479 UserHandle user, String packageAbiOverride) { 8480 super(user); 8481 this.originFile = Preconditions.checkNotNull(originFile); 8482 this.originStaged = originStaged; 8483 this.observer = observer; 8484 this.flags = flags; 8485 this.installerPackageName = installerPackageName; 8486 this.verificationParams = verificationParams; 8487 this.packageAbiOverride = packageAbiOverride; 8488 } 8489 8490 @Override 8491 public String toString() { 8492 return "InstallParams{" 8493 + Integer.toHexString(System.identityHashCode(this)) 8494 + " " + originFile + "}"; 8495 } 8496 8497 public ManifestDigest getManifestDigest() { 8498 if (verificationParams == null) { 8499 return null; 8500 } 8501 return verificationParams.getManifestDigest(); 8502 } 8503 8504 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) { 8505 String packageName = pkgLite.packageName; 8506 int installLocation = pkgLite.installLocation; 8507 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8508 // reader 8509 synchronized (mPackages) { 8510 PackageParser.Package pkg = mPackages.get(packageName); 8511 if (pkg != null) { 8512 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 8513 // Check for downgrading. 8514 if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 8515 if (pkgLite.versionCode < pkg.mVersionCode) { 8516 Slog.w(TAG, "Can't install update of " + packageName 8517 + " update version " + pkgLite.versionCode 8518 + " is older than installed version " 8519 + pkg.mVersionCode); 8520 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 8521 } 8522 } 8523 // Check for updated system application. 8524 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8525 if (onSd) { 8526 Slog.w(TAG, "Cannot install update to system app on sdcard"); 8527 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 8528 } 8529 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8530 } else { 8531 if (onSd) { 8532 // Install flag overrides everything. 8533 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8534 } 8535 // If current upgrade specifies particular preference 8536 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 8537 // Application explicitly specified internal. 8538 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8539 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 8540 // App explictly prefers external. Let policy decide 8541 } else { 8542 // Prefer previous location 8543 if (isExternal(pkg)) { 8544 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8545 } 8546 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8547 } 8548 } 8549 } else { 8550 // Invalid install. Return error code 8551 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 8552 } 8553 } 8554 } 8555 // All the special cases have been taken care of. 8556 // Return result based on recommended install location. 8557 if (onSd) { 8558 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8559 } 8560 return pkgLite.recommendedInstallLocation; 8561 } 8562 8563 private long getMemoryLowThreshold() { 8564 final DeviceStorageMonitorInternal 8565 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 8566 if (dsm == null) { 8567 return 0L; 8568 } 8569 return dsm.getMemoryLowThreshold(); 8570 } 8571 8572 /* 8573 * Invoke remote method to get package information and install 8574 * location values. Override install location based on default 8575 * policy if needed and then create install arguments based 8576 * on the install location. 8577 */ 8578 public void handleStartCopy() throws RemoteException { 8579 int ret = PackageManager.INSTALL_SUCCEEDED; 8580 final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8581 final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0; 8582 PackageInfoLite pkgLite = null; 8583 8584 if (onInt && onSd) { 8585 // Check if both bits are set. 8586 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 8587 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8588 } else { 8589 final long lowThreshold = getMemoryLowThreshold(); 8590 if (lowThreshold == 0L) { 8591 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 8592 } 8593 8594 // Remote call to find out default install location 8595 final String originPath = originFile.getAbsolutePath(); 8596 pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags, lowThreshold, 8597 packageAbiOverride); 8598 // Keep track of whether this package is a multiArch package until 8599 // we perform a full scan of it. We need to do this because we might 8600 // end up extracting the package shared libraries before we perform 8601 // a full scan. 8602 multiArch = pkgLite.multiArch; 8603 8604 /* 8605 * If we have too little free space, try to free cache 8606 * before giving up. 8607 */ 8608 if (pkgLite.recommendedInstallLocation 8609 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8610 final long size = mContainerService.calculateInstalledSize( 8611 originPath, isForwardLocked(), packageAbiOverride); 8612 if (mInstaller.freeCache(size + lowThreshold) >= 0) { 8613 pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags, 8614 lowThreshold, packageAbiOverride); 8615 } 8616 /* 8617 * The cache free must have deleted the file we 8618 * downloaded to install. 8619 * 8620 * TODO: fix the "freeCache" call to not delete 8621 * the file we care about. 8622 */ 8623 if (pkgLite.recommendedInstallLocation 8624 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8625 pkgLite.recommendedInstallLocation 8626 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 8627 } 8628 } 8629 } 8630 8631 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8632 int loc = pkgLite.recommendedInstallLocation; 8633 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 8634 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8635 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 8636 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 8637 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8638 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8639 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 8640 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 8641 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8642 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 8643 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 8644 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 8645 } else { 8646 // Override with defaults if needed. 8647 loc = installLocationPolicy(pkgLite, flags); 8648 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 8649 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 8650 } else if (!onSd && !onInt) { 8651 // Override install location with flags 8652 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 8653 // Set the flag to install on external media. 8654 flags |= PackageManager.INSTALL_EXTERNAL; 8655 flags &= ~PackageManager.INSTALL_INTERNAL; 8656 } else { 8657 // Make sure the flag for installing on external 8658 // media is unset 8659 flags |= PackageManager.INSTALL_INTERNAL; 8660 flags &= ~PackageManager.INSTALL_EXTERNAL; 8661 } 8662 } 8663 } 8664 } 8665 8666 final InstallArgs args = createInstallArgs(this); 8667 mArgs = args; 8668 8669 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8670 /* 8671 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 8672 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 8673 */ 8674 int userIdentifier = getUser().getIdentifier(); 8675 if (userIdentifier == UserHandle.USER_ALL 8676 && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) { 8677 userIdentifier = UserHandle.USER_OWNER; 8678 } 8679 8680 /* 8681 * Determine if we have any installed package verifiers. If we 8682 * do, then we'll defer to them to verify the packages. 8683 */ 8684 final int requiredUid = mRequiredVerifierPackage == null ? -1 8685 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 8686 if (requiredUid != -1 && isVerificationEnabled(userIdentifier, flags)) { 8687 // TODO: send verifier the install session instead of uri 8688 final Intent verification = new Intent( 8689 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 8690 verification.setDataAndType(Uri.fromFile(originFile), PACKAGE_MIME_TYPE); 8691 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8692 8693 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 8694 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 8695 0 /* TODO: Which userId? */); 8696 8697 if (DEBUG_VERIFY) { 8698 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 8699 + verification.toString() + " with " + pkgLite.verifiers.length 8700 + " optional verifiers"); 8701 } 8702 8703 final int verificationId = mPendingVerificationToken++; 8704 8705 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8706 8707 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 8708 installerPackageName); 8709 8710 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags); 8711 8712 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 8713 pkgLite.packageName); 8714 8715 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 8716 pkgLite.versionCode); 8717 8718 if (verificationParams != null) { 8719 if (verificationParams.getVerificationURI() != null) { 8720 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 8721 verificationParams.getVerificationURI()); 8722 } 8723 if (verificationParams.getOriginatingURI() != null) { 8724 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 8725 verificationParams.getOriginatingURI()); 8726 } 8727 if (verificationParams.getReferrer() != null) { 8728 verification.putExtra(Intent.EXTRA_REFERRER, 8729 verificationParams.getReferrer()); 8730 } 8731 if (verificationParams.getOriginatingUid() >= 0) { 8732 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 8733 verificationParams.getOriginatingUid()); 8734 } 8735 if (verificationParams.getInstallerUid() >= 0) { 8736 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 8737 verificationParams.getInstallerUid()); 8738 } 8739 } 8740 8741 final PackageVerificationState verificationState = new PackageVerificationState( 8742 requiredUid, args); 8743 8744 mPendingVerification.append(verificationId, verificationState); 8745 8746 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 8747 receivers, verificationState); 8748 8749 /* 8750 * If any sufficient verifiers were listed in the package 8751 * manifest, attempt to ask them. 8752 */ 8753 if (sufficientVerifiers != null) { 8754 final int N = sufficientVerifiers.size(); 8755 if (N == 0) { 8756 Slog.i(TAG, "Additional verifiers required, but none installed."); 8757 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 8758 } else { 8759 for (int i = 0; i < N; i++) { 8760 final ComponentName verifierComponent = sufficientVerifiers.get(i); 8761 8762 final Intent sufficientIntent = new Intent(verification); 8763 sufficientIntent.setComponent(verifierComponent); 8764 8765 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 8766 } 8767 } 8768 } 8769 8770 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 8771 mRequiredVerifierPackage, receivers); 8772 if (ret == PackageManager.INSTALL_SUCCEEDED 8773 && mRequiredVerifierPackage != null) { 8774 /* 8775 * Send the intent to the required verification agent, 8776 * but only start the verification timeout after the 8777 * target BroadcastReceivers have run. 8778 */ 8779 verification.setComponent(requiredVerifierComponent); 8780 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 8781 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8782 new BroadcastReceiver() { 8783 @Override 8784 public void onReceive(Context context, Intent intent) { 8785 final Message msg = mHandler 8786 .obtainMessage(CHECK_PENDING_VERIFICATION); 8787 msg.arg1 = verificationId; 8788 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 8789 } 8790 }, null, 0, null, null); 8791 8792 /* 8793 * We don't want the copy to proceed until verification 8794 * succeeds, so null out this field. 8795 */ 8796 mArgs = null; 8797 } 8798 } else { 8799 /* 8800 * No package verification is enabled, so immediately start 8801 * the remote call to initiate copy using temporary file. 8802 */ 8803 ret = args.copyApk(mContainerService, true); 8804 } 8805 } 8806 8807 mRet = ret; 8808 } 8809 8810 @Override 8811 void handleReturnCode() { 8812 // If mArgs is null, then MCS couldn't be reached. When it 8813 // reconnects, it will try again to install. At that point, this 8814 // will succeed. 8815 if (mArgs != null) { 8816 processPendingInstall(mArgs, mRet); 8817 } 8818 } 8819 8820 @Override 8821 void handleServiceError() { 8822 mArgs = createInstallArgs(this); 8823 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8824 } 8825 8826 public boolean isForwardLocked() { 8827 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8828 } 8829 } 8830 8831 /* 8832 * Utility class used in movePackage api. 8833 * srcArgs and targetArgs are not set for invalid flags and make 8834 * sure to do null checks when invoking methods on them. 8835 * We probably want to return ErrorPrams for both failed installs 8836 * and moves. 8837 */ 8838 class MoveParams extends HandlerParams { 8839 final IPackageMoveObserver observer; 8840 final int flags; 8841 final String packageName; 8842 final InstallArgs srcArgs; 8843 final InstallArgs targetArgs; 8844 int uid; 8845 int mRet; 8846 8847 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags, 8848 String packageName, String[] instructionSets, int uid, UserHandle user, 8849 boolean isMultiArch) { 8850 super(user); 8851 this.srcArgs = srcArgs; 8852 this.observer = observer; 8853 this.flags = flags; 8854 this.packageName = packageName; 8855 this.uid = uid; 8856 if (srcArgs != null) { 8857 final String codePath = srcArgs.getCodePath(); 8858 targetArgs = createInstallArgsForMoveTarget(codePath, flags, packageName, 8859 instructionSets, isMultiArch); 8860 } else { 8861 targetArgs = null; 8862 } 8863 } 8864 8865 @Override 8866 public String toString() { 8867 return "MoveParams{" 8868 + Integer.toHexString(System.identityHashCode(this)) 8869 + " " + packageName + "}"; 8870 } 8871 8872 public void handleStartCopy() throws RemoteException { 8873 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8874 // Check for storage space on target medium 8875 if (!targetArgs.checkFreeStorage(mContainerService)) { 8876 Log.w(TAG, "Insufficient storage to install"); 8877 return; 8878 } 8879 8880 mRet = srcArgs.doPreCopy(); 8881 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8882 return; 8883 } 8884 8885 mRet = targetArgs.copyApk(mContainerService, false); 8886 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8887 srcArgs.doPostCopy(uid); 8888 return; 8889 } 8890 8891 mRet = srcArgs.doPostCopy(uid); 8892 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8893 return; 8894 } 8895 8896 mRet = targetArgs.doPreInstall(mRet); 8897 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8898 return; 8899 } 8900 8901 if (DEBUG_SD_INSTALL) { 8902 StringBuilder builder = new StringBuilder(); 8903 if (srcArgs != null) { 8904 builder.append("src: "); 8905 builder.append(srcArgs.getCodePath()); 8906 } 8907 if (targetArgs != null) { 8908 builder.append(" target : "); 8909 builder.append(targetArgs.getCodePath()); 8910 } 8911 Log.i(TAG, builder.toString()); 8912 } 8913 } 8914 8915 @Override 8916 void handleReturnCode() { 8917 targetArgs.doPostInstall(mRet, uid); 8918 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 8919 if (mRet == PackageManager.INSTALL_SUCCEEDED) { 8920 currentStatus = PackageManager.MOVE_SUCCEEDED; 8921 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){ 8922 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 8923 } 8924 processPendingMove(this, currentStatus); 8925 } 8926 8927 @Override 8928 void handleServiceError() { 8929 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8930 } 8931 } 8932 8933 /** 8934 * Used during creation of InstallArgs 8935 * 8936 * @param flags package installation flags 8937 * @return true if should be installed on external storage 8938 */ 8939 private static boolean installOnSd(int flags) { 8940 if ((flags & PackageManager.INSTALL_INTERNAL) != 0) { 8941 return false; 8942 } 8943 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) { 8944 return true; 8945 } 8946 return false; 8947 } 8948 8949 /** 8950 * Used during creation of InstallArgs 8951 * 8952 * @param flags package installation flags 8953 * @return true if should be installed as forward locked 8954 */ 8955 private static boolean installForwardLocked(int flags) { 8956 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8957 } 8958 8959 private InstallArgs createInstallArgs(InstallParams params) { 8960 // TODO: extend to support incoming zero-copy locations 8961 8962 if (installOnSd(params.flags) || params.isForwardLocked()) { 8963 return new AsecInstallArgs(params); 8964 } else { 8965 return new FileInstallArgs(params); 8966 } 8967 } 8968 8969 /** 8970 * Create args that describe an existing installed package. Typically used 8971 * when cleaning up old installs, or used as a move source. 8972 */ 8973 private InstallArgs createInstallArgsForExisting(int flags, String codePath, 8974 String resourcePath, String nativeLibraryRoot, String[] instructionSets, 8975 boolean isMultiArch) { 8976 final boolean isInAsec; 8977 if (installOnSd(flags)) { 8978 /* Apps on SD card are always in ASEC containers. */ 8979 isInAsec = true; 8980 } else if (installForwardLocked(flags) 8981 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 8982 /* 8983 * Forward-locked apps are only in ASEC containers if they're the 8984 * new style 8985 */ 8986 isInAsec = true; 8987 } else { 8988 isInAsec = false; 8989 } 8990 8991 if (isInAsec) { 8992 return new AsecInstallArgs(codePath, instructionSets, 8993 installOnSd(flags), installForwardLocked(flags), isMultiArch); 8994 } else { 8995 return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot, 8996 instructionSets, isMultiArch); 8997 } 8998 } 8999 9000 private InstallArgs createInstallArgsForMoveTarget(String codePath, int flags, String pkgName, 9001 String[] instructionSets, boolean isMultiArch) { 9002 final File codeFile = new File(codePath); 9003 if (installOnSd(flags) || installForwardLocked(flags)) { 9004 String cid = getNextCodePath(codePath, pkgName, "/" 9005 + AsecInstallArgs.RES_FILE_NAME); 9006 return new AsecInstallArgs(codeFile, cid, instructionSets, installOnSd(flags), 9007 installForwardLocked(flags), isMultiArch); 9008 } else { 9009 return new FileInstallArgs(codeFile, instructionSets, isMultiArch); 9010 } 9011 } 9012 9013 static abstract class InstallArgs { 9014 /** @see InstallParams#originFile */ 9015 final File originFile; 9016 /** @see InstallParams#originStaged */ 9017 final boolean originStaged; 9018 9019 // TODO: define inherit location 9020 9021 final IPackageInstallObserver2 observer; 9022 // Always refers to PackageManager flags only 9023 final int flags; 9024 final String installerPackageName; 9025 final ManifestDigest manifestDigest; 9026 final UserHandle user; 9027 final String abiOverride; 9028 final boolean multiArch; 9029 9030 // The list of instruction sets supported by this app. This is currently 9031 // only used during the rmdex() phase to clean up resources. We can get rid of this 9032 // if we move dex files under the common app path. 9033 /* nullable */ String[] instructionSets; 9034 9035 InstallArgs(File originFile, boolean originStaged, IPackageInstallObserver2 observer, 9036 int flags, String installerPackageName, ManifestDigest manifestDigest, 9037 UserHandle user, String[] instructionSets, 9038 String abiOverride, boolean multiArch) { 9039 this.originFile = originFile; 9040 this.originStaged = originStaged; 9041 this.flags = flags; 9042 this.observer = observer; 9043 this.installerPackageName = installerPackageName; 9044 this.manifestDigest = manifestDigest; 9045 this.user = user; 9046 this.instructionSets = instructionSets; 9047 this.abiOverride = abiOverride; 9048 this.multiArch = multiArch; 9049 } 9050 9051 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 9052 abstract int doPreInstall(int status); 9053 9054 /** 9055 * Rename package into final resting place. All paths on the given 9056 * scanned package should be updated to reflect the rename. 9057 */ 9058 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 9059 abstract int doPostInstall(int status, int uid); 9060 9061 /** @see PackageSettingBase#codePathString */ 9062 abstract String getCodePath(); 9063 /** @see PackageSettingBase#resourcePathString */ 9064 abstract String getResourcePath(); 9065 abstract String getLegacyNativeLibraryPath(); 9066 9067 // Need installer lock especially for dex file removal. 9068 abstract void cleanUpResourcesLI(); 9069 abstract boolean doPostDeleteLI(boolean delete); 9070 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9071 9072 /** 9073 * Called before the source arguments are copied. This is used mostly 9074 * for MoveParams when it needs to read the source file to put it in the 9075 * destination. 9076 */ 9077 int doPreCopy() { 9078 return PackageManager.INSTALL_SUCCEEDED; 9079 } 9080 9081 /** 9082 * Called after the source arguments are copied. This is used mostly for 9083 * MoveParams when it needs to read the source file to put it in the 9084 * destination. 9085 * 9086 * @return 9087 */ 9088 int doPostCopy(int uid) { 9089 return PackageManager.INSTALL_SUCCEEDED; 9090 } 9091 9092 protected boolean isFwdLocked() { 9093 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9094 } 9095 9096 UserHandle getUser() { 9097 return user; 9098 } 9099 } 9100 9101 /** 9102 * Logic to handle installation of non-ASEC applications, including copying 9103 * and renaming logic. 9104 */ 9105 class FileInstallArgs extends InstallArgs { 9106 private File codeFile; 9107 private File resourceFile; 9108 private File legacyNativeLibraryPath; 9109 9110 // Example topology: 9111 // /data/app/com.example/base.apk 9112 // /data/app/com.example/split_foo.apk 9113 // /data/app/com.example/lib/arm/libfoo.so 9114 // /data/app/com.example/lib/arm64/libfoo.so 9115 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 9116 9117 /** New install */ 9118 FileInstallArgs(InstallParams params) { 9119 super(params.originFile, params.originStaged, params.observer, params.flags, 9120 params.installerPackageName, params.getManifestDigest(), params.getUser(), 9121 null /* instruction sets */, params.packageAbiOverride, 9122 params.multiArch); 9123 if (isFwdLocked()) { 9124 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 9125 } 9126 } 9127 9128 /** Existing install */ 9129 FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath, 9130 String[] instructionSets, boolean isMultiArch) { 9131 super(null, false, null, 0, null, null, null, instructionSets, null, isMultiArch); 9132 this.codeFile = (codePath != null) ? new File(codePath) : null; 9133 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 9134 this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ? 9135 new File(legacyNativeLibraryPath) : null; 9136 } 9137 9138 /** New install from existing */ 9139 FileInstallArgs(File originFile, String[] instructionSets, boolean isMultiArch) { 9140 super(originFile, false, null, 0, null, null, null, instructionSets, null, 9141 isMultiArch); 9142 } 9143 9144 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9145 final long lowThreshold; 9146 9147 final DeviceStorageMonitorInternal 9148 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 9149 if (dsm == null) { 9150 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 9151 lowThreshold = 0L; 9152 } else { 9153 if (dsm.isMemoryLow()) { 9154 Log.w(TAG, "Memory is reported as being too low; aborting package install"); 9155 return false; 9156 } 9157 9158 lowThreshold = dsm.getMemoryLowThreshold(); 9159 } 9160 9161 return imcs.checkInternalFreeStorage(originFile.getAbsolutePath(), isFwdLocked(), 9162 lowThreshold); 9163 } 9164 9165 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9166 int ret = PackageManager.INSTALL_SUCCEEDED; 9167 9168 if (originStaged) { 9169 Slog.d(TAG, originFile + " already staged; skipping copy"); 9170 codeFile = originFile; 9171 resourceFile = originFile; 9172 } else { 9173 try { 9174 final File tempDir = mInstallerService.allocateSessionDir(); 9175 codeFile = tempDir; 9176 resourceFile = tempDir; 9177 } catch (IOException e) { 9178 Slog.w(TAG, "Failed to create copy file: " + e); 9179 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9180 } 9181 9182 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 9183 @Override 9184 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 9185 if (!FileUtils.isValidExtFilename(name)) { 9186 throw new IllegalArgumentException("Invalid filename: " + name); 9187 } 9188 try { 9189 final File file = new File(codeFile, name); 9190 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 9191 O_RDWR | O_CREAT, 0644); 9192 Os.chmod(file.getAbsolutePath(), 0644); 9193 return new ParcelFileDescriptor(fd); 9194 } catch (ErrnoException e) { 9195 throw new RemoteException("Failed to open: " + e.getMessage()); 9196 } 9197 } 9198 }; 9199 9200 ret = imcs.copyPackage(originFile.getAbsolutePath(), target); 9201 if (ret != PackageManager.INSTALL_SUCCEEDED) { 9202 Slog.e(TAG, "Failed to copy package"); 9203 return ret; 9204 } 9205 } 9206 9207 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 9208 NativeLibraryHelper.Handle handle = null; 9209 try { 9210 handle = NativeLibraryHelper.Handle.create(codeFile); 9211 if (multiArch) { 9212 // Warn if we've set an abiOverride for multi-lib packages.. 9213 // By definition, we need to copy both 32 and 64 bit libraries for 9214 // such packages. 9215 if (abiOverride != null) { 9216 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 9217 } 9218 9219 int copyRet = PackageManager.NO_NATIVE_LIBRARIES; 9220 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 9221 copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot, 9222 Build.SUPPORTED_32_BIT_ABIS, true /* use isa specific subdirs */); 9223 maybeThrowExceptionForMultiArchCopy("Failure copying 32 bit native libraries", copyRet); 9224 } 9225 9226 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 9227 copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot, 9228 Build.SUPPORTED_64_BIT_ABIS, true /* use isa specific subdirs */); 9229 maybeThrowExceptionForMultiArchCopy("Failure copying 64 bit native libraries", copyRet); 9230 } 9231 } else { 9232 String[] abiList = (abiOverride != null) ? 9233 new String[] { abiOverride } : Build.SUPPORTED_ABIS; 9234 9235 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && abiOverride == null && 9236 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9237 abiList = Build.SUPPORTED_32_BIT_ABIS; 9238 } 9239 9240 int copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot, abiList, 9241 true /* use isa specific subdirs */); 9242 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9243 Slog.w(TAG, "Failure copying native libraries [errorCode=" + copyRet + "]"); 9244 return copyRet; 9245 } 9246 } 9247 } catch (IOException e) { 9248 Slog.e(TAG, "Copying native libraries failed", e); 9249 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9250 } catch (PackageManagerException pme) { 9251 Slog.e(TAG, "Copying native libraries failed", pme); 9252 ret = pme.error; 9253 } finally { 9254 IoUtils.closeQuietly(handle); 9255 } 9256 9257 return ret; 9258 } 9259 9260 int doPreInstall(int status) { 9261 if (status != PackageManager.INSTALL_SUCCEEDED) { 9262 cleanUp(); 9263 } 9264 return status; 9265 } 9266 9267 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9268 if (status != PackageManager.INSTALL_SUCCEEDED) { 9269 cleanUp(); 9270 return false; 9271 } else { 9272 final File beforeCodeFile = codeFile; 9273 final File afterCodeFile = getNextCodePath(pkg.packageName); 9274 9275 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 9276 try { 9277 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 9278 } catch (ErrnoException e) { 9279 Slog.d(TAG, "Failed to rename", e); 9280 return false; 9281 } 9282 9283 if (!SELinux.restoreconRecursive(afterCodeFile)) { 9284 Slog.d(TAG, "Failed to restorecon"); 9285 return false; 9286 } 9287 9288 // Reflect the rename internally 9289 codeFile = afterCodeFile; 9290 resourceFile = afterCodeFile; 9291 9292 // Reflect the rename in scanned details 9293 pkg.codePath = afterCodeFile.getAbsolutePath(); 9294 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9295 pkg.baseCodePath); 9296 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9297 pkg.splitCodePaths); 9298 9299 // Reflect the rename in app info 9300 pkg.applicationInfo.setCodePath(pkg.codePath); 9301 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9302 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9303 pkg.applicationInfo.setResourcePath(pkg.codePath); 9304 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9305 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9306 9307 return true; 9308 } 9309 } 9310 9311 int doPostInstall(int status, int uid) { 9312 if (status != PackageManager.INSTALL_SUCCEEDED) { 9313 cleanUp(); 9314 } 9315 return status; 9316 } 9317 9318 @Override 9319 String getCodePath() { 9320 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 9321 } 9322 9323 @Override 9324 String getResourcePath() { 9325 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 9326 } 9327 9328 @Override 9329 String getLegacyNativeLibraryPath() { 9330 return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null; 9331 } 9332 9333 private boolean cleanUp() { 9334 if (codeFile == null || !codeFile.exists()) { 9335 return false; 9336 } 9337 9338 if (codeFile.isDirectory()) { 9339 FileUtils.deleteContents(codeFile); 9340 } 9341 codeFile.delete(); 9342 9343 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 9344 resourceFile.delete(); 9345 } 9346 9347 if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) { 9348 if (!FileUtils.deleteContents(legacyNativeLibraryPath)) { 9349 Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath); 9350 } 9351 legacyNativeLibraryPath.delete(); 9352 } 9353 9354 return true; 9355 } 9356 9357 void cleanUpResourcesLI() { 9358 // Try enumerating all code paths before deleting 9359 List<String> allCodePaths = Collections.EMPTY_LIST; 9360 if (codeFile != null && codeFile.exists()) { 9361 try { 9362 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9363 allCodePaths = pkg.getAllCodePaths(); 9364 } catch (PackageParserException e) { 9365 // Ignored; we tried our best 9366 } 9367 } 9368 9369 cleanUp(); 9370 9371 if (!allCodePaths.isEmpty()) { 9372 if (instructionSets == null) { 9373 throw new IllegalStateException("instructionSet == null"); 9374 } 9375 9376 for (String codePath : allCodePaths) { 9377 for (String instructionSet : instructionSets) { 9378 int retCode = mInstaller.rmdex(codePath, instructionSet); 9379 if (retCode < 0) { 9380 Slog.w(TAG, "Couldn't remove dex file for package: " 9381 + " at location " + codePath + ", retcode=" + retCode); 9382 // we don't consider this to be a failure of the core package deletion 9383 } 9384 } 9385 } 9386 } 9387 } 9388 9389 boolean doPostDeleteLI(boolean delete) { 9390 // XXX err, shouldn't we respect the delete flag? 9391 cleanUpResourcesLI(); 9392 return true; 9393 } 9394 } 9395 9396 private boolean isAsecExternal(String cid) { 9397 final String asecPath = PackageHelper.getSdFilesystem(cid); 9398 return !asecPath.startsWith(mAsecInternalPath); 9399 } 9400 9401 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 9402 PackageManagerException { 9403 if (copyRet < 0) { 9404 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 9405 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 9406 throw new PackageManagerException(copyRet, message); 9407 } 9408 } 9409 } 9410 9411 /** 9412 * Extract the MountService "container ID" from the full code path of an 9413 * .apk. 9414 */ 9415 static String cidFromCodePath(String fullCodePath) { 9416 int eidx = fullCodePath.lastIndexOf("/"); 9417 String subStr1 = fullCodePath.substring(0, eidx); 9418 int sidx = subStr1.lastIndexOf("/"); 9419 return subStr1.substring(sidx+1, eidx); 9420 } 9421 9422 /** 9423 * Logic to handle installation of ASEC applications, including copying and 9424 * renaming logic. 9425 */ 9426 class AsecInstallArgs extends InstallArgs { 9427 // TODO: teach about handling cluster directories 9428 9429 static final String RES_FILE_NAME = "pkg.apk"; 9430 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 9431 9432 String cid; 9433 String packagePath; 9434 String resourcePath; 9435 String legacyNativeLibraryDir; 9436 9437 /** New install */ 9438 AsecInstallArgs(InstallParams params) { 9439 super(params.originFile, params.originStaged, params.observer, params.flags, 9440 params.installerPackageName, params.getManifestDigest(), 9441 params.getUser(), null /* instruction sets */, 9442 params.packageAbiOverride, params.multiArch); 9443 } 9444 9445 /** Existing install */ 9446 AsecInstallArgs(String fullCodePath, String[] instructionSets, 9447 boolean isExternal, boolean isForwardLocked, boolean isMultiArch) { 9448 super(null, false, null, (isExternal ? INSTALL_EXTERNAL : 0) 9449 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9450 instructionSets, null, isMultiArch); 9451 // Extract cid from fullCodePath 9452 int eidx = fullCodePath.lastIndexOf("/"); 9453 String subStr1 = fullCodePath.substring(0, eidx); 9454 int sidx = subStr1.lastIndexOf("/"); 9455 cid = subStr1.substring(sidx+1, eidx); 9456 setCachePath(subStr1); 9457 } 9458 9459 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked, 9460 boolean isMultiArch) { 9461 super(null, false, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 9462 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9463 instructionSets, null, isMultiArch); 9464 this.cid = cid; 9465 setCachePath(PackageHelper.getSdDir(cid)); 9466 } 9467 9468 /** New install from existing */ 9469 AsecInstallArgs(File originPackageFile, String cid, String[] instructionSets, 9470 boolean isExternal, boolean isForwardLocked, boolean isMultiArch) { 9471 super(originPackageFile, false, null, (isExternal ? INSTALL_EXTERNAL : 0) 9472 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9473 instructionSets, null, isMultiArch); 9474 this.cid = cid; 9475 } 9476 9477 void createCopyFile() { 9478 cid = getTempContainerId(); 9479 } 9480 9481 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9482 return imcs.checkExternalFreeStorage(originFile.getAbsolutePath(), isFwdLocked(), 9483 abiOverride); 9484 } 9485 9486 private final boolean isExternal() { 9487 return (flags & PackageManager.INSTALL_EXTERNAL) != 0; 9488 } 9489 9490 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9491 if (temp) { 9492 createCopyFile(); 9493 } else { 9494 /* 9495 * Pre-emptively destroy the container since it's destroyed if 9496 * copying fails due to it existing anyway. 9497 */ 9498 PackageHelper.destroySdDir(cid); 9499 } 9500 9501 final String newCachePath = imcs.copyPackageToContainer( 9502 originFile.getAbsolutePath(), cid, getEncryptKey(), isExternal(), 9503 isFwdLocked(), abiOverride); 9504 9505 if (newCachePath != null) { 9506 setCachePath(newCachePath); 9507 return PackageManager.INSTALL_SUCCEEDED; 9508 } else { 9509 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9510 } 9511 } 9512 9513 @Override 9514 String getCodePath() { 9515 return packagePath; 9516 } 9517 9518 @Override 9519 String getResourcePath() { 9520 return resourcePath; 9521 } 9522 9523 @Override 9524 String getLegacyNativeLibraryPath() { 9525 return legacyNativeLibraryDir; 9526 } 9527 9528 int doPreInstall(int status) { 9529 if (status != PackageManager.INSTALL_SUCCEEDED) { 9530 // Destroy container 9531 PackageHelper.destroySdDir(cid); 9532 } else { 9533 boolean mounted = PackageHelper.isContainerMounted(cid); 9534 if (!mounted) { 9535 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), 9536 Process.SYSTEM_UID); 9537 if (newCachePath != null) { 9538 setCachePath(newCachePath); 9539 } else { 9540 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9541 } 9542 } 9543 } 9544 return status; 9545 } 9546 9547 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9548 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 9549 String newCachePath = null; 9550 if (PackageHelper.isContainerMounted(cid)) { 9551 // Unmount the container 9552 if (!PackageHelper.unMountSdDir(cid)) { 9553 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9554 return false; 9555 } 9556 } 9557 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9558 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9559 " which might be stale. Will try to clean up."); 9560 // Clean up the stale container and proceed to recreate. 9561 if (!PackageHelper.destroySdDir(newCacheId)) { 9562 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9563 return false; 9564 } 9565 // Successfully cleaned up stale container. Try to rename again. 9566 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9567 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9568 + " inspite of cleaning it up."); 9569 return false; 9570 } 9571 } 9572 if (!PackageHelper.isContainerMounted(newCacheId)) { 9573 Slog.w(TAG, "Mounting container " + newCacheId); 9574 newCachePath = PackageHelper.mountSdDir(newCacheId, 9575 getEncryptKey(), Process.SYSTEM_UID); 9576 } else { 9577 newCachePath = PackageHelper.getSdDir(newCacheId); 9578 } 9579 if (newCachePath == null) { 9580 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9581 return false; 9582 } 9583 Log.i(TAG, "Succesfully renamed " + cid + 9584 " to " + newCacheId + 9585 " at new path: " + newCachePath); 9586 cid = newCacheId; 9587 setCachePath(newCachePath); 9588 9589 // TODO: extend to support split APKs 9590 pkg.codePath = getCodePath(); 9591 pkg.baseCodePath = getCodePath(); 9592 pkg.splitCodePaths = null; 9593 9594 pkg.applicationInfo.setCodePath(getCodePath()); 9595 pkg.applicationInfo.setBaseCodePath(getCodePath()); 9596 pkg.applicationInfo.setSplitCodePaths(null); 9597 pkg.applicationInfo.setResourcePath(getResourcePath()); 9598 pkg.applicationInfo.setBaseResourcePath(getResourcePath()); 9599 pkg.applicationInfo.setSplitResourcePaths(null); 9600 9601 return true; 9602 } 9603 9604 private void setCachePath(String newCachePath) { 9605 File cachePath = new File(newCachePath); 9606 legacyNativeLibraryDir = new File(cachePath, LIB_DIR_NAME).getPath(); 9607 packagePath = new File(cachePath, RES_FILE_NAME).getPath(); 9608 9609 if (isFwdLocked()) { 9610 resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath(); 9611 } else { 9612 resourcePath = packagePath; 9613 } 9614 } 9615 9616 int doPostInstall(int status, int uid) { 9617 if (status != PackageManager.INSTALL_SUCCEEDED) { 9618 cleanUp(); 9619 } else { 9620 final int groupOwner; 9621 final String protectedFile; 9622 if (isFwdLocked()) { 9623 groupOwner = UserHandle.getSharedAppGid(uid); 9624 protectedFile = RES_FILE_NAME; 9625 } else { 9626 groupOwner = -1; 9627 protectedFile = null; 9628 } 9629 9630 if (uid < Process.FIRST_APPLICATION_UID 9631 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9632 Slog.e(TAG, "Failed to finalize " + cid); 9633 PackageHelper.destroySdDir(cid); 9634 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9635 } 9636 9637 boolean mounted = PackageHelper.isContainerMounted(cid); 9638 if (!mounted) { 9639 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9640 } 9641 } 9642 return status; 9643 } 9644 9645 private void cleanUp() { 9646 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9647 9648 // Destroy secure container 9649 PackageHelper.destroySdDir(cid); 9650 } 9651 9652 void cleanUpResourcesLI() { 9653 String sourceFile = getCodePath(); 9654 // Remove dex file 9655 if (instructionSets == null) { 9656 throw new IllegalStateException("instructionSet == null"); 9657 } 9658 for (String instructionSet : instructionSets) { 9659 int retCode = mInstaller.rmdex(sourceFile, instructionSet); 9660 if (retCode < 0) { 9661 Slog.w(TAG, "Couldn't remove dex file for package: " 9662 + " at location " 9663 + sourceFile.toString() + ", retcode=" + retCode); 9664 // we don't consider this to be a failure of the core package deletion 9665 } 9666 } 9667 cleanUp(); 9668 } 9669 9670 boolean matchContainer(String app) { 9671 if (cid.startsWith(app)) { 9672 return true; 9673 } 9674 return false; 9675 } 9676 9677 String getPackageName() { 9678 return getAsecPackageName(cid); 9679 } 9680 9681 boolean doPostDeleteLI(boolean delete) { 9682 boolean ret = false; 9683 boolean mounted = PackageHelper.isContainerMounted(cid); 9684 if (mounted) { 9685 // Unmount first 9686 ret = PackageHelper.unMountSdDir(cid); 9687 } 9688 if (ret && delete) { 9689 cleanUpResourcesLI(); 9690 } 9691 return ret; 9692 } 9693 9694 @Override 9695 int doPreCopy() { 9696 if (isFwdLocked()) { 9697 if (!PackageHelper.fixSdPermissions(cid, 9698 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 9699 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9700 } 9701 } 9702 9703 return PackageManager.INSTALL_SUCCEEDED; 9704 } 9705 9706 @Override 9707 int doPostCopy(int uid) { 9708 if (isFwdLocked()) { 9709 if (uid < Process.FIRST_APPLICATION_UID 9710 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 9711 RES_FILE_NAME)) { 9712 Slog.e(TAG, "Failed to finalize " + cid); 9713 PackageHelper.destroySdDir(cid); 9714 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9715 } 9716 } 9717 9718 return PackageManager.INSTALL_SUCCEEDED; 9719 } 9720 } 9721 9722 static String getAsecPackageName(String packageCid) { 9723 int idx = packageCid.lastIndexOf("-"); 9724 if (idx == -1) { 9725 return packageCid; 9726 } 9727 return packageCid.substring(0, idx); 9728 } 9729 9730 // Utility method used to create code paths based on package name and available index. 9731 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 9732 String idxStr = ""; 9733 int idx = 1; 9734 // Fall back to default value of idx=1 if prefix is not 9735 // part of oldCodePath 9736 if (oldCodePath != null) { 9737 String subStr = oldCodePath; 9738 // Drop the suffix right away 9739 if (suffix != null && subStr.endsWith(suffix)) { 9740 subStr = subStr.substring(0, subStr.length() - suffix.length()); 9741 } 9742 // If oldCodePath already contains prefix find out the 9743 // ending index to either increment or decrement. 9744 int sidx = subStr.lastIndexOf(prefix); 9745 if (sidx != -1) { 9746 subStr = subStr.substring(sidx + prefix.length()); 9747 if (subStr != null) { 9748 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 9749 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 9750 } 9751 try { 9752 idx = Integer.parseInt(subStr); 9753 if (idx <= 1) { 9754 idx++; 9755 } else { 9756 idx--; 9757 } 9758 } catch(NumberFormatException e) { 9759 } 9760 } 9761 } 9762 } 9763 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 9764 return prefix + idxStr; 9765 } 9766 9767 private File getNextCodePath(String packageName) { 9768 int suffix = 1; 9769 File result; 9770 do { 9771 result = new File(mAppInstallDir, packageName + "-" + suffix); 9772 suffix++; 9773 } while (result.exists()); 9774 return result; 9775 } 9776 9777 // Utility method used to ignore ADD/REMOVE events 9778 // by directory observer. 9779 private static boolean ignoreCodePath(String fullPathStr) { 9780 String apkName = deriveCodePathName(fullPathStr); 9781 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 9782 if (idx != -1 && ((idx+1) < apkName.length())) { 9783 // Make sure the package ends with a numeral 9784 String version = apkName.substring(idx+1); 9785 try { 9786 Integer.parseInt(version); 9787 return true; 9788 } catch (NumberFormatException e) {} 9789 } 9790 return false; 9791 } 9792 9793 // Utility method that returns the relative package path with respect 9794 // to the installation directory. Like say for /data/data/com.test-1.apk 9795 // string com.test-1 is returned. 9796 static String deriveCodePathName(String codePath) { 9797 if (codePath == null) { 9798 return null; 9799 } 9800 final File codeFile = new File(codePath); 9801 final String name = codeFile.getName(); 9802 if (codeFile.isDirectory()) { 9803 return name; 9804 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 9805 final int lastDot = name.lastIndexOf('.'); 9806 return name.substring(0, lastDot); 9807 } else { 9808 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 9809 return null; 9810 } 9811 } 9812 9813 class PackageInstalledInfo { 9814 String name; 9815 int uid; 9816 // The set of users that originally had this package installed. 9817 int[] origUsers; 9818 // The set of users that now have this package installed. 9819 int[] newUsers; 9820 PackageParser.Package pkg; 9821 int returnCode; 9822 String returnMsg; 9823 PackageRemovedInfo removedInfo; 9824 9825 public void setError(int code, String msg) { 9826 returnCode = code; 9827 returnMsg = msg; 9828 Slog.w(TAG, msg); 9829 } 9830 9831 public void setError(String msg, PackageParserException e) { 9832 returnCode = e.error; 9833 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9834 Slog.w(TAG, msg, e); 9835 } 9836 9837 public void setError(String msg, PackageManagerException e) { 9838 returnCode = e.error; 9839 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9840 Slog.w(TAG, msg, e); 9841 } 9842 9843 // In some error cases we want to convey more info back to the observer 9844 String origPackage; 9845 String origPermission; 9846 } 9847 9848 /* 9849 * Install a non-existing package. 9850 */ 9851 private void installNewPackageLI(PackageParser.Package pkg, 9852 int parseFlags, int scanMode, UserHandle user, 9853 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9854 // Remember this for later, in case we need to rollback this install 9855 String pkgName = pkg.packageName; 9856 9857 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 9858 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 9859 synchronized(mPackages) { 9860 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 9861 // A package with the same name is already installed, though 9862 // it has been renamed to an older name. The package we 9863 // are trying to install should be installed as an update to 9864 // the existing one, but that has not been requested, so bail. 9865 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9866 + " without first uninstalling package running as " 9867 + mSettings.mRenamedPackages.get(pkgName)); 9868 return; 9869 } 9870 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.codePath)) { 9871 // Don't allow installation over an existing package with the same name. 9872 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9873 + " without first uninstalling."); 9874 return; 9875 } 9876 } 9877 9878 try { 9879 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode, 9880 System.currentTimeMillis(), user, abiOverride); 9881 9882 updateSettingsLI(newPackage, installerPackageName, null, null, res); 9883 // delete the partially installed application. the data directory will have to be 9884 // restored if it was already existing 9885 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9886 // remove package from internal structures. Note that we want deletePackageX to 9887 // delete the package data and cache directories that it created in 9888 // scanPackageLocked, unless those directories existed before we even tried to 9889 // install. 9890 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 9891 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 9892 res.removedInfo, true); 9893 } 9894 9895 } catch (PackageManagerException e) { 9896 res.setError("Package couldn't be installed in " + pkg.codePath, e); 9897 } 9898 } 9899 9900 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 9901 // Upgrade keysets are being used. Determine if new package has a superset of the 9902 // required keys. 9903 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 9904 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9905 for (int i = 0; i < upgradeKeySets.length; i++) { 9906 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 9907 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 9908 return true; 9909 } 9910 } 9911 return false; 9912 } 9913 9914 private void replacePackageLI(PackageParser.Package pkg, 9915 int parseFlags, int scanMode, UserHandle user, 9916 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9917 PackageParser.Package oldPackage; 9918 String pkgName = pkg.packageName; 9919 int[] allUsers; 9920 boolean[] perUserInstalled; 9921 9922 // First find the old package info and check signatures 9923 synchronized(mPackages) { 9924 oldPackage = mPackages.get(pkgName); 9925 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 9926 PackageSetting ps = mSettings.mPackages.get(pkgName); 9927 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 9928 // default to original signature matching 9929 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 9930 != PackageManager.SIGNATURE_MATCH) { 9931 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9932 "New package has a different signature: " + pkgName); 9933 return; 9934 } 9935 } else { 9936 if(!checkUpgradeKeySetLP(ps, pkg)) { 9937 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9938 "New package not signed by keys specified by upgrade-keysets: " 9939 + pkgName); 9940 return; 9941 } 9942 } 9943 9944 // In case of rollback, remember per-user/profile install state 9945 allUsers = sUserManager.getUserIds(); 9946 perUserInstalled = new boolean[allUsers.length]; 9947 for (int i = 0; i < allUsers.length; i++) { 9948 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 9949 } 9950 } 9951 9952 boolean sysPkg = (isSystemApp(oldPackage)); 9953 if (sysPkg) { 9954 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 9955 user, allUsers, perUserInstalled, installerPackageName, res, 9956 abiOverride); 9957 } else { 9958 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 9959 user, allUsers, perUserInstalled, installerPackageName, res, 9960 abiOverride); 9961 } 9962 } 9963 9964 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 9965 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 9966 int[] allUsers, boolean[] perUserInstalled, 9967 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9968 String pkgName = deletedPackage.packageName; 9969 boolean deletedPkg = true; 9970 boolean updatedSettings = false; 9971 9972 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 9973 + deletedPackage); 9974 long origUpdateTime; 9975 if (pkg.mExtras != null) { 9976 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 9977 } else { 9978 origUpdateTime = 0; 9979 } 9980 9981 // First delete the existing package while retaining the data directory 9982 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 9983 res.removedInfo, true)) { 9984 // If the existing package wasn't successfully deleted 9985 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 9986 deletedPkg = false; 9987 } else { 9988 // Successfully deleted the old package. Now proceed with re-installation 9989 deleteCodeCacheDirsLI(pkgName); 9990 try { 9991 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 9992 scanMode | SCAN_UPDATE_TIME, System.currentTimeMillis(), user, abiOverride); 9993 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 9994 updatedSettings = true; 9995 } catch (PackageManagerException e) { 9996 res.setError("Package couldn't be installed in " + pkg.codePath, e); 9997 } 9998 } 9999 10000 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10001 // remove package from internal structures. Note that we want deletePackageX to 10002 // delete the package data and cache directories that it created in 10003 // scanPackageLocked, unless those directories existed before we even tried to 10004 // install. 10005 if(updatedSettings) { 10006 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 10007 deletePackageLI( 10008 pkgName, null, true, allUsers, perUserInstalled, 10009 PackageManager.DELETE_KEEP_DATA, 10010 res.removedInfo, true); 10011 } 10012 // Since we failed to install the new package we need to restore the old 10013 // package that we deleted. 10014 if (deletedPkg) { 10015 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 10016 File restoreFile = new File(deletedPackage.codePath); 10017 // Parse old package 10018 boolean oldOnSd = isExternal(deletedPackage); 10019 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 10020 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) | 10021 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 10022 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE 10023 | SCAN_UPDATE_TIME; 10024 try { 10025 scanPackageLI(restoreFile, oldParseFlags, oldScanMode, origUpdateTime, null, 10026 null); 10027 } catch (PackageManagerException e) { 10028 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 10029 + e.getMessage()); 10030 return; 10031 } 10032 // Restore of old package succeeded. Update permissions. 10033 // writer 10034 synchronized (mPackages) { 10035 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 10036 UPDATE_PERMISSIONS_ALL); 10037 // can downgrade to reader 10038 mSettings.writeLPr(); 10039 } 10040 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 10041 } 10042 } 10043 } 10044 10045 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 10046 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 10047 int[] allUsers, boolean[] perUserInstalled, 10048 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 10049 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 10050 + ", old=" + deletedPackage); 10051 boolean updatedSettings = false; 10052 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING | 10053 PackageParser.PARSE_IS_SYSTEM; 10054 if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) { 10055 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10056 } 10057 String packageName = deletedPackage.packageName; 10058 if (packageName == null) { 10059 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10060 "Attempt to delete null packageName."); 10061 return; 10062 } 10063 PackageParser.Package oldPkg; 10064 PackageSetting oldPkgSetting; 10065 // reader 10066 synchronized (mPackages) { 10067 oldPkg = mPackages.get(packageName); 10068 oldPkgSetting = mSettings.mPackages.get(packageName); 10069 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 10070 (oldPkgSetting == null)) { 10071 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10072 "Couldn't find package:" + packageName + " information"); 10073 return; 10074 } 10075 } 10076 10077 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 10078 10079 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10080 res.removedInfo.removedPackage = packageName; 10081 // Remove existing system package 10082 removePackageLI(oldPkgSetting, true); 10083 // writer 10084 synchronized (mPackages) { 10085 if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) { 10086 // We didn't need to disable the .apk as a current system package, 10087 // which means we are replacing another update that is already 10088 // installed. We need to make sure to delete the older one's .apk. 10089 res.removedInfo.args = createInstallArgsForExisting(0, 10090 deletedPackage.applicationInfo.getCodePath(), 10091 deletedPackage.applicationInfo.getResourcePath(), 10092 deletedPackage.applicationInfo.nativeLibraryRootDir, 10093 getAppDexInstructionSets(deletedPackage.applicationInfo), 10094 isMultiArch(deletedPackage.applicationInfo)); 10095 } else { 10096 res.removedInfo.args = null; 10097 } 10098 } 10099 10100 // Successfully disabled the old package. Now proceed with re-installation 10101 deleteCodeCacheDirsLI(packageName); 10102 10103 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10104 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10105 10106 PackageParser.Package newPackage = null; 10107 try { 10108 newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user, abiOverride); 10109 if (newPackage.mExtras != null) { 10110 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 10111 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10112 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10113 10114 // is the update attempting to change shared user? that isn't going to work... 10115 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10116 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 10117 "Forbidding shared user change from " + oldPkgSetting.sharedUser 10118 + " to " + newPkgSetting.sharedUser); 10119 updatedSettings = true; 10120 } 10121 } 10122 10123 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10124 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10125 updatedSettings = true; 10126 } 10127 10128 } catch (PackageManagerException e) { 10129 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10130 } 10131 10132 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10133 // Re installation failed. Restore old information 10134 // Remove new pkg information 10135 if (newPackage != null) { 10136 removeInstalledPackageLI(newPackage, true); 10137 } 10138 // Add back the old system package 10139 try { 10140 scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user, 10141 null); 10142 } catch (PackageManagerException e) { 10143 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 10144 } 10145 // Restore the old system information in Settings 10146 synchronized(mPackages) { 10147 if (updatedSettings) { 10148 mSettings.enableSystemPackageLPw(packageName); 10149 mSettings.setInstallerPackageName(packageName, 10150 oldPkgSetting.installerPackageName); 10151 } 10152 mSettings.writeLPr(); 10153 } 10154 } 10155 } 10156 10157 // Utility method used to move dex files during install. 10158 private int moveDexFilesLI(String oldCodePath, PackageParser.Package newPackage) { 10159 // TODO: extend to move split APK dex files 10160 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) { 10161 final String[] instructionSets = getAppDexInstructionSets(newPackage.applicationInfo); 10162 for (String instructionSet : instructionSets) { 10163 int retCode = mInstaller.movedex(oldCodePath, newPackage.baseCodePath, 10164 instructionSet); 10165 if (retCode != 0) { 10166 /* 10167 * Programs may be lazily run through dexopt, so the 10168 * source may not exist. However, something seems to 10169 * have gone wrong, so note that dexopt needs to be 10170 * run again and remove the source file. In addition, 10171 * remove the target to make sure there isn't a stale 10172 * file from a previous version of the package. 10173 */ 10174 newPackage.mDexOptPerformed.clear(); 10175 mInstaller.rmdex(oldCodePath, instructionSet); 10176 mInstaller.rmdex(newPackage.baseCodePath, instructionSet); 10177 } 10178 } 10179 } 10180 return PackageManager.INSTALL_SUCCEEDED; 10181 } 10182 10183 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10184 int[] allUsers, boolean[] perUserInstalled, 10185 PackageInstalledInfo res) { 10186 String pkgName = newPackage.packageName; 10187 synchronized (mPackages) { 10188 //write settings. the installStatus will be incomplete at this stage. 10189 //note that the new package setting would have already been 10190 //added to mPackages. It hasn't been persisted yet. 10191 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10192 mSettings.writeLPr(); 10193 } 10194 10195 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10196 10197 synchronized (mPackages) { 10198 updatePermissionsLPw(newPackage.packageName, newPackage, 10199 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10200 ? UPDATE_PERMISSIONS_ALL : 0)); 10201 // For system-bundled packages, we assume that installing an upgraded version 10202 // of the package implies that the user actually wants to run that new code, 10203 // so we enable the package. 10204 if (isSystemApp(newPackage)) { 10205 // NB: implicit assumption that system package upgrades apply to all users 10206 if (DEBUG_INSTALL) { 10207 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10208 } 10209 PackageSetting ps = mSettings.mPackages.get(pkgName); 10210 if (ps != null) { 10211 if (res.origUsers != null) { 10212 for (int userHandle : res.origUsers) { 10213 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10214 userHandle, installerPackageName); 10215 } 10216 } 10217 // Also convey the prior install/uninstall state 10218 if (allUsers != null && perUserInstalled != null) { 10219 for (int i = 0; i < allUsers.length; i++) { 10220 if (DEBUG_INSTALL) { 10221 Slog.d(TAG, " user " + allUsers[i] 10222 + " => " + perUserInstalled[i]); 10223 } 10224 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10225 } 10226 // these install state changes will be persisted in the 10227 // upcoming call to mSettings.writeLPr(). 10228 } 10229 } 10230 } 10231 res.name = pkgName; 10232 res.uid = newPackage.applicationInfo.uid; 10233 res.pkg = newPackage; 10234 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10235 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10236 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10237 //to update install status 10238 mSettings.writeLPr(); 10239 } 10240 } 10241 10242 private void installPackageLI(InstallArgs args, boolean newInstall, PackageInstalledInfo res) { 10243 int pFlags = args.flags; 10244 String installerPackageName = args.installerPackageName; 10245 File tmpPackageFile = new File(args.getCodePath()); 10246 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10247 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0); 10248 boolean replace = false; 10249 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE 10250 | (newInstall ? SCAN_NEW_INSTALL : 0); 10251 // Result object to be returned 10252 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10253 10254 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10255 // Retrieve PackageSettings and parse package 10256 int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10257 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10258 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 10259 PackageParser pp = new PackageParser(); 10260 pp.setSeparateProcesses(mSeparateProcesses); 10261 pp.setDisplayMetrics(mMetrics); 10262 10263 final PackageParser.Package pkg; 10264 try { 10265 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 10266 } catch (PackageParserException e) { 10267 res.setError("Failed parse during installPackageLI", e); 10268 return; 10269 } 10270 10271 String pkgName = res.name = pkg.packageName; 10272 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 10273 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) { 10274 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 10275 return; 10276 } 10277 } 10278 10279 try { 10280 pp.collectCertificates(pkg, parseFlags); 10281 pp.collectManifestDigest(pkg); 10282 } catch (PackageParserException e) { 10283 res.setError("Failed collect during installPackageLI", e); 10284 return; 10285 } 10286 10287 /* If the installer passed in a manifest digest, compare it now. */ 10288 if (args.manifestDigest != null) { 10289 if (DEBUG_INSTALL) { 10290 final String parsedManifest = pkg.manifestDigest == null ? "null" 10291 : pkg.manifestDigest.toString(); 10292 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 10293 + parsedManifest); 10294 } 10295 10296 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 10297 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 10298 return; 10299 } 10300 } else if (DEBUG_INSTALL) { 10301 final String parsedManifest = pkg.manifestDigest == null 10302 ? "null" : pkg.manifestDigest.toString(); 10303 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 10304 } 10305 10306 // Get rid of all references to package scan path via parser. 10307 pp = null; 10308 String oldCodePath = null; 10309 boolean systemApp = false; 10310 synchronized (mPackages) { 10311 // Check whether the newly-scanned package wants to define an already-defined perm 10312 int N = pkg.permissions.size(); 10313 for (int i = N-1; i >= 0; i--) { 10314 PackageParser.Permission perm = pkg.permissions.get(i); 10315 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 10316 if (bp != null) { 10317 // If the defining package is signed with our cert, it's okay. This 10318 // also includes the "updating the same package" case, of course. 10319 if (compareSignatures(bp.packageSetting.signatures.mSignatures, 10320 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 10321 // If the owning package is the system itself, we log but allow 10322 // install to proceed; we fail the install on all other permission 10323 // redefinitions. 10324 if (!bp.sourcePackage.equals("android")) { 10325 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 10326 + pkg.packageName + " attempting to redeclare permission " 10327 + perm.info.name + " already owned by " + bp.sourcePackage); 10328 res.origPermission = perm.info.name; 10329 res.origPackage = bp.sourcePackage; 10330 return; 10331 } else { 10332 Slog.w(TAG, "Package " + pkg.packageName 10333 + " attempting to redeclare system permission " 10334 + perm.info.name + "; ignoring new declaration"); 10335 pkg.permissions.remove(i); 10336 } 10337 } 10338 } 10339 } 10340 10341 // Check if installing already existing package 10342 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10343 String oldName = mSettings.mRenamedPackages.get(pkgName); 10344 if (pkg.mOriginalPackages != null 10345 && pkg.mOriginalPackages.contains(oldName) 10346 && mPackages.containsKey(oldName)) { 10347 // This package is derived from an original package, 10348 // and this device has been updating from that original 10349 // name. We must continue using the original name, so 10350 // rename the new package here. 10351 pkg.setPackageName(oldName); 10352 pkgName = pkg.packageName; 10353 replace = true; 10354 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 10355 + oldName + " pkgName=" + pkgName); 10356 } else if (mPackages.containsKey(pkgName)) { 10357 // This package, under its official name, already exists 10358 // on the device; we should replace it. 10359 replace = true; 10360 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 10361 } 10362 } 10363 PackageSetting ps = mSettings.mPackages.get(pkgName); 10364 if (ps != null) { 10365 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 10366 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 10367 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 10368 systemApp = (ps.pkg.applicationInfo.flags & 10369 ApplicationInfo.FLAG_SYSTEM) != 0; 10370 } 10371 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10372 } 10373 } 10374 10375 if (systemApp && onSd) { 10376 // Disable updates to system apps on sdcard 10377 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 10378 "Cannot install updates to system apps on sdcard"); 10379 return; 10380 } 10381 10382 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 10383 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 10384 return; 10385 } 10386 10387 if (replace) { 10388 replacePackageLI(pkg, parseFlags, scanMode, args.user, 10389 installerPackageName, res, args.abiOverride); 10390 } else { 10391 installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user, 10392 installerPackageName, res, args.abiOverride); 10393 } 10394 synchronized (mPackages) { 10395 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10396 if (ps != null) { 10397 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10398 } 10399 } 10400 } 10401 10402 private static boolean isForwardLocked(PackageParser.Package pkg) { 10403 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10404 } 10405 10406 private static boolean isForwardLocked(ApplicationInfo info) { 10407 return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10408 } 10409 10410 private boolean isForwardLocked(PackageSetting ps) { 10411 return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10412 } 10413 10414 private static boolean isMultiArch(PackageSetting ps) { 10415 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10416 } 10417 10418 private static boolean isMultiArch(ApplicationInfo info) { 10419 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10420 } 10421 10422 private static boolean isExternal(PackageParser.Package pkg) { 10423 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10424 } 10425 10426 private static boolean isExternal(PackageSetting ps) { 10427 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10428 } 10429 10430 private static boolean isExternal(ApplicationInfo info) { 10431 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10432 } 10433 10434 private static boolean isSystemApp(PackageParser.Package pkg) { 10435 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10436 } 10437 10438 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 10439 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0; 10440 } 10441 10442 private static boolean isSystemApp(ApplicationInfo info) { 10443 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10444 } 10445 10446 private static boolean isSystemApp(PackageSetting ps) { 10447 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 10448 } 10449 10450 private static boolean isUpdatedSystemApp(PackageSetting ps) { 10451 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10452 } 10453 10454 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 10455 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10456 } 10457 10458 private static boolean isUpdatedSystemApp(ApplicationInfo info) { 10459 return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10460 } 10461 10462 private int packageFlagsToInstallFlags(PackageSetting ps) { 10463 int installFlags = 0; 10464 if (isExternal(ps)) { 10465 installFlags |= PackageManager.INSTALL_EXTERNAL; 10466 } 10467 if (isForwardLocked(ps)) { 10468 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 10469 } 10470 return installFlags; 10471 } 10472 10473 private void deleteTempPackageFiles() { 10474 final FilenameFilter filter = new FilenameFilter() { 10475 public boolean accept(File dir, String name) { 10476 return name.startsWith("vmdl") && name.endsWith(".tmp"); 10477 } 10478 }; 10479 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 10480 file.delete(); 10481 } 10482 } 10483 10484 @Override 10485 public void deletePackageAsUser(final String packageName, 10486 final IPackageDeleteObserver observer, 10487 final int userId, final int flags) { 10488 mContext.enforceCallingOrSelfPermission( 10489 android.Manifest.permission.DELETE_PACKAGES, null); 10490 final int uid = Binder.getCallingUid(); 10491 if (UserHandle.getUserId(uid) != userId) { 10492 mContext.enforceCallingPermission( 10493 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 10494 "deletePackage for user " + userId); 10495 } 10496 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 10497 try { 10498 observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_USER_RESTRICTED); 10499 } catch (RemoteException re) { 10500 } 10501 return; 10502 } 10503 10504 boolean uninstallBlocked = false; 10505 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 10506 int[] users = sUserManager.getUserIds(); 10507 for (int i = 0; i < users.length; ++i) { 10508 if (getBlockUninstallForUser(packageName, users[i])) { 10509 uninstallBlocked = true; 10510 break; 10511 } 10512 } 10513 } else { 10514 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 10515 } 10516 if (uninstallBlocked) { 10517 try { 10518 observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED); 10519 } catch (RemoteException re) { 10520 } 10521 return; 10522 } 10523 10524 if (DEBUG_REMOVE) { 10525 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 10526 } 10527 // Queue up an async operation since the package deletion may take a little while. 10528 mHandler.post(new Runnable() { 10529 public void run() { 10530 mHandler.removeCallbacks(this); 10531 final int returnCode = deletePackageX(packageName, userId, flags); 10532 if (observer != null) { 10533 try { 10534 observer.packageDeleted(packageName, returnCode); 10535 } catch (RemoteException e) { 10536 Log.i(TAG, "Observer no longer exists."); 10537 } //end catch 10538 } //end if 10539 } //end run 10540 }); 10541 } 10542 10543 private boolean isPackageDeviceAdmin(String packageName, int userId) { 10544 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 10545 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 10546 try { 10547 if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId) 10548 || dpm.isDeviceOwner(packageName))) { 10549 return true; 10550 } 10551 } catch (RemoteException e) { 10552 } 10553 return false; 10554 } 10555 10556 /** 10557 * This method is an internal method that could be get invoked either 10558 * to delete an installed package or to clean up a failed installation. 10559 * After deleting an installed package, a broadcast is sent to notify any 10560 * listeners that the package has been installed. For cleaning up a failed 10561 * installation, the broadcast is not necessary since the package's 10562 * installation wouldn't have sent the initial broadcast either 10563 * The key steps in deleting a package are 10564 * deleting the package information in internal structures like mPackages, 10565 * deleting the packages base directories through installd 10566 * updating mSettings to reflect current status 10567 * persisting settings for later use 10568 * sending a broadcast if necessary 10569 */ 10570 private int deletePackageX(String packageName, int userId, int flags) { 10571 final PackageRemovedInfo info = new PackageRemovedInfo(); 10572 final boolean res; 10573 10574 if (isPackageDeviceAdmin(packageName, userId)) { 10575 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 10576 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 10577 } 10578 10579 boolean removedForAllUsers = false; 10580 boolean systemUpdate = false; 10581 10582 // for the uninstall-updates case and restricted profiles, remember the per- 10583 // userhandle installed state 10584 int[] allUsers; 10585 boolean[] perUserInstalled; 10586 synchronized (mPackages) { 10587 PackageSetting ps = mSettings.mPackages.get(packageName); 10588 allUsers = sUserManager.getUserIds(); 10589 perUserInstalled = new boolean[allUsers.length]; 10590 for (int i = 0; i < allUsers.length; i++) { 10591 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10592 } 10593 } 10594 10595 synchronized (mInstallLock) { 10596 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 10597 res = deletePackageLI(packageName, 10598 (flags & PackageManager.DELETE_ALL_USERS) != 0 10599 ? UserHandle.ALL : new UserHandle(userId), 10600 true, allUsers, perUserInstalled, 10601 flags | REMOVE_CHATTY, info, true); 10602 systemUpdate = info.isRemovedPackageSystemUpdate; 10603 if (res && !systemUpdate && mPackages.get(packageName) == null) { 10604 removedForAllUsers = true; 10605 } 10606 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 10607 + " removedForAllUsers=" + removedForAllUsers); 10608 } 10609 10610 if (res) { 10611 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 10612 10613 // If the removed package was a system update, the old system package 10614 // was re-enabled; we need to broadcast this information 10615 if (systemUpdate) { 10616 Bundle extras = new Bundle(1); 10617 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 10618 ? info.removedAppId : info.uid); 10619 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10620 10621 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 10622 extras, null, null, null); 10623 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 10624 extras, null, null, null); 10625 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 10626 null, packageName, null, null); 10627 } 10628 } 10629 // Force a gc here. 10630 Runtime.getRuntime().gc(); 10631 // Delete the resources here after sending the broadcast to let 10632 // other processes clean up before deleting resources. 10633 if (info.args != null) { 10634 synchronized (mInstallLock) { 10635 info.args.doPostDeleteLI(true); 10636 } 10637 } 10638 10639 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10640 } 10641 10642 static class PackageRemovedInfo { 10643 String removedPackage; 10644 int uid = -1; 10645 int removedAppId = -1; 10646 int[] removedUsers = null; 10647 boolean isRemovedPackageSystemUpdate = false; 10648 // Clean up resources deleted packages. 10649 InstallArgs args = null; 10650 10651 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 10652 Bundle extras = new Bundle(1); 10653 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 10654 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 10655 if (replacing) { 10656 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10657 } 10658 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 10659 if (removedPackage != null) { 10660 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 10661 extras, null, null, removedUsers); 10662 if (fullRemove && !replacing) { 10663 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 10664 extras, null, null, removedUsers); 10665 } 10666 } 10667 if (removedAppId >= 0) { 10668 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 10669 removedUsers); 10670 } 10671 } 10672 } 10673 10674 /* 10675 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 10676 * flag is not set, the data directory is removed as well. 10677 * make sure this flag is set for partially installed apps. If not its meaningless to 10678 * delete a partially installed application. 10679 */ 10680 private void removePackageDataLI(PackageSetting ps, 10681 int[] allUserHandles, boolean[] perUserInstalled, 10682 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 10683 String packageName = ps.name; 10684 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 10685 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 10686 // Retrieve object to delete permissions for shared user later on 10687 final PackageSetting deletedPs; 10688 // reader 10689 synchronized (mPackages) { 10690 deletedPs = mSettings.mPackages.get(packageName); 10691 if (outInfo != null) { 10692 outInfo.removedPackage = packageName; 10693 outInfo.removedUsers = deletedPs != null 10694 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 10695 : null; 10696 } 10697 } 10698 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10699 removeDataDirsLI(packageName); 10700 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 10701 } 10702 // writer 10703 synchronized (mPackages) { 10704 if (deletedPs != null) { 10705 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10706 if (outInfo != null) { 10707 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 10708 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 10709 } 10710 if (deletedPs != null) { 10711 updatePermissionsLPw(deletedPs.name, null, 0); 10712 if (deletedPs.sharedUser != null) { 10713 // remove permissions associated with package 10714 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 10715 } 10716 } 10717 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 10718 } 10719 // make sure to preserve per-user disabled state if this removal was just 10720 // a downgrade of a system app to the factory package 10721 if (allUserHandles != null && perUserInstalled != null) { 10722 if (DEBUG_REMOVE) { 10723 Slog.d(TAG, "Propagating install state across downgrade"); 10724 } 10725 for (int i = 0; i < allUserHandles.length; i++) { 10726 if (DEBUG_REMOVE) { 10727 Slog.d(TAG, " user " + allUserHandles[i] 10728 + " => " + perUserInstalled[i]); 10729 } 10730 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10731 } 10732 } 10733 } 10734 // can downgrade to reader 10735 if (writeSettings) { 10736 // Save settings now 10737 mSettings.writeLPr(); 10738 } 10739 } 10740 if (outInfo != null) { 10741 // A user ID was deleted here. Go through all users and remove it 10742 // from KeyStore. 10743 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 10744 } 10745 } 10746 10747 static boolean locationIsPrivileged(File path) { 10748 try { 10749 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 10750 .getCanonicalPath(); 10751 return path.getCanonicalPath().startsWith(privilegedAppDir); 10752 } catch (IOException e) { 10753 Slog.e(TAG, "Unable to access code path " + path); 10754 } 10755 return false; 10756 } 10757 10758 /* 10759 * Tries to delete system package. 10760 */ 10761 private boolean deleteSystemPackageLI(PackageSetting newPs, 10762 int[] allUserHandles, boolean[] perUserInstalled, 10763 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 10764 final boolean applyUserRestrictions 10765 = (allUserHandles != null) && (perUserInstalled != null); 10766 PackageSetting disabledPs = null; 10767 // Confirm if the system package has been updated 10768 // An updated system app can be deleted. This will also have to restore 10769 // the system pkg from system partition 10770 // reader 10771 synchronized (mPackages) { 10772 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 10773 } 10774 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 10775 + " disabledPs=" + disabledPs); 10776 if (disabledPs == null) { 10777 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 10778 return false; 10779 } else if (DEBUG_REMOVE) { 10780 Slog.d(TAG, "Deleting system pkg from data partition"); 10781 } 10782 if (DEBUG_REMOVE) { 10783 if (applyUserRestrictions) { 10784 Slog.d(TAG, "Remembering install states:"); 10785 for (int i = 0; i < allUserHandles.length; i++) { 10786 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 10787 } 10788 } 10789 } 10790 // Delete the updated package 10791 outInfo.isRemovedPackageSystemUpdate = true; 10792 if (disabledPs.versionCode < newPs.versionCode) { 10793 // Delete data for downgrades 10794 flags &= ~PackageManager.DELETE_KEEP_DATA; 10795 } else { 10796 // Preserve data by setting flag 10797 flags |= PackageManager.DELETE_KEEP_DATA; 10798 } 10799 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 10800 allUserHandles, perUserInstalled, outInfo, writeSettings); 10801 if (!ret) { 10802 return false; 10803 } 10804 // writer 10805 synchronized (mPackages) { 10806 // Reinstate the old system package 10807 mSettings.enableSystemPackageLPw(newPs.name); 10808 // Remove any native libraries from the upgraded package. 10809 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 10810 } 10811 // Install the system package 10812 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 10813 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 10814 if (locationIsPrivileged(disabledPs.codePath)) { 10815 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10816 } 10817 10818 final PackageParser.Package newPkg; 10819 try { 10820 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, 10821 null, null); 10822 } catch (PackageManagerException e) { 10823 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 10824 return false; 10825 } 10826 10827 // writer 10828 synchronized (mPackages) { 10829 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 10830 updatePermissionsLPw(newPkg.packageName, newPkg, 10831 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 10832 if (applyUserRestrictions) { 10833 if (DEBUG_REMOVE) { 10834 Slog.d(TAG, "Propagating install state across reinstall"); 10835 } 10836 for (int i = 0; i < allUserHandles.length; i++) { 10837 if (DEBUG_REMOVE) { 10838 Slog.d(TAG, " user " + allUserHandles[i] 10839 + " => " + perUserInstalled[i]); 10840 } 10841 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10842 } 10843 // Regardless of writeSettings we need to ensure that this restriction 10844 // state propagation is persisted 10845 mSettings.writeAllUsersPackageRestrictionsLPr(); 10846 } 10847 // can downgrade to reader here 10848 if (writeSettings) { 10849 mSettings.writeLPr(); 10850 } 10851 } 10852 return true; 10853 } 10854 10855 private boolean deleteInstalledPackageLI(PackageSetting ps, 10856 boolean deleteCodeAndResources, int flags, 10857 int[] allUserHandles, boolean[] perUserInstalled, 10858 PackageRemovedInfo outInfo, boolean writeSettings) { 10859 if (outInfo != null) { 10860 outInfo.uid = ps.appId; 10861 } 10862 10863 // Delete package data from internal structures and also remove data if flag is set 10864 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 10865 10866 // Delete application code and resources 10867 if (deleteCodeAndResources && (outInfo != null)) { 10868 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 10869 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 10870 getAppDexInstructionSets(ps), isMultiArch(ps)); 10871 } 10872 return true; 10873 } 10874 10875 @Override 10876 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 10877 int userId) { 10878 mContext.enforceCallingOrSelfPermission( 10879 android.Manifest.permission.DELETE_PACKAGES, null); 10880 synchronized (mPackages) { 10881 PackageSetting ps = mSettings.mPackages.get(packageName); 10882 if (ps == null) { 10883 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 10884 return false; 10885 } 10886 if (!ps.getInstalled(userId)) { 10887 // Can't block uninstall for an app that is not installed or enabled. 10888 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 10889 return false; 10890 } 10891 ps.setBlockUninstall(blockUninstall, userId); 10892 mSettings.writePackageRestrictionsLPr(userId); 10893 } 10894 return true; 10895 } 10896 10897 @Override 10898 public boolean getBlockUninstallForUser(String packageName, int userId) { 10899 synchronized (mPackages) { 10900 PackageSetting ps = mSettings.mPackages.get(packageName); 10901 if (ps == null) { 10902 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 10903 return false; 10904 } 10905 return ps.getBlockUninstall(userId); 10906 } 10907 } 10908 10909 /* 10910 * This method handles package deletion in general 10911 */ 10912 private boolean deletePackageLI(String packageName, UserHandle user, 10913 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 10914 int flags, PackageRemovedInfo outInfo, 10915 boolean writeSettings) { 10916 if (packageName == null) { 10917 Slog.w(TAG, "Attempt to delete null packageName."); 10918 return false; 10919 } 10920 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 10921 PackageSetting ps; 10922 boolean dataOnly = false; 10923 int removeUser = -1; 10924 int appId = -1; 10925 synchronized (mPackages) { 10926 ps = mSettings.mPackages.get(packageName); 10927 if (ps == null) { 10928 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 10929 return false; 10930 } 10931 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 10932 && user.getIdentifier() != UserHandle.USER_ALL) { 10933 // The caller is asking that the package only be deleted for a single 10934 // user. To do this, we just mark its uninstalled state and delete 10935 // its data. If this is a system app, we only allow this to happen if 10936 // they have set the special DELETE_SYSTEM_APP which requests different 10937 // semantics than normal for uninstalling system apps. 10938 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 10939 ps.setUserState(user.getIdentifier(), 10940 COMPONENT_ENABLED_STATE_DEFAULT, 10941 false, //installed 10942 true, //stopped 10943 true, //notLaunched 10944 false, //hidden 10945 null, null, null, 10946 false // blockUninstall 10947 ); 10948 if (!isSystemApp(ps)) { 10949 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 10950 // Other user still have this package installed, so all 10951 // we need to do is clear this user's data and save that 10952 // it is uninstalled. 10953 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 10954 removeUser = user.getIdentifier(); 10955 appId = ps.appId; 10956 mSettings.writePackageRestrictionsLPr(removeUser); 10957 } else { 10958 // We need to set it back to 'installed' so the uninstall 10959 // broadcasts will be sent correctly. 10960 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 10961 ps.setInstalled(true, user.getIdentifier()); 10962 } 10963 } else { 10964 // This is a system app, so we assume that the 10965 // other users still have this package installed, so all 10966 // we need to do is clear this user's data and save that 10967 // it is uninstalled. 10968 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 10969 removeUser = user.getIdentifier(); 10970 appId = ps.appId; 10971 mSettings.writePackageRestrictionsLPr(removeUser); 10972 } 10973 } 10974 } 10975 10976 if (removeUser >= 0) { 10977 // From above, we determined that we are deleting this only 10978 // for a single user. Continue the work here. 10979 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 10980 if (outInfo != null) { 10981 outInfo.removedPackage = packageName; 10982 outInfo.removedAppId = appId; 10983 outInfo.removedUsers = new int[] {removeUser}; 10984 } 10985 mInstaller.clearUserData(packageName, removeUser); 10986 removeKeystoreDataIfNeeded(removeUser, appId); 10987 schedulePackageCleaning(packageName, removeUser, false); 10988 return true; 10989 } 10990 10991 if (dataOnly) { 10992 // Delete application data first 10993 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 10994 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 10995 return true; 10996 } 10997 10998 boolean ret = false; 10999 if (isSystemApp(ps)) { 11000 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 11001 // When an updated system application is deleted we delete the existing resources as well and 11002 // fall back to existing code in system partition 11003 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 11004 flags, outInfo, writeSettings); 11005 } else { 11006 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 11007 // Kill application pre-emptively especially for apps on sd. 11008 killApplication(packageName, ps.appId, "uninstall pkg"); 11009 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 11010 allUserHandles, perUserInstalled, 11011 outInfo, writeSettings); 11012 } 11013 11014 return ret; 11015 } 11016 11017 private final class ClearStorageConnection implements ServiceConnection { 11018 IMediaContainerService mContainerService; 11019 11020 @Override 11021 public void onServiceConnected(ComponentName name, IBinder service) { 11022 synchronized (this) { 11023 mContainerService = IMediaContainerService.Stub.asInterface(service); 11024 notifyAll(); 11025 } 11026 } 11027 11028 @Override 11029 public void onServiceDisconnected(ComponentName name) { 11030 } 11031 } 11032 11033 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 11034 final boolean mounted; 11035 if (Environment.isExternalStorageEmulated()) { 11036 mounted = true; 11037 } else { 11038 final String status = Environment.getExternalStorageState(); 11039 11040 mounted = status.equals(Environment.MEDIA_MOUNTED) 11041 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 11042 } 11043 11044 if (!mounted) { 11045 return; 11046 } 11047 11048 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 11049 int[] users; 11050 if (userId == UserHandle.USER_ALL) { 11051 users = sUserManager.getUserIds(); 11052 } else { 11053 users = new int[] { userId }; 11054 } 11055 final ClearStorageConnection conn = new ClearStorageConnection(); 11056 if (mContext.bindServiceAsUser( 11057 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 11058 try { 11059 for (int curUser : users) { 11060 long timeout = SystemClock.uptimeMillis() + 5000; 11061 synchronized (conn) { 11062 long now = SystemClock.uptimeMillis(); 11063 while (conn.mContainerService == null && now < timeout) { 11064 try { 11065 conn.wait(timeout - now); 11066 } catch (InterruptedException e) { 11067 } 11068 } 11069 } 11070 if (conn.mContainerService == null) { 11071 return; 11072 } 11073 11074 final UserEnvironment userEnv = new UserEnvironment(curUser); 11075 clearDirectory(conn.mContainerService, 11076 userEnv.buildExternalStorageAppCacheDirs(packageName)); 11077 if (allData) { 11078 clearDirectory(conn.mContainerService, 11079 userEnv.buildExternalStorageAppDataDirs(packageName)); 11080 clearDirectory(conn.mContainerService, 11081 userEnv.buildExternalStorageAppMediaDirs(packageName)); 11082 } 11083 } 11084 } finally { 11085 mContext.unbindService(conn); 11086 } 11087 } 11088 } 11089 11090 @Override 11091 public void clearApplicationUserData(final String packageName, 11092 final IPackageDataObserver observer, final int userId) { 11093 mContext.enforceCallingOrSelfPermission( 11094 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 11095 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data"); 11096 // Queue up an async operation since the package deletion may take a little while. 11097 mHandler.post(new Runnable() { 11098 public void run() { 11099 mHandler.removeCallbacks(this); 11100 final boolean succeeded; 11101 synchronized (mInstallLock) { 11102 succeeded = clearApplicationUserDataLI(packageName, userId); 11103 } 11104 clearExternalStorageDataSync(packageName, userId, true); 11105 if (succeeded) { 11106 // invoke DeviceStorageMonitor's update method to clear any notifications 11107 DeviceStorageMonitorInternal 11108 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 11109 if (dsm != null) { 11110 dsm.checkMemory(); 11111 } 11112 } 11113 if(observer != null) { 11114 try { 11115 observer.onRemoveCompleted(packageName, succeeded); 11116 } catch (RemoteException e) { 11117 Log.i(TAG, "Observer no longer exists."); 11118 } 11119 } //end if observer 11120 } //end run 11121 }); 11122 } 11123 11124 private boolean clearApplicationUserDataLI(String packageName, int userId) { 11125 if (packageName == null) { 11126 Slog.w(TAG, "Attempt to delete null packageName."); 11127 return false; 11128 } 11129 PackageParser.Package p; 11130 boolean dataOnly = false; 11131 final int appId; 11132 synchronized (mPackages) { 11133 p = mPackages.get(packageName); 11134 if (p == null) { 11135 dataOnly = true; 11136 PackageSetting ps = mSettings.mPackages.get(packageName); 11137 if ((ps == null) || (ps.pkg == null)) { 11138 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11139 return false; 11140 } 11141 p = ps.pkg; 11142 } 11143 if (!dataOnly) { 11144 // need to check this only for fully installed applications 11145 if (p == null) { 11146 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11147 return false; 11148 } 11149 final ApplicationInfo applicationInfo = p.applicationInfo; 11150 if (applicationInfo == null) { 11151 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11152 return false; 11153 } 11154 } 11155 if (p != null && p.applicationInfo != null) { 11156 appId = p.applicationInfo.uid; 11157 } else { 11158 appId = -1; 11159 } 11160 } 11161 int retCode = mInstaller.clearUserData(packageName, userId); 11162 if (retCode < 0) { 11163 Slog.w(TAG, "Couldn't remove cache files for package: " 11164 + packageName); 11165 return false; 11166 } 11167 removeKeystoreDataIfNeeded(userId, appId); 11168 return true; 11169 } 11170 11171 /** 11172 * Remove entries from the keystore daemon. Will only remove it if the 11173 * {@code appId} is valid. 11174 */ 11175 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 11176 if (appId < 0) { 11177 return; 11178 } 11179 11180 final KeyStore keyStore = KeyStore.getInstance(); 11181 if (keyStore != null) { 11182 if (userId == UserHandle.USER_ALL) { 11183 for (final int individual : sUserManager.getUserIds()) { 11184 keyStore.clearUid(UserHandle.getUid(individual, appId)); 11185 } 11186 } else { 11187 keyStore.clearUid(UserHandle.getUid(userId, appId)); 11188 } 11189 } else { 11190 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 11191 } 11192 } 11193 11194 @Override 11195 public void deleteApplicationCacheFiles(final String packageName, 11196 final IPackageDataObserver observer) { 11197 mContext.enforceCallingOrSelfPermission( 11198 android.Manifest.permission.DELETE_CACHE_FILES, null); 11199 // Queue up an async operation since the package deletion may take a little while. 11200 final int userId = UserHandle.getCallingUserId(); 11201 mHandler.post(new Runnable() { 11202 public void run() { 11203 mHandler.removeCallbacks(this); 11204 final boolean succeded; 11205 synchronized (mInstallLock) { 11206 succeded = deleteApplicationCacheFilesLI(packageName, userId); 11207 } 11208 clearExternalStorageDataSync(packageName, userId, false); 11209 if(observer != null) { 11210 try { 11211 observer.onRemoveCompleted(packageName, succeded); 11212 } catch (RemoteException e) { 11213 Log.i(TAG, "Observer no longer exists."); 11214 } 11215 } //end if observer 11216 } //end run 11217 }); 11218 } 11219 11220 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 11221 if (packageName == null) { 11222 Slog.w(TAG, "Attempt to delete null packageName."); 11223 return false; 11224 } 11225 PackageParser.Package p; 11226 synchronized (mPackages) { 11227 p = mPackages.get(packageName); 11228 } 11229 if (p == null) { 11230 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11231 return false; 11232 } 11233 final ApplicationInfo applicationInfo = p.applicationInfo; 11234 if (applicationInfo == null) { 11235 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11236 return false; 11237 } 11238 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 11239 if (retCode < 0) { 11240 Slog.w(TAG, "Couldn't remove cache files for package: " 11241 + packageName + " u" + userId); 11242 return false; 11243 } 11244 return true; 11245 } 11246 11247 @Override 11248 public void getPackageSizeInfo(final String packageName, int userHandle, 11249 final IPackageStatsObserver observer) { 11250 mContext.enforceCallingOrSelfPermission( 11251 android.Manifest.permission.GET_PACKAGE_SIZE, null); 11252 if (packageName == null) { 11253 throw new IllegalArgumentException("Attempt to get size of null packageName"); 11254 } 11255 11256 PackageStats stats = new PackageStats(packageName, userHandle); 11257 11258 /* 11259 * Queue up an async operation since the package measurement may take a 11260 * little while. 11261 */ 11262 Message msg = mHandler.obtainMessage(INIT_COPY); 11263 msg.obj = new MeasureParams(stats, observer); 11264 mHandler.sendMessage(msg); 11265 } 11266 11267 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 11268 PackageStats pStats) { 11269 if (packageName == null) { 11270 Slog.w(TAG, "Attempt to get size of null packageName."); 11271 return false; 11272 } 11273 PackageParser.Package p; 11274 boolean dataOnly = false; 11275 String libDirRoot = null; 11276 String asecPath = null; 11277 PackageSetting ps = null; 11278 synchronized (mPackages) { 11279 p = mPackages.get(packageName); 11280 ps = mSettings.mPackages.get(packageName); 11281 if(p == null) { 11282 dataOnly = true; 11283 if((ps == null) || (ps.pkg == null)) { 11284 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11285 return false; 11286 } 11287 p = ps.pkg; 11288 } 11289 if (ps != null) { 11290 libDirRoot = ps.legacyNativeLibraryPathString; 11291 } 11292 if (p != null && (isExternal(p) || isForwardLocked(p))) { 11293 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 11294 if (secureContainerId != null) { 11295 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 11296 } 11297 } 11298 } 11299 String publicSrcDir = null; 11300 if(!dataOnly) { 11301 final ApplicationInfo applicationInfo = p.applicationInfo; 11302 if (applicationInfo == null) { 11303 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11304 return false; 11305 } 11306 if (isForwardLocked(p)) { 11307 publicSrcDir = applicationInfo.getBaseResourcePath(); 11308 } 11309 } 11310 // TODO: extend to measure size of split APKs 11311 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 11312 // not just the first level. 11313 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 11314 // just the primary. 11315 int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot, 11316 publicSrcDir, asecPath, getAppDexInstructionSets(ps), 11317 pStats); 11318 if (res < 0) { 11319 return false; 11320 } 11321 11322 // Fix-up for forward-locked applications in ASEC containers. 11323 if (!isExternal(p)) { 11324 pStats.codeSize += pStats.externalCodeSize; 11325 pStats.externalCodeSize = 0L; 11326 } 11327 11328 return true; 11329 } 11330 11331 11332 @Override 11333 public void addPackageToPreferred(String packageName) { 11334 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 11335 } 11336 11337 @Override 11338 public void removePackageFromPreferred(String packageName) { 11339 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 11340 } 11341 11342 @Override 11343 public List<PackageInfo> getPreferredPackages(int flags) { 11344 return new ArrayList<PackageInfo>(); 11345 } 11346 11347 private int getUidTargetSdkVersionLockedLPr(int uid) { 11348 Object obj = mSettings.getUserIdLPr(uid); 11349 if (obj instanceof SharedUserSetting) { 11350 final SharedUserSetting sus = (SharedUserSetting) obj; 11351 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 11352 final Iterator<PackageSetting> it = sus.packages.iterator(); 11353 while (it.hasNext()) { 11354 final PackageSetting ps = it.next(); 11355 if (ps.pkg != null) { 11356 int v = ps.pkg.applicationInfo.targetSdkVersion; 11357 if (v < vers) vers = v; 11358 } 11359 } 11360 return vers; 11361 } else if (obj instanceof PackageSetting) { 11362 final PackageSetting ps = (PackageSetting) obj; 11363 if (ps.pkg != null) { 11364 return ps.pkg.applicationInfo.targetSdkVersion; 11365 } 11366 } 11367 return Build.VERSION_CODES.CUR_DEVELOPMENT; 11368 } 11369 11370 @Override 11371 public void addPreferredActivity(IntentFilter filter, int match, 11372 ComponentName[] set, ComponentName activity, int userId) { 11373 addPreferredActivityInternal(filter, match, set, activity, true, userId); 11374 } 11375 11376 private void addPreferredActivityInternal(IntentFilter filter, int match, 11377 ComponentName[] set, ComponentName activity, boolean always, int userId) { 11378 // writer 11379 int callingUid = Binder.getCallingUid(); 11380 enforceCrossUserPermission(callingUid, userId, true, "add preferred activity"); 11381 if (filter.countActions() == 0) { 11382 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11383 return; 11384 } 11385 synchronized (mPackages) { 11386 if (mContext.checkCallingOrSelfPermission( 11387 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11388 != PackageManager.PERMISSION_GRANTED) { 11389 if (getUidTargetSdkVersionLockedLPr(callingUid) 11390 < Build.VERSION_CODES.FROYO) { 11391 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 11392 + callingUid); 11393 return; 11394 } 11395 mContext.enforceCallingOrSelfPermission( 11396 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11397 } 11398 11399 Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :"); 11400 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11401 mSettings.editPreferredActivitiesLPw(userId).addFilter( 11402 new PreferredActivity(filter, match, set, activity, always)); 11403 mSettings.writePackageRestrictionsLPr(userId); 11404 } 11405 } 11406 11407 @Override 11408 public void replacePreferredActivity(IntentFilter filter, int match, 11409 ComponentName[] set, ComponentName activity) { 11410 if (filter.countActions() != 1) { 11411 throw new IllegalArgumentException( 11412 "replacePreferredActivity expects filter to have only 1 action."); 11413 } 11414 if (filter.countDataAuthorities() != 0 11415 || filter.countDataPaths() != 0 11416 || filter.countDataSchemes() > 1 11417 || filter.countDataTypes() != 0) { 11418 throw new IllegalArgumentException( 11419 "replacePreferredActivity expects filter to have no data authorities, " + 11420 "paths, or types; and at most one scheme."); 11421 } 11422 synchronized (mPackages) { 11423 if (mContext.checkCallingOrSelfPermission( 11424 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11425 != PackageManager.PERMISSION_GRANTED) { 11426 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11427 < Build.VERSION_CODES.FROYO) { 11428 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 11429 + Binder.getCallingUid()); 11430 return; 11431 } 11432 mContext.enforceCallingOrSelfPermission( 11433 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11434 } 11435 11436 final int callingUserId = UserHandle.getCallingUserId(); 11437 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId); 11438 if (pir != null) { 11439 Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0)); 11440 if (filter.countDataSchemes() == 1) { 11441 Uri.Builder builder = new Uri.Builder(); 11442 builder.scheme(filter.getDataScheme(0)); 11443 intent.setData(builder.build()); 11444 } 11445 List<PreferredActivity> matches = pir.queryIntent( 11446 intent, null, true, callingUserId); 11447 if (DEBUG_PREFERRED) { 11448 Slog.i(TAG, matches.size() + " preferred matches for " + intent); 11449 } 11450 for (int i = 0; i < matches.size(); i++) { 11451 PreferredActivity pa = matches.get(i); 11452 if (DEBUG_PREFERRED) { 11453 Slog.i(TAG, "Removing preferred activity " 11454 + pa.mPref.mComponent + ":"); 11455 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11456 } 11457 pir.removeFilter(pa); 11458 } 11459 } 11460 addPreferredActivityInternal(filter, match, set, activity, true, callingUserId); 11461 } 11462 } 11463 11464 @Override 11465 public void clearPackagePreferredActivities(String packageName) { 11466 final int uid = Binder.getCallingUid(); 11467 // writer 11468 synchronized (mPackages) { 11469 PackageParser.Package pkg = mPackages.get(packageName); 11470 if (pkg == null || pkg.applicationInfo.uid != uid) { 11471 if (mContext.checkCallingOrSelfPermission( 11472 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11473 != PackageManager.PERMISSION_GRANTED) { 11474 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11475 < Build.VERSION_CODES.FROYO) { 11476 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 11477 + Binder.getCallingUid()); 11478 return; 11479 } 11480 mContext.enforceCallingOrSelfPermission( 11481 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11482 } 11483 } 11484 11485 int user = UserHandle.getCallingUserId(); 11486 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 11487 mSettings.writePackageRestrictionsLPr(user); 11488 scheduleWriteSettingsLocked(); 11489 } 11490 } 11491 } 11492 11493 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 11494 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 11495 ArrayList<PreferredActivity> removed = null; 11496 boolean changed = false; 11497 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11498 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 11499 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11500 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 11501 continue; 11502 } 11503 Iterator<PreferredActivity> it = pir.filterIterator(); 11504 while (it.hasNext()) { 11505 PreferredActivity pa = it.next(); 11506 // Mark entry for removal only if it matches the package name 11507 // and the entry is of type "always". 11508 if (packageName == null || 11509 (pa.mPref.mComponent.getPackageName().equals(packageName) 11510 && pa.mPref.mAlways)) { 11511 if (removed == null) { 11512 removed = new ArrayList<PreferredActivity>(); 11513 } 11514 removed.add(pa); 11515 } 11516 } 11517 if (removed != null) { 11518 for (int j=0; j<removed.size(); j++) { 11519 PreferredActivity pa = removed.get(j); 11520 pir.removeFilter(pa); 11521 } 11522 changed = true; 11523 } 11524 } 11525 return changed; 11526 } 11527 11528 @Override 11529 public void resetPreferredActivities(int userId) { 11530 mContext.enforceCallingOrSelfPermission( 11531 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11532 // writer 11533 synchronized (mPackages) { 11534 int user = UserHandle.getCallingUserId(); 11535 clearPackagePreferredActivitiesLPw(null, user); 11536 mSettings.readDefaultPreferredAppsLPw(this, user); 11537 mSettings.writePackageRestrictionsLPr(user); 11538 scheduleWriteSettingsLocked(); 11539 } 11540 } 11541 11542 @Override 11543 public int getPreferredActivities(List<IntentFilter> outFilters, 11544 List<ComponentName> outActivities, String packageName) { 11545 11546 int num = 0; 11547 final int userId = UserHandle.getCallingUserId(); 11548 // reader 11549 synchronized (mPackages) { 11550 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11551 if (pir != null) { 11552 final Iterator<PreferredActivity> it = pir.filterIterator(); 11553 while (it.hasNext()) { 11554 final PreferredActivity pa = it.next(); 11555 if (packageName == null 11556 || (pa.mPref.mComponent.getPackageName().equals(packageName) 11557 && pa.mPref.mAlways)) { 11558 if (outFilters != null) { 11559 outFilters.add(new IntentFilter(pa)); 11560 } 11561 if (outActivities != null) { 11562 outActivities.add(pa.mPref.mComponent); 11563 } 11564 } 11565 } 11566 } 11567 } 11568 11569 return num; 11570 } 11571 11572 @Override 11573 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 11574 int userId) { 11575 int callingUid = Binder.getCallingUid(); 11576 if (callingUid != Process.SYSTEM_UID) { 11577 throw new SecurityException( 11578 "addPersistentPreferredActivity can only be run by the system"); 11579 } 11580 if (filter.countActions() == 0) { 11581 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11582 return; 11583 } 11584 synchronized (mPackages) { 11585 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 11586 " :"); 11587 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11588 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 11589 new PersistentPreferredActivity(filter, activity)); 11590 mSettings.writePackageRestrictionsLPr(userId); 11591 } 11592 } 11593 11594 @Override 11595 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 11596 int callingUid = Binder.getCallingUid(); 11597 if (callingUid != Process.SYSTEM_UID) { 11598 throw new SecurityException( 11599 "clearPackagePersistentPreferredActivities can only be run by the system"); 11600 } 11601 ArrayList<PersistentPreferredActivity> removed = null; 11602 boolean changed = false; 11603 synchronized (mPackages) { 11604 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 11605 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 11606 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 11607 .valueAt(i); 11608 if (userId != thisUserId) { 11609 continue; 11610 } 11611 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 11612 while (it.hasNext()) { 11613 PersistentPreferredActivity ppa = it.next(); 11614 // Mark entry for removal only if it matches the package name. 11615 if (ppa.mComponent.getPackageName().equals(packageName)) { 11616 if (removed == null) { 11617 removed = new ArrayList<PersistentPreferredActivity>(); 11618 } 11619 removed.add(ppa); 11620 } 11621 } 11622 if (removed != null) { 11623 for (int j=0; j<removed.size(); j++) { 11624 PersistentPreferredActivity ppa = removed.get(j); 11625 ppir.removeFilter(ppa); 11626 } 11627 changed = true; 11628 } 11629 } 11630 11631 if (changed) { 11632 mSettings.writePackageRestrictionsLPr(userId); 11633 } 11634 } 11635 } 11636 11637 @Override 11638 public void addCrossProfileIntentFilter(IntentFilter intentFilter, int sourceUserId, 11639 int targetUserId, int flags) { 11640 mContext.enforceCallingOrSelfPermission( 11641 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11642 if (intentFilter.countActions() == 0) { 11643 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 11644 return; 11645 } 11646 synchronized (mPackages) { 11647 CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter, 11648 targetUserId, flags); 11649 mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter); 11650 mSettings.writePackageRestrictionsLPr(sourceUserId); 11651 } 11652 } 11653 11654 public void addCrossProfileIntentsForPackage(String packageName, 11655 int sourceUserId, int targetUserId) { 11656 mContext.enforceCallingOrSelfPermission( 11657 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11658 mSettings.addCrossProfilePackage(packageName, sourceUserId, targetUserId); 11659 mSettings.writePackageRestrictionsLPr(sourceUserId); 11660 } 11661 11662 public void removeCrossProfileIntentsForPackage(String packageName, 11663 int sourceUserId, int targetUserId) { 11664 mContext.enforceCallingOrSelfPermission( 11665 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11666 mSettings.removeCrossProfilePackage(packageName, sourceUserId, targetUserId); 11667 mSettings.writePackageRestrictionsLPr(sourceUserId); 11668 } 11669 11670 @Override 11671 public void clearCrossProfileIntentFilters(int sourceUserId) { 11672 mContext.enforceCallingOrSelfPermission( 11673 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11674 synchronized (mPackages) { 11675 CrossProfileIntentResolver resolver = 11676 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11677 HashSet<CrossProfileIntentFilter> set = 11678 new HashSet<CrossProfileIntentFilter>(resolver.filterSet()); 11679 for (CrossProfileIntentFilter filter : set) { 11680 if ((filter.getFlags() & PackageManager.SET_BY_PROFILE_OWNER) != 0) { 11681 resolver.removeFilter(filter); 11682 } 11683 } 11684 mSettings.writePackageRestrictionsLPr(sourceUserId); 11685 } 11686 } 11687 11688 @Override 11689 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 11690 Intent intent = new Intent(Intent.ACTION_MAIN); 11691 intent.addCategory(Intent.CATEGORY_HOME); 11692 11693 final int callingUserId = UserHandle.getCallingUserId(); 11694 List<ResolveInfo> list = queryIntentActivities(intent, null, 11695 PackageManager.GET_META_DATA, callingUserId); 11696 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 11697 true, false, false, callingUserId); 11698 11699 allHomeCandidates.clear(); 11700 if (list != null) { 11701 for (ResolveInfo ri : list) { 11702 allHomeCandidates.add(ri); 11703 } 11704 } 11705 return (preferred == null || preferred.activityInfo == null) 11706 ? null 11707 : new ComponentName(preferred.activityInfo.packageName, 11708 preferred.activityInfo.name); 11709 } 11710 11711 /** 11712 * Check if calling UID is the current home app. This handles both the case 11713 * where the user has selected a specific home app, and where there is only 11714 * one home app. 11715 */ 11716 public boolean checkCallerIsHomeApp() { 11717 final Intent intent = new Intent(Intent.ACTION_MAIN); 11718 intent.addCategory(Intent.CATEGORY_HOME); 11719 11720 final int callingUid = Binder.getCallingUid(); 11721 final int callingUserId = UserHandle.getCallingUserId(); 11722 final List<ResolveInfo> allHomes = queryIntentActivities(intent, null, 0, callingUserId); 11723 final ResolveInfo preferredHome = findPreferredActivity(intent, null, 0, allHomes, 0, true, 11724 false, false, callingUserId); 11725 11726 if (preferredHome != null) { 11727 if (callingUid == preferredHome.activityInfo.applicationInfo.uid) { 11728 return true; 11729 } 11730 } else { 11731 for (ResolveInfo info : allHomes) { 11732 if (callingUid == info.activityInfo.applicationInfo.uid) { 11733 return true; 11734 } 11735 } 11736 } 11737 11738 return false; 11739 } 11740 11741 /** 11742 * Enforce that calling UID is the current home app. This handles both the 11743 * case where the user has selected a specific home app, and where there is 11744 * only one home app. 11745 */ 11746 public void enforceCallerIsHomeApp() { 11747 if (!checkCallerIsHomeApp()) { 11748 throw new SecurityException("Caller is not currently selected home app"); 11749 } 11750 } 11751 11752 @Override 11753 public void setApplicationEnabledSetting(String appPackageName, 11754 int newState, int flags, int userId, String callingPackage) { 11755 if (!sUserManager.exists(userId)) return; 11756 if (callingPackage == null) { 11757 callingPackage = Integer.toString(Binder.getCallingUid()); 11758 } 11759 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 11760 } 11761 11762 @Override 11763 public void setComponentEnabledSetting(ComponentName componentName, 11764 int newState, int flags, int userId) { 11765 if (!sUserManager.exists(userId)) return; 11766 setEnabledSetting(componentName.getPackageName(), 11767 componentName.getClassName(), newState, flags, userId, null); 11768 } 11769 11770 private void setEnabledSetting(final String packageName, String className, int newState, 11771 final int flags, int userId, String callingPackage) { 11772 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 11773 || newState == COMPONENT_ENABLED_STATE_ENABLED 11774 || newState == COMPONENT_ENABLED_STATE_DISABLED 11775 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 11776 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 11777 throw new IllegalArgumentException("Invalid new component state: " 11778 + newState); 11779 } 11780 PackageSetting pkgSetting; 11781 final int uid = Binder.getCallingUid(); 11782 final int permission = mContext.checkCallingOrSelfPermission( 11783 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11784 enforceCrossUserPermission(uid, userId, false, "set enabled"); 11785 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11786 boolean sendNow = false; 11787 boolean isApp = (className == null); 11788 String componentName = isApp ? packageName : className; 11789 int packageUid = -1; 11790 ArrayList<String> components; 11791 11792 // writer 11793 synchronized (mPackages) { 11794 pkgSetting = mSettings.mPackages.get(packageName); 11795 if (pkgSetting == null) { 11796 if (className == null) { 11797 throw new IllegalArgumentException( 11798 "Unknown package: " + packageName); 11799 } 11800 throw new IllegalArgumentException( 11801 "Unknown component: " + packageName 11802 + "/" + className); 11803 } 11804 // Allow root and verify that userId is not being specified by a different user 11805 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 11806 throw new SecurityException( 11807 "Permission Denial: attempt to change component state from pid=" 11808 + Binder.getCallingPid() 11809 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 11810 } 11811 if (className == null) { 11812 // We're dealing with an application/package level state change 11813 if (pkgSetting.getEnabled(userId) == newState) { 11814 // Nothing to do 11815 return; 11816 } 11817 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 11818 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 11819 // Don't care about who enables an app. 11820 callingPackage = null; 11821 } 11822 pkgSetting.setEnabled(newState, userId, callingPackage); 11823 // pkgSetting.pkg.mSetEnabled = newState; 11824 } else { 11825 // We're dealing with a component level state change 11826 // First, verify that this is a valid class name. 11827 PackageParser.Package pkg = pkgSetting.pkg; 11828 if (pkg == null || !pkg.hasComponentClassName(className)) { 11829 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 11830 throw new IllegalArgumentException("Component class " + className 11831 + " does not exist in " + packageName); 11832 } else { 11833 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 11834 + className + " does not exist in " + packageName); 11835 } 11836 } 11837 switch (newState) { 11838 case COMPONENT_ENABLED_STATE_ENABLED: 11839 if (!pkgSetting.enableComponentLPw(className, userId)) { 11840 return; 11841 } 11842 break; 11843 case COMPONENT_ENABLED_STATE_DISABLED: 11844 if (!pkgSetting.disableComponentLPw(className, userId)) { 11845 return; 11846 } 11847 break; 11848 case COMPONENT_ENABLED_STATE_DEFAULT: 11849 if (!pkgSetting.restoreComponentLPw(className, userId)) { 11850 return; 11851 } 11852 break; 11853 default: 11854 Slog.e(TAG, "Invalid new component state: " + newState); 11855 return; 11856 } 11857 } 11858 mSettings.writePackageRestrictionsLPr(userId); 11859 components = mPendingBroadcasts.get(userId, packageName); 11860 final boolean newPackage = components == null; 11861 if (newPackage) { 11862 components = new ArrayList<String>(); 11863 } 11864 if (!components.contains(componentName)) { 11865 components.add(componentName); 11866 } 11867 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 11868 sendNow = true; 11869 // Purge entry from pending broadcast list if another one exists already 11870 // since we are sending one right away. 11871 mPendingBroadcasts.remove(userId, packageName); 11872 } else { 11873 if (newPackage) { 11874 mPendingBroadcasts.put(userId, packageName, components); 11875 } 11876 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 11877 // Schedule a message 11878 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 11879 } 11880 } 11881 } 11882 11883 long callingId = Binder.clearCallingIdentity(); 11884 try { 11885 if (sendNow) { 11886 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 11887 sendPackageChangedBroadcast(packageName, 11888 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 11889 } 11890 } finally { 11891 Binder.restoreCallingIdentity(callingId); 11892 } 11893 } 11894 11895 private void sendPackageChangedBroadcast(String packageName, 11896 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 11897 if (DEBUG_INSTALL) 11898 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 11899 + componentNames); 11900 Bundle extras = new Bundle(4); 11901 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 11902 String nameList[] = new String[componentNames.size()]; 11903 componentNames.toArray(nameList); 11904 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 11905 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 11906 extras.putInt(Intent.EXTRA_UID, packageUid); 11907 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 11908 new int[] {UserHandle.getUserId(packageUid)}); 11909 } 11910 11911 @Override 11912 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 11913 if (!sUserManager.exists(userId)) return; 11914 final int uid = Binder.getCallingUid(); 11915 final int permission = mContext.checkCallingOrSelfPermission( 11916 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11917 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11918 enforceCrossUserPermission(uid, userId, true, "stop package"); 11919 // writer 11920 synchronized (mPackages) { 11921 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 11922 uid, userId)) { 11923 scheduleWritePackageRestrictionsLocked(userId); 11924 } 11925 } 11926 } 11927 11928 @Override 11929 public String getInstallerPackageName(String packageName) { 11930 // reader 11931 synchronized (mPackages) { 11932 return mSettings.getInstallerPackageNameLPr(packageName); 11933 } 11934 } 11935 11936 @Override 11937 public int getApplicationEnabledSetting(String packageName, int userId) { 11938 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11939 int uid = Binder.getCallingUid(); 11940 enforceCrossUserPermission(uid, userId, false, "get enabled"); 11941 // reader 11942 synchronized (mPackages) { 11943 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 11944 } 11945 } 11946 11947 @Override 11948 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 11949 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11950 int uid = Binder.getCallingUid(); 11951 enforceCrossUserPermission(uid, userId, false, "get component enabled"); 11952 // reader 11953 synchronized (mPackages) { 11954 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 11955 } 11956 } 11957 11958 @Override 11959 public void enterSafeMode() { 11960 enforceSystemOrRoot("Only the system can request entering safe mode"); 11961 11962 if (!mSystemReady) { 11963 mSafeMode = true; 11964 } 11965 } 11966 11967 @Override 11968 public void systemReady() { 11969 mSystemReady = true; 11970 11971 // Read the compatibilty setting when the system is ready. 11972 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 11973 mContext.getContentResolver(), 11974 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 11975 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 11976 if (DEBUG_SETTINGS) { 11977 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 11978 } 11979 11980 synchronized (mPackages) { 11981 // Verify that all of the preferred activity components actually 11982 // exist. It is possible for applications to be updated and at 11983 // that point remove a previously declared activity component that 11984 // had been set as a preferred activity. We try to clean this up 11985 // the next time we encounter that preferred activity, but it is 11986 // possible for the user flow to never be able to return to that 11987 // situation so here we do a sanity check to make sure we haven't 11988 // left any junk around. 11989 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 11990 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11991 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11992 removed.clear(); 11993 for (PreferredActivity pa : pir.filterSet()) { 11994 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 11995 removed.add(pa); 11996 } 11997 } 11998 if (removed.size() > 0) { 11999 for (int r=0; r<removed.size(); r++) { 12000 PreferredActivity pa = removed.get(r); 12001 Slog.w(TAG, "Removing dangling preferred activity: " 12002 + pa.mPref.mComponent); 12003 pir.removeFilter(pa); 12004 } 12005 mSettings.writePackageRestrictionsLPr( 12006 mSettings.mPreferredActivities.keyAt(i)); 12007 } 12008 } 12009 } 12010 sUserManager.systemReady(); 12011 } 12012 12013 @Override 12014 public boolean isSafeMode() { 12015 return mSafeMode; 12016 } 12017 12018 @Override 12019 public boolean hasSystemUidErrors() { 12020 return mHasSystemUidErrors; 12021 } 12022 12023 static String arrayToString(int[] array) { 12024 StringBuffer buf = new StringBuffer(128); 12025 buf.append('['); 12026 if (array != null) { 12027 for (int i=0; i<array.length; i++) { 12028 if (i > 0) buf.append(", "); 12029 buf.append(array[i]); 12030 } 12031 } 12032 buf.append(']'); 12033 return buf.toString(); 12034 } 12035 12036 static class DumpState { 12037 public static final int DUMP_LIBS = 1 << 0; 12038 public static final int DUMP_FEATURES = 1 << 1; 12039 public static final int DUMP_RESOLVERS = 1 << 2; 12040 public static final int DUMP_PERMISSIONS = 1 << 3; 12041 public static final int DUMP_PACKAGES = 1 << 4; 12042 public static final int DUMP_SHARED_USERS = 1 << 5; 12043 public static final int DUMP_MESSAGES = 1 << 6; 12044 public static final int DUMP_PROVIDERS = 1 << 7; 12045 public static final int DUMP_VERIFIERS = 1 << 8; 12046 public static final int DUMP_PREFERRED = 1 << 9; 12047 public static final int DUMP_PREFERRED_XML = 1 << 10; 12048 public static final int DUMP_KEYSETS = 1 << 11; 12049 public static final int DUMP_VERSION = 1 << 12; 12050 public static final int DUMP_INSTALLS = 1 << 13; 12051 12052 public static final int OPTION_SHOW_FILTERS = 1 << 0; 12053 12054 private int mTypes; 12055 12056 private int mOptions; 12057 12058 private boolean mTitlePrinted; 12059 12060 private SharedUserSetting mSharedUser; 12061 12062 public boolean isDumping(int type) { 12063 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 12064 return true; 12065 } 12066 12067 return (mTypes & type) != 0; 12068 } 12069 12070 public void setDump(int type) { 12071 mTypes |= type; 12072 } 12073 12074 public boolean isOptionEnabled(int option) { 12075 return (mOptions & option) != 0; 12076 } 12077 12078 public void setOptionEnabled(int option) { 12079 mOptions |= option; 12080 } 12081 12082 public boolean onTitlePrinted() { 12083 final boolean printed = mTitlePrinted; 12084 mTitlePrinted = true; 12085 return printed; 12086 } 12087 12088 public boolean getTitlePrinted() { 12089 return mTitlePrinted; 12090 } 12091 12092 public void setTitlePrinted(boolean enabled) { 12093 mTitlePrinted = enabled; 12094 } 12095 12096 public SharedUserSetting getSharedUser() { 12097 return mSharedUser; 12098 } 12099 12100 public void setSharedUser(SharedUserSetting user) { 12101 mSharedUser = user; 12102 } 12103 } 12104 12105 @Override 12106 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 12107 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 12108 != PackageManager.PERMISSION_GRANTED) { 12109 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 12110 + Binder.getCallingPid() 12111 + ", uid=" + Binder.getCallingUid() 12112 + " without permission " 12113 + android.Manifest.permission.DUMP); 12114 return; 12115 } 12116 12117 DumpState dumpState = new DumpState(); 12118 boolean fullPreferred = false; 12119 boolean checkin = false; 12120 12121 String packageName = null; 12122 12123 int opti = 0; 12124 while (opti < args.length) { 12125 String opt = args[opti]; 12126 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 12127 break; 12128 } 12129 opti++; 12130 if ("-a".equals(opt)) { 12131 // Right now we only know how to print all. 12132 } else if ("-h".equals(opt)) { 12133 pw.println("Package manager dump options:"); 12134 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 12135 pw.println(" --checkin: dump for a checkin"); 12136 pw.println(" -f: print details of intent filters"); 12137 pw.println(" -h: print this help"); 12138 pw.println(" cmd may be one of:"); 12139 pw.println(" l[ibraries]: list known shared libraries"); 12140 pw.println(" f[ibraries]: list device features"); 12141 pw.println(" k[eysets]: print known keysets"); 12142 pw.println(" r[esolvers]: dump intent resolvers"); 12143 pw.println(" perm[issions]: dump permissions"); 12144 pw.println(" pref[erred]: print preferred package settings"); 12145 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 12146 pw.println(" prov[iders]: dump content providers"); 12147 pw.println(" p[ackages]: dump installed packages"); 12148 pw.println(" s[hared-users]: dump shared user IDs"); 12149 pw.println(" m[essages]: print collected runtime messages"); 12150 pw.println(" v[erifiers]: print package verifier info"); 12151 pw.println(" version: print database version info"); 12152 pw.println(" write: write current settings now"); 12153 pw.println(" <package.name>: info about given package"); 12154 pw.println(" installs: details about install sessions"); 12155 return; 12156 } else if ("--checkin".equals(opt)) { 12157 checkin = true; 12158 } else if ("-f".equals(opt)) { 12159 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12160 } else { 12161 pw.println("Unknown argument: " + opt + "; use -h for help"); 12162 } 12163 } 12164 12165 // Is the caller requesting to dump a particular piece of data? 12166 if (opti < args.length) { 12167 String cmd = args[opti]; 12168 opti++; 12169 // Is this a package name? 12170 if ("android".equals(cmd) || cmd.contains(".")) { 12171 packageName = cmd; 12172 // When dumping a single package, we always dump all of its 12173 // filter information since the amount of data will be reasonable. 12174 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12175 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 12176 dumpState.setDump(DumpState.DUMP_LIBS); 12177 } else if ("f".equals(cmd) || "features".equals(cmd)) { 12178 dumpState.setDump(DumpState.DUMP_FEATURES); 12179 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 12180 dumpState.setDump(DumpState.DUMP_RESOLVERS); 12181 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 12182 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 12183 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 12184 dumpState.setDump(DumpState.DUMP_PREFERRED); 12185 } else if ("preferred-xml".equals(cmd)) { 12186 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 12187 if (opti < args.length && "--full".equals(args[opti])) { 12188 fullPreferred = true; 12189 opti++; 12190 } 12191 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 12192 dumpState.setDump(DumpState.DUMP_PACKAGES); 12193 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 12194 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 12195 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 12196 dumpState.setDump(DumpState.DUMP_PROVIDERS); 12197 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 12198 dumpState.setDump(DumpState.DUMP_MESSAGES); 12199 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 12200 dumpState.setDump(DumpState.DUMP_VERIFIERS); 12201 } else if ("version".equals(cmd)) { 12202 dumpState.setDump(DumpState.DUMP_VERSION); 12203 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 12204 dumpState.setDump(DumpState.DUMP_KEYSETS); 12205 } else if ("write".equals(cmd)) { 12206 synchronized (mPackages) { 12207 mSettings.writeLPr(); 12208 pw.println("Settings written."); 12209 return; 12210 } 12211 } else if ("installs".equals(cmd)) { 12212 dumpState.setDump(DumpState.DUMP_INSTALLS); 12213 } 12214 } 12215 12216 if (checkin) { 12217 pw.println("vers,1"); 12218 } 12219 12220 // reader 12221 synchronized (mPackages) { 12222 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 12223 if (!checkin) { 12224 if (dumpState.onTitlePrinted()) 12225 pw.println(); 12226 pw.println("Database versions:"); 12227 pw.print(" SDK Version:"); 12228 pw.print(" internal="); 12229 pw.print(mSettings.mInternalSdkPlatform); 12230 pw.print(" external="); 12231 pw.println(mSettings.mExternalSdkPlatform); 12232 pw.print(" DB Version:"); 12233 pw.print(" internal="); 12234 pw.print(mSettings.mInternalDatabaseVersion); 12235 pw.print(" external="); 12236 pw.println(mSettings.mExternalDatabaseVersion); 12237 } 12238 } 12239 12240 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 12241 if (!checkin) { 12242 if (dumpState.onTitlePrinted()) 12243 pw.println(); 12244 pw.println("Verifiers:"); 12245 pw.print(" Required: "); 12246 pw.print(mRequiredVerifierPackage); 12247 pw.print(" (uid="); 12248 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 12249 pw.println(")"); 12250 } else if (mRequiredVerifierPackage != null) { 12251 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 12252 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 12253 } 12254 } 12255 12256 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 12257 boolean printedHeader = false; 12258 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 12259 while (it.hasNext()) { 12260 String name = it.next(); 12261 SharedLibraryEntry ent = mSharedLibraries.get(name); 12262 if (!checkin) { 12263 if (!printedHeader) { 12264 if (dumpState.onTitlePrinted()) 12265 pw.println(); 12266 pw.println("Libraries:"); 12267 printedHeader = true; 12268 } 12269 pw.print(" "); 12270 } else { 12271 pw.print("lib,"); 12272 } 12273 pw.print(name); 12274 if (!checkin) { 12275 pw.print(" -> "); 12276 } 12277 if (ent.path != null) { 12278 if (!checkin) { 12279 pw.print("(jar) "); 12280 pw.print(ent.path); 12281 } else { 12282 pw.print(",jar,"); 12283 pw.print(ent.path); 12284 } 12285 } else { 12286 if (!checkin) { 12287 pw.print("(apk) "); 12288 pw.print(ent.apk); 12289 } else { 12290 pw.print(",apk,"); 12291 pw.print(ent.apk); 12292 } 12293 } 12294 pw.println(); 12295 } 12296 } 12297 12298 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 12299 if (dumpState.onTitlePrinted()) 12300 pw.println(); 12301 if (!checkin) { 12302 pw.println("Features:"); 12303 } 12304 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 12305 while (it.hasNext()) { 12306 String name = it.next(); 12307 if (!checkin) { 12308 pw.print(" "); 12309 } else { 12310 pw.print("feat,"); 12311 } 12312 pw.println(name); 12313 } 12314 } 12315 12316 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 12317 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 12318 : "Activity Resolver Table:", " ", packageName, 12319 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12320 dumpState.setTitlePrinted(true); 12321 } 12322 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 12323 : "Receiver Resolver Table:", " ", packageName, 12324 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12325 dumpState.setTitlePrinted(true); 12326 } 12327 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 12328 : "Service Resolver Table:", " ", packageName, 12329 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12330 dumpState.setTitlePrinted(true); 12331 } 12332 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 12333 : "Provider Resolver Table:", " ", packageName, 12334 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12335 dumpState.setTitlePrinted(true); 12336 } 12337 } 12338 12339 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 12340 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12341 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12342 int user = mSettings.mPreferredActivities.keyAt(i); 12343 if (pir.dump(pw, 12344 dumpState.getTitlePrinted() 12345 ? "\nPreferred Activities User " + user + ":" 12346 : "Preferred Activities User " + user + ":", " ", 12347 packageName, true)) { 12348 dumpState.setTitlePrinted(true); 12349 } 12350 } 12351 } 12352 12353 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 12354 pw.flush(); 12355 FileOutputStream fout = new FileOutputStream(fd); 12356 BufferedOutputStream str = new BufferedOutputStream(fout); 12357 XmlSerializer serializer = new FastXmlSerializer(); 12358 try { 12359 serializer.setOutput(str, "utf-8"); 12360 serializer.startDocument(null, true); 12361 serializer.setFeature( 12362 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 12363 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 12364 serializer.endDocument(); 12365 serializer.flush(); 12366 } catch (IllegalArgumentException e) { 12367 pw.println("Failed writing: " + e); 12368 } catch (IllegalStateException e) { 12369 pw.println("Failed writing: " + e); 12370 } catch (IOException e) { 12371 pw.println("Failed writing: " + e); 12372 } 12373 } 12374 12375 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 12376 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 12377 if (packageName == null) { 12378 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 12379 if (iperm == 0) { 12380 if (dumpState.onTitlePrinted()) 12381 pw.println(); 12382 pw.println("AppOp Permissions:"); 12383 } 12384 pw.print(" AppOp Permission "); 12385 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 12386 pw.println(":"); 12387 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 12388 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 12389 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 12390 } 12391 } 12392 } 12393 } 12394 12395 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 12396 boolean printedSomething = false; 12397 for (PackageParser.Provider p : mProviders.mProviders.values()) { 12398 if (packageName != null && !packageName.equals(p.info.packageName)) { 12399 continue; 12400 } 12401 if (!printedSomething) { 12402 if (dumpState.onTitlePrinted()) 12403 pw.println(); 12404 pw.println("Registered ContentProviders:"); 12405 printedSomething = true; 12406 } 12407 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 12408 pw.print(" "); pw.println(p.toString()); 12409 } 12410 printedSomething = false; 12411 for (Map.Entry<String, PackageParser.Provider> entry : 12412 mProvidersByAuthority.entrySet()) { 12413 PackageParser.Provider p = entry.getValue(); 12414 if (packageName != null && !packageName.equals(p.info.packageName)) { 12415 continue; 12416 } 12417 if (!printedSomething) { 12418 if (dumpState.onTitlePrinted()) 12419 pw.println(); 12420 pw.println("ContentProvider Authorities:"); 12421 printedSomething = true; 12422 } 12423 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 12424 pw.print(" "); pw.println(p.toString()); 12425 if (p.info != null && p.info.applicationInfo != null) { 12426 final String appInfo = p.info.applicationInfo.toString(); 12427 pw.print(" applicationInfo="); pw.println(appInfo); 12428 } 12429 } 12430 } 12431 12432 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 12433 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 12434 } 12435 12436 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 12437 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 12438 } 12439 12440 if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 12441 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState); 12442 } 12443 12444 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS)) { 12445 if (dumpState.onTitlePrinted()) pw.println(); 12446 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 12447 } 12448 12449 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 12450 if (dumpState.onTitlePrinted()) pw.println(); 12451 mSettings.dumpReadMessagesLPr(pw, dumpState); 12452 12453 pw.println(); 12454 pw.println("Package warning messages:"); 12455 final File fname = getSettingsProblemFile(); 12456 FileInputStream in = null; 12457 try { 12458 in = new FileInputStream(fname); 12459 final int avail = in.available(); 12460 final byte[] data = new byte[avail]; 12461 in.read(data); 12462 pw.print(new String(data)); 12463 } catch (FileNotFoundException e) { 12464 } catch (IOException e) { 12465 } finally { 12466 if (in != null) { 12467 try { 12468 in.close(); 12469 } catch (IOException e) { 12470 } 12471 } 12472 } 12473 } 12474 } 12475 } 12476 12477 // ------- apps on sdcard specific code ------- 12478 static final boolean DEBUG_SD_INSTALL = false; 12479 12480 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 12481 12482 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 12483 12484 private boolean mMediaMounted = false; 12485 12486 private String getEncryptKey() { 12487 try { 12488 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 12489 SD_ENCRYPTION_KEYSTORE_NAME); 12490 if (sdEncKey == null) { 12491 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 12492 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 12493 if (sdEncKey == null) { 12494 Slog.e(TAG, "Failed to create encryption keys"); 12495 return null; 12496 } 12497 } 12498 return sdEncKey; 12499 } catch (NoSuchAlgorithmException nsae) { 12500 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 12501 return null; 12502 } catch (IOException ioe) { 12503 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 12504 return null; 12505 } 12506 12507 } 12508 12509 /* package */static String getTempContainerId() { 12510 int tmpIdx = 1; 12511 String list[] = PackageHelper.getSecureContainerList(); 12512 if (list != null) { 12513 for (final String name : list) { 12514 // Ignore null and non-temporary container entries 12515 if (name == null || !name.startsWith(mTempContainerPrefix)) { 12516 continue; 12517 } 12518 12519 String subStr = name.substring(mTempContainerPrefix.length()); 12520 try { 12521 int cid = Integer.parseInt(subStr); 12522 if (cid >= tmpIdx) { 12523 tmpIdx = cid + 1; 12524 } 12525 } catch (NumberFormatException e) { 12526 } 12527 } 12528 } 12529 return mTempContainerPrefix + tmpIdx; 12530 } 12531 12532 /* 12533 * Update media status on PackageManager. 12534 */ 12535 @Override 12536 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 12537 int callingUid = Binder.getCallingUid(); 12538 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 12539 throw new SecurityException("Media status can only be updated by the system"); 12540 } 12541 // reader; this apparently protects mMediaMounted, but should probably 12542 // be a different lock in that case. 12543 synchronized (mPackages) { 12544 Log.i(TAG, "Updating external media status from " 12545 + (mMediaMounted ? "mounted" : "unmounted") + " to " 12546 + (mediaStatus ? "mounted" : "unmounted")); 12547 if (DEBUG_SD_INSTALL) 12548 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 12549 + ", mMediaMounted=" + mMediaMounted); 12550 if (mediaStatus == mMediaMounted) { 12551 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 12552 : 0, -1); 12553 mHandler.sendMessage(msg); 12554 return; 12555 } 12556 mMediaMounted = mediaStatus; 12557 } 12558 // Queue up an async operation since the package installation may take a 12559 // little while. 12560 mHandler.post(new Runnable() { 12561 public void run() { 12562 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 12563 } 12564 }); 12565 } 12566 12567 /** 12568 * Called by MountService when the initial ASECs to scan are available. 12569 * Should block until all the ASEC containers are finished being scanned. 12570 */ 12571 public void scanAvailableAsecs() { 12572 updateExternalMediaStatusInner(true, false, false); 12573 if (mShouldRestoreconData) { 12574 SELinuxMMAC.setRestoreconDone(); 12575 mShouldRestoreconData = false; 12576 } 12577 } 12578 12579 /* 12580 * Collect information of applications on external media, map them against 12581 * existing containers and update information based on current mount status. 12582 * Please note that we always have to report status if reportStatus has been 12583 * set to true especially when unloading packages. 12584 */ 12585 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 12586 boolean externalStorage) { 12587 // Collection of uids 12588 int uidArr[] = null; 12589 // Collection of stale containers 12590 HashSet<String> removeCids = new HashSet<String>(); 12591 // Collection of packages on external media with valid containers. 12592 HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>(); 12593 // Get list of secure containers. 12594 final String list[] = PackageHelper.getSecureContainerList(); 12595 if (list == null || list.length == 0) { 12596 Log.i(TAG, "No secure containers on sdcard"); 12597 } else { 12598 // Process list of secure containers and categorize them 12599 // as active or stale based on their package internal state. 12600 int uidList[] = new int[list.length]; 12601 int num = 0; 12602 // reader 12603 synchronized (mPackages) { 12604 for (String cid : list) { 12605 if (DEBUG_SD_INSTALL) 12606 Log.i(TAG, "Processing container " + cid); 12607 String pkgName = getAsecPackageName(cid); 12608 if (pkgName == null) { 12609 if (DEBUG_SD_INSTALL) 12610 Log.i(TAG, "Container : " + cid + " stale"); 12611 removeCids.add(cid); 12612 continue; 12613 } 12614 if (DEBUG_SD_INSTALL) 12615 Log.i(TAG, "Looking for pkg : " + pkgName); 12616 12617 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12618 if (ps == null) { 12619 Log.i(TAG, "Deleting container with no matching settings " + cid); 12620 removeCids.add(cid); 12621 continue; 12622 } 12623 12624 /* 12625 * Skip packages that are not external if we're unmounting 12626 * external storage. 12627 */ 12628 if (externalStorage && !isMounted && !isExternal(ps)) { 12629 continue; 12630 } 12631 12632 final AsecInstallArgs args = new AsecInstallArgs(cid, 12633 getAppDexInstructionSets(ps), isForwardLocked(ps), isMultiArch(ps)); 12634 // The package status is changed only if the code path 12635 // matches between settings and the container id. 12636 if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) { 12637 if (DEBUG_SD_INSTALL) { 12638 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 12639 + " at code path: " + ps.codePathString); 12640 } 12641 12642 // We do have a valid package installed on sdcard 12643 processCids.put(args, ps.codePathString); 12644 final int uid = ps.appId; 12645 if (uid != -1) { 12646 uidList[num++] = uid; 12647 } 12648 } else { 12649 Log.i(TAG, "Deleting stale container for " + cid); 12650 removeCids.add(cid); 12651 } 12652 } 12653 } 12654 12655 if (num > 0) { 12656 // Sort uid list 12657 Arrays.sort(uidList, 0, num); 12658 // Throw away duplicates 12659 uidArr = new int[num]; 12660 uidArr[0] = uidList[0]; 12661 int di = 0; 12662 for (int i = 1; i < num; i++) { 12663 if (uidList[i - 1] != uidList[i]) { 12664 uidArr[di++] = uidList[i]; 12665 } 12666 } 12667 } 12668 } 12669 // Process packages with valid entries. 12670 if (isMounted) { 12671 if (DEBUG_SD_INSTALL) 12672 Log.i(TAG, "Loading packages"); 12673 loadMediaPackages(processCids, uidArr, removeCids); 12674 startCleaningPackages(); 12675 } else { 12676 if (DEBUG_SD_INSTALL) 12677 Log.i(TAG, "Unloading packages"); 12678 unloadMediaPackages(processCids, uidArr, reportStatus); 12679 } 12680 } 12681 12682 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 12683 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 12684 int size = pkgList.size(); 12685 if (size > 0) { 12686 // Send broadcasts here 12687 Bundle extras = new Bundle(); 12688 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 12689 .toArray(new String[size])); 12690 if (uidArr != null) { 12691 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 12692 } 12693 if (replacing) { 12694 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 12695 } 12696 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 12697 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 12698 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 12699 } 12700 } 12701 12702 /* 12703 * Look at potentially valid container ids from processCids If package 12704 * information doesn't match the one on record or package scanning fails, 12705 * the cid is added to list of removeCids. We currently don't delete stale 12706 * containers. 12707 */ 12708 private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 12709 HashSet<String> removeCids) { 12710 ArrayList<String> pkgList = new ArrayList<String>(); 12711 Set<AsecInstallArgs> keys = processCids.keySet(); 12712 boolean doGc = false; 12713 for (AsecInstallArgs args : keys) { 12714 String codePath = processCids.get(args); 12715 if (DEBUG_SD_INSTALL) 12716 Log.i(TAG, "Loading container : " + args.cid); 12717 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12718 try { 12719 // Make sure there are no container errors first. 12720 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 12721 Slog.e(TAG, "Failed to mount cid : " + args.cid 12722 + " when installing from sdcard"); 12723 continue; 12724 } 12725 // Check code path here. 12726 if (codePath == null || !codePath.equals(args.getCodePath())) { 12727 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 12728 + " does not match one in settings " + codePath); 12729 continue; 12730 } 12731 // Parse package 12732 int parseFlags = mDefParseFlags; 12733 if (args.isExternal()) { 12734 parseFlags |= PackageParser.PARSE_ON_SDCARD; 12735 } 12736 if (args.isFwdLocked()) { 12737 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 12738 } 12739 12740 doGc = true; 12741 synchronized (mInstallLock) { 12742 PackageParser.Package pkg = null; 12743 try { 12744 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null, null); 12745 } catch (PackageManagerException e) { 12746 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 12747 } 12748 // Scan the package 12749 if (pkg != null) { 12750 /* 12751 * TODO why is the lock being held? doPostInstall is 12752 * called in other places without the lock. This needs 12753 * to be straightened out. 12754 */ 12755 // writer 12756 synchronized (mPackages) { 12757 retCode = PackageManager.INSTALL_SUCCEEDED; 12758 pkgList.add(pkg.packageName); 12759 // Post process args 12760 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 12761 pkg.applicationInfo.uid); 12762 } 12763 } else { 12764 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 12765 } 12766 } 12767 12768 } finally { 12769 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 12770 // Don't destroy container here. Wait till gc clears things 12771 // up. 12772 removeCids.add(args.cid); 12773 } 12774 } 12775 } 12776 // writer 12777 synchronized (mPackages) { 12778 // If the platform SDK has changed since the last time we booted, 12779 // we need to re-grant app permission to catch any new ones that 12780 // appear. This is really a hack, and means that apps can in some 12781 // cases get permissions that the user didn't initially explicitly 12782 // allow... it would be nice to have some better way to handle 12783 // this situation. 12784 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 12785 if (regrantPermissions) 12786 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 12787 + mSdkVersion + "; regranting permissions for external storage"); 12788 mSettings.mExternalSdkPlatform = mSdkVersion; 12789 12790 // Make sure group IDs have been assigned, and any permission 12791 // changes in other apps are accounted for 12792 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 12793 | (regrantPermissions 12794 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 12795 : 0)); 12796 12797 mSettings.updateExternalDatabaseVersion(); 12798 12799 // can downgrade to reader 12800 // Persist settings 12801 mSettings.writeLPr(); 12802 } 12803 // Send a broadcast to let everyone know we are done processing 12804 if (pkgList.size() > 0) { 12805 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12806 } 12807 // Force gc to avoid any stale parser references that we might have. 12808 if (doGc) { 12809 Runtime.getRuntime().gc(); 12810 } 12811 // List stale containers and destroy stale temporary containers. 12812 if (removeCids != null) { 12813 for (String cid : removeCids) { 12814 if (cid.startsWith(mTempContainerPrefix)) { 12815 Log.i(TAG, "Destroying stale temporary container " + cid); 12816 PackageHelper.destroySdDir(cid); 12817 } else { 12818 Log.w(TAG, "Container " + cid + " is stale"); 12819 } 12820 } 12821 } 12822 } 12823 12824 /* 12825 * Utility method to unload a list of specified containers 12826 */ 12827 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 12828 // Just unmount all valid containers. 12829 for (AsecInstallArgs arg : cidArgs) { 12830 synchronized (mInstallLock) { 12831 arg.doPostDeleteLI(false); 12832 } 12833 } 12834 } 12835 12836 /* 12837 * Unload packages mounted on external media. This involves deleting package 12838 * data from internal structures, sending broadcasts about diabled packages, 12839 * gc'ing to free up references, unmounting all secure containers 12840 * corresponding to packages on external media, and posting a 12841 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 12842 * that we always have to post this message if status has been requested no 12843 * matter what. 12844 */ 12845 private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 12846 final boolean reportStatus) { 12847 if (DEBUG_SD_INSTALL) 12848 Log.i(TAG, "unloading media packages"); 12849 ArrayList<String> pkgList = new ArrayList<String>(); 12850 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 12851 final Set<AsecInstallArgs> keys = processCids.keySet(); 12852 for (AsecInstallArgs args : keys) { 12853 String pkgName = args.getPackageName(); 12854 if (DEBUG_SD_INSTALL) 12855 Log.i(TAG, "Trying to unload pkg : " + pkgName); 12856 // Delete package internally 12857 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 12858 synchronized (mInstallLock) { 12859 boolean res = deletePackageLI(pkgName, null, false, null, null, 12860 PackageManager.DELETE_KEEP_DATA, outInfo, false); 12861 if (res) { 12862 pkgList.add(pkgName); 12863 } else { 12864 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 12865 failedList.add(args); 12866 } 12867 } 12868 } 12869 12870 // reader 12871 synchronized (mPackages) { 12872 // We didn't update the settings after removing each package; 12873 // write them now for all packages. 12874 mSettings.writeLPr(); 12875 } 12876 12877 // We have to absolutely send UPDATED_MEDIA_STATUS only 12878 // after confirming that all the receivers processed the ordered 12879 // broadcast when packages get disabled, force a gc to clean things up. 12880 // and unload all the containers. 12881 if (pkgList.size() > 0) { 12882 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 12883 new IIntentReceiver.Stub() { 12884 public void performReceive(Intent intent, int resultCode, String data, 12885 Bundle extras, boolean ordered, boolean sticky, 12886 int sendingUser) throws RemoteException { 12887 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 12888 reportStatus ? 1 : 0, 1, keys); 12889 mHandler.sendMessage(msg); 12890 } 12891 }); 12892 } else { 12893 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 12894 keys); 12895 mHandler.sendMessage(msg); 12896 } 12897 } 12898 12899 /** Binder call */ 12900 @Override 12901 public void movePackage(final String packageName, final IPackageMoveObserver observer, 12902 final int flags) { 12903 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 12904 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 12905 int returnCode = PackageManager.MOVE_SUCCEEDED; 12906 int currFlags = 0; 12907 int newFlags = 0; 12908 // reader 12909 synchronized (mPackages) { 12910 PackageParser.Package pkg = mPackages.get(packageName); 12911 if (pkg == null) { 12912 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12913 } else { 12914 // Disable moving fwd locked apps and system packages 12915 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 12916 Slog.w(TAG, "Cannot move system application"); 12917 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 12918 } else if (pkg.mOperationPending) { 12919 Slog.w(TAG, "Attempt to move package which has pending operations"); 12920 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 12921 } else { 12922 // Find install location first 12923 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 12924 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 12925 Slog.w(TAG, "Ambigous flags specified for move location."); 12926 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12927 } else { 12928 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL 12929 : PackageManager.INSTALL_INTERNAL; 12930 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL 12931 : PackageManager.INSTALL_INTERNAL; 12932 12933 if (newFlags == currFlags) { 12934 Slog.w(TAG, "No move required. Trying to move to same location"); 12935 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12936 } else { 12937 if (isForwardLocked(pkg)) { 12938 currFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12939 newFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12940 } 12941 } 12942 } 12943 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12944 pkg.mOperationPending = true; 12945 } 12946 } 12947 } 12948 12949 /* 12950 * TODO this next block probably shouldn't be inside the lock. We 12951 * can't guarantee these won't change after this is fired off 12952 * anyway. 12953 */ 12954 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 12955 processPendingMove(new MoveParams(null, observer, 0, packageName, null, -1, user, false), 12956 returnCode); 12957 } else { 12958 Message msg = mHandler.obtainMessage(INIT_COPY); 12959 final String[] instructionSets = getAppDexInstructionSets(pkg.applicationInfo); 12960 final boolean multiArch = isMultiArch(pkg.applicationInfo); 12961 InstallArgs srcArgs = createInstallArgsForExisting(currFlags, 12962 pkg.applicationInfo.getCodePath(), pkg.applicationInfo.getResourcePath(), 12963 pkg.applicationInfo.nativeLibraryRootDir, instructionSets, multiArch); 12964 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName, 12965 instructionSets, pkg.applicationInfo.uid, user, multiArch); 12966 msg.obj = mp; 12967 mHandler.sendMessage(msg); 12968 } 12969 } 12970 } 12971 12972 private void processPendingMove(final MoveParams mp, final int currentStatus) { 12973 // Queue up an async operation since the package deletion may take a 12974 // little while. 12975 mHandler.post(new Runnable() { 12976 public void run() { 12977 // TODO fix this; this does nothing. 12978 mHandler.removeCallbacks(this); 12979 int returnCode = currentStatus; 12980 if (currentStatus == PackageManager.MOVE_SUCCEEDED) { 12981 int uidArr[] = null; 12982 ArrayList<String> pkgList = null; 12983 synchronized (mPackages) { 12984 PackageParser.Package pkg = mPackages.get(mp.packageName); 12985 if (pkg == null) { 12986 Slog.w(TAG, " Package " + mp.packageName 12987 + " doesn't exist. Aborting move"); 12988 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12989 } else if (!mp.srcArgs.getCodePath().equals( 12990 pkg.applicationInfo.getCodePath())) { 12991 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " 12992 + mp.srcArgs.getCodePath() + " to " 12993 + pkg.applicationInfo.getCodePath() 12994 + " Aborting move and returning error"); 12995 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 12996 } else { 12997 uidArr = new int[] { 12998 pkg.applicationInfo.uid 12999 }; 13000 pkgList = new ArrayList<String>(); 13001 pkgList.add(mp.packageName); 13002 } 13003 } 13004 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13005 // Send resources unavailable broadcast 13006 sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null); 13007 // Update package code and resource paths 13008 synchronized (mInstallLock) { 13009 synchronized (mPackages) { 13010 PackageParser.Package pkg = mPackages.get(mp.packageName); 13011 // Recheck for package again. 13012 if (pkg == null) { 13013 Slog.w(TAG, " Package " + mp.packageName 13014 + " doesn't exist. Aborting move"); 13015 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 13016 } else if (!mp.srcArgs.getCodePath().equals( 13017 pkg.applicationInfo.getCodePath())) { 13018 Slog.w(TAG, "Package " + mp.packageName 13019 + " code path changed from " + mp.srcArgs.getCodePath() 13020 + " to " + pkg.applicationInfo.getCodePath() 13021 + " Aborting move and returning error"); 13022 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 13023 } else { 13024 final String oldCodePath = pkg.codePath; 13025 final String newCodePath = mp.targetArgs.getCodePath(); 13026 final String newResPath = mp.targetArgs.getResourcePath(); 13027 // TODO: This assumes the new style of installation. 13028 // should we look at legacyNativeLibraryPath ? 13029 final String newNativeRoot = new File(pkg.codePath, LIB_DIR_NAME).getAbsolutePath(); 13030 final File newNativeDir = new File(newNativeRoot); 13031 13032 if (!isForwardLocked(pkg) && !isExternal(pkg)) { 13033 // TODO(multiArch): Fix this so that it looks at the existing 13034 // recorded CPU abis from the package. There's no need for a separate 13035 // round of ABI scanning here. 13036 NativeLibraryHelper.Handle handle = null; 13037 try { 13038 handle = NativeLibraryHelper.Handle.create( 13039 new File(newCodePath)); 13040 final int abi = NativeLibraryHelper.findSupportedAbi( 13041 handle, Build.SUPPORTED_ABIS); 13042 if (abi >= 0) { 13043 NativeLibraryHelper.copyNativeBinariesIfNeededLI( 13044 handle, newNativeDir, Build.SUPPORTED_ABIS[abi]); 13045 } 13046 } catch (IOException ioe) { 13047 Slog.w(TAG, "Unable to extract native libs for package :" 13048 + mp.packageName, ioe); 13049 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 13050 } finally { 13051 IoUtils.closeQuietly(handle); 13052 } 13053 } 13054 13055 final int[] users = sUserManager.getUserIds(); 13056 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13057 for (int user : users) { 13058 // TODO(multiArch): Fix this so that it links to the 13059 // correct directory. We're currently pointing to root. but we 13060 // must point to the arch specific subdirectory (if applicable). 13061 // 13062 // TODO(multiArch): Bogus reference to nativeLibraryDir. 13063 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, 13064 newNativeRoot, user) < 0) { 13065 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 13066 } 13067 } 13068 } 13069 13070 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13071 pkg.codePath = newCodePath; 13072 pkg.baseCodePath = newCodePath; 13073 // Move dex files around 13074 if (moveDexFilesLI(oldCodePath, pkg) != PackageManager.INSTALL_SUCCEEDED) { 13075 // Moving of dex files failed. Set 13076 // error code and abort move. 13077 pkg.codePath = oldCodePath; 13078 pkg.baseCodePath = oldCodePath; 13079 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 13080 } 13081 } 13082 13083 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13084 pkg.applicationInfo.setCodePath(newCodePath); 13085 pkg.applicationInfo.setBaseCodePath(newCodePath); 13086 pkg.applicationInfo.setSplitCodePaths(null); 13087 pkg.applicationInfo.setResourcePath(newResPath); 13088 pkg.applicationInfo.setBaseResourcePath(newResPath); 13089 pkg.applicationInfo.setSplitResourcePaths(null); 13090 13091 PackageSetting ps = (PackageSetting) pkg.mExtras; 13092 ps.codePath = new File(pkg.applicationInfo.getCodePath()); 13093 ps.codePathString = ps.codePath.getPath(); 13094 ps.resourcePath = new File(pkg.applicationInfo.getResourcePath()); 13095 ps.resourcePathString = ps.resourcePath.getPath(); 13096 13097 // Note that we don't have to recalculate the primary and secondary 13098 // CPU ABIs because they must already have been calculated during the 13099 // initial install of the app. 13100 ps.legacyNativeLibraryPathString = null; 13101 13102 // Set the application info flag 13103 // correctly. 13104 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) { 13105 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE; 13106 } else { 13107 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE; 13108 } 13109 ps.setFlags(pkg.applicationInfo.flags); 13110 mAppDirs.remove(oldCodePath); 13111 mAppDirs.put(newCodePath, pkg); 13112 // Persist settings 13113 mSettings.writeLPr(); 13114 } 13115 } 13116 } 13117 } 13118 // Send resources available broadcast 13119 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 13120 } 13121 } 13122 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 13123 // Clean up failed installation 13124 if (mp.targetArgs != null) { 13125 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR, 13126 -1); 13127 } 13128 } else { 13129 // Force a gc to clear things up. 13130 Runtime.getRuntime().gc(); 13131 // Delete older code 13132 synchronized (mInstallLock) { 13133 mp.srcArgs.doPostDeleteLI(true); 13134 } 13135 } 13136 13137 // Allow more operations on this file if we didn't fail because 13138 // an operation was already pending for this package. 13139 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) { 13140 synchronized (mPackages) { 13141 PackageParser.Package pkg = mPackages.get(mp.packageName); 13142 if (pkg != null) { 13143 pkg.mOperationPending = false; 13144 } 13145 } 13146 } 13147 13148 IPackageMoveObserver observer = mp.observer; 13149 if (observer != null) { 13150 try { 13151 observer.packageMoved(mp.packageName, returnCode); 13152 } catch (RemoteException e) { 13153 Log.i(TAG, "Observer no longer exists."); 13154 } 13155 } 13156 } 13157 }); 13158 } 13159 13160 @Override 13161 public boolean setInstallLocation(int loc) { 13162 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 13163 null); 13164 if (getInstallLocation() == loc) { 13165 return true; 13166 } 13167 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 13168 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 13169 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 13170 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 13171 return true; 13172 } 13173 return false; 13174 } 13175 13176 @Override 13177 public int getInstallLocation() { 13178 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13179 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 13180 PackageHelper.APP_INSTALL_AUTO); 13181 } 13182 13183 /** Called by UserManagerService */ 13184 void cleanUpUserLILPw(int userHandle) { 13185 mDirtyUsers.remove(userHandle); 13186 mSettings.removeUserLPw(userHandle); 13187 mPendingBroadcasts.remove(userHandle); 13188 if (mInstaller != null) { 13189 // Technically, we shouldn't be doing this with the package lock 13190 // held. However, this is very rare, and there is already so much 13191 // other disk I/O going on, that we'll let it slide for now. 13192 mInstaller.removeUserDataDirs(userHandle); 13193 } 13194 mUserNeedsBadging.delete(userHandle); 13195 } 13196 13197 /** Called by UserManagerService */ 13198 void createNewUserLILPw(int userHandle, File path) { 13199 if (mInstaller != null) { 13200 mInstaller.createUserConfig(userHandle); 13201 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 13202 } 13203 } 13204 13205 @Override 13206 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 13207 mContext.enforceCallingOrSelfPermission( 13208 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13209 "Only package verification agents can read the verifier device identity"); 13210 13211 synchronized (mPackages) { 13212 return mSettings.getVerifierDeviceIdentityLPw(); 13213 } 13214 } 13215 13216 @Override 13217 public void setPermissionEnforced(String permission, boolean enforced) { 13218 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 13219 if (READ_EXTERNAL_STORAGE.equals(permission)) { 13220 synchronized (mPackages) { 13221 if (mSettings.mReadExternalStorageEnforced == null 13222 || mSettings.mReadExternalStorageEnforced != enforced) { 13223 mSettings.mReadExternalStorageEnforced = enforced; 13224 mSettings.writeLPr(); 13225 } 13226 } 13227 // kill any non-foreground processes so we restart them and 13228 // grant/revoke the GID. 13229 final IActivityManager am = ActivityManagerNative.getDefault(); 13230 if (am != null) { 13231 final long token = Binder.clearCallingIdentity(); 13232 try { 13233 am.killProcessesBelowForeground("setPermissionEnforcement"); 13234 } catch (RemoteException e) { 13235 } finally { 13236 Binder.restoreCallingIdentity(token); 13237 } 13238 } 13239 } else { 13240 throw new IllegalArgumentException("No selective enforcement for " + permission); 13241 } 13242 } 13243 13244 @Override 13245 @Deprecated 13246 public boolean isPermissionEnforced(String permission) { 13247 return true; 13248 } 13249 13250 @Override 13251 public boolean isStorageLow() { 13252 final long token = Binder.clearCallingIdentity(); 13253 try { 13254 final DeviceStorageMonitorInternal 13255 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13256 if (dsm != null) { 13257 return dsm.isMemoryLow(); 13258 } else { 13259 return false; 13260 } 13261 } finally { 13262 Binder.restoreCallingIdentity(token); 13263 } 13264 } 13265 13266 @Override 13267 public IPackageInstaller getPackageInstaller() { 13268 return mInstallerService; 13269 } 13270 13271 private boolean userNeedsBadging(int userId) { 13272 int index = mUserNeedsBadging.indexOfKey(userId); 13273 if (index < 0) { 13274 final UserInfo userInfo; 13275 final long token = Binder.clearCallingIdentity(); 13276 try { 13277 userInfo = sUserManager.getUserInfo(userId); 13278 } finally { 13279 Binder.restoreCallingIdentity(token); 13280 } 13281 final boolean b; 13282 if (userInfo != null && userInfo.isManagedProfile()) { 13283 b = true; 13284 } else { 13285 b = false; 13286 } 13287 mUserNeedsBadging.put(userId, b); 13288 return b; 13289 } 13290 return mUserNeedsBadging.valueAt(index); 13291 } 13292 13293 @Override 13294 public KeySetHandle getKeySetByAlias(String packageName, String alias) { 13295 if (packageName == null || alias == null) { 13296 return null; 13297 } 13298 synchronized(mPackages) { 13299 final PackageParser.Package pkg = mPackages.get(packageName); 13300 if (pkg == null) { 13301 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13302 throw new IllegalArgumentException("Unknown package: " + packageName); 13303 } 13304 if (pkg.applicationInfo.uid != Binder.getCallingUid() 13305 && Process.SYSTEM_UID != Binder.getCallingUid()) { 13306 throw new SecurityException("May not access KeySets defined by" 13307 + " aliases in other applications."); 13308 } 13309 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13310 return ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias); 13311 } 13312 } 13313 13314 @Override 13315 public KeySetHandle getSigningKeySet(String packageName) { 13316 if (packageName == null) { 13317 return null; 13318 } 13319 synchronized(mPackages) { 13320 final PackageParser.Package pkg = mPackages.get(packageName); 13321 if (pkg == null) { 13322 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13323 throw new IllegalArgumentException("Unknown package: " + packageName); 13324 } 13325 if (pkg.applicationInfo.uid != Binder.getCallingUid() 13326 && Process.SYSTEM_UID != Binder.getCallingUid()) { 13327 throw new SecurityException("May not access signing KeySet of other apps."); 13328 } 13329 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13330 return ksms.getSigningKeySetByPackageNameLPr(packageName); 13331 } 13332 } 13333 13334 @Override 13335 public boolean isPackageSignedByKeySet(String packageName, IBinder ks) { 13336 if (packageName == null || ks == null) { 13337 return false; 13338 } 13339 synchronized(mPackages) { 13340 final PackageParser.Package pkg = mPackages.get(packageName); 13341 if (pkg == null) { 13342 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13343 throw new IllegalArgumentException("Unknown package: " + packageName); 13344 } 13345 if (ks instanceof KeySetHandle) { 13346 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13347 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ks); 13348 } 13349 return false; 13350 } 13351 } 13352 13353 @Override 13354 public boolean isPackageSignedByKeySetExactly(String packageName, IBinder ks) { 13355 if (packageName == null || ks == null) { 13356 return false; 13357 } 13358 synchronized(mPackages) { 13359 final PackageParser.Package pkg = mPackages.get(packageName); 13360 if (pkg == null) { 13361 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13362 throw new IllegalArgumentException("Unknown package: " + packageName); 13363 } 13364 if (ks instanceof KeySetHandle) { 13365 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13366 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ks); 13367 } 13368 return false; 13369 } 13370 } 13371} 13372