PackageManagerService.java revision e107c3eb79be40f1071c4370fd9a3f9e4fd6d6de
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS; 20import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 21import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 26import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 27import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 28import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 29import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 30import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 32import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 33import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 34import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 36import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 37import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 38import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 39import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 41import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 42import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 44import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 45import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 46import static android.content.pm.PackageParser.isApkFile; 47import static android.os.Process.PACKAGE_INFO_GID; 48import static android.os.Process.SYSTEM_UID; 49import static android.system.OsConstants.O_CREAT; 50import static android.system.OsConstants.O_RDWR; 51import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 52import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 53import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 54import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 55import static com.android.internal.util.ArrayUtils.appendInt; 56import static com.android.internal.util.ArrayUtils.removeInt; 57 58import android.util.ArrayMap; 59 60import com.android.internal.R; 61import com.android.internal.app.IMediaContainerService; 62import com.android.internal.app.ResolverActivity; 63import com.android.internal.content.NativeLibraryHelper; 64import com.android.internal.content.PackageHelper; 65import com.android.internal.os.IParcelFileDescriptorFactory; 66import com.android.internal.util.ArrayUtils; 67import com.android.internal.util.FastPrintWriter; 68import com.android.internal.util.FastXmlSerializer; 69import com.android.internal.util.IndentingPrintWriter; 70import com.android.server.EventLogTags; 71import com.android.server.IntentResolver; 72import com.android.server.LocalServices; 73import com.android.server.ServiceThread; 74import com.android.server.SystemConfig; 75import com.android.server.Watchdog; 76import com.android.server.pm.Settings.DatabaseVersion; 77import com.android.server.storage.DeviceStorageMonitorInternal; 78 79import org.xmlpull.v1.XmlSerializer; 80 81import android.app.ActivityManager; 82import android.app.ActivityManagerNative; 83import android.app.IActivityManager; 84import android.app.admin.IDevicePolicyManager; 85import android.app.backup.IBackupManager; 86import android.content.BroadcastReceiver; 87import android.content.ComponentName; 88import android.content.Context; 89import android.content.IIntentReceiver; 90import android.content.Intent; 91import android.content.IntentFilter; 92import android.content.IntentSender; 93import android.content.IntentSender.SendIntentException; 94import android.content.ServiceConnection; 95import android.content.pm.ActivityInfo; 96import android.content.pm.ApplicationInfo; 97import android.content.pm.FeatureInfo; 98import android.content.pm.IPackageDataObserver; 99import android.content.pm.IPackageDeleteObserver; 100import android.content.pm.IPackageDeleteObserver2; 101import android.content.pm.IPackageInstallObserver2; 102import android.content.pm.IPackageInstaller; 103import android.content.pm.IPackageManager; 104import android.content.pm.IPackageMoveObserver; 105import android.content.pm.IPackageStatsObserver; 106import android.content.pm.InstrumentationInfo; 107import android.content.pm.KeySet; 108import android.content.pm.ManifestDigest; 109import android.content.pm.PackageCleanItem; 110import android.content.pm.PackageInfo; 111import android.content.pm.PackageInfoLite; 112import android.content.pm.PackageInstaller; 113import android.content.pm.PackageManager; 114import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 115import android.content.pm.PackageParser.ActivityIntentInfo; 116import android.content.pm.PackageParser.PackageLite; 117import android.content.pm.PackageParser.PackageParserException; 118import android.content.pm.PackageParser; 119import android.content.pm.PackageStats; 120import android.content.pm.PackageUserState; 121import android.content.pm.ParceledListSlice; 122import android.content.pm.PermissionGroupInfo; 123import android.content.pm.PermissionInfo; 124import android.content.pm.ProviderInfo; 125import android.content.pm.ResolveInfo; 126import android.content.pm.ServiceInfo; 127import android.content.pm.Signature; 128import android.content.pm.UserInfo; 129import android.content.pm.VerificationParams; 130import android.content.pm.VerifierDeviceIdentity; 131import android.content.pm.VerifierInfo; 132import android.content.res.Resources; 133import android.hardware.display.DisplayManager; 134import android.net.Uri; 135import android.os.Binder; 136import android.os.Build; 137import android.os.Bundle; 138import android.os.Environment; 139import android.os.Environment.UserEnvironment; 140import android.os.storage.StorageManager; 141import android.os.FileUtils; 142import android.os.Handler; 143import android.os.IBinder; 144import android.os.Looper; 145import android.os.Message; 146import android.os.Parcel; 147import android.os.ParcelFileDescriptor; 148import android.os.Process; 149import android.os.RemoteException; 150import android.os.SELinux; 151import android.os.ServiceManager; 152import android.os.SystemClock; 153import android.os.SystemProperties; 154import android.os.UserHandle; 155import android.os.UserManager; 156import android.security.KeyStore; 157import android.security.SystemKeyStore; 158import android.system.ErrnoException; 159import android.system.Os; 160import android.system.StructStat; 161import android.text.TextUtils; 162import android.util.ArraySet; 163import android.util.AtomicFile; 164import android.util.DisplayMetrics; 165import android.util.EventLog; 166import android.util.ExceptionUtils; 167import android.util.Log; 168import android.util.LogPrinter; 169import android.util.PrintStreamPrinter; 170import android.util.Slog; 171import android.util.SparseArray; 172import android.util.SparseBooleanArray; 173import android.view.Display; 174 175import java.io.BufferedInputStream; 176import java.io.BufferedOutputStream; 177import java.io.File; 178import java.io.FileDescriptor; 179import java.io.FileInputStream; 180import java.io.FileNotFoundException; 181import java.io.FileOutputStream; 182import java.io.FilenameFilter; 183import java.io.IOException; 184import java.io.InputStream; 185import java.io.PrintWriter; 186import java.nio.charset.StandardCharsets; 187import java.security.NoSuchAlgorithmException; 188import java.security.PublicKey; 189import java.security.cert.CertificateEncodingException; 190import java.security.cert.CertificateException; 191import java.text.SimpleDateFormat; 192import java.util.ArrayList; 193import java.util.Arrays; 194import java.util.Collection; 195import java.util.Collections; 196import java.util.Comparator; 197import java.util.Date; 198import java.util.HashMap; 199import java.util.HashSet; 200import java.util.Iterator; 201import java.util.List; 202import java.util.Map; 203import java.util.Set; 204import java.util.concurrent.atomic.AtomicBoolean; 205import java.util.concurrent.atomic.AtomicLong; 206 207import dalvik.system.DexFile; 208import dalvik.system.StaleDexCacheError; 209import dalvik.system.VMRuntime; 210 211import libcore.io.IoUtils; 212import libcore.util.EmptyArray; 213 214/** 215 * Keep track of all those .apks everywhere. 216 * 217 * This is very central to the platform's security; please run the unit 218 * tests whenever making modifications here: 219 * 220mmm frameworks/base/tests/AndroidTests 221adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 222adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 223 * 224 * {@hide} 225 */ 226public class PackageManagerService extends IPackageManager.Stub { 227 static final String TAG = "PackageManager"; 228 static final boolean DEBUG_SETTINGS = false; 229 static final boolean DEBUG_PREFERRED = false; 230 static final boolean DEBUG_UPGRADE = false; 231 private static final boolean DEBUG_INSTALL = false; 232 private static final boolean DEBUG_REMOVE = false; 233 private static final boolean DEBUG_BROADCASTS = false; 234 private static final boolean DEBUG_SHOW_INFO = false; 235 private static final boolean DEBUG_PACKAGE_INFO = false; 236 private static final boolean DEBUG_INTENT_MATCHING = false; 237 private static final boolean DEBUG_PACKAGE_SCANNING = false; 238 private static final boolean DEBUG_VERIFY = false; 239 private static final boolean DEBUG_DEXOPT = false; 240 private static final boolean DEBUG_ABI_SELECTION = false; 241 242 private static final int RADIO_UID = Process.PHONE_UID; 243 private static final int LOG_UID = Process.LOG_UID; 244 private static final int NFC_UID = Process.NFC_UID; 245 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 246 private static final int SHELL_UID = Process.SHELL_UID; 247 248 // Cap the size of permission trees that 3rd party apps can define 249 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 250 251 // Suffix used during package installation when copying/moving 252 // package apks to install directory. 253 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 254 255 static final int SCAN_NO_DEX = 1<<1; 256 static final int SCAN_FORCE_DEX = 1<<2; 257 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 258 static final int SCAN_NEW_INSTALL = 1<<4; 259 static final int SCAN_NO_PATHS = 1<<5; 260 static final int SCAN_UPDATE_TIME = 1<<6; 261 static final int SCAN_DEFER_DEX = 1<<7; 262 static final int SCAN_BOOTING = 1<<8; 263 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 264 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 265 static final int SCAN_REPLACING = 1<<11; 266 267 static final int REMOVE_CHATTY = 1<<16; 268 269 /** 270 * Timeout (in milliseconds) after which the watchdog should declare that 271 * our handler thread is wedged. The usual default for such things is one 272 * minute but we sometimes do very lengthy I/O operations on this thread, 273 * such as installing multi-gigabyte applications, so ours needs to be longer. 274 */ 275 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 276 277 /** 278 * Whether verification is enabled by default. 279 */ 280 private static final boolean DEFAULT_VERIFY_ENABLE = true; 281 282 /** 283 * The default maximum time to wait for the verification agent to return in 284 * milliseconds. 285 */ 286 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 287 288 /** 289 * The default response for package verification timeout. 290 * 291 * This can be either PackageManager.VERIFICATION_ALLOW or 292 * PackageManager.VERIFICATION_REJECT. 293 */ 294 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 295 296 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 297 298 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 299 DEFAULT_CONTAINER_PACKAGE, 300 "com.android.defcontainer.DefaultContainerService"); 301 302 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 303 304 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 305 306 private static String sPreferredInstructionSet; 307 308 final ServiceThread mHandlerThread; 309 310 private static final String IDMAP_PREFIX = "/data/resource-cache/"; 311 private static final String IDMAP_SUFFIX = "@idmap"; 312 313 final PackageHandler mHandler; 314 315 /** 316 * Messages for {@link #mHandler} that need to wait for system ready before 317 * being dispatched. 318 */ 319 private ArrayList<Message> mPostSystemReadyMessages; 320 321 final int mSdkVersion = Build.VERSION.SDK_INT; 322 323 final Context mContext; 324 final boolean mFactoryTest; 325 final boolean mOnlyCore; 326 final boolean mLazyDexOpt; 327 final DisplayMetrics mMetrics; 328 final int mDefParseFlags; 329 final String[] mSeparateProcesses; 330 331 // This is where all application persistent data goes. 332 final File mAppDataDir; 333 334 // This is where all application persistent data goes for secondary users. 335 final File mUserAppDataDir; 336 337 /** The location for ASEC container files on internal storage. */ 338 final String mAsecInternalPath; 339 340 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 341 // LOCK HELD. Can be called with mInstallLock held. 342 final Installer mInstaller; 343 344 /** Directory where installed third-party apps stored */ 345 final File mAppInstallDir; 346 347 /** 348 * Directory to which applications installed internally have their 349 * 32 bit native libraries copied. 350 */ 351 private File mAppLib32InstallDir; 352 353 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 354 // apps. 355 final File mDrmAppPrivateInstallDir; 356 357 // ---------------------------------------------------------------- 358 359 // Lock for state used when installing and doing other long running 360 // operations. Methods that must be called with this lock held have 361 // the suffix "LI". 362 final Object mInstallLock = new Object(); 363 364 // ---------------------------------------------------------------- 365 366 // Keys are String (package name), values are Package. This also serves 367 // as the lock for the global state. Methods that must be called with 368 // this lock held have the prefix "LP". 369 final HashMap<String, PackageParser.Package> mPackages = 370 new HashMap<String, PackageParser.Package>(); 371 372 // Tracks available target package names -> overlay package paths. 373 final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays = 374 new HashMap<String, HashMap<String, PackageParser.Package>>(); 375 376 final Settings mSettings; 377 boolean mRestoredSettings; 378 379 // System configuration read by SystemConfig. 380 final int[] mGlobalGids; 381 final SparseArray<HashSet<String>> mSystemPermissions; 382 final HashMap<String, FeatureInfo> mAvailableFeatures; 383 384 // If mac_permissions.xml was found for seinfo labeling. 385 boolean mFoundPolicyFile; 386 387 // If a recursive restorecon of /data/data/<pkg> is needed. 388 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 389 390 public static final class SharedLibraryEntry { 391 public final String path; 392 public final String apk; 393 394 SharedLibraryEntry(String _path, String _apk) { 395 path = _path; 396 apk = _apk; 397 } 398 } 399 400 // Currently known shared libraries. 401 final HashMap<String, SharedLibraryEntry> mSharedLibraries = 402 new HashMap<String, SharedLibraryEntry>(); 403 404 // All available activities, for your resolving pleasure. 405 final ActivityIntentResolver mActivities = 406 new ActivityIntentResolver(); 407 408 // All available receivers, for your resolving pleasure. 409 final ActivityIntentResolver mReceivers = 410 new ActivityIntentResolver(); 411 412 // All available services, for your resolving pleasure. 413 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 414 415 // All available providers, for your resolving pleasure. 416 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 417 418 // Mapping from provider base names (first directory in content URI codePath) 419 // to the provider information. 420 final HashMap<String, PackageParser.Provider> mProvidersByAuthority = 421 new HashMap<String, PackageParser.Provider>(); 422 423 // Mapping from instrumentation class names to info about them. 424 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 425 new HashMap<ComponentName, PackageParser.Instrumentation>(); 426 427 // Mapping from permission names to info about them. 428 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups = 429 new HashMap<String, PackageParser.PermissionGroup>(); 430 431 // Packages whose data we have transfered into another package, thus 432 // should no longer exist. 433 final HashSet<String> mTransferedPackages = new HashSet<String>(); 434 435 // Broadcast actions that are only available to the system. 436 final HashSet<String> mProtectedBroadcasts = new HashSet<String>(); 437 438 /** List of packages waiting for verification. */ 439 final SparseArray<PackageVerificationState> mPendingVerification 440 = new SparseArray<PackageVerificationState>(); 441 442 /** Set of packages associated with each app op permission. */ 443 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 444 445 final PackageInstallerService mInstallerService; 446 447 HashSet<PackageParser.Package> mDeferredDexOpt = null; 448 449 // Cache of users who need badging. 450 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 451 452 /** Token for keys in mPendingVerification. */ 453 private int mPendingVerificationToken = 0; 454 455 volatile boolean mSystemReady; 456 volatile boolean mSafeMode; 457 volatile boolean mHasSystemUidErrors; 458 459 ApplicationInfo mAndroidApplication; 460 final ActivityInfo mResolveActivity = new ActivityInfo(); 461 final ResolveInfo mResolveInfo = new ResolveInfo(); 462 ComponentName mResolveComponentName; 463 PackageParser.Package mPlatformPackage; 464 ComponentName mCustomResolverComponentName; 465 466 boolean mResolverReplaced = false; 467 468 // Set of pending broadcasts for aggregating enable/disable of components. 469 static class PendingPackageBroadcasts { 470 // for each user id, a map of <package name -> components within that package> 471 final SparseArray<HashMap<String, ArrayList<String>>> mUidMap; 472 473 public PendingPackageBroadcasts() { 474 mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2); 475 } 476 477 public ArrayList<String> get(int userId, String packageName) { 478 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 479 return packages.get(packageName); 480 } 481 482 public void put(int userId, String packageName, ArrayList<String> components) { 483 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 484 packages.put(packageName, components); 485 } 486 487 public void remove(int userId, String packageName) { 488 HashMap<String, ArrayList<String>> packages = mUidMap.get(userId); 489 if (packages != null) { 490 packages.remove(packageName); 491 } 492 } 493 494 public void remove(int userId) { 495 mUidMap.remove(userId); 496 } 497 498 public int userIdCount() { 499 return mUidMap.size(); 500 } 501 502 public int userIdAt(int n) { 503 return mUidMap.keyAt(n); 504 } 505 506 public HashMap<String, ArrayList<String>> packagesForUserId(int userId) { 507 return mUidMap.get(userId); 508 } 509 510 public int size() { 511 // total number of pending broadcast entries across all userIds 512 int num = 0; 513 for (int i = 0; i< mUidMap.size(); i++) { 514 num += mUidMap.valueAt(i).size(); 515 } 516 return num; 517 } 518 519 public void clear() { 520 mUidMap.clear(); 521 } 522 523 private HashMap<String, ArrayList<String>> getOrAllocate(int userId) { 524 HashMap<String, ArrayList<String>> map = mUidMap.get(userId); 525 if (map == null) { 526 map = new HashMap<String, ArrayList<String>>(); 527 mUidMap.put(userId, map); 528 } 529 return map; 530 } 531 } 532 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 533 534 // Service Connection to remote media container service to copy 535 // package uri's from external media onto secure containers 536 // or internal storage. 537 private IMediaContainerService mContainerService = null; 538 539 static final int SEND_PENDING_BROADCAST = 1; 540 static final int MCS_BOUND = 3; 541 static final int END_COPY = 4; 542 static final int INIT_COPY = 5; 543 static final int MCS_UNBIND = 6; 544 static final int START_CLEANING_PACKAGE = 7; 545 static final int FIND_INSTALL_LOC = 8; 546 static final int POST_INSTALL = 9; 547 static final int MCS_RECONNECT = 10; 548 static final int MCS_GIVE_UP = 11; 549 static final int UPDATED_MEDIA_STATUS = 12; 550 static final int WRITE_SETTINGS = 13; 551 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 552 static final int PACKAGE_VERIFIED = 15; 553 static final int CHECK_PENDING_VERIFICATION = 16; 554 555 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 556 557 // Delay time in millisecs 558 static final int BROADCAST_DELAY = 10 * 1000; 559 560 static UserManagerService sUserManager; 561 562 // Stores a list of users whose package restrictions file needs to be updated 563 private HashSet<Integer> mDirtyUsers = new HashSet<Integer>(); 564 565 final private DefaultContainerConnection mDefContainerConn = 566 new DefaultContainerConnection(); 567 class DefaultContainerConnection implements ServiceConnection { 568 public void onServiceConnected(ComponentName name, IBinder service) { 569 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 570 IMediaContainerService imcs = 571 IMediaContainerService.Stub.asInterface(service); 572 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 573 } 574 575 public void onServiceDisconnected(ComponentName name) { 576 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 577 } 578 }; 579 580 // Recordkeeping of restore-after-install operations that are currently in flight 581 // between the Package Manager and the Backup Manager 582 class PostInstallData { 583 public InstallArgs args; 584 public PackageInstalledInfo res; 585 586 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 587 args = _a; 588 res = _r; 589 } 590 }; 591 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 592 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 593 594 private final String mRequiredVerifierPackage; 595 596 private final PackageUsage mPackageUsage = new PackageUsage(); 597 598 private class PackageUsage { 599 private static final int WRITE_INTERVAL 600 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 601 602 private final Object mFileLock = new Object(); 603 private final AtomicLong mLastWritten = new AtomicLong(0); 604 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 605 606 private boolean mIsHistoricalPackageUsageAvailable = true; 607 608 boolean isHistoricalPackageUsageAvailable() { 609 return mIsHistoricalPackageUsageAvailable; 610 } 611 612 void write(boolean force) { 613 if (force) { 614 writeInternal(); 615 return; 616 } 617 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 618 && !DEBUG_DEXOPT) { 619 return; 620 } 621 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 622 new Thread("PackageUsage_DiskWriter") { 623 @Override 624 public void run() { 625 try { 626 writeInternal(); 627 } finally { 628 mBackgroundWriteRunning.set(false); 629 } 630 } 631 }.start(); 632 } 633 } 634 635 private void writeInternal() { 636 synchronized (mPackages) { 637 synchronized (mFileLock) { 638 AtomicFile file = getFile(); 639 FileOutputStream f = null; 640 try { 641 f = file.startWrite(); 642 BufferedOutputStream out = new BufferedOutputStream(f); 643 FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID); 644 StringBuilder sb = new StringBuilder(); 645 for (PackageParser.Package pkg : mPackages.values()) { 646 if (pkg.mLastPackageUsageTimeInMills == 0) { 647 continue; 648 } 649 sb.setLength(0); 650 sb.append(pkg.packageName); 651 sb.append(' '); 652 sb.append((long)pkg.mLastPackageUsageTimeInMills); 653 sb.append('\n'); 654 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 655 } 656 out.flush(); 657 file.finishWrite(f); 658 } catch (IOException e) { 659 if (f != null) { 660 file.failWrite(f); 661 } 662 Log.e(TAG, "Failed to write package usage times", e); 663 } 664 } 665 } 666 mLastWritten.set(SystemClock.elapsedRealtime()); 667 } 668 669 void readLP() { 670 synchronized (mFileLock) { 671 AtomicFile file = getFile(); 672 BufferedInputStream in = null; 673 try { 674 in = new BufferedInputStream(file.openRead()); 675 StringBuffer sb = new StringBuffer(); 676 while (true) { 677 String packageName = readToken(in, sb, ' '); 678 if (packageName == null) { 679 break; 680 } 681 String timeInMillisString = readToken(in, sb, '\n'); 682 if (timeInMillisString == null) { 683 throw new IOException("Failed to find last usage time for package " 684 + packageName); 685 } 686 PackageParser.Package pkg = mPackages.get(packageName); 687 if (pkg == null) { 688 continue; 689 } 690 long timeInMillis; 691 try { 692 timeInMillis = Long.parseLong(timeInMillisString.toString()); 693 } catch (NumberFormatException e) { 694 throw new IOException("Failed to parse " + timeInMillisString 695 + " as a long.", e); 696 } 697 pkg.mLastPackageUsageTimeInMills = timeInMillis; 698 } 699 } catch (FileNotFoundException expected) { 700 mIsHistoricalPackageUsageAvailable = false; 701 } catch (IOException e) { 702 Log.w(TAG, "Failed to read package usage times", e); 703 } finally { 704 IoUtils.closeQuietly(in); 705 } 706 } 707 mLastWritten.set(SystemClock.elapsedRealtime()); 708 } 709 710 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 711 throws IOException { 712 sb.setLength(0); 713 while (true) { 714 int ch = in.read(); 715 if (ch == -1) { 716 if (sb.length() == 0) { 717 return null; 718 } 719 throw new IOException("Unexpected EOF"); 720 } 721 if (ch == endOfToken) { 722 return sb.toString(); 723 } 724 sb.append((char)ch); 725 } 726 } 727 728 private AtomicFile getFile() { 729 File dataDir = Environment.getDataDirectory(); 730 File systemDir = new File(dataDir, "system"); 731 File fname = new File(systemDir, "package-usage.list"); 732 return new AtomicFile(fname); 733 } 734 } 735 736 class PackageHandler extends Handler { 737 private boolean mBound = false; 738 final ArrayList<HandlerParams> mPendingInstalls = 739 new ArrayList<HandlerParams>(); 740 741 private boolean connectToService() { 742 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 743 " DefaultContainerService"); 744 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 745 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 746 if (mContext.bindServiceAsUser(service, mDefContainerConn, 747 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 748 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 749 mBound = true; 750 return true; 751 } 752 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 753 return false; 754 } 755 756 private void disconnectService() { 757 mContainerService = null; 758 mBound = false; 759 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 760 mContext.unbindService(mDefContainerConn); 761 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 762 } 763 764 PackageHandler(Looper looper) { 765 super(looper); 766 } 767 768 public void handleMessage(Message msg) { 769 try { 770 doHandleMessage(msg); 771 } finally { 772 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 773 } 774 } 775 776 void doHandleMessage(Message msg) { 777 switch (msg.what) { 778 case INIT_COPY: { 779 HandlerParams params = (HandlerParams) msg.obj; 780 int idx = mPendingInstalls.size(); 781 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 782 // If a bind was already initiated we dont really 783 // need to do anything. The pending install 784 // will be processed later on. 785 if (!mBound) { 786 // If this is the only one pending we might 787 // have to bind to the service again. 788 if (!connectToService()) { 789 Slog.e(TAG, "Failed to bind to media container service"); 790 params.serviceError(); 791 return; 792 } else { 793 // Once we bind to the service, the first 794 // pending request will be processed. 795 mPendingInstalls.add(idx, params); 796 } 797 } else { 798 mPendingInstalls.add(idx, params); 799 // Already bound to the service. Just make 800 // sure we trigger off processing the first request. 801 if (idx == 0) { 802 mHandler.sendEmptyMessage(MCS_BOUND); 803 } 804 } 805 break; 806 } 807 case MCS_BOUND: { 808 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 809 if (msg.obj != null) { 810 mContainerService = (IMediaContainerService) msg.obj; 811 } 812 if (mContainerService == null) { 813 // Something seriously wrong. Bail out 814 Slog.e(TAG, "Cannot bind to media container service"); 815 for (HandlerParams params : mPendingInstalls) { 816 // Indicate service bind error 817 params.serviceError(); 818 } 819 mPendingInstalls.clear(); 820 } else if (mPendingInstalls.size() > 0) { 821 HandlerParams params = mPendingInstalls.get(0); 822 if (params != null) { 823 if (params.startCopy()) { 824 // We are done... look for more work or to 825 // go idle. 826 if (DEBUG_SD_INSTALL) Log.i(TAG, 827 "Checking for more work or unbind..."); 828 // Delete pending install 829 if (mPendingInstalls.size() > 0) { 830 mPendingInstalls.remove(0); 831 } 832 if (mPendingInstalls.size() == 0) { 833 if (mBound) { 834 if (DEBUG_SD_INSTALL) Log.i(TAG, 835 "Posting delayed MCS_UNBIND"); 836 removeMessages(MCS_UNBIND); 837 Message ubmsg = obtainMessage(MCS_UNBIND); 838 // Unbind after a little delay, to avoid 839 // continual thrashing. 840 sendMessageDelayed(ubmsg, 10000); 841 } 842 } else { 843 // There are more pending requests in queue. 844 // Just post MCS_BOUND message to trigger processing 845 // of next pending install. 846 if (DEBUG_SD_INSTALL) Log.i(TAG, 847 "Posting MCS_BOUND for next work"); 848 mHandler.sendEmptyMessage(MCS_BOUND); 849 } 850 } 851 } 852 } else { 853 // Should never happen ideally. 854 Slog.w(TAG, "Empty queue"); 855 } 856 break; 857 } 858 case MCS_RECONNECT: { 859 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 860 if (mPendingInstalls.size() > 0) { 861 if (mBound) { 862 disconnectService(); 863 } 864 if (!connectToService()) { 865 Slog.e(TAG, "Failed to bind to media container service"); 866 for (HandlerParams params : mPendingInstalls) { 867 // Indicate service bind error 868 params.serviceError(); 869 } 870 mPendingInstalls.clear(); 871 } 872 } 873 break; 874 } 875 case MCS_UNBIND: { 876 // If there is no actual work left, then time to unbind. 877 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 878 879 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 880 if (mBound) { 881 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 882 883 disconnectService(); 884 } 885 } else if (mPendingInstalls.size() > 0) { 886 // There are more pending requests in queue. 887 // Just post MCS_BOUND message to trigger processing 888 // of next pending install. 889 mHandler.sendEmptyMessage(MCS_BOUND); 890 } 891 892 break; 893 } 894 case MCS_GIVE_UP: { 895 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 896 mPendingInstalls.remove(0); 897 break; 898 } 899 case SEND_PENDING_BROADCAST: { 900 String packages[]; 901 ArrayList<String> components[]; 902 int size = 0; 903 int uids[]; 904 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 905 synchronized (mPackages) { 906 if (mPendingBroadcasts == null) { 907 return; 908 } 909 size = mPendingBroadcasts.size(); 910 if (size <= 0) { 911 // Nothing to be done. Just return 912 return; 913 } 914 packages = new String[size]; 915 components = new ArrayList[size]; 916 uids = new int[size]; 917 int i = 0; // filling out the above arrays 918 919 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 920 int packageUserId = mPendingBroadcasts.userIdAt(n); 921 Iterator<Map.Entry<String, ArrayList<String>>> it 922 = mPendingBroadcasts.packagesForUserId(packageUserId) 923 .entrySet().iterator(); 924 while (it.hasNext() && i < size) { 925 Map.Entry<String, ArrayList<String>> ent = it.next(); 926 packages[i] = ent.getKey(); 927 components[i] = ent.getValue(); 928 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 929 uids[i] = (ps != null) 930 ? UserHandle.getUid(packageUserId, ps.appId) 931 : -1; 932 i++; 933 } 934 } 935 size = i; 936 mPendingBroadcasts.clear(); 937 } 938 // Send broadcasts 939 for (int i = 0; i < size; i++) { 940 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 941 } 942 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 943 break; 944 } 945 case START_CLEANING_PACKAGE: { 946 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 947 final String packageName = (String)msg.obj; 948 final int userId = msg.arg1; 949 final boolean andCode = msg.arg2 != 0; 950 synchronized (mPackages) { 951 if (userId == UserHandle.USER_ALL) { 952 int[] users = sUserManager.getUserIds(); 953 for (int user : users) { 954 mSettings.addPackageToCleanLPw( 955 new PackageCleanItem(user, packageName, andCode)); 956 } 957 } else { 958 mSettings.addPackageToCleanLPw( 959 new PackageCleanItem(userId, packageName, andCode)); 960 } 961 } 962 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 963 startCleaningPackages(); 964 } break; 965 case POST_INSTALL: { 966 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 967 PostInstallData data = mRunningInstalls.get(msg.arg1); 968 mRunningInstalls.delete(msg.arg1); 969 boolean deleteOld = false; 970 971 if (data != null) { 972 InstallArgs args = data.args; 973 PackageInstalledInfo res = data.res; 974 975 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 976 res.removedInfo.sendBroadcast(false, true, false); 977 Bundle extras = new Bundle(1); 978 extras.putInt(Intent.EXTRA_UID, res.uid); 979 // Determine the set of users who are adding this 980 // package for the first time vs. those who are seeing 981 // an update. 982 int[] firstUsers; 983 int[] updateUsers = new int[0]; 984 if (res.origUsers == null || res.origUsers.length == 0) { 985 firstUsers = res.newUsers; 986 } else { 987 firstUsers = new int[0]; 988 for (int i=0; i<res.newUsers.length; i++) { 989 int user = res.newUsers[i]; 990 boolean isNew = true; 991 for (int j=0; j<res.origUsers.length; j++) { 992 if (res.origUsers[j] == user) { 993 isNew = false; 994 break; 995 } 996 } 997 if (isNew) { 998 int[] newFirst = new int[firstUsers.length+1]; 999 System.arraycopy(firstUsers, 0, newFirst, 0, 1000 firstUsers.length); 1001 newFirst[firstUsers.length] = user; 1002 firstUsers = newFirst; 1003 } else { 1004 int[] newUpdate = new int[updateUsers.length+1]; 1005 System.arraycopy(updateUsers, 0, newUpdate, 0, 1006 updateUsers.length); 1007 newUpdate[updateUsers.length] = user; 1008 updateUsers = newUpdate; 1009 } 1010 } 1011 } 1012 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1013 res.pkg.applicationInfo.packageName, 1014 extras, null, null, firstUsers); 1015 final boolean update = res.removedInfo.removedPackage != null; 1016 if (update) { 1017 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1018 } 1019 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1020 res.pkg.applicationInfo.packageName, 1021 extras, null, null, updateUsers); 1022 if (update) { 1023 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1024 res.pkg.applicationInfo.packageName, 1025 extras, null, null, updateUsers); 1026 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1027 null, null, 1028 res.pkg.applicationInfo.packageName, null, updateUsers); 1029 1030 // treat asec-hosted packages like removable media on upgrade 1031 if (isForwardLocked(res.pkg) || isExternal(res.pkg)) { 1032 if (DEBUG_INSTALL) { 1033 Slog.i(TAG, "upgrading pkg " + res.pkg 1034 + " is ASEC-hosted -> AVAILABLE"); 1035 } 1036 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1037 ArrayList<String> pkgList = new ArrayList<String>(1); 1038 pkgList.add(res.pkg.applicationInfo.packageName); 1039 sendResourcesChangedBroadcast(true, true, 1040 pkgList,uidArray, null); 1041 } 1042 } 1043 if (res.removedInfo.args != null) { 1044 // Remove the replaced package's older resources safely now 1045 deleteOld = true; 1046 } 1047 1048 // Log current value of "unknown sources" setting 1049 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1050 getUnknownSourcesSettings()); 1051 } 1052 // Force a gc to clear up things 1053 Runtime.getRuntime().gc(); 1054 // We delete after a gc for applications on sdcard. 1055 if (deleteOld) { 1056 synchronized (mInstallLock) { 1057 res.removedInfo.args.doPostDeleteLI(true); 1058 } 1059 } 1060 if (args.observer != null) { 1061 try { 1062 Bundle extras = extrasForInstallResult(res); 1063 args.observer.onPackageInstalled(res.name, res.returnCode, 1064 res.returnMsg, extras); 1065 } catch (RemoteException e) { 1066 Slog.i(TAG, "Observer no longer exists."); 1067 } 1068 } 1069 } else { 1070 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1071 } 1072 } break; 1073 case UPDATED_MEDIA_STATUS: { 1074 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1075 boolean reportStatus = msg.arg1 == 1; 1076 boolean doGc = msg.arg2 == 1; 1077 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1078 if (doGc) { 1079 // Force a gc to clear up stale containers. 1080 Runtime.getRuntime().gc(); 1081 } 1082 if (msg.obj != null) { 1083 @SuppressWarnings("unchecked") 1084 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1085 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1086 // Unload containers 1087 unloadAllContainers(args); 1088 } 1089 if (reportStatus) { 1090 try { 1091 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1092 PackageHelper.getMountService().finishMediaUpdate(); 1093 } catch (RemoteException e) { 1094 Log.e(TAG, "MountService not running?"); 1095 } 1096 } 1097 } break; 1098 case WRITE_SETTINGS: { 1099 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1100 synchronized (mPackages) { 1101 removeMessages(WRITE_SETTINGS); 1102 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1103 mSettings.writeLPr(); 1104 mDirtyUsers.clear(); 1105 } 1106 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1107 } break; 1108 case WRITE_PACKAGE_RESTRICTIONS: { 1109 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1110 synchronized (mPackages) { 1111 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1112 for (int userId : mDirtyUsers) { 1113 mSettings.writePackageRestrictionsLPr(userId); 1114 } 1115 mDirtyUsers.clear(); 1116 } 1117 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1118 } break; 1119 case CHECK_PENDING_VERIFICATION: { 1120 final int verificationId = msg.arg1; 1121 final PackageVerificationState state = mPendingVerification.get(verificationId); 1122 1123 if ((state != null) && !state.timeoutExtended()) { 1124 final InstallArgs args = state.getInstallArgs(); 1125 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1126 1127 Slog.i(TAG, "Verification timed out for " + originUri); 1128 mPendingVerification.remove(verificationId); 1129 1130 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1131 1132 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1133 Slog.i(TAG, "Continuing with installation of " + originUri); 1134 state.setVerifierResponse(Binder.getCallingUid(), 1135 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1136 broadcastPackageVerified(verificationId, originUri, 1137 PackageManager.VERIFICATION_ALLOW, 1138 state.getInstallArgs().getUser()); 1139 try { 1140 ret = args.copyApk(mContainerService, true); 1141 } catch (RemoteException e) { 1142 Slog.e(TAG, "Could not contact the ContainerService"); 1143 } 1144 } else { 1145 broadcastPackageVerified(verificationId, originUri, 1146 PackageManager.VERIFICATION_REJECT, 1147 state.getInstallArgs().getUser()); 1148 } 1149 1150 processPendingInstall(args, ret); 1151 mHandler.sendEmptyMessage(MCS_UNBIND); 1152 } 1153 break; 1154 } 1155 case PACKAGE_VERIFIED: { 1156 final int verificationId = msg.arg1; 1157 1158 final PackageVerificationState state = mPendingVerification.get(verificationId); 1159 if (state == null) { 1160 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1161 break; 1162 } 1163 1164 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1165 1166 state.setVerifierResponse(response.callerUid, response.code); 1167 1168 if (state.isVerificationComplete()) { 1169 mPendingVerification.remove(verificationId); 1170 1171 final InstallArgs args = state.getInstallArgs(); 1172 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1173 1174 int ret; 1175 if (state.isInstallAllowed()) { 1176 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1177 broadcastPackageVerified(verificationId, originUri, 1178 response.code, state.getInstallArgs().getUser()); 1179 try { 1180 ret = args.copyApk(mContainerService, true); 1181 } catch (RemoteException e) { 1182 Slog.e(TAG, "Could not contact the ContainerService"); 1183 } 1184 } else { 1185 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1186 } 1187 1188 processPendingInstall(args, ret); 1189 1190 mHandler.sendEmptyMessage(MCS_UNBIND); 1191 } 1192 1193 break; 1194 } 1195 } 1196 } 1197 } 1198 1199 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1200 Bundle extras = null; 1201 switch (res.returnCode) { 1202 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1203 extras = new Bundle(); 1204 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1205 res.origPermission); 1206 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1207 res.origPackage); 1208 break; 1209 } 1210 } 1211 return extras; 1212 } 1213 1214 void scheduleWriteSettingsLocked() { 1215 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1216 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1217 } 1218 } 1219 1220 void scheduleWritePackageRestrictionsLocked(int userId) { 1221 if (!sUserManager.exists(userId)) return; 1222 mDirtyUsers.add(userId); 1223 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1224 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1225 } 1226 } 1227 1228 public static final PackageManagerService main(Context context, Installer installer, 1229 boolean factoryTest, boolean onlyCore) { 1230 PackageManagerService m = new PackageManagerService(context, installer, 1231 factoryTest, onlyCore); 1232 ServiceManager.addService("package", m); 1233 return m; 1234 } 1235 1236 static String[] splitString(String str, char sep) { 1237 int count = 1; 1238 int i = 0; 1239 while ((i=str.indexOf(sep, i)) >= 0) { 1240 count++; 1241 i++; 1242 } 1243 1244 String[] res = new String[count]; 1245 i=0; 1246 count = 0; 1247 int lastI=0; 1248 while ((i=str.indexOf(sep, i)) >= 0) { 1249 res[count] = str.substring(lastI, i); 1250 count++; 1251 i++; 1252 lastI = i; 1253 } 1254 res[count] = str.substring(lastI, str.length()); 1255 return res; 1256 } 1257 1258 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1259 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1260 Context.DISPLAY_SERVICE); 1261 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1262 } 1263 1264 public PackageManagerService(Context context, Installer installer, 1265 boolean factoryTest, boolean onlyCore) { 1266 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1267 SystemClock.uptimeMillis()); 1268 1269 if (mSdkVersion <= 0) { 1270 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1271 } 1272 1273 mContext = context; 1274 mFactoryTest = factoryTest; 1275 mOnlyCore = onlyCore; 1276 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1277 mMetrics = new DisplayMetrics(); 1278 mSettings = new Settings(context); 1279 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1280 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1281 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1282 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1283 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1284 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1285 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1286 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1287 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1288 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1289 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1290 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1291 1292 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1293 if (separateProcesses != null && separateProcesses.length() > 0) { 1294 if ("*".equals(separateProcesses)) { 1295 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1296 mSeparateProcesses = null; 1297 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1298 } else { 1299 mDefParseFlags = 0; 1300 mSeparateProcesses = separateProcesses.split(","); 1301 Slog.w(TAG, "Running with debug.separate_processes: " 1302 + separateProcesses); 1303 } 1304 } else { 1305 mDefParseFlags = 0; 1306 mSeparateProcesses = null; 1307 } 1308 1309 mInstaller = installer; 1310 1311 getDefaultDisplayMetrics(context, mMetrics); 1312 1313 SystemConfig systemConfig = SystemConfig.getInstance(); 1314 mGlobalGids = systemConfig.getGlobalGids(); 1315 mSystemPermissions = systemConfig.getSystemPermissions(); 1316 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1317 1318 synchronized (mInstallLock) { 1319 // writer 1320 synchronized (mPackages) { 1321 mHandlerThread = new ServiceThread(TAG, 1322 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1323 mHandlerThread.start(); 1324 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1325 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1326 1327 File dataDir = Environment.getDataDirectory(); 1328 mAppDataDir = new File(dataDir, "data"); 1329 mAppInstallDir = new File(dataDir, "app"); 1330 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1331 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1332 mUserAppDataDir = new File(dataDir, "user"); 1333 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1334 1335 sUserManager = new UserManagerService(context, this, 1336 mInstallLock, mPackages); 1337 1338 // Propagate permission configuration in to package manager. 1339 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1340 = systemConfig.getPermissions(); 1341 for (int i=0; i<permConfig.size(); i++) { 1342 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1343 BasePermission bp = mSettings.mPermissions.get(perm.name); 1344 if (bp == null) { 1345 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1346 mSettings.mPermissions.put(perm.name, bp); 1347 } 1348 if (perm.gids != null) { 1349 bp.gids = appendInts(bp.gids, perm.gids); 1350 } 1351 } 1352 1353 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1354 for (int i=0; i<libConfig.size(); i++) { 1355 mSharedLibraries.put(libConfig.keyAt(i), 1356 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1357 } 1358 1359 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1360 1361 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1362 mSdkVersion, mOnlyCore); 1363 1364 String customResolverActivity = Resources.getSystem().getString( 1365 R.string.config_customResolverActivity); 1366 if (TextUtils.isEmpty(customResolverActivity)) { 1367 customResolverActivity = null; 1368 } else { 1369 mCustomResolverComponentName = ComponentName.unflattenFromString( 1370 customResolverActivity); 1371 } 1372 1373 long startTime = SystemClock.uptimeMillis(); 1374 1375 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1376 startTime); 1377 1378 // Set flag to monitor and not change apk file paths when 1379 // scanning install directories. 1380 int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1381 1382 final HashSet<String> alreadyDexOpted = new HashSet<String>(); 1383 1384 /** 1385 * Add everything in the in the boot class path to the 1386 * list of process files because dexopt will have been run 1387 * if necessary during zygote startup. 1388 */ 1389 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1390 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1391 1392 if (bootClassPath != null) { 1393 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1394 for (String element : bootClassPathElements) { 1395 alreadyDexOpted.add(element); 1396 } 1397 } else { 1398 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1399 } 1400 1401 if (systemServerClassPath != null) { 1402 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1403 for (String element : systemServerClassPathElements) { 1404 alreadyDexOpted.add(element); 1405 } 1406 } else { 1407 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1408 } 1409 1410 boolean didDexOptLibraryOrTool = false; 1411 1412 final List<String> allInstructionSets = getAllInstructionSets(); 1413 final String[] dexCodeInstructionSets = 1414 getDexCodeInstructionSets(allInstructionSets.toArray(new String[allInstructionSets.size()])); 1415 1416 /** 1417 * Ensure all external libraries have had dexopt run on them. 1418 */ 1419 if (mSharedLibraries.size() > 0) { 1420 // NOTE: For now, we're compiling these system "shared libraries" 1421 // (and framework jars) into all available architectures. It's possible 1422 // to compile them only when we come across an app that uses them (there's 1423 // already logic for that in scanPackageLI) but that adds some complexity. 1424 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1425 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1426 final String lib = libEntry.path; 1427 if (lib == null) { 1428 continue; 1429 } 1430 1431 try { 1432 byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null, 1433 dexCodeInstructionSet, 1434 false); 1435 if (dexoptRequired != DexFile.UP_TO_DATE) { 1436 alreadyDexOpted.add(lib); 1437 1438 // The list of "shared libraries" we have at this point is 1439 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1440 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1441 } else { 1442 mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1443 } 1444 didDexOptLibraryOrTool = true; 1445 } 1446 } catch (FileNotFoundException e) { 1447 Slog.w(TAG, "Library not found: " + lib); 1448 } catch (IOException e) { 1449 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1450 + e.getMessage()); 1451 } 1452 } 1453 } 1454 } 1455 1456 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1457 1458 // Gross hack for now: we know this file doesn't contain any 1459 // code, so don't dexopt it to avoid the resulting log spew. 1460 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1461 1462 // Gross hack for now: we know this file is only part of 1463 // the boot class path for art, so don't dexopt it to 1464 // avoid the resulting log spew. 1465 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1466 1467 /** 1468 * And there are a number of commands implemented in Java, which 1469 * we currently need to do the dexopt on so that they can be 1470 * run from a non-root shell. 1471 */ 1472 String[] frameworkFiles = frameworkDir.list(); 1473 if (frameworkFiles != null) { 1474 // TODO: We could compile these only for the most preferred ABI. We should 1475 // first double check that the dex files for these commands are not referenced 1476 // by other system apps. 1477 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1478 for (int i=0; i<frameworkFiles.length; i++) { 1479 File libPath = new File(frameworkDir, frameworkFiles[i]); 1480 String path = libPath.getPath(); 1481 // Skip the file if we already did it. 1482 if (alreadyDexOpted.contains(path)) { 1483 continue; 1484 } 1485 // Skip the file if it is not a type we want to dexopt. 1486 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1487 continue; 1488 } 1489 try { 1490 byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null, 1491 dexCodeInstructionSet, 1492 false); 1493 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1494 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1495 didDexOptLibraryOrTool = true; 1496 } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) { 1497 mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1498 didDexOptLibraryOrTool = true; 1499 } 1500 } catch (FileNotFoundException e) { 1501 Slog.w(TAG, "Jar not found: " + path); 1502 } catch (IOException e) { 1503 Slog.w(TAG, "Exception reading jar: " + path, e); 1504 } 1505 } 1506 } 1507 } 1508 1509 // Collect vendor overlay packages. 1510 // (Do this before scanning any apps.) 1511 // For security and version matching reason, only consider 1512 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1513 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1514 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1515 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1516 1517 // Find base frameworks (resource packages without code). 1518 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1519 | PackageParser.PARSE_IS_SYSTEM_DIR 1520 | PackageParser.PARSE_IS_PRIVILEGED, 1521 scanFlags | SCAN_NO_DEX, 0); 1522 1523 // Collected privileged system packages. 1524 File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1525 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1526 | PackageParser.PARSE_IS_SYSTEM_DIR 1527 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1528 1529 // Collect ordinary system packages. 1530 File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1531 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1532 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1533 1534 // Collect all vendor packages. 1535 File vendorAppDir = new File("/vendor/app"); 1536 try { 1537 vendorAppDir = vendorAppDir.getCanonicalFile(); 1538 } catch (IOException e) { 1539 // failed to look up canonical path, continue with original one 1540 } 1541 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1542 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1543 1544 // Collect all OEM packages. 1545 File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1546 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1547 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1548 1549 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1550 mInstaller.moveFiles(); 1551 1552 // Prune any system packages that no longer exist. 1553 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1554 if (!mOnlyCore) { 1555 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1556 while (psit.hasNext()) { 1557 PackageSetting ps = psit.next(); 1558 1559 /* 1560 * If this is not a system app, it can't be a 1561 * disable system app. 1562 */ 1563 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1564 continue; 1565 } 1566 1567 /* 1568 * If the package is scanned, it's not erased. 1569 */ 1570 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1571 if (scannedPkg != null) { 1572 /* 1573 * If the system app is both scanned and in the 1574 * disabled packages list, then it must have been 1575 * added via OTA. Remove it from the currently 1576 * scanned package so the previously user-installed 1577 * application can be scanned. 1578 */ 1579 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1580 Slog.i(TAG, "Expecting better updatd system app for " + ps.name 1581 + "; removing system app"); 1582 removePackageLI(ps, true); 1583 } 1584 1585 continue; 1586 } 1587 1588 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1589 psit.remove(); 1590 String msg = "System package " + ps.name 1591 + " no longer exists; wiping its data"; 1592 reportSettingsProblem(Log.WARN, msg); 1593 removeDataDirsLI(ps.name); 1594 } else { 1595 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1596 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1597 possiblyDeletedUpdatedSystemApps.add(ps.name); 1598 } 1599 } 1600 } 1601 } 1602 1603 //look for any incomplete package installations 1604 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1605 //clean up list 1606 for(int i = 0; i < deletePkgsList.size(); i++) { 1607 //clean up here 1608 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1609 } 1610 //delete tmp files 1611 deleteTempPackageFiles(); 1612 1613 // Remove any shared userIDs that have no associated packages 1614 mSettings.pruneSharedUsersLPw(); 1615 1616 if (!mOnlyCore) { 1617 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 1618 SystemClock.uptimeMillis()); 1619 scanDirLI(mAppInstallDir, 0, scanFlags, 0); 1620 1621 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 1622 scanFlags, 0); 1623 1624 /** 1625 * Remove disable package settings for any updated system 1626 * apps that were removed via an OTA. If they're not a 1627 * previously-updated app, remove them completely. 1628 * Otherwise, just revoke their system-level permissions. 1629 */ 1630 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 1631 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 1632 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 1633 1634 String msg; 1635 if (deletedPkg == null) { 1636 msg = "Updated system package " + deletedAppName 1637 + " no longer exists; wiping its data"; 1638 removeDataDirsLI(deletedAppName); 1639 } else { 1640 msg = "Updated system app + " + deletedAppName 1641 + " no longer present; removing system privileges for " 1642 + deletedAppName; 1643 1644 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 1645 1646 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 1647 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 1648 } 1649 reportSettingsProblem(Log.WARN, msg); 1650 } 1651 } 1652 1653 // Now that we know all of the shared libraries, update all clients to have 1654 // the correct library paths. 1655 updateAllSharedLibrariesLPw(); 1656 1657 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 1658 // NOTE: We ignore potential failures here during a system scan (like 1659 // the rest of the commands above) because there's precious little we 1660 // can do about it. A settings error is reported, though. 1661 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 1662 false /* force dexopt */, false /* defer dexopt */); 1663 } 1664 1665 // Now that we know all the packages we are keeping, 1666 // read and update their last usage times. 1667 mPackageUsage.readLP(); 1668 1669 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 1670 SystemClock.uptimeMillis()); 1671 Slog.i(TAG, "Time to scan packages: " 1672 + ((SystemClock.uptimeMillis()-startTime)/1000f) 1673 + " seconds"); 1674 1675 // If the platform SDK has changed since the last time we booted, 1676 // we need to re-grant app permission to catch any new ones that 1677 // appear. This is really a hack, and means that apps can in some 1678 // cases get permissions that the user didn't initially explicitly 1679 // allow... it would be nice to have some better way to handle 1680 // this situation. 1681 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 1682 != mSdkVersion; 1683 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 1684 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 1685 + "; regranting permissions for internal storage"); 1686 mSettings.mInternalSdkPlatform = mSdkVersion; 1687 1688 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 1689 | (regrantPermissions 1690 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 1691 : 0)); 1692 1693 // If this is the first boot, and it is a normal boot, then 1694 // we need to initialize the default preferred apps. 1695 if (!mRestoredSettings && !onlyCore) { 1696 mSettings.readDefaultPreferredAppsLPw(this, 0); 1697 } 1698 1699 // If this is first boot after an OTA, and a normal boot, then 1700 // we need to clear code cache directories. 1701 if (!Build.FINGERPRINT.equals(mSettings.mFingerprint) && !onlyCore) { 1702 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 1703 for (String pkgName : mSettings.mPackages.keySet()) { 1704 deleteCodeCacheDirsLI(pkgName); 1705 } 1706 mSettings.mFingerprint = Build.FINGERPRINT; 1707 } 1708 1709 // All the changes are done during package scanning. 1710 mSettings.updateInternalDatabaseVersion(); 1711 1712 // can downgrade to reader 1713 mSettings.writeLPr(); 1714 1715 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 1716 SystemClock.uptimeMillis()); 1717 1718 1719 mRequiredVerifierPackage = getRequiredVerifierLPr(); 1720 } // synchronized (mPackages) 1721 } // synchronized (mInstallLock) 1722 1723 mInstallerService = new PackageInstallerService(context, this, mAppInstallDir); 1724 1725 // Now after opening every single application zip, make sure they 1726 // are all flushed. Not really needed, but keeps things nice and 1727 // tidy. 1728 Runtime.getRuntime().gc(); 1729 } 1730 1731 @Override 1732 public boolean isFirstBoot() { 1733 return !mRestoredSettings; 1734 } 1735 1736 @Override 1737 public boolean isOnlyCoreApps() { 1738 return mOnlyCore; 1739 } 1740 1741 private String getRequiredVerifierLPr() { 1742 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 1743 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 1744 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 1745 1746 String requiredVerifier = null; 1747 1748 final int N = receivers.size(); 1749 for (int i = 0; i < N; i++) { 1750 final ResolveInfo info = receivers.get(i); 1751 1752 if (info.activityInfo == null) { 1753 continue; 1754 } 1755 1756 final String packageName = info.activityInfo.packageName; 1757 1758 final PackageSetting ps = mSettings.mPackages.get(packageName); 1759 if (ps == null) { 1760 continue; 1761 } 1762 1763 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1764 if (!gp.grantedPermissions 1765 .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) { 1766 continue; 1767 } 1768 1769 if (requiredVerifier != null) { 1770 throw new RuntimeException("There can be only one required verifier"); 1771 } 1772 1773 requiredVerifier = packageName; 1774 } 1775 1776 return requiredVerifier; 1777 } 1778 1779 @Override 1780 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 1781 throws RemoteException { 1782 try { 1783 return super.onTransact(code, data, reply, flags); 1784 } catch (RuntimeException e) { 1785 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 1786 Slog.wtf(TAG, "Package Manager Crash", e); 1787 } 1788 throw e; 1789 } 1790 } 1791 1792 void cleanupInstallFailedPackage(PackageSetting ps) { 1793 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name); 1794 removeDataDirsLI(ps.name); 1795 1796 // TODO: try cleaning up codePath directory contents first, since it 1797 // might be a cluster 1798 1799 if (ps.codePath != null) { 1800 if (!ps.codePath.delete()) { 1801 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath); 1802 } 1803 } 1804 if (ps.resourcePath != null) { 1805 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) { 1806 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath); 1807 } 1808 } 1809 mSettings.removePackageLPw(ps.name); 1810 } 1811 1812 static int[] appendInts(int[] cur, int[] add) { 1813 if (add == null) return cur; 1814 if (cur == null) return add; 1815 final int N = add.length; 1816 for (int i=0; i<N; i++) { 1817 cur = appendInt(cur, add[i]); 1818 } 1819 return cur; 1820 } 1821 1822 static int[] removeInts(int[] cur, int[] rem) { 1823 if (rem == null) return cur; 1824 if (cur == null) return cur; 1825 final int N = rem.length; 1826 for (int i=0; i<N; i++) { 1827 cur = removeInt(cur, rem[i]); 1828 } 1829 return cur; 1830 } 1831 1832 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 1833 if (!sUserManager.exists(userId)) return null; 1834 final PackageSetting ps = (PackageSetting) p.mExtras; 1835 if (ps == null) { 1836 return null; 1837 } 1838 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1839 final PackageUserState state = ps.readUserState(userId); 1840 return PackageParser.generatePackageInfo(p, gp.gids, flags, 1841 ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions, 1842 state, userId); 1843 } 1844 1845 @Override 1846 public boolean isPackageAvailable(String packageName, int userId) { 1847 if (!sUserManager.exists(userId)) return false; 1848 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available"); 1849 synchronized (mPackages) { 1850 PackageParser.Package p = mPackages.get(packageName); 1851 if (p != null) { 1852 final PackageSetting ps = (PackageSetting) p.mExtras; 1853 if (ps != null) { 1854 final PackageUserState state = ps.readUserState(userId); 1855 if (state != null) { 1856 return PackageParser.isAvailable(state); 1857 } 1858 } 1859 } 1860 } 1861 return false; 1862 } 1863 1864 @Override 1865 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 1866 if (!sUserManager.exists(userId)) return null; 1867 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info"); 1868 // reader 1869 synchronized (mPackages) { 1870 PackageParser.Package p = mPackages.get(packageName); 1871 if (DEBUG_PACKAGE_INFO) 1872 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 1873 if (p != null) { 1874 return generatePackageInfo(p, flags, userId); 1875 } 1876 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 1877 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 1878 } 1879 } 1880 return null; 1881 } 1882 1883 @Override 1884 public String[] currentToCanonicalPackageNames(String[] names) { 1885 String[] out = new String[names.length]; 1886 // reader 1887 synchronized (mPackages) { 1888 for (int i=names.length-1; i>=0; i--) { 1889 PackageSetting ps = mSettings.mPackages.get(names[i]); 1890 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 1891 } 1892 } 1893 return out; 1894 } 1895 1896 @Override 1897 public String[] canonicalToCurrentPackageNames(String[] names) { 1898 String[] out = new String[names.length]; 1899 // reader 1900 synchronized (mPackages) { 1901 for (int i=names.length-1; i>=0; i--) { 1902 String cur = mSettings.mRenamedPackages.get(names[i]); 1903 out[i] = cur != null ? cur : names[i]; 1904 } 1905 } 1906 return out; 1907 } 1908 1909 @Override 1910 public int getPackageUid(String packageName, int userId) { 1911 if (!sUserManager.exists(userId)) return -1; 1912 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid"); 1913 // reader 1914 synchronized (mPackages) { 1915 PackageParser.Package p = mPackages.get(packageName); 1916 if(p != null) { 1917 return UserHandle.getUid(userId, p.applicationInfo.uid); 1918 } 1919 PackageSetting ps = mSettings.mPackages.get(packageName); 1920 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 1921 return -1; 1922 } 1923 p = ps.pkg; 1924 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 1925 } 1926 } 1927 1928 @Override 1929 public int[] getPackageGids(String packageName) { 1930 // reader 1931 synchronized (mPackages) { 1932 PackageParser.Package p = mPackages.get(packageName); 1933 if (DEBUG_PACKAGE_INFO) 1934 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 1935 if (p != null) { 1936 final PackageSetting ps = (PackageSetting)p.mExtras; 1937 return ps.getGids(); 1938 } 1939 } 1940 // stupid thing to indicate an error. 1941 return new int[0]; 1942 } 1943 1944 static final PermissionInfo generatePermissionInfo( 1945 BasePermission bp, int flags) { 1946 if (bp.perm != null) { 1947 return PackageParser.generatePermissionInfo(bp.perm, flags); 1948 } 1949 PermissionInfo pi = new PermissionInfo(); 1950 pi.name = bp.name; 1951 pi.packageName = bp.sourcePackage; 1952 pi.nonLocalizedLabel = bp.name; 1953 pi.protectionLevel = bp.protectionLevel; 1954 return pi; 1955 } 1956 1957 @Override 1958 public PermissionInfo getPermissionInfo(String name, int flags) { 1959 // reader 1960 synchronized (mPackages) { 1961 final BasePermission p = mSettings.mPermissions.get(name); 1962 if (p != null) { 1963 return generatePermissionInfo(p, flags); 1964 } 1965 return null; 1966 } 1967 } 1968 1969 @Override 1970 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 1971 // reader 1972 synchronized (mPackages) { 1973 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 1974 for (BasePermission p : mSettings.mPermissions.values()) { 1975 if (group == null) { 1976 if (p.perm == null || p.perm.info.group == null) { 1977 out.add(generatePermissionInfo(p, flags)); 1978 } 1979 } else { 1980 if (p.perm != null && group.equals(p.perm.info.group)) { 1981 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 1982 } 1983 } 1984 } 1985 1986 if (out.size() > 0) { 1987 return out; 1988 } 1989 return mPermissionGroups.containsKey(group) ? out : null; 1990 } 1991 } 1992 1993 @Override 1994 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 1995 // reader 1996 synchronized (mPackages) { 1997 return PackageParser.generatePermissionGroupInfo( 1998 mPermissionGroups.get(name), flags); 1999 } 2000 } 2001 2002 @Override 2003 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2004 // reader 2005 synchronized (mPackages) { 2006 final int N = mPermissionGroups.size(); 2007 ArrayList<PermissionGroupInfo> out 2008 = new ArrayList<PermissionGroupInfo>(N); 2009 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2010 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2011 } 2012 return out; 2013 } 2014 } 2015 2016 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2017 int userId) { 2018 if (!sUserManager.exists(userId)) return null; 2019 PackageSetting ps = mSettings.mPackages.get(packageName); 2020 if (ps != null) { 2021 if (ps.pkg == null) { 2022 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2023 flags, userId); 2024 if (pInfo != null) { 2025 return pInfo.applicationInfo; 2026 } 2027 return null; 2028 } 2029 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2030 ps.readUserState(userId), userId); 2031 } 2032 return null; 2033 } 2034 2035 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2036 int userId) { 2037 if (!sUserManager.exists(userId)) return null; 2038 PackageSetting ps = mSettings.mPackages.get(packageName); 2039 if (ps != null) { 2040 PackageParser.Package pkg = ps.pkg; 2041 if (pkg == null) { 2042 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2043 return null; 2044 } 2045 // Only data remains, so we aren't worried about code paths 2046 pkg = new PackageParser.Package(packageName); 2047 pkg.applicationInfo.packageName = packageName; 2048 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2049 pkg.applicationInfo.dataDir = 2050 getDataPathForPackage(packageName, 0).getPath(); 2051 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2052 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2053 } 2054 return generatePackageInfo(pkg, flags, userId); 2055 } 2056 return null; 2057 } 2058 2059 @Override 2060 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2061 if (!sUserManager.exists(userId)) return null; 2062 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info"); 2063 // writer 2064 synchronized (mPackages) { 2065 PackageParser.Package p = mPackages.get(packageName); 2066 if (DEBUG_PACKAGE_INFO) Log.v( 2067 TAG, "getApplicationInfo " + packageName 2068 + ": " + p); 2069 if (p != null) { 2070 PackageSetting ps = mSettings.mPackages.get(packageName); 2071 if (ps == null) return null; 2072 // Note: isEnabledLP() does not apply here - always return info 2073 return PackageParser.generateApplicationInfo( 2074 p, flags, ps.readUserState(userId), userId); 2075 } 2076 if ("android".equals(packageName)||"system".equals(packageName)) { 2077 return mAndroidApplication; 2078 } 2079 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2080 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2081 } 2082 } 2083 return null; 2084 } 2085 2086 2087 @Override 2088 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2089 mContext.enforceCallingOrSelfPermission( 2090 android.Manifest.permission.CLEAR_APP_CACHE, null); 2091 // Queue up an async operation since clearing cache may take a little while. 2092 mHandler.post(new Runnable() { 2093 public void run() { 2094 mHandler.removeCallbacks(this); 2095 int retCode = -1; 2096 synchronized (mInstallLock) { 2097 retCode = mInstaller.freeCache(freeStorageSize); 2098 if (retCode < 0) { 2099 Slog.w(TAG, "Couldn't clear application caches"); 2100 } 2101 } 2102 if (observer != null) { 2103 try { 2104 observer.onRemoveCompleted(null, (retCode >= 0)); 2105 } catch (RemoteException e) { 2106 Slog.w(TAG, "RemoveException when invoking call back"); 2107 } 2108 } 2109 } 2110 }); 2111 } 2112 2113 @Override 2114 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2115 mContext.enforceCallingOrSelfPermission( 2116 android.Manifest.permission.CLEAR_APP_CACHE, null); 2117 // Queue up an async operation since clearing cache may take a little while. 2118 mHandler.post(new Runnable() { 2119 public void run() { 2120 mHandler.removeCallbacks(this); 2121 int retCode = -1; 2122 synchronized (mInstallLock) { 2123 retCode = mInstaller.freeCache(freeStorageSize); 2124 if (retCode < 0) { 2125 Slog.w(TAG, "Couldn't clear application caches"); 2126 } 2127 } 2128 if(pi != null) { 2129 try { 2130 // Callback via pending intent 2131 int code = (retCode >= 0) ? 1 : 0; 2132 pi.sendIntent(null, code, null, 2133 null, null); 2134 } catch (SendIntentException e1) { 2135 Slog.i(TAG, "Failed to send pending intent"); 2136 } 2137 } 2138 } 2139 }); 2140 } 2141 2142 void freeStorage(long freeStorageSize) throws IOException { 2143 synchronized (mInstallLock) { 2144 if (mInstaller.freeCache(freeStorageSize) < 0) { 2145 throw new IOException("Failed to free enough space"); 2146 } 2147 } 2148 } 2149 2150 @Override 2151 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2152 if (!sUserManager.exists(userId)) return null; 2153 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info"); 2154 synchronized (mPackages) { 2155 PackageParser.Activity a = mActivities.mActivities.get(component); 2156 2157 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2158 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2159 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2160 if (ps == null) return null; 2161 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2162 userId); 2163 } 2164 if (mResolveComponentName.equals(component)) { 2165 return mResolveActivity; 2166 } 2167 } 2168 return null; 2169 } 2170 2171 @Override 2172 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2173 String resolvedType) { 2174 synchronized (mPackages) { 2175 PackageParser.Activity a = mActivities.mActivities.get(component); 2176 if (a == null) { 2177 return false; 2178 } 2179 for (int i=0; i<a.intents.size(); i++) { 2180 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2181 intent.getData(), intent.getCategories(), TAG) >= 0) { 2182 return true; 2183 } 2184 } 2185 return false; 2186 } 2187 } 2188 2189 @Override 2190 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2191 if (!sUserManager.exists(userId)) return null; 2192 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info"); 2193 synchronized (mPackages) { 2194 PackageParser.Activity a = mReceivers.mActivities.get(component); 2195 if (DEBUG_PACKAGE_INFO) Log.v( 2196 TAG, "getReceiverInfo " + component + ": " + a); 2197 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2198 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2199 if (ps == null) return null; 2200 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2201 userId); 2202 } 2203 } 2204 return null; 2205 } 2206 2207 @Override 2208 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2209 if (!sUserManager.exists(userId)) return null; 2210 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info"); 2211 synchronized (mPackages) { 2212 PackageParser.Service s = mServices.mServices.get(component); 2213 if (DEBUG_PACKAGE_INFO) Log.v( 2214 TAG, "getServiceInfo " + component + ": " + s); 2215 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2216 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2217 if (ps == null) return null; 2218 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2219 userId); 2220 } 2221 } 2222 return null; 2223 } 2224 2225 @Override 2226 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2227 if (!sUserManager.exists(userId)) return null; 2228 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info"); 2229 synchronized (mPackages) { 2230 PackageParser.Provider p = mProviders.mProviders.get(component); 2231 if (DEBUG_PACKAGE_INFO) Log.v( 2232 TAG, "getProviderInfo " + component + ": " + p); 2233 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2234 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2235 if (ps == null) return null; 2236 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2237 userId); 2238 } 2239 } 2240 return null; 2241 } 2242 2243 @Override 2244 public String[] getSystemSharedLibraryNames() { 2245 Set<String> libSet; 2246 synchronized (mPackages) { 2247 libSet = mSharedLibraries.keySet(); 2248 int size = libSet.size(); 2249 if (size > 0) { 2250 String[] libs = new String[size]; 2251 libSet.toArray(libs); 2252 return libs; 2253 } 2254 } 2255 return null; 2256 } 2257 2258 @Override 2259 public FeatureInfo[] getSystemAvailableFeatures() { 2260 Collection<FeatureInfo> featSet; 2261 synchronized (mPackages) { 2262 featSet = mAvailableFeatures.values(); 2263 int size = featSet.size(); 2264 if (size > 0) { 2265 FeatureInfo[] features = new FeatureInfo[size+1]; 2266 featSet.toArray(features); 2267 FeatureInfo fi = new FeatureInfo(); 2268 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2269 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2270 features[size] = fi; 2271 return features; 2272 } 2273 } 2274 return null; 2275 } 2276 2277 @Override 2278 public boolean hasSystemFeature(String name) { 2279 synchronized (mPackages) { 2280 return mAvailableFeatures.containsKey(name); 2281 } 2282 } 2283 2284 private void checkValidCaller(int uid, int userId) { 2285 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2286 return; 2287 2288 throw new SecurityException("Caller uid=" + uid 2289 + " is not privileged to communicate with user=" + userId); 2290 } 2291 2292 @Override 2293 public int checkPermission(String permName, String pkgName) { 2294 synchronized (mPackages) { 2295 PackageParser.Package p = mPackages.get(pkgName); 2296 if (p != null && p.mExtras != null) { 2297 PackageSetting ps = (PackageSetting)p.mExtras; 2298 if (ps.sharedUser != null) { 2299 if (ps.sharedUser.grantedPermissions.contains(permName)) { 2300 return PackageManager.PERMISSION_GRANTED; 2301 } 2302 } else if (ps.grantedPermissions.contains(permName)) { 2303 return PackageManager.PERMISSION_GRANTED; 2304 } 2305 } 2306 } 2307 return PackageManager.PERMISSION_DENIED; 2308 } 2309 2310 @Override 2311 public int checkUidPermission(String permName, int uid) { 2312 synchronized (mPackages) { 2313 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2314 if (obj != null) { 2315 GrantedPermissions gp = (GrantedPermissions)obj; 2316 if (gp.grantedPermissions.contains(permName)) { 2317 return PackageManager.PERMISSION_GRANTED; 2318 } 2319 } else { 2320 HashSet<String> perms = mSystemPermissions.get(uid); 2321 if (perms != null && perms.contains(permName)) { 2322 return PackageManager.PERMISSION_GRANTED; 2323 } 2324 } 2325 } 2326 return PackageManager.PERMISSION_DENIED; 2327 } 2328 2329 /** 2330 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2331 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2332 * @param message the message to log on security exception 2333 */ 2334 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2335 String message) { 2336 if (userId < 0) { 2337 throw new IllegalArgumentException("Invalid userId " + userId); 2338 } 2339 if (userId == UserHandle.getUserId(callingUid)) return; 2340 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2341 if (requireFullPermission) { 2342 mContext.enforceCallingOrSelfPermission( 2343 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2344 } else { 2345 try { 2346 mContext.enforceCallingOrSelfPermission( 2347 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2348 } catch (SecurityException se) { 2349 mContext.enforceCallingOrSelfPermission( 2350 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2351 } 2352 } 2353 } 2354 } 2355 2356 private BasePermission findPermissionTreeLP(String permName) { 2357 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2358 if (permName.startsWith(bp.name) && 2359 permName.length() > bp.name.length() && 2360 permName.charAt(bp.name.length()) == '.') { 2361 return bp; 2362 } 2363 } 2364 return null; 2365 } 2366 2367 private BasePermission checkPermissionTreeLP(String permName) { 2368 if (permName != null) { 2369 BasePermission bp = findPermissionTreeLP(permName); 2370 if (bp != null) { 2371 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2372 return bp; 2373 } 2374 throw new SecurityException("Calling uid " 2375 + Binder.getCallingUid() 2376 + " is not allowed to add to permission tree " 2377 + bp.name + " owned by uid " + bp.uid); 2378 } 2379 } 2380 throw new SecurityException("No permission tree found for " + permName); 2381 } 2382 2383 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2384 if (s1 == null) { 2385 return s2 == null; 2386 } 2387 if (s2 == null) { 2388 return false; 2389 } 2390 if (s1.getClass() != s2.getClass()) { 2391 return false; 2392 } 2393 return s1.equals(s2); 2394 } 2395 2396 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2397 if (pi1.icon != pi2.icon) return false; 2398 if (pi1.logo != pi2.logo) return false; 2399 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2400 if (!compareStrings(pi1.name, pi2.name)) return false; 2401 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2402 // We'll take care of setting this one. 2403 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2404 // These are not currently stored in settings. 2405 //if (!compareStrings(pi1.group, pi2.group)) return false; 2406 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2407 //if (pi1.labelRes != pi2.labelRes) return false; 2408 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2409 return true; 2410 } 2411 2412 int permissionInfoFootprint(PermissionInfo info) { 2413 int size = info.name.length(); 2414 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2415 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2416 return size; 2417 } 2418 2419 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2420 int size = 0; 2421 for (BasePermission perm : mSettings.mPermissions.values()) { 2422 if (perm.uid == tree.uid) { 2423 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2424 } 2425 } 2426 return size; 2427 } 2428 2429 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2430 // We calculate the max size of permissions defined by this uid and throw 2431 // if that plus the size of 'info' would exceed our stated maximum. 2432 if (tree.uid != Process.SYSTEM_UID) { 2433 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2434 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2435 throw new SecurityException("Permission tree size cap exceeded"); 2436 } 2437 } 2438 } 2439 2440 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2441 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2442 throw new SecurityException("Label must be specified in permission"); 2443 } 2444 BasePermission tree = checkPermissionTreeLP(info.name); 2445 BasePermission bp = mSettings.mPermissions.get(info.name); 2446 boolean added = bp == null; 2447 boolean changed = true; 2448 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2449 if (added) { 2450 enforcePermissionCapLocked(info, tree); 2451 bp = new BasePermission(info.name, tree.sourcePackage, 2452 BasePermission.TYPE_DYNAMIC); 2453 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2454 throw new SecurityException( 2455 "Not allowed to modify non-dynamic permission " 2456 + info.name); 2457 } else { 2458 if (bp.protectionLevel == fixedLevel 2459 && bp.perm.owner.equals(tree.perm.owner) 2460 && bp.uid == tree.uid 2461 && comparePermissionInfos(bp.perm.info, info)) { 2462 changed = false; 2463 } 2464 } 2465 bp.protectionLevel = fixedLevel; 2466 info = new PermissionInfo(info); 2467 info.protectionLevel = fixedLevel; 2468 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 2469 bp.perm.info.packageName = tree.perm.info.packageName; 2470 bp.uid = tree.uid; 2471 if (added) { 2472 mSettings.mPermissions.put(info.name, bp); 2473 } 2474 if (changed) { 2475 if (!async) { 2476 mSettings.writeLPr(); 2477 } else { 2478 scheduleWriteSettingsLocked(); 2479 } 2480 } 2481 return added; 2482 } 2483 2484 @Override 2485 public boolean addPermission(PermissionInfo info) { 2486 synchronized (mPackages) { 2487 return addPermissionLocked(info, false); 2488 } 2489 } 2490 2491 @Override 2492 public boolean addPermissionAsync(PermissionInfo info) { 2493 synchronized (mPackages) { 2494 return addPermissionLocked(info, true); 2495 } 2496 } 2497 2498 @Override 2499 public void removePermission(String name) { 2500 synchronized (mPackages) { 2501 checkPermissionTreeLP(name); 2502 BasePermission bp = mSettings.mPermissions.get(name); 2503 if (bp != null) { 2504 if (bp.type != BasePermission.TYPE_DYNAMIC) { 2505 throw new SecurityException( 2506 "Not allowed to modify non-dynamic permission " 2507 + name); 2508 } 2509 mSettings.mPermissions.remove(name); 2510 mSettings.writeLPr(); 2511 } 2512 } 2513 } 2514 2515 private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) { 2516 int index = pkg.requestedPermissions.indexOf(bp.name); 2517 if (index == -1) { 2518 throw new SecurityException("Package " + pkg.packageName 2519 + " has not requested permission " + bp.name); 2520 } 2521 boolean isNormal = 2522 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2523 == PermissionInfo.PROTECTION_NORMAL); 2524 boolean isDangerous = 2525 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2526 == PermissionInfo.PROTECTION_DANGEROUS); 2527 boolean isDevelopment = 2528 ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0); 2529 2530 if (!isNormal && !isDangerous && !isDevelopment) { 2531 throw new SecurityException("Permission " + bp.name 2532 + " is not a changeable permission type"); 2533 } 2534 2535 if (isNormal || isDangerous) { 2536 if (pkg.requestedPermissionsRequired.get(index)) { 2537 throw new SecurityException("Can't change " + bp.name 2538 + ". It is required by the application"); 2539 } 2540 } 2541 } 2542 2543 @Override 2544 public void grantPermission(String packageName, String permissionName) { 2545 mContext.enforceCallingOrSelfPermission( 2546 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2547 synchronized (mPackages) { 2548 final PackageParser.Package pkg = mPackages.get(packageName); 2549 if (pkg == null) { 2550 throw new IllegalArgumentException("Unknown package: " + packageName); 2551 } 2552 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2553 if (bp == null) { 2554 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2555 } 2556 2557 checkGrantRevokePermissions(pkg, bp); 2558 2559 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2560 if (ps == null) { 2561 return; 2562 } 2563 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2564 if (gp.grantedPermissions.add(permissionName)) { 2565 if (ps.haveGids) { 2566 gp.gids = appendInts(gp.gids, bp.gids); 2567 } 2568 mSettings.writeLPr(); 2569 } 2570 } 2571 } 2572 2573 @Override 2574 public void revokePermission(String packageName, String permissionName) { 2575 int changedAppId = -1; 2576 2577 synchronized (mPackages) { 2578 final PackageParser.Package pkg = mPackages.get(packageName); 2579 if (pkg == null) { 2580 throw new IllegalArgumentException("Unknown package: " + packageName); 2581 } 2582 if (pkg.applicationInfo.uid != Binder.getCallingUid()) { 2583 mContext.enforceCallingOrSelfPermission( 2584 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2585 } 2586 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2587 if (bp == null) { 2588 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2589 } 2590 2591 checkGrantRevokePermissions(pkg, bp); 2592 2593 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2594 if (ps == null) { 2595 return; 2596 } 2597 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2598 if (gp.grantedPermissions.remove(permissionName)) { 2599 gp.grantedPermissions.remove(permissionName); 2600 if (ps.haveGids) { 2601 gp.gids = removeInts(gp.gids, bp.gids); 2602 } 2603 mSettings.writeLPr(); 2604 changedAppId = ps.appId; 2605 } 2606 } 2607 2608 if (changedAppId >= 0) { 2609 // We changed the perm on someone, kill its processes. 2610 IActivityManager am = ActivityManagerNative.getDefault(); 2611 if (am != null) { 2612 final int callingUserId = UserHandle.getCallingUserId(); 2613 final long ident = Binder.clearCallingIdentity(); 2614 try { 2615 //XXX we should only revoke for the calling user's app permissions, 2616 // but for now we impact all users. 2617 //am.killUid(UserHandle.getUid(callingUserId, changedAppId), 2618 // "revoke " + permissionName); 2619 int[] users = sUserManager.getUserIds(); 2620 for (int user : users) { 2621 am.killUid(UserHandle.getUid(user, changedAppId), 2622 "revoke " + permissionName); 2623 } 2624 } catch (RemoteException e) { 2625 } finally { 2626 Binder.restoreCallingIdentity(ident); 2627 } 2628 } 2629 } 2630 } 2631 2632 @Override 2633 public boolean isProtectedBroadcast(String actionName) { 2634 synchronized (mPackages) { 2635 return mProtectedBroadcasts.contains(actionName); 2636 } 2637 } 2638 2639 @Override 2640 public int checkSignatures(String pkg1, String pkg2) { 2641 synchronized (mPackages) { 2642 final PackageParser.Package p1 = mPackages.get(pkg1); 2643 final PackageParser.Package p2 = mPackages.get(pkg2); 2644 if (p1 == null || p1.mExtras == null 2645 || p2 == null || p2.mExtras == null) { 2646 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2647 } 2648 return compareSignatures(p1.mSignatures, p2.mSignatures); 2649 } 2650 } 2651 2652 @Override 2653 public int checkUidSignatures(int uid1, int uid2) { 2654 // Map to base uids. 2655 uid1 = UserHandle.getAppId(uid1); 2656 uid2 = UserHandle.getAppId(uid2); 2657 // reader 2658 synchronized (mPackages) { 2659 Signature[] s1; 2660 Signature[] s2; 2661 Object obj = mSettings.getUserIdLPr(uid1); 2662 if (obj != null) { 2663 if (obj instanceof SharedUserSetting) { 2664 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 2665 } else if (obj instanceof PackageSetting) { 2666 s1 = ((PackageSetting)obj).signatures.mSignatures; 2667 } else { 2668 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2669 } 2670 } else { 2671 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2672 } 2673 obj = mSettings.getUserIdLPr(uid2); 2674 if (obj != null) { 2675 if (obj instanceof SharedUserSetting) { 2676 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 2677 } else if (obj instanceof PackageSetting) { 2678 s2 = ((PackageSetting)obj).signatures.mSignatures; 2679 } else { 2680 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2681 } 2682 } else { 2683 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2684 } 2685 return compareSignatures(s1, s2); 2686 } 2687 } 2688 2689 /** 2690 * Compares two sets of signatures. Returns: 2691 * <br /> 2692 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 2693 * <br /> 2694 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 2695 * <br /> 2696 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 2697 * <br /> 2698 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 2699 * <br /> 2700 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 2701 */ 2702 static int compareSignatures(Signature[] s1, Signature[] s2) { 2703 if (s1 == null) { 2704 return s2 == null 2705 ? PackageManager.SIGNATURE_NEITHER_SIGNED 2706 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 2707 } 2708 2709 if (s2 == null) { 2710 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 2711 } 2712 2713 if (s1.length != s2.length) { 2714 return PackageManager.SIGNATURE_NO_MATCH; 2715 } 2716 2717 // Since both signature sets are of size 1, we can compare without HashSets. 2718 if (s1.length == 1) { 2719 return s1[0].equals(s2[0]) ? 2720 PackageManager.SIGNATURE_MATCH : 2721 PackageManager.SIGNATURE_NO_MATCH; 2722 } 2723 2724 HashSet<Signature> set1 = new HashSet<Signature>(); 2725 for (Signature sig : s1) { 2726 set1.add(sig); 2727 } 2728 HashSet<Signature> set2 = new HashSet<Signature>(); 2729 for (Signature sig : s2) { 2730 set2.add(sig); 2731 } 2732 // Make sure s2 contains all signatures in s1. 2733 if (set1.equals(set2)) { 2734 return PackageManager.SIGNATURE_MATCH; 2735 } 2736 return PackageManager.SIGNATURE_NO_MATCH; 2737 } 2738 2739 /** 2740 * If the database version for this type of package (internal storage or 2741 * external storage) is less than the version where package signatures 2742 * were updated, return true. 2743 */ 2744 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2745 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 2746 DatabaseVersion.SIGNATURE_END_ENTITY)) 2747 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 2748 DatabaseVersion.SIGNATURE_END_ENTITY)); 2749 } 2750 2751 /** 2752 * Used for backward compatibility to make sure any packages with 2753 * certificate chains get upgraded to the new style. {@code existingSigs} 2754 * will be in the old format (since they were stored on disk from before the 2755 * system upgrade) and {@code scannedSigs} will be in the newer format. 2756 */ 2757 private int compareSignaturesCompat(PackageSignatures existingSigs, 2758 PackageParser.Package scannedPkg) { 2759 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 2760 return PackageManager.SIGNATURE_NO_MATCH; 2761 } 2762 2763 HashSet<Signature> existingSet = new HashSet<Signature>(); 2764 for (Signature sig : existingSigs.mSignatures) { 2765 existingSet.add(sig); 2766 } 2767 HashSet<Signature> scannedCompatSet = new HashSet<Signature>(); 2768 for (Signature sig : scannedPkg.mSignatures) { 2769 try { 2770 Signature[] chainSignatures = sig.getChainSignatures(); 2771 for (Signature chainSig : chainSignatures) { 2772 scannedCompatSet.add(chainSig); 2773 } 2774 } catch (CertificateEncodingException e) { 2775 scannedCompatSet.add(sig); 2776 } 2777 } 2778 /* 2779 * Make sure the expanded scanned set contains all signatures in the 2780 * existing one. 2781 */ 2782 if (scannedCompatSet.equals(existingSet)) { 2783 // Migrate the old signatures to the new scheme. 2784 existingSigs.assignSignatures(scannedPkg.mSignatures); 2785 // The new KeySets will be re-added later in the scanning process. 2786 synchronized (mPackages) { 2787 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 2788 } 2789 return PackageManager.SIGNATURE_MATCH; 2790 } 2791 return PackageManager.SIGNATURE_NO_MATCH; 2792 } 2793 2794 @Override 2795 public String[] getPackagesForUid(int uid) { 2796 uid = UserHandle.getAppId(uid); 2797 // reader 2798 synchronized (mPackages) { 2799 Object obj = mSettings.getUserIdLPr(uid); 2800 if (obj instanceof SharedUserSetting) { 2801 final SharedUserSetting sus = (SharedUserSetting) obj; 2802 final int N = sus.packages.size(); 2803 final String[] res = new String[N]; 2804 final Iterator<PackageSetting> it = sus.packages.iterator(); 2805 int i = 0; 2806 while (it.hasNext()) { 2807 res[i++] = it.next().name; 2808 } 2809 return res; 2810 } else if (obj instanceof PackageSetting) { 2811 final PackageSetting ps = (PackageSetting) obj; 2812 return new String[] { ps.name }; 2813 } 2814 } 2815 return null; 2816 } 2817 2818 @Override 2819 public String getNameForUid(int uid) { 2820 // reader 2821 synchronized (mPackages) { 2822 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2823 if (obj instanceof SharedUserSetting) { 2824 final SharedUserSetting sus = (SharedUserSetting) obj; 2825 return sus.name + ":" + sus.userId; 2826 } else if (obj instanceof PackageSetting) { 2827 final PackageSetting ps = (PackageSetting) obj; 2828 return ps.name; 2829 } 2830 } 2831 return null; 2832 } 2833 2834 @Override 2835 public int getUidForSharedUser(String sharedUserName) { 2836 if(sharedUserName == null) { 2837 return -1; 2838 } 2839 // reader 2840 synchronized (mPackages) { 2841 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false); 2842 if (suid == null) { 2843 return -1; 2844 } 2845 return suid.userId; 2846 } 2847 } 2848 2849 @Override 2850 public int getFlagsForUid(int uid) { 2851 synchronized (mPackages) { 2852 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2853 if (obj instanceof SharedUserSetting) { 2854 final SharedUserSetting sus = (SharedUserSetting) obj; 2855 return sus.pkgFlags; 2856 } else if (obj instanceof PackageSetting) { 2857 final PackageSetting ps = (PackageSetting) obj; 2858 return ps.pkgFlags; 2859 } 2860 } 2861 return 0; 2862 } 2863 2864 @Override 2865 public String[] getAppOpPermissionPackages(String permissionName) { 2866 synchronized (mPackages) { 2867 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 2868 if (pkgs == null) { 2869 return null; 2870 } 2871 return pkgs.toArray(new String[pkgs.size()]); 2872 } 2873 } 2874 2875 @Override 2876 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 2877 int flags, int userId) { 2878 if (!sUserManager.exists(userId)) return null; 2879 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent"); 2880 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2881 return chooseBestActivity(intent, resolvedType, flags, query, userId); 2882 } 2883 2884 @Override 2885 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 2886 IntentFilter filter, int match, ComponentName activity) { 2887 final int userId = UserHandle.getCallingUserId(); 2888 if (DEBUG_PREFERRED) { 2889 Log.v(TAG, "setLastChosenActivity intent=" + intent 2890 + " resolvedType=" + resolvedType 2891 + " flags=" + flags 2892 + " filter=" + filter 2893 + " match=" + match 2894 + " activity=" + activity); 2895 filter.dump(new PrintStreamPrinter(System.out), " "); 2896 } 2897 intent.setComponent(null); 2898 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2899 // Find any earlier preferred or last chosen entries and nuke them 2900 findPreferredActivity(intent, resolvedType, 2901 flags, query, 0, false, true, false, userId); 2902 // Add the new activity as the last chosen for this filter 2903 addPreferredActivityInternal(filter, match, null, activity, false, userId, 2904 "Setting last chosen"); 2905 } 2906 2907 @Override 2908 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 2909 final int userId = UserHandle.getCallingUserId(); 2910 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 2911 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2912 return findPreferredActivity(intent, resolvedType, flags, query, 0, 2913 false, false, false, userId); 2914 } 2915 2916 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 2917 int flags, List<ResolveInfo> query, int userId) { 2918 if (query != null) { 2919 final int N = query.size(); 2920 if (N == 1) { 2921 return query.get(0); 2922 } else if (N > 1) { 2923 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 2924 // If there is more than one activity with the same priority, 2925 // then let the user decide between them. 2926 ResolveInfo r0 = query.get(0); 2927 ResolveInfo r1 = query.get(1); 2928 if (DEBUG_INTENT_MATCHING || debug) { 2929 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 2930 + r1.activityInfo.name + "=" + r1.priority); 2931 } 2932 // If the first activity has a higher priority, or a different 2933 // default, then it is always desireable to pick it. 2934 if (r0.priority != r1.priority 2935 || r0.preferredOrder != r1.preferredOrder 2936 || r0.isDefault != r1.isDefault) { 2937 return query.get(0); 2938 } 2939 // If we have saved a preference for a preferred activity for 2940 // this Intent, use that. 2941 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 2942 flags, query, r0.priority, true, false, debug, userId); 2943 if (ri != null) { 2944 return ri; 2945 } 2946 if (userId != 0) { 2947 ri = new ResolveInfo(mResolveInfo); 2948 ri.activityInfo = new ActivityInfo(ri.activityInfo); 2949 ri.activityInfo.applicationInfo = new ApplicationInfo( 2950 ri.activityInfo.applicationInfo); 2951 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 2952 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 2953 return ri; 2954 } 2955 return mResolveInfo; 2956 } 2957 } 2958 return null; 2959 } 2960 2961 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 2962 int flags, List<ResolveInfo> query, boolean debug, int userId) { 2963 final int N = query.size(); 2964 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 2965 .get(userId); 2966 // Get the list of persistent preferred activities that handle the intent 2967 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 2968 List<PersistentPreferredActivity> pprefs = ppir != null 2969 ? ppir.queryIntent(intent, resolvedType, 2970 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 2971 : null; 2972 if (pprefs != null && pprefs.size() > 0) { 2973 final int M = pprefs.size(); 2974 for (int i=0; i<M; i++) { 2975 final PersistentPreferredActivity ppa = pprefs.get(i); 2976 if (DEBUG_PREFERRED || debug) { 2977 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 2978 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 2979 + "\n component=" + ppa.mComponent); 2980 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 2981 } 2982 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 2983 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 2984 if (DEBUG_PREFERRED || debug) { 2985 Slog.v(TAG, "Found persistent preferred activity:"); 2986 if (ai != null) { 2987 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 2988 } else { 2989 Slog.v(TAG, " null"); 2990 } 2991 } 2992 if (ai == null) { 2993 // This previously registered persistent preferred activity 2994 // component is no longer known. Ignore it and do NOT remove it. 2995 continue; 2996 } 2997 for (int j=0; j<N; j++) { 2998 final ResolveInfo ri = query.get(j); 2999 if (!ri.activityInfo.applicationInfo.packageName 3000 .equals(ai.applicationInfo.packageName)) { 3001 continue; 3002 } 3003 if (!ri.activityInfo.name.equals(ai.name)) { 3004 continue; 3005 } 3006 // Found a persistent preference that can handle the intent. 3007 if (DEBUG_PREFERRED || debug) { 3008 Slog.v(TAG, "Returning persistent preferred activity: " + 3009 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3010 } 3011 return ri; 3012 } 3013 } 3014 } 3015 return null; 3016 } 3017 3018 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3019 List<ResolveInfo> query, int priority, boolean always, 3020 boolean removeMatches, boolean debug, int userId) { 3021 if (!sUserManager.exists(userId)) return null; 3022 // writer 3023 synchronized (mPackages) { 3024 if (intent.getSelector() != null) { 3025 intent = intent.getSelector(); 3026 } 3027 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3028 3029 // Try to find a matching persistent preferred activity. 3030 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3031 debug, userId); 3032 3033 // If a persistent preferred activity matched, use it. 3034 if (pri != null) { 3035 return pri; 3036 } 3037 3038 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3039 // Get the list of preferred activities that handle the intent 3040 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3041 List<PreferredActivity> prefs = pir != null 3042 ? pir.queryIntent(intent, resolvedType, 3043 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3044 : null; 3045 if (prefs != null && prefs.size() > 0) { 3046 boolean changed = false; 3047 try { 3048 // First figure out how good the original match set is. 3049 // We will only allow preferred activities that came 3050 // from the same match quality. 3051 int match = 0; 3052 3053 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3054 3055 final int N = query.size(); 3056 for (int j=0; j<N; j++) { 3057 final ResolveInfo ri = query.get(j); 3058 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3059 + ": 0x" + Integer.toHexString(match)); 3060 if (ri.match > match) { 3061 match = ri.match; 3062 } 3063 } 3064 3065 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3066 + Integer.toHexString(match)); 3067 3068 match &= IntentFilter.MATCH_CATEGORY_MASK; 3069 final int M = prefs.size(); 3070 for (int i=0; i<M; i++) { 3071 final PreferredActivity pa = prefs.get(i); 3072 if (DEBUG_PREFERRED || debug) { 3073 Slog.v(TAG, "Checking PreferredActivity ds=" 3074 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3075 + "\n component=" + pa.mPref.mComponent); 3076 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3077 } 3078 if (pa.mPref.mMatch != match) { 3079 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3080 + Integer.toHexString(pa.mPref.mMatch)); 3081 continue; 3082 } 3083 // If it's not an "always" type preferred activity and that's what we're 3084 // looking for, skip it. 3085 if (always && !pa.mPref.mAlways) { 3086 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3087 continue; 3088 } 3089 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3090 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3091 if (DEBUG_PREFERRED || debug) { 3092 Slog.v(TAG, "Found preferred activity:"); 3093 if (ai != null) { 3094 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3095 } else { 3096 Slog.v(TAG, " null"); 3097 } 3098 } 3099 if (ai == null) { 3100 // This previously registered preferred activity 3101 // component is no longer known. Most likely an update 3102 // to the app was installed and in the new version this 3103 // component no longer exists. Clean it up by removing 3104 // it from the preferred activities list, and skip it. 3105 Slog.w(TAG, "Removing dangling preferred activity: " 3106 + pa.mPref.mComponent); 3107 pir.removeFilter(pa); 3108 changed = true; 3109 continue; 3110 } 3111 for (int j=0; j<N; j++) { 3112 final ResolveInfo ri = query.get(j); 3113 if (!ri.activityInfo.applicationInfo.packageName 3114 .equals(ai.applicationInfo.packageName)) { 3115 continue; 3116 } 3117 if (!ri.activityInfo.name.equals(ai.name)) { 3118 continue; 3119 } 3120 3121 if (removeMatches) { 3122 pir.removeFilter(pa); 3123 changed = true; 3124 if (DEBUG_PREFERRED) { 3125 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3126 } 3127 break; 3128 } 3129 3130 // Okay we found a previously set preferred or last chosen app. 3131 // If the result set is different from when this 3132 // was created, we need to clear it and re-ask the 3133 // user their preference, if we're looking for an "always" type entry. 3134 if (always && !pa.mPref.sameSet(query, priority)) { 3135 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3136 + intent + " type " + resolvedType); 3137 if (DEBUG_PREFERRED) { 3138 Slog.v(TAG, "Removing preferred activity since set changed " 3139 + pa.mPref.mComponent); 3140 } 3141 pir.removeFilter(pa); 3142 // Re-add the filter as a "last chosen" entry (!always) 3143 PreferredActivity lastChosen = new PreferredActivity( 3144 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3145 pir.addFilter(lastChosen); 3146 changed = true; 3147 return null; 3148 } 3149 3150 // Yay! Either the set matched or we're looking for the last chosen 3151 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3152 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3153 return ri; 3154 } 3155 } 3156 } finally { 3157 if (changed) { 3158 if (DEBUG_PREFERRED) { 3159 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 3160 } 3161 mSettings.writePackageRestrictionsLPr(userId); 3162 } 3163 } 3164 } 3165 } 3166 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3167 return null; 3168 } 3169 3170 /* 3171 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3172 */ 3173 @Override 3174 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3175 int targetUserId) { 3176 mContext.enforceCallingOrSelfPermission( 3177 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3178 List<CrossProfileIntentFilter> matches = 3179 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3180 if (matches != null) { 3181 int size = matches.size(); 3182 for (int i = 0; i < size; i++) { 3183 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3184 } 3185 } 3186 return false; 3187 } 3188 3189 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3190 String resolvedType, int userId) { 3191 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3192 if (resolver != null) { 3193 return resolver.queryIntent(intent, resolvedType, false, userId); 3194 } 3195 return null; 3196 } 3197 3198 @Override 3199 public List<ResolveInfo> queryIntentActivities(Intent intent, 3200 String resolvedType, int flags, int userId) { 3201 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3202 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities"); 3203 ComponentName comp = intent.getComponent(); 3204 if (comp == null) { 3205 if (intent.getSelector() != null) { 3206 intent = intent.getSelector(); 3207 comp = intent.getComponent(); 3208 } 3209 } 3210 3211 if (comp != null) { 3212 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3213 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3214 if (ai != null) { 3215 final ResolveInfo ri = new ResolveInfo(); 3216 ri.activityInfo = ai; 3217 list.add(ri); 3218 } 3219 return list; 3220 } 3221 3222 // reader 3223 synchronized (mPackages) { 3224 final String pkgName = intent.getPackage(); 3225 if (pkgName == null) { 3226 List<CrossProfileIntentFilter> matchingFilters = 3227 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3228 // Check for results that need to skip the current profile. 3229 ResolveInfo resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3230 resolvedType, flags, userId); 3231 if (resolveInfo != null) { 3232 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3233 result.add(resolveInfo); 3234 return result; 3235 } 3236 // Check for cross profile results. 3237 resolveInfo = queryCrossProfileIntents( 3238 matchingFilters, intent, resolvedType, flags, userId); 3239 3240 // Check for results in the current profile. 3241 List<ResolveInfo> result = mActivities.queryIntent( 3242 intent, resolvedType, flags, userId); 3243 if (resolveInfo != null) { 3244 result.add(resolveInfo); 3245 Collections.sort(result, mResolvePrioritySorter); 3246 } 3247 return result; 3248 } 3249 final PackageParser.Package pkg = mPackages.get(pkgName); 3250 if (pkg != null) { 3251 return mActivities.queryIntentForPackage(intent, resolvedType, flags, 3252 pkg.activities, userId); 3253 } 3254 return new ArrayList<ResolveInfo>(); 3255 } 3256 } 3257 3258 private ResolveInfo querySkipCurrentProfileIntents( 3259 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3260 int flags, int sourceUserId) { 3261 if (matchingFilters != null) { 3262 int size = matchingFilters.size(); 3263 for (int i = 0; i < size; i ++) { 3264 CrossProfileIntentFilter filter = matchingFilters.get(i); 3265 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 3266 // Checking if there are activities in the target user that can handle the 3267 // intent. 3268 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3269 flags, sourceUserId); 3270 if (resolveInfo != null) { 3271 return resolveInfo; 3272 } 3273 } 3274 } 3275 } 3276 return null; 3277 } 3278 3279 // Return matching ResolveInfo if any for skip current profile intent filters. 3280 private ResolveInfo queryCrossProfileIntents( 3281 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3282 int flags, int sourceUserId) { 3283 if (matchingFilters != null) { 3284 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 3285 // match the same intent. For performance reasons, it is better not to 3286 // run queryIntent twice for the same userId 3287 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 3288 int size = matchingFilters.size(); 3289 for (int i = 0; i < size; i++) { 3290 CrossProfileIntentFilter filter = matchingFilters.get(i); 3291 int targetUserId = filter.getTargetUserId(); 3292 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 3293 && !alreadyTriedUserIds.get(targetUserId)) { 3294 // Checking if there are activities in the target user that can handle the 3295 // intent. 3296 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3297 flags, sourceUserId); 3298 if (resolveInfo != null) return resolveInfo; 3299 alreadyTriedUserIds.put(targetUserId, true); 3300 } 3301 } 3302 } 3303 return null; 3304 } 3305 3306 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 3307 String resolvedType, int flags, int sourceUserId) { 3308 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 3309 resolvedType, flags, filter.getTargetUserId()); 3310 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 3311 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 3312 } 3313 return null; 3314 } 3315 3316 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 3317 int sourceUserId, int targetUserId) { 3318 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 3319 String className; 3320 if (targetUserId == UserHandle.USER_OWNER) { 3321 className = FORWARD_INTENT_TO_USER_OWNER; 3322 } else { 3323 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 3324 } 3325 ComponentName forwardingActivityComponentName = new ComponentName( 3326 mAndroidApplication.packageName, className); 3327 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 3328 sourceUserId); 3329 if (targetUserId == UserHandle.USER_OWNER) { 3330 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 3331 forwardingResolveInfo.noResourceId = true; 3332 } 3333 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 3334 forwardingResolveInfo.priority = 0; 3335 forwardingResolveInfo.preferredOrder = 0; 3336 forwardingResolveInfo.match = 0; 3337 forwardingResolveInfo.isDefault = true; 3338 forwardingResolveInfo.filter = filter; 3339 forwardingResolveInfo.targetUserId = targetUserId; 3340 return forwardingResolveInfo; 3341 } 3342 3343 @Override 3344 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 3345 Intent[] specifics, String[] specificTypes, Intent intent, 3346 String resolvedType, int flags, int userId) { 3347 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3348 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 3349 "query intent activity options"); 3350 final String resultsAction = intent.getAction(); 3351 3352 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 3353 | PackageManager.GET_RESOLVED_FILTER, userId); 3354 3355 if (DEBUG_INTENT_MATCHING) { 3356 Log.v(TAG, "Query " + intent + ": " + results); 3357 } 3358 3359 int specificsPos = 0; 3360 int N; 3361 3362 // todo: note that the algorithm used here is O(N^2). This 3363 // isn't a problem in our current environment, but if we start running 3364 // into situations where we have more than 5 or 10 matches then this 3365 // should probably be changed to something smarter... 3366 3367 // First we go through and resolve each of the specific items 3368 // that were supplied, taking care of removing any corresponding 3369 // duplicate items in the generic resolve list. 3370 if (specifics != null) { 3371 for (int i=0; i<specifics.length; i++) { 3372 final Intent sintent = specifics[i]; 3373 if (sintent == null) { 3374 continue; 3375 } 3376 3377 if (DEBUG_INTENT_MATCHING) { 3378 Log.v(TAG, "Specific #" + i + ": " + sintent); 3379 } 3380 3381 String action = sintent.getAction(); 3382 if (resultsAction != null && resultsAction.equals(action)) { 3383 // If this action was explicitly requested, then don't 3384 // remove things that have it. 3385 action = null; 3386 } 3387 3388 ResolveInfo ri = null; 3389 ActivityInfo ai = null; 3390 3391 ComponentName comp = sintent.getComponent(); 3392 if (comp == null) { 3393 ri = resolveIntent( 3394 sintent, 3395 specificTypes != null ? specificTypes[i] : null, 3396 flags, userId); 3397 if (ri == null) { 3398 continue; 3399 } 3400 if (ri == mResolveInfo) { 3401 // ACK! Must do something better with this. 3402 } 3403 ai = ri.activityInfo; 3404 comp = new ComponentName(ai.applicationInfo.packageName, 3405 ai.name); 3406 } else { 3407 ai = getActivityInfo(comp, flags, userId); 3408 if (ai == null) { 3409 continue; 3410 } 3411 } 3412 3413 // Look for any generic query activities that are duplicates 3414 // of this specific one, and remove them from the results. 3415 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 3416 N = results.size(); 3417 int j; 3418 for (j=specificsPos; j<N; j++) { 3419 ResolveInfo sri = results.get(j); 3420 if ((sri.activityInfo.name.equals(comp.getClassName()) 3421 && sri.activityInfo.applicationInfo.packageName.equals( 3422 comp.getPackageName())) 3423 || (action != null && sri.filter.matchAction(action))) { 3424 results.remove(j); 3425 if (DEBUG_INTENT_MATCHING) Log.v( 3426 TAG, "Removing duplicate item from " + j 3427 + " due to specific " + specificsPos); 3428 if (ri == null) { 3429 ri = sri; 3430 } 3431 j--; 3432 N--; 3433 } 3434 } 3435 3436 // Add this specific item to its proper place. 3437 if (ri == null) { 3438 ri = new ResolveInfo(); 3439 ri.activityInfo = ai; 3440 } 3441 results.add(specificsPos, ri); 3442 ri.specificIndex = i; 3443 specificsPos++; 3444 } 3445 } 3446 3447 // Now we go through the remaining generic results and remove any 3448 // duplicate actions that are found here. 3449 N = results.size(); 3450 for (int i=specificsPos; i<N-1; i++) { 3451 final ResolveInfo rii = results.get(i); 3452 if (rii.filter == null) { 3453 continue; 3454 } 3455 3456 // Iterate over all of the actions of this result's intent 3457 // filter... typically this should be just one. 3458 final Iterator<String> it = rii.filter.actionsIterator(); 3459 if (it == null) { 3460 continue; 3461 } 3462 while (it.hasNext()) { 3463 final String action = it.next(); 3464 if (resultsAction != null && resultsAction.equals(action)) { 3465 // If this action was explicitly requested, then don't 3466 // remove things that have it. 3467 continue; 3468 } 3469 for (int j=i+1; j<N; j++) { 3470 final ResolveInfo rij = results.get(j); 3471 if (rij.filter != null && rij.filter.hasAction(action)) { 3472 results.remove(j); 3473 if (DEBUG_INTENT_MATCHING) Log.v( 3474 TAG, "Removing duplicate item from " + j 3475 + " due to action " + action + " at " + i); 3476 j--; 3477 N--; 3478 } 3479 } 3480 } 3481 3482 // If the caller didn't request filter information, drop it now 3483 // so we don't have to marshall/unmarshall it. 3484 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3485 rii.filter = null; 3486 } 3487 } 3488 3489 // Filter out the caller activity if so requested. 3490 if (caller != null) { 3491 N = results.size(); 3492 for (int i=0; i<N; i++) { 3493 ActivityInfo ainfo = results.get(i).activityInfo; 3494 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 3495 && caller.getClassName().equals(ainfo.name)) { 3496 results.remove(i); 3497 break; 3498 } 3499 } 3500 } 3501 3502 // If the caller didn't request filter information, 3503 // drop them now so we don't have to 3504 // marshall/unmarshall it. 3505 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3506 N = results.size(); 3507 for (int i=0; i<N; i++) { 3508 results.get(i).filter = null; 3509 } 3510 } 3511 3512 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 3513 return results; 3514 } 3515 3516 @Override 3517 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 3518 int userId) { 3519 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3520 ComponentName comp = intent.getComponent(); 3521 if (comp == null) { 3522 if (intent.getSelector() != null) { 3523 intent = intent.getSelector(); 3524 comp = intent.getComponent(); 3525 } 3526 } 3527 if (comp != null) { 3528 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3529 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 3530 if (ai != null) { 3531 ResolveInfo ri = new ResolveInfo(); 3532 ri.activityInfo = ai; 3533 list.add(ri); 3534 } 3535 return list; 3536 } 3537 3538 // reader 3539 synchronized (mPackages) { 3540 String pkgName = intent.getPackage(); 3541 if (pkgName == null) { 3542 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 3543 } 3544 final PackageParser.Package pkg = mPackages.get(pkgName); 3545 if (pkg != null) { 3546 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 3547 userId); 3548 } 3549 return null; 3550 } 3551 } 3552 3553 @Override 3554 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 3555 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 3556 if (!sUserManager.exists(userId)) return null; 3557 if (query != null) { 3558 if (query.size() >= 1) { 3559 // If there is more than one service with the same priority, 3560 // just arbitrarily pick the first one. 3561 return query.get(0); 3562 } 3563 } 3564 return null; 3565 } 3566 3567 @Override 3568 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 3569 int userId) { 3570 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3571 ComponentName comp = intent.getComponent(); 3572 if (comp == null) { 3573 if (intent.getSelector() != null) { 3574 intent = intent.getSelector(); 3575 comp = intent.getComponent(); 3576 } 3577 } 3578 if (comp != null) { 3579 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3580 final ServiceInfo si = getServiceInfo(comp, flags, userId); 3581 if (si != null) { 3582 final ResolveInfo ri = new ResolveInfo(); 3583 ri.serviceInfo = si; 3584 list.add(ri); 3585 } 3586 return list; 3587 } 3588 3589 // reader 3590 synchronized (mPackages) { 3591 String pkgName = intent.getPackage(); 3592 if (pkgName == null) { 3593 return mServices.queryIntent(intent, resolvedType, flags, userId); 3594 } 3595 final PackageParser.Package pkg = mPackages.get(pkgName); 3596 if (pkg != null) { 3597 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 3598 userId); 3599 } 3600 return null; 3601 } 3602 } 3603 3604 @Override 3605 public List<ResolveInfo> queryIntentContentProviders( 3606 Intent intent, String resolvedType, int flags, int userId) { 3607 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3608 ComponentName comp = intent.getComponent(); 3609 if (comp == null) { 3610 if (intent.getSelector() != null) { 3611 intent = intent.getSelector(); 3612 comp = intent.getComponent(); 3613 } 3614 } 3615 if (comp != null) { 3616 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3617 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 3618 if (pi != null) { 3619 final ResolveInfo ri = new ResolveInfo(); 3620 ri.providerInfo = pi; 3621 list.add(ri); 3622 } 3623 return list; 3624 } 3625 3626 // reader 3627 synchronized (mPackages) { 3628 String pkgName = intent.getPackage(); 3629 if (pkgName == null) { 3630 return mProviders.queryIntent(intent, resolvedType, flags, userId); 3631 } 3632 final PackageParser.Package pkg = mPackages.get(pkgName); 3633 if (pkg != null) { 3634 return mProviders.queryIntentForPackage( 3635 intent, resolvedType, flags, pkg.providers, userId); 3636 } 3637 return null; 3638 } 3639 } 3640 3641 @Override 3642 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 3643 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3644 3645 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages"); 3646 3647 // writer 3648 synchronized (mPackages) { 3649 ArrayList<PackageInfo> list; 3650 if (listUninstalled) { 3651 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 3652 for (PackageSetting ps : mSettings.mPackages.values()) { 3653 PackageInfo pi; 3654 if (ps.pkg != null) { 3655 pi = generatePackageInfo(ps.pkg, flags, userId); 3656 } else { 3657 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3658 } 3659 if (pi != null) { 3660 list.add(pi); 3661 } 3662 } 3663 } else { 3664 list = new ArrayList<PackageInfo>(mPackages.size()); 3665 for (PackageParser.Package p : mPackages.values()) { 3666 PackageInfo pi = generatePackageInfo(p, flags, userId); 3667 if (pi != null) { 3668 list.add(pi); 3669 } 3670 } 3671 } 3672 3673 return new ParceledListSlice<PackageInfo>(list); 3674 } 3675 } 3676 3677 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 3678 String[] permissions, boolean[] tmp, int flags, int userId) { 3679 int numMatch = 0; 3680 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 3681 for (int i=0; i<permissions.length; i++) { 3682 if (gp.grantedPermissions.contains(permissions[i])) { 3683 tmp[i] = true; 3684 numMatch++; 3685 } else { 3686 tmp[i] = false; 3687 } 3688 } 3689 if (numMatch == 0) { 3690 return; 3691 } 3692 PackageInfo pi; 3693 if (ps.pkg != null) { 3694 pi = generatePackageInfo(ps.pkg, flags, userId); 3695 } else { 3696 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3697 } 3698 // The above might return null in cases of uninstalled apps or install-state 3699 // skew across users/profiles. 3700 if (pi != null) { 3701 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 3702 if (numMatch == permissions.length) { 3703 pi.requestedPermissions = permissions; 3704 } else { 3705 pi.requestedPermissions = new String[numMatch]; 3706 numMatch = 0; 3707 for (int i=0; i<permissions.length; i++) { 3708 if (tmp[i]) { 3709 pi.requestedPermissions[numMatch] = permissions[i]; 3710 numMatch++; 3711 } 3712 } 3713 } 3714 } 3715 list.add(pi); 3716 } 3717 } 3718 3719 @Override 3720 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 3721 String[] permissions, int flags, int userId) { 3722 if (!sUserManager.exists(userId)) return null; 3723 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3724 3725 // writer 3726 synchronized (mPackages) { 3727 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 3728 boolean[] tmpBools = new boolean[permissions.length]; 3729 if (listUninstalled) { 3730 for (PackageSetting ps : mSettings.mPackages.values()) { 3731 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 3732 } 3733 } else { 3734 for (PackageParser.Package pkg : mPackages.values()) { 3735 PackageSetting ps = (PackageSetting)pkg.mExtras; 3736 if (ps != null) { 3737 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 3738 userId); 3739 } 3740 } 3741 } 3742 3743 return new ParceledListSlice<PackageInfo>(list); 3744 } 3745 } 3746 3747 @Override 3748 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 3749 if (!sUserManager.exists(userId)) return null; 3750 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3751 3752 // writer 3753 synchronized (mPackages) { 3754 ArrayList<ApplicationInfo> list; 3755 if (listUninstalled) { 3756 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 3757 for (PackageSetting ps : mSettings.mPackages.values()) { 3758 ApplicationInfo ai; 3759 if (ps.pkg != null) { 3760 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3761 ps.readUserState(userId), userId); 3762 } else { 3763 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 3764 } 3765 if (ai != null) { 3766 list.add(ai); 3767 } 3768 } 3769 } else { 3770 list = new ArrayList<ApplicationInfo>(mPackages.size()); 3771 for (PackageParser.Package p : mPackages.values()) { 3772 if (p.mExtras != null) { 3773 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3774 ((PackageSetting)p.mExtras).readUserState(userId), userId); 3775 if (ai != null) { 3776 list.add(ai); 3777 } 3778 } 3779 } 3780 } 3781 3782 return new ParceledListSlice<ApplicationInfo>(list); 3783 } 3784 } 3785 3786 public List<ApplicationInfo> getPersistentApplications(int flags) { 3787 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 3788 3789 // reader 3790 synchronized (mPackages) { 3791 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 3792 final int userId = UserHandle.getCallingUserId(); 3793 while (i.hasNext()) { 3794 final PackageParser.Package p = i.next(); 3795 if (p.applicationInfo != null 3796 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 3797 && (!mSafeMode || isSystemApp(p))) { 3798 PackageSetting ps = mSettings.mPackages.get(p.packageName); 3799 if (ps != null) { 3800 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3801 ps.readUserState(userId), userId); 3802 if (ai != null) { 3803 finalList.add(ai); 3804 } 3805 } 3806 } 3807 } 3808 } 3809 3810 return finalList; 3811 } 3812 3813 @Override 3814 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 3815 if (!sUserManager.exists(userId)) return null; 3816 // reader 3817 synchronized (mPackages) { 3818 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 3819 PackageSetting ps = provider != null 3820 ? mSettings.mPackages.get(provider.owner.packageName) 3821 : null; 3822 return ps != null 3823 && mSettings.isEnabledLPr(provider.info, flags, userId) 3824 && (!mSafeMode || (provider.info.applicationInfo.flags 3825 &ApplicationInfo.FLAG_SYSTEM) != 0) 3826 ? PackageParser.generateProviderInfo(provider, flags, 3827 ps.readUserState(userId), userId) 3828 : null; 3829 } 3830 } 3831 3832 /** 3833 * @deprecated 3834 */ 3835 @Deprecated 3836 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 3837 // reader 3838 synchronized (mPackages) { 3839 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 3840 .entrySet().iterator(); 3841 final int userId = UserHandle.getCallingUserId(); 3842 while (i.hasNext()) { 3843 Map.Entry<String, PackageParser.Provider> entry = i.next(); 3844 PackageParser.Provider p = entry.getValue(); 3845 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3846 3847 if (ps != null && p.syncable 3848 && (!mSafeMode || (p.info.applicationInfo.flags 3849 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 3850 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 3851 ps.readUserState(userId), userId); 3852 if (info != null) { 3853 outNames.add(entry.getKey()); 3854 outInfo.add(info); 3855 } 3856 } 3857 } 3858 } 3859 } 3860 3861 @Override 3862 public List<ProviderInfo> queryContentProviders(String processName, 3863 int uid, int flags) { 3864 ArrayList<ProviderInfo> finalList = null; 3865 // reader 3866 synchronized (mPackages) { 3867 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 3868 final int userId = processName != null ? 3869 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 3870 while (i.hasNext()) { 3871 final PackageParser.Provider p = i.next(); 3872 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3873 if (ps != null && p.info.authority != null 3874 && (processName == null 3875 || (p.info.processName.equals(processName) 3876 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 3877 && mSettings.isEnabledLPr(p.info, flags, userId) 3878 && (!mSafeMode 3879 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 3880 if (finalList == null) { 3881 finalList = new ArrayList<ProviderInfo>(3); 3882 } 3883 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 3884 ps.readUserState(userId), userId); 3885 if (info != null) { 3886 finalList.add(info); 3887 } 3888 } 3889 } 3890 } 3891 3892 if (finalList != null) { 3893 Collections.sort(finalList, mProviderInitOrderSorter); 3894 } 3895 3896 return finalList; 3897 } 3898 3899 @Override 3900 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 3901 int flags) { 3902 // reader 3903 synchronized (mPackages) { 3904 final PackageParser.Instrumentation i = mInstrumentation.get(name); 3905 return PackageParser.generateInstrumentationInfo(i, flags); 3906 } 3907 } 3908 3909 @Override 3910 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 3911 int flags) { 3912 ArrayList<InstrumentationInfo> finalList = 3913 new ArrayList<InstrumentationInfo>(); 3914 3915 // reader 3916 synchronized (mPackages) { 3917 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 3918 while (i.hasNext()) { 3919 final PackageParser.Instrumentation p = i.next(); 3920 if (targetPackage == null 3921 || targetPackage.equals(p.info.targetPackage)) { 3922 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 3923 flags); 3924 if (ii != null) { 3925 finalList.add(ii); 3926 } 3927 } 3928 } 3929 } 3930 3931 return finalList; 3932 } 3933 3934 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 3935 HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 3936 if (overlays == null) { 3937 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 3938 return; 3939 } 3940 for (PackageParser.Package opkg : overlays.values()) { 3941 // Not much to do if idmap fails: we already logged the error 3942 // and we certainly don't want to abort installation of pkg simply 3943 // because an overlay didn't fit properly. For these reasons, 3944 // ignore the return value of createIdmapForPackagePairLI. 3945 createIdmapForPackagePairLI(pkg, opkg); 3946 } 3947 } 3948 3949 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 3950 PackageParser.Package opkg) { 3951 if (!opkg.mTrustedOverlay) { 3952 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 3953 opkg.baseCodePath + ": overlay not trusted"); 3954 return false; 3955 } 3956 HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 3957 if (overlaySet == null) { 3958 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 3959 opkg.baseCodePath + " but target package has no known overlays"); 3960 return false; 3961 } 3962 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 3963 // TODO: generate idmap for split APKs 3964 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 3965 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 3966 + opkg.baseCodePath); 3967 return false; 3968 } 3969 PackageParser.Package[] overlayArray = 3970 overlaySet.values().toArray(new PackageParser.Package[0]); 3971 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 3972 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 3973 return p1.mOverlayPriority - p2.mOverlayPriority; 3974 } 3975 }; 3976 Arrays.sort(overlayArray, cmp); 3977 3978 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 3979 int i = 0; 3980 for (PackageParser.Package p : overlayArray) { 3981 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 3982 } 3983 return true; 3984 } 3985 3986 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 3987 final File[] files = dir.listFiles(); 3988 if (ArrayUtils.isEmpty(files)) { 3989 Log.d(TAG, "No files in app dir " + dir); 3990 return; 3991 } 3992 3993 if (DEBUG_PACKAGE_SCANNING) { 3994 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 3995 + " flags=0x" + Integer.toHexString(parseFlags)); 3996 } 3997 3998 for (File file : files) { 3999 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 4000 && !PackageInstallerService.isStageName(file.getName()); 4001 if (!isPackage) { 4002 // Ignore entries which are not packages 4003 continue; 4004 } 4005 try { 4006 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 4007 scanFlags, currentTime, null); 4008 } catch (PackageManagerException e) { 4009 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4010 4011 // Delete invalid userdata apps 4012 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4013 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4014 Slog.w(TAG, "Deleting invalid package at " + file); 4015 if (file.isDirectory()) { 4016 FileUtils.deleteContents(file); 4017 } 4018 file.delete(); 4019 } 4020 } 4021 } 4022 } 4023 4024 private static File getSettingsProblemFile() { 4025 File dataDir = Environment.getDataDirectory(); 4026 File systemDir = new File(dataDir, "system"); 4027 File fname = new File(systemDir, "uiderrors.txt"); 4028 return fname; 4029 } 4030 4031 static void reportSettingsProblem(int priority, String msg) { 4032 try { 4033 File fname = getSettingsProblemFile(); 4034 FileOutputStream out = new FileOutputStream(fname, true); 4035 PrintWriter pw = new FastPrintWriter(out); 4036 SimpleDateFormat formatter = new SimpleDateFormat(); 4037 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4038 pw.println(dateString + ": " + msg); 4039 pw.close(); 4040 FileUtils.setPermissions( 4041 fname.toString(), 4042 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4043 -1, -1); 4044 } catch (java.io.IOException e) { 4045 } 4046 Slog.println(priority, TAG, msg); 4047 } 4048 4049 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 4050 PackageParser.Package pkg, File srcFile, int parseFlags) 4051 throws PackageManagerException { 4052 if (ps != null 4053 && ps.codePath.equals(srcFile) 4054 && ps.timeStamp == srcFile.lastModified() 4055 && !isCompatSignatureUpdateNeeded(pkg)) { 4056 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4057 if (ps.signatures.mSignatures != null 4058 && ps.signatures.mSignatures.length != 0 4059 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4060 // Optimization: reuse the existing cached certificates 4061 // if the package appears to be unchanged. 4062 pkg.mSignatures = ps.signatures.mSignatures; 4063 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4064 synchronized (mPackages) { 4065 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 4066 } 4067 return; 4068 } 4069 4070 Slog.w(TAG, "PackageSetting for " + ps.name 4071 + " is missing signatures. Collecting certs again to recover them."); 4072 } else { 4073 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4074 } 4075 4076 try { 4077 pp.collectCertificates(pkg, parseFlags); 4078 pp.collectManifestDigest(pkg); 4079 } catch (PackageParserException e) { 4080 throw PackageManagerException.from(e); 4081 } 4082 } 4083 4084 /* 4085 * Scan a package and return the newly parsed package. 4086 * Returns null in case of errors and the error code is stored in mLastScanError 4087 */ 4088 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 4089 long currentTime, UserHandle user) throws PackageManagerException { 4090 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4091 parseFlags |= mDefParseFlags; 4092 PackageParser pp = new PackageParser(); 4093 pp.setSeparateProcesses(mSeparateProcesses); 4094 pp.setOnlyCoreApps(mOnlyCore); 4095 pp.setDisplayMetrics(mMetrics); 4096 4097 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 4098 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4099 } 4100 4101 final PackageParser.Package pkg; 4102 try { 4103 pkg = pp.parsePackage(scanFile, parseFlags); 4104 } catch (PackageParserException e) { 4105 throw PackageManagerException.from(e); 4106 } 4107 4108 PackageSetting ps = null; 4109 PackageSetting updatedPkg; 4110 // reader 4111 synchronized (mPackages) { 4112 // Look to see if we already know about this package. 4113 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4114 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4115 // This package has been renamed to its original name. Let's 4116 // use that. 4117 ps = mSettings.peekPackageLPr(oldName); 4118 } 4119 // If there was no original package, see one for the real package name. 4120 if (ps == null) { 4121 ps = mSettings.peekPackageLPr(pkg.packageName); 4122 } 4123 // Check to see if this package could be hiding/updating a system 4124 // package. Must look for it either under the original or real 4125 // package name depending on our state. 4126 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4127 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4128 } 4129 boolean updatedPkgBetter = false; 4130 // First check if this is a system package that may involve an update 4131 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4132 if (ps != null && !ps.codePath.equals(scanFile)) { 4133 // The path has changed from what was last scanned... check the 4134 // version of the new path against what we have stored to determine 4135 // what to do. 4136 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4137 if (pkg.mVersionCode < ps.versionCode) { 4138 // The system package has been updated and the code path does not match 4139 // Ignore entry. Skip it. 4140 Log.i(TAG, "Package " + ps.name + " at " + scanFile 4141 + " ignored: updated version " + ps.versionCode 4142 + " better than this " + pkg.mVersionCode); 4143 if (!updatedPkg.codePath.equals(scanFile)) { 4144 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4145 + ps.name + " changing from " + updatedPkg.codePathString 4146 + " to " + scanFile); 4147 updatedPkg.codePath = scanFile; 4148 updatedPkg.codePathString = scanFile.toString(); 4149 // This is the point at which we know that the system-disk APK 4150 // for this package has moved during a reboot (e.g. due to an OTA), 4151 // so we need to reevaluate it for privilege policy. 4152 if (locationIsPrivileged(scanFile)) { 4153 updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED; 4154 } 4155 } 4156 updatedPkg.pkg = pkg; 4157 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 4158 } else { 4159 // The current app on the system partition is better than 4160 // what we have updated to on the data partition; switch 4161 // back to the system partition version. 4162 // At this point, its safely assumed that package installation for 4163 // apps in system partition will go through. If not there won't be a working 4164 // version of the app 4165 // writer 4166 synchronized (mPackages) { 4167 // Just remove the loaded entries from package lists. 4168 mPackages.remove(ps.name); 4169 } 4170 Slog.w(TAG, "Package " + ps.name + " at " + scanFile 4171 + "reverting from " + ps.codePathString 4172 + ": new version " + pkg.mVersionCode 4173 + " better than installed " + ps.versionCode); 4174 4175 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4176 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4177 getAppDexInstructionSets(ps)); 4178 synchronized (mInstallLock) { 4179 args.cleanUpResourcesLI(); 4180 } 4181 synchronized (mPackages) { 4182 mSettings.enableSystemPackageLPw(ps.name); 4183 } 4184 updatedPkgBetter = true; 4185 } 4186 } 4187 } 4188 4189 if (updatedPkg != null) { 4190 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4191 // initially 4192 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4193 4194 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4195 // flag set initially 4196 if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) { 4197 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4198 } 4199 } 4200 4201 // Verify certificates against what was last scanned 4202 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 4203 4204 /* 4205 * A new system app appeared, but we already had a non-system one of the 4206 * same name installed earlier. 4207 */ 4208 boolean shouldHideSystemApp = false; 4209 if (updatedPkg == null && ps != null 4210 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4211 /* 4212 * Check to make sure the signatures match first. If they don't, 4213 * wipe the installed application and its data. 4214 */ 4215 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4216 != PackageManager.SIGNATURE_MATCH) { 4217 if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!"); 4218 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4219 ps = null; 4220 } else { 4221 /* 4222 * If the newly-added system app is an older version than the 4223 * already installed version, hide it. It will be scanned later 4224 * and re-added like an update. 4225 */ 4226 if (pkg.mVersionCode < ps.versionCode) { 4227 shouldHideSystemApp = true; 4228 } else { 4229 /* 4230 * The newly found system app is a newer version that the 4231 * one previously installed. Simply remove the 4232 * already-installed application and replace it with our own 4233 * while keeping the application data. 4234 */ 4235 Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from " 4236 + ps.codePathString + ": new version " + pkg.mVersionCode 4237 + " better than installed " + ps.versionCode); 4238 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4239 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4240 getAppDexInstructionSets(ps)); 4241 synchronized (mInstallLock) { 4242 args.cleanUpResourcesLI(); 4243 } 4244 } 4245 } 4246 } 4247 4248 // The apk is forward locked (not public) if its code and resources 4249 // are kept in different files. (except for app in either system or 4250 // vendor path). 4251 // TODO grab this value from PackageSettings 4252 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4253 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4254 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 4255 } 4256 } 4257 4258 // TODO: extend to support forward-locked splits 4259 String resourcePath = null; 4260 String baseResourcePath = null; 4261 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 4262 if (ps != null && ps.resourcePathString != null) { 4263 resourcePath = ps.resourcePathString; 4264 baseResourcePath = ps.resourcePathString; 4265 } else { 4266 // Should not happen at all. Just log an error. 4267 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 4268 } 4269 } else { 4270 resourcePath = pkg.codePath; 4271 baseResourcePath = pkg.baseCodePath; 4272 } 4273 4274 // Set application objects path explicitly. 4275 pkg.applicationInfo.setCodePath(pkg.codePath); 4276 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 4277 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 4278 pkg.applicationInfo.setResourcePath(resourcePath); 4279 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 4280 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 4281 4282 // Note that we invoke the following method only if we are about to unpack an application 4283 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 4284 | SCAN_UPDATE_SIGNATURE, currentTime, user); 4285 4286 /* 4287 * If the system app should be overridden by a previously installed 4288 * data, hide the system app now and let the /data/app scan pick it up 4289 * again. 4290 */ 4291 if (shouldHideSystemApp) { 4292 synchronized (mPackages) { 4293 /* 4294 * We have to grant systems permissions before we hide, because 4295 * grantPermissions will assume the package update is trying to 4296 * expand its permissions. 4297 */ 4298 grantPermissionsLPw(pkg, true); 4299 mSettings.disableSystemPackageLPw(pkg.packageName); 4300 } 4301 } 4302 4303 return scannedPkg; 4304 } 4305 4306 private static String fixProcessName(String defProcessName, 4307 String processName, int uid) { 4308 if (processName == null) { 4309 return defProcessName; 4310 } 4311 return processName; 4312 } 4313 4314 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 4315 throws PackageManagerException { 4316 if (pkgSetting.signatures.mSignatures != null) { 4317 // Already existing package. Make sure signatures match 4318 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 4319 == PackageManager.SIGNATURE_MATCH; 4320 if (!match) { 4321 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 4322 == PackageManager.SIGNATURE_MATCH; 4323 } 4324 if (!match) { 4325 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 4326 + pkg.packageName + " signatures do not match the " 4327 + "previously installed version; ignoring!"); 4328 } 4329 } 4330 4331 // Check for shared user signatures 4332 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 4333 // Already existing package. Make sure signatures match 4334 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4335 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 4336 if (!match) { 4337 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 4338 == PackageManager.SIGNATURE_MATCH; 4339 } 4340 if (!match) { 4341 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 4342 "Package " + pkg.packageName 4343 + " has no signatures that match those in shared user " 4344 + pkgSetting.sharedUser.name + "; ignoring!"); 4345 } 4346 } 4347 } 4348 4349 /** 4350 * Enforces that only the system UID or root's UID can call a method exposed 4351 * via Binder. 4352 * 4353 * @param message used as message if SecurityException is thrown 4354 * @throws SecurityException if the caller is not system or root 4355 */ 4356 private static final void enforceSystemOrRoot(String message) { 4357 final int uid = Binder.getCallingUid(); 4358 if (uid != Process.SYSTEM_UID && uid != 0) { 4359 throw new SecurityException(message); 4360 } 4361 } 4362 4363 @Override 4364 public void performBootDexOpt() { 4365 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4366 4367 final HashSet<PackageParser.Package> pkgs; 4368 synchronized (mPackages) { 4369 pkgs = mDeferredDexOpt; 4370 mDeferredDexOpt = null; 4371 } 4372 4373 if (pkgs != null) { 4374 // Filter out packages that aren't recently used. 4375 // 4376 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 4377 // should do a full dexopt. 4378 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 4379 // TODO: add a property to control this? 4380 long dexOptLRUThresholdInMinutes; 4381 if (mLazyDexOpt) { 4382 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 4383 } else { 4384 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 4385 } 4386 long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 4387 4388 int total = pkgs.size(); 4389 int skipped = 0; 4390 long now = System.currentTimeMillis(); 4391 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 4392 PackageParser.Package pkg = i.next(); 4393 long then = pkg.mLastPackageUsageTimeInMills; 4394 if (then + dexOptLRUThresholdInMills < now) { 4395 if (DEBUG_DEXOPT) { 4396 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 4397 ((then == 0) ? "never" : new Date(then))); 4398 } 4399 i.remove(); 4400 skipped++; 4401 } 4402 } 4403 if (DEBUG_DEXOPT) { 4404 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 4405 } 4406 } 4407 4408 int i = 0; 4409 for (PackageParser.Package pkg : pkgs) { 4410 i++; 4411 if (DEBUG_DEXOPT) { 4412 Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size() 4413 + ": " + pkg.packageName); 4414 } 4415 if (!isFirstBoot()) { 4416 try { 4417 ActivityManagerNative.getDefault().showBootMessage( 4418 mContext.getResources().getString( 4419 R.string.android_upgrading_apk, 4420 i, pkgs.size()), true); 4421 } catch (RemoteException e) { 4422 } 4423 } 4424 PackageParser.Package p = pkg; 4425 synchronized (mInstallLock) { 4426 performDexOptLI(p, null /* instruction sets */, false /* force dex */, false /* defer */, 4427 true /* include dependencies */); 4428 } 4429 } 4430 } 4431 } 4432 4433 @Override 4434 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 4435 return performDexOpt(packageName, instructionSet, false); 4436 } 4437 4438 private static String getPrimaryInstructionSet(ApplicationInfo info) { 4439 if (info.primaryCpuAbi == null) { 4440 return getPreferredInstructionSet(); 4441 } 4442 4443 return VMRuntime.getInstructionSet(info.primaryCpuAbi); 4444 } 4445 4446 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 4447 boolean dexopt = mLazyDexOpt || backgroundDexopt; 4448 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 4449 if (!dexopt && !updateUsage) { 4450 // We aren't going to dexopt or update usage, so bail early. 4451 return false; 4452 } 4453 PackageParser.Package p; 4454 final String targetInstructionSet; 4455 synchronized (mPackages) { 4456 p = mPackages.get(packageName); 4457 if (p == null) { 4458 return false; 4459 } 4460 if (updateUsage) { 4461 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 4462 } 4463 mPackageUsage.write(false); 4464 if (!dexopt) { 4465 // We aren't going to dexopt, so bail early. 4466 return false; 4467 } 4468 4469 targetInstructionSet = instructionSet != null ? instructionSet : 4470 getPrimaryInstructionSet(p.applicationInfo); 4471 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 4472 return false; 4473 } 4474 } 4475 4476 synchronized (mInstallLock) { 4477 final String[] instructionSets = new String[] { targetInstructionSet }; 4478 return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */, 4479 true /* include dependencies */) == DEX_OPT_PERFORMED; 4480 } 4481 } 4482 4483 public HashSet<String> getPackagesThatNeedDexOpt() { 4484 HashSet<String> pkgs = null; 4485 synchronized (mPackages) { 4486 for (PackageParser.Package p : mPackages.values()) { 4487 if (DEBUG_DEXOPT) { 4488 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 4489 } 4490 if (!p.mDexOptPerformed.isEmpty()) { 4491 continue; 4492 } 4493 if (pkgs == null) { 4494 pkgs = new HashSet<String>(); 4495 } 4496 pkgs.add(p.packageName); 4497 } 4498 } 4499 return pkgs; 4500 } 4501 4502 public void shutdown() { 4503 mPackageUsage.write(true); 4504 } 4505 4506 private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets, 4507 boolean forceDex, boolean defer, HashSet<String> done) { 4508 for (int i=0; i<libs.size(); i++) { 4509 PackageParser.Package libPkg; 4510 String libName; 4511 synchronized (mPackages) { 4512 libName = libs.get(i); 4513 SharedLibraryEntry lib = mSharedLibraries.get(libName); 4514 if (lib != null && lib.apk != null) { 4515 libPkg = mPackages.get(lib.apk); 4516 } else { 4517 libPkg = null; 4518 } 4519 } 4520 if (libPkg != null && !done.contains(libName)) { 4521 performDexOptLI(libPkg, instructionSets, forceDex, defer, done); 4522 } 4523 } 4524 } 4525 4526 static final int DEX_OPT_SKIPPED = 0; 4527 static final int DEX_OPT_PERFORMED = 1; 4528 static final int DEX_OPT_DEFERRED = 2; 4529 static final int DEX_OPT_FAILED = -1; 4530 4531 private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets, 4532 boolean forceDex, boolean defer, HashSet<String> done) { 4533 final String[] instructionSets = targetInstructionSets != null ? 4534 targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo); 4535 4536 if (done != null) { 4537 done.add(pkg.packageName); 4538 if (pkg.usesLibraries != null) { 4539 performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done); 4540 } 4541 if (pkg.usesOptionalLibraries != null) { 4542 performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done); 4543 } 4544 } 4545 4546 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) { 4547 return DEX_OPT_SKIPPED; 4548 } 4549 4550 final boolean vmSafeMode = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0; 4551 4552 final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly(); 4553 boolean performedDexOpt = false; 4554 // There are three basic cases here: 4555 // 1.) we need to dexopt, either because we are forced or it is needed 4556 // 2.) we are defering a needed dexopt 4557 // 3.) we are skipping an unneeded dexopt 4558 final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 4559 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 4560 if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) { 4561 continue; 4562 } 4563 4564 for (String path : paths) { 4565 try { 4566 // This will return DEXOPT_NEEDED if we either cannot find any odex file for this 4567 // patckage or the one we find does not match the image checksum (i.e. it was 4568 // compiled against an old image). It will return PATCHOAT_NEEDED if we can find a 4569 // odex file and it matches the checksum of the image but not its base address, 4570 // meaning we need to move it. 4571 final byte isDexOptNeeded = DexFile.isDexOptNeededInternal(path, 4572 pkg.packageName, dexCodeInstructionSet, defer); 4573 if (forceDex || (!defer && isDexOptNeeded == DexFile.DEXOPT_NEEDED)) { 4574 Log.i(TAG, "Running dexopt on: " + path + " pkg=" 4575 + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet 4576 + " vmSafeMode=" + vmSafeMode); 4577 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4578 final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg), 4579 pkg.packageName, dexCodeInstructionSet, vmSafeMode); 4580 4581 if (ret < 0) { 4582 // Don't bother running dexopt again if we failed, it will probably 4583 // just result in an error again. Also, don't bother dexopting for other 4584 // paths & ISAs. 4585 return DEX_OPT_FAILED; 4586 } 4587 4588 performedDexOpt = true; 4589 } else if (!defer && isDexOptNeeded == DexFile.PATCHOAT_NEEDED) { 4590 Log.i(TAG, "Running patchoat on: " + pkg.applicationInfo.packageName); 4591 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4592 final int ret = mInstaller.patchoat(path, sharedGid, !isForwardLocked(pkg), 4593 pkg.packageName, dexCodeInstructionSet); 4594 4595 if (ret < 0) { 4596 // Don't bother running patchoat again if we failed, it will probably 4597 // just result in an error again. Also, don't bother dexopting for other 4598 // paths & ISAs. 4599 return DEX_OPT_FAILED; 4600 } 4601 4602 performedDexOpt = true; 4603 } 4604 4605 // We're deciding to defer a needed dexopt. Don't bother dexopting for other 4606 // paths and instruction sets. We'll deal with them all together when we process 4607 // our list of deferred dexopts. 4608 if (defer && isDexOptNeeded != DexFile.UP_TO_DATE) { 4609 if (mDeferredDexOpt == null) { 4610 mDeferredDexOpt = new HashSet<PackageParser.Package>(); 4611 } 4612 mDeferredDexOpt.add(pkg); 4613 return DEX_OPT_DEFERRED; 4614 } 4615 } catch (FileNotFoundException e) { 4616 Slog.w(TAG, "Apk not found for dexopt: " + path); 4617 return DEX_OPT_FAILED; 4618 } catch (IOException e) { 4619 Slog.w(TAG, "IOException reading apk: " + path, e); 4620 return DEX_OPT_FAILED; 4621 } catch (StaleDexCacheError e) { 4622 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e); 4623 return DEX_OPT_FAILED; 4624 } catch (Exception e) { 4625 Slog.w(TAG, "Exception when doing dexopt : ", e); 4626 return DEX_OPT_FAILED; 4627 } 4628 } 4629 4630 // At this point we haven't failed dexopt and we haven't deferred dexopt. We must 4631 // either have either succeeded dexopt, or have had isDexOptNeededInternal tell us 4632 // it isn't required. We therefore mark that this package doesn't need dexopt unless 4633 // it's forced. performedDexOpt will tell us whether we performed dex-opt or skipped 4634 // it. 4635 pkg.mDexOptPerformed.add(dexCodeInstructionSet); 4636 } 4637 4638 // If we've gotten here, we're sure that no error occurred and that we haven't 4639 // deferred dex-opt. We've either dex-opted one more paths or instruction sets or 4640 // we've skipped all of them because they are up to date. In both cases this 4641 // package doesn't need dexopt any longer. 4642 return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED; 4643 } 4644 4645 private static String[] getAppDexInstructionSets(ApplicationInfo info) { 4646 if (info.primaryCpuAbi != null) { 4647 if (info.secondaryCpuAbi != null) { 4648 return new String[] { 4649 VMRuntime.getInstructionSet(info.primaryCpuAbi), 4650 VMRuntime.getInstructionSet(info.secondaryCpuAbi) }; 4651 } else { 4652 return new String[] { 4653 VMRuntime.getInstructionSet(info.primaryCpuAbi) }; 4654 } 4655 } 4656 4657 return new String[] { getPreferredInstructionSet() }; 4658 } 4659 4660 private static String[] getAppDexInstructionSets(PackageSetting ps) { 4661 if (ps.primaryCpuAbiString != null) { 4662 if (ps.secondaryCpuAbiString != null) { 4663 return new String[] { 4664 VMRuntime.getInstructionSet(ps.primaryCpuAbiString), 4665 VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) }; 4666 } else { 4667 return new String[] { 4668 VMRuntime.getInstructionSet(ps.primaryCpuAbiString) }; 4669 } 4670 } 4671 4672 return new String[] { getPreferredInstructionSet() }; 4673 } 4674 4675 private static String getPreferredInstructionSet() { 4676 if (sPreferredInstructionSet == null) { 4677 sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]); 4678 } 4679 4680 return sPreferredInstructionSet; 4681 } 4682 4683 private static List<String> getAllInstructionSets() { 4684 final String[] allAbis = Build.SUPPORTED_ABIS; 4685 final List<String> allInstructionSets = new ArrayList<String>(allAbis.length); 4686 4687 for (String abi : allAbis) { 4688 final String instructionSet = VMRuntime.getInstructionSet(abi); 4689 if (!allInstructionSets.contains(instructionSet)) { 4690 allInstructionSets.add(instructionSet); 4691 } 4692 } 4693 4694 return allInstructionSets; 4695 } 4696 4697 /** 4698 * Returns the instruction set that should be used to compile dex code. In the presence of 4699 * a native bridge this might be different than the one shared libraries use. 4700 */ 4701 private static String getDexCodeInstructionSet(String sharedLibraryIsa) { 4702 String dexCodeIsa = SystemProperties.get("ro.dalvik.vm.isa." + sharedLibraryIsa); 4703 return (dexCodeIsa.isEmpty() ? sharedLibraryIsa : dexCodeIsa); 4704 } 4705 4706 private static String[] getDexCodeInstructionSets(String[] instructionSets) { 4707 HashSet<String> dexCodeInstructionSets = new HashSet<String>(instructionSets.length); 4708 for (String instructionSet : instructionSets) { 4709 dexCodeInstructionSets.add(getDexCodeInstructionSet(instructionSet)); 4710 } 4711 return dexCodeInstructionSets.toArray(new String[dexCodeInstructionSets.size()]); 4712 } 4713 4714 @Override 4715 public void forceDexOpt(String packageName) { 4716 enforceSystemOrRoot("forceDexOpt"); 4717 4718 PackageParser.Package pkg; 4719 synchronized (mPackages) { 4720 pkg = mPackages.get(packageName); 4721 if (pkg == null) { 4722 throw new IllegalArgumentException("Missing package: " + packageName); 4723 } 4724 } 4725 4726 synchronized (mInstallLock) { 4727 final String[] instructionSets = new String[] { 4728 getPrimaryInstructionSet(pkg.applicationInfo) }; 4729 final int res = performDexOptLI(pkg, instructionSets, true, false, true); 4730 if (res != DEX_OPT_PERFORMED) { 4731 throw new IllegalStateException("Failed to dexopt: " + res); 4732 } 4733 } 4734 } 4735 4736 private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets, 4737 boolean forceDex, boolean defer, boolean inclDependencies) { 4738 HashSet<String> done; 4739 if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) { 4740 done = new HashSet<String>(); 4741 done.add(pkg.packageName); 4742 } else { 4743 done = null; 4744 } 4745 return performDexOptLI(pkg, instructionSets, forceDex, defer, done); 4746 } 4747 4748 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 4749 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 4750 Slog.w(TAG, "Unable to update from " + oldPkg.name 4751 + " to " + newPkg.packageName 4752 + ": old package not in system partition"); 4753 return false; 4754 } else if (mPackages.get(oldPkg.name) != null) { 4755 Slog.w(TAG, "Unable to update from " + oldPkg.name 4756 + " to " + newPkg.packageName 4757 + ": old package still exists"); 4758 return false; 4759 } 4760 return true; 4761 } 4762 4763 File getDataPathForUser(int userId) { 4764 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId); 4765 } 4766 4767 private File getDataPathForPackage(String packageName, int userId) { 4768 /* 4769 * Until we fully support multiple users, return the directory we 4770 * previously would have. The PackageManagerTests will need to be 4771 * revised when this is changed back.. 4772 */ 4773 if (userId == 0) { 4774 return new File(mAppDataDir, packageName); 4775 } else { 4776 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 4777 + File.separator + packageName); 4778 } 4779 } 4780 4781 private int createDataDirsLI(String packageName, int uid, String seinfo) { 4782 int[] users = sUserManager.getUserIds(); 4783 int res = mInstaller.install(packageName, uid, uid, seinfo); 4784 if (res < 0) { 4785 return res; 4786 } 4787 for (int user : users) { 4788 if (user != 0) { 4789 res = mInstaller.createUserData(packageName, 4790 UserHandle.getUid(user, uid), user, seinfo); 4791 if (res < 0) { 4792 return res; 4793 } 4794 } 4795 } 4796 return res; 4797 } 4798 4799 private int removeDataDirsLI(String packageName) { 4800 int[] users = sUserManager.getUserIds(); 4801 int res = 0; 4802 for (int user : users) { 4803 int resInner = mInstaller.remove(packageName, user); 4804 if (resInner < 0) { 4805 res = resInner; 4806 } 4807 } 4808 4809 return res; 4810 } 4811 4812 private int deleteCodeCacheDirsLI(String packageName) { 4813 int[] users = sUserManager.getUserIds(); 4814 int res = 0; 4815 for (int user : users) { 4816 int resInner = mInstaller.deleteCodeCacheFiles(packageName, user); 4817 if (resInner < 0) { 4818 res = resInner; 4819 } 4820 } 4821 return res; 4822 } 4823 4824 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 4825 PackageParser.Package changingLib) { 4826 if (file.path != null) { 4827 usesLibraryFiles.add(file.path); 4828 return; 4829 } 4830 PackageParser.Package p = mPackages.get(file.apk); 4831 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 4832 // If we are doing this while in the middle of updating a library apk, 4833 // then we need to make sure to use that new apk for determining the 4834 // dependencies here. (We haven't yet finished committing the new apk 4835 // to the package manager state.) 4836 if (p == null || p.packageName.equals(changingLib.packageName)) { 4837 p = changingLib; 4838 } 4839 } 4840 if (p != null) { 4841 usesLibraryFiles.addAll(p.getAllCodePaths()); 4842 } 4843 } 4844 4845 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 4846 PackageParser.Package changingLib) throws PackageManagerException { 4847 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 4848 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 4849 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 4850 for (int i=0; i<N; i++) { 4851 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 4852 if (file == null) { 4853 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 4854 "Package " + pkg.packageName + " requires unavailable shared library " 4855 + pkg.usesLibraries.get(i) + "; failing!"); 4856 } 4857 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4858 } 4859 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 4860 for (int i=0; i<N; i++) { 4861 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 4862 if (file == null) { 4863 Slog.w(TAG, "Package " + pkg.packageName 4864 + " desires unavailable shared library " 4865 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 4866 } else { 4867 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4868 } 4869 } 4870 N = usesLibraryFiles.size(); 4871 if (N > 0) { 4872 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 4873 } else { 4874 pkg.usesLibraryFiles = null; 4875 } 4876 } 4877 } 4878 4879 private static boolean hasString(List<String> list, List<String> which) { 4880 if (list == null) { 4881 return false; 4882 } 4883 for (int i=list.size()-1; i>=0; i--) { 4884 for (int j=which.size()-1; j>=0; j--) { 4885 if (which.get(j).equals(list.get(i))) { 4886 return true; 4887 } 4888 } 4889 } 4890 return false; 4891 } 4892 4893 private void updateAllSharedLibrariesLPw() { 4894 for (PackageParser.Package pkg : mPackages.values()) { 4895 try { 4896 updateSharedLibrariesLPw(pkg, null); 4897 } catch (PackageManagerException e) { 4898 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 4899 } 4900 } 4901 } 4902 4903 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 4904 PackageParser.Package changingPkg) { 4905 ArrayList<PackageParser.Package> res = null; 4906 for (PackageParser.Package pkg : mPackages.values()) { 4907 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 4908 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 4909 if (res == null) { 4910 res = new ArrayList<PackageParser.Package>(); 4911 } 4912 res.add(pkg); 4913 try { 4914 updateSharedLibrariesLPw(pkg, changingPkg); 4915 } catch (PackageManagerException e) { 4916 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 4917 } 4918 } 4919 } 4920 return res; 4921 } 4922 4923 /** 4924 * Derive the value of the {@code cpuAbiOverride} based on the provided 4925 * value and an optional stored value from the package settings. 4926 */ 4927 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 4928 String cpuAbiOverride = null; 4929 4930 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 4931 cpuAbiOverride = null; 4932 } else if (abiOverride != null) { 4933 cpuAbiOverride = abiOverride; 4934 } else if (settings != null) { 4935 cpuAbiOverride = settings.cpuAbiOverrideString; 4936 } 4937 4938 return cpuAbiOverride; 4939 } 4940 4941 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 4942 int scanFlags, long currentTime, UserHandle user) 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 ((scanFlags & 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 = (scanFlags & 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 || (scanFlags&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 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 5378 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 5379 setBundledAppAbisAndRoots(pkg, pkgSetting); 5380 5381 // If we haven't found any native libraries for the app, check if it has 5382 // renderscript code. We'll need to force the app to 32 bit if it has 5383 // renderscript bitcode. 5384 if (pkg.applicationInfo.primaryCpuAbi == null 5385 && pkg.applicationInfo.secondaryCpuAbi == null 5386 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5387 NativeLibraryHelper.Handle handle = null; 5388 try { 5389 handle = NativeLibraryHelper.Handle.create(scanFile); 5390 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5391 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 5392 } 5393 } catch (IOException ioe) { 5394 Slog.w(TAG, "Error scanning system app : " + ioe); 5395 } finally { 5396 IoUtils.closeQuietly(handle); 5397 } 5398 } 5399 5400 setNativeLibraryPaths(pkg); 5401 } else { 5402 // TODO: We can probably be smarter about this stuff. For installed apps, 5403 // we can calculate this information at install time once and for all. For 5404 // system apps, we can probably assume that this information doesn't change 5405 // after the first boot scan. As things stand, we do lots of unnecessary work. 5406 5407 // Give ourselves some initial paths; we'll come back for another 5408 // pass once we've determined ABI below. 5409 setNativeLibraryPaths(pkg); 5410 5411 final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg); 5412 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 5413 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 5414 5415 NativeLibraryHelper.Handle handle = null; 5416 try { 5417 handle = NativeLibraryHelper.Handle.create(scanFile); 5418 // TODO(multiArch): This can be null for apps that didn't go through the 5419 // usual installation process. We can calculate it again, like we 5420 // do during install time. 5421 // 5422 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 5423 // unnecessary. 5424 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 5425 5426 // Null out the abis so that they can be recalculated. 5427 pkg.applicationInfo.primaryCpuAbi = null; 5428 pkg.applicationInfo.secondaryCpuAbi = null; 5429 if (isMultiArch(pkg.applicationInfo)) { 5430 // Warn if we've set an abiOverride for multi-lib packages.. 5431 // By definition, we need to copy both 32 and 64 bit libraries for 5432 // such packages. 5433 if (pkg.cpuAbiOverride != null 5434 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 5435 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 5436 } 5437 5438 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 5439 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 5440 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 5441 if (isAsec) { 5442 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 5443 } else { 5444 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5445 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 5446 useIsaSpecificSubdirs); 5447 } 5448 } 5449 5450 maybeThrowExceptionForMultiArchCopy( 5451 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 5452 5453 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5454 if (isAsec) { 5455 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 5456 } else { 5457 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5458 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 5459 useIsaSpecificSubdirs); 5460 } 5461 } 5462 5463 maybeThrowExceptionForMultiArchCopy( 5464 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 5465 5466 if (abi64 >= 0) { 5467 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 5468 } 5469 5470 if (abi32 >= 0) { 5471 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 5472 if (abi64 >= 0) { 5473 pkg.applicationInfo.secondaryCpuAbi = abi; 5474 } else { 5475 pkg.applicationInfo.primaryCpuAbi = abi; 5476 } 5477 } 5478 } else { 5479 String[] abiList = (cpuAbiOverride != null) ? 5480 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 5481 5482 // Enable gross and lame hacks for apps that are built with old 5483 // SDK tools. We must scan their APKs for renderscript bitcode and 5484 // not launch them if it's present. Don't bother checking on devices 5485 // that don't have 64 bit support. 5486 boolean needsRenderScriptOverride = false; 5487 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 5488 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5489 abiList = Build.SUPPORTED_32_BIT_ABIS; 5490 needsRenderScriptOverride = true; 5491 } 5492 5493 final int copyRet; 5494 if (isAsec) { 5495 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 5496 } else { 5497 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5498 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 5499 } 5500 5501 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5502 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5503 "Error unpackaging native libs for app, errorCode=" + copyRet); 5504 } 5505 5506 if (copyRet >= 0) { 5507 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 5508 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 5509 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 5510 } else if (needsRenderScriptOverride) { 5511 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 5512 } 5513 } 5514 } catch (IOException ioe) { 5515 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 5516 } finally { 5517 IoUtils.closeQuietly(handle); 5518 } 5519 5520 // Now that we've calculated the ABIs and determined if it's an internal app, 5521 // we will go ahead and populate the nativeLibraryPath. 5522 setNativeLibraryPaths(pkg); 5523 5524 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 5525 final int[] userIds = sUserManager.getUserIds(); 5526 synchronized (mInstallLock) { 5527 // Create a native library symlink only if we have native libraries 5528 // and if the native libraries are 32 bit libraries. We do not provide 5529 // this symlink for 64 bit libraries. 5530 if (pkg.applicationInfo.primaryCpuAbi != null && 5531 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 5532 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 5533 for (int userId : userIds) { 5534 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 5535 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5536 "Failed linking native library dir (user=" + userId + ")"); 5537 } 5538 } 5539 } 5540 } 5541 } 5542 5543 // This is a special case for the "system" package, where the ABI is 5544 // dictated by the zygote configuration (and init.rc). We should keep track 5545 // of this ABI so that we can deal with "normal" applications that run under 5546 // the same UID correctly. 5547 if (mPlatformPackage == pkg) { 5548 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 5549 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 5550 } 5551 5552 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 5553 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 5554 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 5555 // Copy the derived override back to the parsed package, so that we can 5556 // update the package settings accordingly. 5557 pkg.cpuAbiOverride = cpuAbiOverride; 5558 5559 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 5560 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 5561 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 5562 5563 // Push the derived path down into PackageSettings so we know what to 5564 // clean up at uninstall time. 5565 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 5566 5567 if (DEBUG_ABI_SELECTION) { 5568 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 5569 " primary=" + pkg.applicationInfo.primaryCpuAbi + 5570 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 5571 } 5572 5573 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 5574 // We don't do this here during boot because we can do it all 5575 // at once after scanning all existing packages. 5576 // 5577 // We also do this *before* we perform dexopt on this package, so that 5578 // we can avoid redundant dexopts, and also to make sure we've got the 5579 // code and package path correct. 5580 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 5581 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 5582 } 5583 5584 if ((scanFlags&SCAN_NO_DEX) == 0) { 5585 if (performDexOptLI(pkg, null /* instruction sets */, forceDex, (scanFlags&SCAN_DEFER_DEX) != 0, false) 5586 == DEX_OPT_FAILED) { 5587 if ((scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5588 removeDataDirsLI(pkg.packageName); 5589 } 5590 5591 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 5592 } 5593 } 5594 5595 if (mFactoryTest && pkg.requestedPermissions.contains( 5596 android.Manifest.permission.FACTORY_TEST)) { 5597 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 5598 } 5599 5600 ArrayList<PackageParser.Package> clientLibPkgs = null; 5601 5602 // writer 5603 synchronized (mPackages) { 5604 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5605 // Only system apps can add new shared libraries. 5606 if (pkg.libraryNames != null) { 5607 for (int i=0; i<pkg.libraryNames.size(); i++) { 5608 String name = pkg.libraryNames.get(i); 5609 boolean allowed = false; 5610 if (isUpdatedSystemApp(pkg)) { 5611 // New library entries can only be added through the 5612 // system image. This is important to get rid of a lot 5613 // of nasty edge cases: for example if we allowed a non- 5614 // system update of the app to add a library, then uninstalling 5615 // the update would make the library go away, and assumptions 5616 // we made such as through app install filtering would now 5617 // have allowed apps on the device which aren't compatible 5618 // with it. Better to just have the restriction here, be 5619 // conservative, and create many fewer cases that can negatively 5620 // impact the user experience. 5621 final PackageSetting sysPs = mSettings 5622 .getDisabledSystemPkgLPr(pkg.packageName); 5623 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 5624 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 5625 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 5626 allowed = true; 5627 allowed = true; 5628 break; 5629 } 5630 } 5631 } 5632 } else { 5633 allowed = true; 5634 } 5635 if (allowed) { 5636 if (!mSharedLibraries.containsKey(name)) { 5637 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 5638 } else if (!name.equals(pkg.packageName)) { 5639 Slog.w(TAG, "Package " + pkg.packageName + " library " 5640 + name + " already exists; skipping"); 5641 } 5642 } else { 5643 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 5644 + name + " that is not declared on system image; skipping"); 5645 } 5646 } 5647 if ((scanFlags&SCAN_BOOTING) == 0) { 5648 // If we are not booting, we need to update any applications 5649 // that are clients of our shared library. If we are booting, 5650 // this will all be done once the scan is complete. 5651 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 5652 } 5653 } 5654 } 5655 } 5656 5657 // We also need to dexopt any apps that are dependent on this library. Note that 5658 // if these fail, we should abort the install since installing the library will 5659 // result in some apps being broken. 5660 if (clientLibPkgs != null) { 5661 if ((scanFlags&SCAN_NO_DEX) == 0) { 5662 for (int i=0; i<clientLibPkgs.size(); i++) { 5663 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5664 if (performDexOptLI(clientPkg, null /* instruction sets */, 5665 forceDex, (scanFlags&SCAN_DEFER_DEX) != 0, false) 5666 == DEX_OPT_FAILED) { 5667 if ((scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5668 removeDataDirsLI(pkg.packageName); 5669 } 5670 5671 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 5672 "scanPackageLI failed to dexopt clientLibPkgs"); 5673 } 5674 } 5675 } 5676 } 5677 5678 // Request the ActivityManager to kill the process(only for existing packages) 5679 // so that we do not end up in a confused state while the user is still using the older 5680 // version of the application while the new one gets installed. 5681 if ((scanFlags & SCAN_REPLACING) != 0) { 5682 killApplication(pkg.applicationInfo.packageName, 5683 pkg.applicationInfo.uid, "update pkg"); 5684 } 5685 5686 // Also need to kill any apps that are dependent on the library. 5687 if (clientLibPkgs != null) { 5688 for (int i=0; i<clientLibPkgs.size(); i++) { 5689 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5690 killApplication(clientPkg.applicationInfo.packageName, 5691 clientPkg.applicationInfo.uid, "update lib"); 5692 } 5693 } 5694 5695 // writer 5696 synchronized (mPackages) { 5697 // We don't expect installation to fail beyond this point 5698 5699 // Add the new setting to mSettings 5700 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 5701 // Add the new setting to mPackages 5702 mPackages.put(pkg.applicationInfo.packageName, pkg); 5703 // Make sure we don't accidentally delete its data. 5704 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 5705 while (iter.hasNext()) { 5706 PackageCleanItem item = iter.next(); 5707 if (pkgName.equals(item.packageName)) { 5708 iter.remove(); 5709 } 5710 } 5711 5712 // Take care of first install / last update times. 5713 if (currentTime != 0) { 5714 if (pkgSetting.firstInstallTime == 0) { 5715 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 5716 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 5717 pkgSetting.lastUpdateTime = currentTime; 5718 } 5719 } else if (pkgSetting.firstInstallTime == 0) { 5720 // We need *something*. Take time time stamp of the file. 5721 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 5722 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 5723 if (scanFileTime != pkgSetting.timeStamp) { 5724 // A package on the system image has changed; consider this 5725 // to be an update. 5726 pkgSetting.lastUpdateTime = scanFileTime; 5727 } 5728 } 5729 5730 // Add the package's KeySets to the global KeySetManagerService 5731 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5732 try { 5733 // Old KeySetData no longer valid. 5734 ksms.removeAppKeySetDataLPw(pkg.packageName); 5735 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 5736 if (pkg.mKeySetMapping != null) { 5737 for (Map.Entry<String, ArraySet<PublicKey>> entry : 5738 pkg.mKeySetMapping.entrySet()) { 5739 if (entry.getValue() != null) { 5740 ksms.addDefinedKeySetToPackageLPw(pkg.packageName, 5741 entry.getValue(), entry.getKey()); 5742 } 5743 } 5744 if (pkg.mUpgradeKeySets != null) { 5745 for (String upgradeAlias : pkg.mUpgradeKeySets) { 5746 ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias); 5747 } 5748 } 5749 } 5750 } catch (NullPointerException e) { 5751 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 5752 } catch (IllegalArgumentException e) { 5753 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 5754 } 5755 5756 int N = pkg.providers.size(); 5757 StringBuilder r = null; 5758 int i; 5759 for (i=0; i<N; i++) { 5760 PackageParser.Provider p = pkg.providers.get(i); 5761 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 5762 p.info.processName, pkg.applicationInfo.uid); 5763 mProviders.addProvider(p); 5764 p.syncable = p.info.isSyncable; 5765 if (p.info.authority != null) { 5766 String names[] = p.info.authority.split(";"); 5767 p.info.authority = null; 5768 for (int j = 0; j < names.length; j++) { 5769 if (j == 1 && p.syncable) { 5770 // We only want the first authority for a provider to possibly be 5771 // syncable, so if we already added this provider using a different 5772 // authority clear the syncable flag. We copy the provider before 5773 // changing it because the mProviders object contains a reference 5774 // to a provider that we don't want to change. 5775 // Only do this for the second authority since the resulting provider 5776 // object can be the same for all future authorities for this provider. 5777 p = new PackageParser.Provider(p); 5778 p.syncable = false; 5779 } 5780 if (!mProvidersByAuthority.containsKey(names[j])) { 5781 mProvidersByAuthority.put(names[j], p); 5782 if (p.info.authority == null) { 5783 p.info.authority = names[j]; 5784 } else { 5785 p.info.authority = p.info.authority + ";" + names[j]; 5786 } 5787 if (DEBUG_PACKAGE_SCANNING) { 5788 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5789 Log.d(TAG, "Registered content provider: " + names[j] 5790 + ", className = " + p.info.name + ", isSyncable = " 5791 + p.info.isSyncable); 5792 } 5793 } else { 5794 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5795 Slog.w(TAG, "Skipping provider name " + names[j] + 5796 " (in package " + pkg.applicationInfo.packageName + 5797 "): name already used by " 5798 + ((other != null && other.getComponentName() != null) 5799 ? other.getComponentName().getPackageName() : "?")); 5800 } 5801 } 5802 } 5803 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5804 if (r == null) { 5805 r = new StringBuilder(256); 5806 } else { 5807 r.append(' '); 5808 } 5809 r.append(p.info.name); 5810 } 5811 } 5812 if (r != null) { 5813 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 5814 } 5815 5816 N = pkg.services.size(); 5817 r = null; 5818 for (i=0; i<N; i++) { 5819 PackageParser.Service s = pkg.services.get(i); 5820 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 5821 s.info.processName, pkg.applicationInfo.uid); 5822 mServices.addService(s); 5823 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5824 if (r == null) { 5825 r = new StringBuilder(256); 5826 } else { 5827 r.append(' '); 5828 } 5829 r.append(s.info.name); 5830 } 5831 } 5832 if (r != null) { 5833 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 5834 } 5835 5836 N = pkg.receivers.size(); 5837 r = null; 5838 for (i=0; i<N; i++) { 5839 PackageParser.Activity a = pkg.receivers.get(i); 5840 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5841 a.info.processName, pkg.applicationInfo.uid); 5842 mReceivers.addActivity(a, "receiver"); 5843 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5844 if (r == null) { 5845 r = new StringBuilder(256); 5846 } else { 5847 r.append(' '); 5848 } 5849 r.append(a.info.name); 5850 } 5851 } 5852 if (r != null) { 5853 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 5854 } 5855 5856 N = pkg.activities.size(); 5857 r = null; 5858 for (i=0; i<N; i++) { 5859 PackageParser.Activity a = pkg.activities.get(i); 5860 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5861 a.info.processName, pkg.applicationInfo.uid); 5862 mActivities.addActivity(a, "activity"); 5863 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5864 if (r == null) { 5865 r = new StringBuilder(256); 5866 } else { 5867 r.append(' '); 5868 } 5869 r.append(a.info.name); 5870 } 5871 } 5872 if (r != null) { 5873 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 5874 } 5875 5876 N = pkg.permissionGroups.size(); 5877 r = null; 5878 for (i=0; i<N; i++) { 5879 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 5880 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 5881 if (cur == null) { 5882 mPermissionGroups.put(pg.info.name, pg); 5883 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5884 if (r == null) { 5885 r = new StringBuilder(256); 5886 } else { 5887 r.append(' '); 5888 } 5889 r.append(pg.info.name); 5890 } 5891 } else { 5892 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 5893 + pg.info.packageName + " ignored: original from " 5894 + cur.info.packageName); 5895 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5896 if (r == null) { 5897 r = new StringBuilder(256); 5898 } else { 5899 r.append(' '); 5900 } 5901 r.append("DUP:"); 5902 r.append(pg.info.name); 5903 } 5904 } 5905 } 5906 if (r != null) { 5907 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 5908 } 5909 5910 N = pkg.permissions.size(); 5911 r = null; 5912 for (i=0; i<N; i++) { 5913 PackageParser.Permission p = pkg.permissions.get(i); 5914 HashMap<String, BasePermission> permissionMap = 5915 p.tree ? mSettings.mPermissionTrees 5916 : mSettings.mPermissions; 5917 p.group = mPermissionGroups.get(p.info.group); 5918 if (p.info.group == null || p.group != null) { 5919 BasePermission bp = permissionMap.get(p.info.name); 5920 if (bp == null) { 5921 bp = new BasePermission(p.info.name, p.info.packageName, 5922 BasePermission.TYPE_NORMAL); 5923 permissionMap.put(p.info.name, bp); 5924 } 5925 if (bp.perm == null) { 5926 if (bp.sourcePackage != null 5927 && !bp.sourcePackage.equals(p.info.packageName)) { 5928 // If this is a permission that was formerly defined by a non-system 5929 // app, but is now defined by a system app (following an upgrade), 5930 // discard the previous declaration and consider the system's to be 5931 // canonical. 5932 if (isSystemApp(p.owner)) { 5933 String msg = "New decl " + p.owner + " of permission " 5934 + p.info.name + " is system"; 5935 reportSettingsProblem(Log.WARN, msg); 5936 bp.sourcePackage = null; 5937 } 5938 } 5939 if (bp.sourcePackage == null 5940 || bp.sourcePackage.equals(p.info.packageName)) { 5941 BasePermission tree = findPermissionTreeLP(p.info.name); 5942 if (tree == null 5943 || tree.sourcePackage.equals(p.info.packageName)) { 5944 bp.packageSetting = pkgSetting; 5945 bp.perm = p; 5946 bp.uid = pkg.applicationInfo.uid; 5947 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5948 if (r == null) { 5949 r = new StringBuilder(256); 5950 } else { 5951 r.append(' '); 5952 } 5953 r.append(p.info.name); 5954 } 5955 } else { 5956 Slog.w(TAG, "Permission " + p.info.name + " from package " 5957 + p.info.packageName + " ignored: base tree " 5958 + tree.name + " is from package " 5959 + tree.sourcePackage); 5960 } 5961 } else { 5962 Slog.w(TAG, "Permission " + p.info.name + " from package " 5963 + p.info.packageName + " ignored: original from " 5964 + bp.sourcePackage); 5965 } 5966 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5967 if (r == null) { 5968 r = new StringBuilder(256); 5969 } else { 5970 r.append(' '); 5971 } 5972 r.append("DUP:"); 5973 r.append(p.info.name); 5974 } 5975 if (bp.perm == p) { 5976 bp.protectionLevel = p.info.protectionLevel; 5977 } 5978 } else { 5979 Slog.w(TAG, "Permission " + p.info.name + " from package " 5980 + p.info.packageName + " ignored: no group " 5981 + p.group); 5982 } 5983 } 5984 if (r != null) { 5985 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 5986 } 5987 5988 N = pkg.instrumentation.size(); 5989 r = null; 5990 for (i=0; i<N; i++) { 5991 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 5992 a.info.packageName = pkg.applicationInfo.packageName; 5993 a.info.sourceDir = pkg.applicationInfo.sourceDir; 5994 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 5995 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 5996 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 5997 a.info.dataDir = pkg.applicationInfo.dataDir; 5998 5999 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6000 // need other information about the application, like the ABI and what not ? 6001 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6002 mInstrumentation.put(a.getComponentName(), a); 6003 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6004 if (r == null) { 6005 r = new StringBuilder(256); 6006 } else { 6007 r.append(' '); 6008 } 6009 r.append(a.info.name); 6010 } 6011 } 6012 if (r != null) { 6013 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6014 } 6015 6016 if (pkg.protectedBroadcasts != null) { 6017 N = pkg.protectedBroadcasts.size(); 6018 for (i=0; i<N; i++) { 6019 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6020 } 6021 } 6022 6023 pkgSetting.setTimeStamp(scanFileTime); 6024 6025 // Create idmap files for pairs of (packages, overlay packages). 6026 // Note: "android", ie framework-res.apk, is handled by native layers. 6027 if (pkg.mOverlayTarget != null) { 6028 // This is an overlay package. 6029 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6030 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6031 mOverlays.put(pkg.mOverlayTarget, 6032 new HashMap<String, PackageParser.Package>()); 6033 } 6034 HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6035 map.put(pkg.packageName, pkg); 6036 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6037 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6038 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6039 "scanPackageLI failed to createIdmap"); 6040 } 6041 } 6042 } else if (mOverlays.containsKey(pkg.packageName) && 6043 !pkg.packageName.equals("android")) { 6044 // This is a regular package, with one or more known overlay packages. 6045 createIdmapsForPackageLI(pkg); 6046 } 6047 } 6048 6049 return pkg; 6050 } 6051 6052 /** 6053 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6054 * i.e, so that all packages can be run inside a single process if required. 6055 * 6056 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6057 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6058 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6059 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6060 * updating a package that belongs to a shared user. 6061 * 6062 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6063 * adds unnecessary complexity. 6064 */ 6065 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6066 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6067 String requiredInstructionSet = null; 6068 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6069 requiredInstructionSet = VMRuntime.getInstructionSet( 6070 scannedPackage.applicationInfo.primaryCpuAbi); 6071 } 6072 6073 PackageSetting requirer = null; 6074 for (PackageSetting ps : packagesForUser) { 6075 // If packagesForUser contains scannedPackage, we skip it. This will happen 6076 // when scannedPackage is an update of an existing package. Without this check, 6077 // we will never be able to change the ABI of any package belonging to a shared 6078 // user, even if it's compatible with other packages. 6079 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6080 if (ps.primaryCpuAbiString == null) { 6081 continue; 6082 } 6083 6084 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6085 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6086 // We have a mismatch between instruction sets (say arm vs arm64) warn about 6087 // this but there's not much we can do. 6088 String errorMessage = "Instruction set mismatch, " 6089 + ((requirer == null) ? "[caller]" : requirer) 6090 + " requires " + requiredInstructionSet + " whereas " + ps 6091 + " requires " + instructionSet; 6092 Slog.w(TAG, errorMessage); 6093 } 6094 6095 if (requiredInstructionSet == null) { 6096 requiredInstructionSet = instructionSet; 6097 requirer = ps; 6098 } 6099 } 6100 } 6101 6102 if (requiredInstructionSet != null) { 6103 String adjustedAbi; 6104 if (requirer != null) { 6105 // requirer != null implies that either scannedPackage was null or that scannedPackage 6106 // did not require an ABI, in which case we have to adjust scannedPackage to match 6107 // the ABI of the set (which is the same as requirer's ABI) 6108 adjustedAbi = requirer.primaryCpuAbiString; 6109 if (scannedPackage != null) { 6110 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6111 } 6112 } else { 6113 // requirer == null implies that we're updating all ABIs in the set to 6114 // match scannedPackage. 6115 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6116 } 6117 6118 for (PackageSetting ps : packagesForUser) { 6119 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6120 if (ps.primaryCpuAbiString != null) { 6121 continue; 6122 } 6123 6124 ps.primaryCpuAbiString = adjustedAbi; 6125 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6126 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6127 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6128 6129 if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt, 6130 deferDexOpt, true) == DEX_OPT_FAILED) { 6131 ps.primaryCpuAbiString = null; 6132 ps.pkg.applicationInfo.primaryCpuAbi = null; 6133 return; 6134 } else { 6135 mInstaller.rmdex(ps.codePathString, 6136 getDexCodeInstructionSet(getPreferredInstructionSet())); 6137 } 6138 } 6139 } 6140 } 6141 } 6142 } 6143 6144 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6145 synchronized (mPackages) { 6146 mResolverReplaced = true; 6147 // Set up information for custom user intent resolution activity. 6148 mResolveActivity.applicationInfo = pkg.applicationInfo; 6149 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6150 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6151 mResolveActivity.processName = null; 6152 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6153 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6154 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6155 mResolveActivity.theme = 0; 6156 mResolveActivity.exported = true; 6157 mResolveActivity.enabled = true; 6158 mResolveInfo.activityInfo = mResolveActivity; 6159 mResolveInfo.priority = 0; 6160 mResolveInfo.preferredOrder = 0; 6161 mResolveInfo.match = 0; 6162 mResolveComponentName = mCustomResolverComponentName; 6163 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6164 mResolveComponentName); 6165 } 6166 } 6167 6168 private static String calculateBundledApkRoot(final String codePathString) { 6169 final File codePath = new File(codePathString); 6170 final File codeRoot; 6171 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6172 codeRoot = Environment.getRootDirectory(); 6173 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6174 codeRoot = Environment.getOemDirectory(); 6175 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6176 codeRoot = Environment.getVendorDirectory(); 6177 } else { 6178 // Unrecognized code path; take its top real segment as the apk root: 6179 // e.g. /something/app/blah.apk => /something 6180 try { 6181 File f = codePath.getCanonicalFile(); 6182 File parent = f.getParentFile(); // non-null because codePath is a file 6183 File tmp; 6184 while ((tmp = parent.getParentFile()) != null) { 6185 f = parent; 6186 parent = tmp; 6187 } 6188 codeRoot = f; 6189 Slog.w(TAG, "Unrecognized code path " 6190 + codePath + " - using " + codeRoot); 6191 } catch (IOException e) { 6192 // Can't canonicalize the code path -- shenanigans? 6193 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6194 return Environment.getRootDirectory().getPath(); 6195 } 6196 } 6197 return codeRoot.getPath(); 6198 } 6199 6200 /** 6201 * Derive and set the location of native libraries for the given package, 6202 * which varies depending on where and how the package was installed. 6203 */ 6204 private void setNativeLibraryPaths(PackageParser.Package pkg) { 6205 final ApplicationInfo info = pkg.applicationInfo; 6206 final String codePath = pkg.codePath; 6207 final File codeFile = new File(codePath); 6208 final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info); 6209 final boolean asecApp = isForwardLocked(info) || isExternal(info); 6210 6211 info.nativeLibraryRootDir = null; 6212 info.nativeLibraryRootRequiresIsa = false; 6213 info.nativeLibraryDir = null; 6214 info.secondaryNativeLibraryDir = null; 6215 6216 if (isApkFile(codeFile)) { 6217 // Monolithic install 6218 if (bundledApp) { 6219 // If "/system/lib64/apkname" exists, assume that is the per-package 6220 // native library directory to use; otherwise use "/system/lib/apkname". 6221 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 6222 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 6223 getPrimaryInstructionSet(info)); 6224 6225 // This is a bundled system app so choose the path based on the ABI. 6226 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 6227 // is just the default path. 6228 final String apkName = deriveCodePathName(codePath); 6229 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 6230 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 6231 apkName).getAbsolutePath(); 6232 6233 if (info.secondaryCpuAbi != null) { 6234 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 6235 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 6236 secondaryLibDir, apkName).getAbsolutePath(); 6237 } 6238 } else if (asecApp) { 6239 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 6240 .getAbsolutePath(); 6241 } else { 6242 final String apkName = deriveCodePathName(codePath); 6243 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 6244 .getAbsolutePath(); 6245 } 6246 6247 info.nativeLibraryRootRequiresIsa = false; 6248 info.nativeLibraryDir = info.nativeLibraryRootDir; 6249 } else { 6250 // Cluster install 6251 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 6252 info.nativeLibraryRootRequiresIsa = true; 6253 6254 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 6255 getPrimaryInstructionSet(info)).getAbsolutePath(); 6256 6257 if (info.secondaryCpuAbi != null) { 6258 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 6259 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 6260 } 6261 } 6262 } 6263 6264 /** 6265 * Calculate the abis and roots for a bundled app. These can uniquely 6266 * be determined from the contents of the system partition, i.e whether 6267 * it contains 64 or 32 bit shared libraries etc. We do not validate any 6268 * of this information, and instead assume that the system was built 6269 * sensibly. 6270 */ 6271 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 6272 PackageSetting pkgSetting) { 6273 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 6274 6275 // If "/system/lib64/apkname" exists, assume that is the per-package 6276 // native library directory to use; otherwise use "/system/lib/apkname". 6277 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 6278 setBundledAppAbi(pkg, apkRoot, apkName); 6279 // pkgSetting might be null during rescan following uninstall of updates 6280 // to a bundled app, so accommodate that possibility. The settings in 6281 // that case will be established later from the parsed package. 6282 // 6283 // If the settings aren't null, sync them up with what we've just derived. 6284 // note that apkRoot isn't stored in the package settings. 6285 if (pkgSetting != null) { 6286 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6287 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6288 } 6289 } 6290 6291 /** 6292 * Deduces the ABI of a bundled app and sets the relevant fields on the 6293 * parsed pkg object. 6294 * 6295 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 6296 * under which system libraries are installed. 6297 * @param apkName the name of the installed package. 6298 */ 6299 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 6300 final File codeFile = new File(pkg.codePath); 6301 6302 final boolean has64BitLibs; 6303 final boolean has32BitLibs; 6304 if (isApkFile(codeFile)) { 6305 // Monolithic install 6306 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 6307 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 6308 } else { 6309 // Cluster install 6310 final File rootDir = new File(codeFile, LIB_DIR_NAME); 6311 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 6312 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 6313 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 6314 has64BitLibs = (new File(rootDir, isa)).exists(); 6315 } else { 6316 has64BitLibs = false; 6317 } 6318 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 6319 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 6320 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 6321 has32BitLibs = (new File(rootDir, isa)).exists(); 6322 } else { 6323 has32BitLibs = false; 6324 } 6325 } 6326 6327 if (has64BitLibs && !has32BitLibs) { 6328 // The package has 64 bit libs, but not 32 bit libs. Its primary 6329 // ABI should be 64 bit. We can safely assume here that the bundled 6330 // native libraries correspond to the most preferred ABI in the list. 6331 6332 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6333 pkg.applicationInfo.secondaryCpuAbi = null; 6334 } else if (has32BitLibs && !has64BitLibs) { 6335 // The package has 32 bit libs but not 64 bit libs. Its primary 6336 // ABI should be 32 bit. 6337 6338 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6339 pkg.applicationInfo.secondaryCpuAbi = null; 6340 } else if (has32BitLibs && has64BitLibs) { 6341 // The application has both 64 and 32 bit bundled libraries. We check 6342 // here that the app declares multiArch support, and warn if it doesn't. 6343 // 6344 // We will be lenient here and record both ABIs. The primary will be the 6345 // ABI that's higher on the list, i.e, a device that's configured to prefer 6346 // 64 bit apps will see a 64 bit primary ABI, 6347 6348 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 6349 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 6350 } 6351 6352 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 6353 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6354 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6355 } else { 6356 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6357 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6358 } 6359 } else { 6360 pkg.applicationInfo.primaryCpuAbi = null; 6361 pkg.applicationInfo.secondaryCpuAbi = null; 6362 } 6363 } 6364 6365 private void killApplication(String pkgName, int appId, String reason) { 6366 // Request the ActivityManager to kill the process(only for existing packages) 6367 // so that we do not end up in a confused state while the user is still using the older 6368 // version of the application while the new one gets installed. 6369 IActivityManager am = ActivityManagerNative.getDefault(); 6370 if (am != null) { 6371 try { 6372 am.killApplicationWithAppId(pkgName, appId, reason); 6373 } catch (RemoteException e) { 6374 } 6375 } 6376 } 6377 6378 void removePackageLI(PackageSetting ps, boolean chatty) { 6379 if (DEBUG_INSTALL) { 6380 if (chatty) 6381 Log.d(TAG, "Removing package " + ps.name); 6382 } 6383 6384 // writer 6385 synchronized (mPackages) { 6386 mPackages.remove(ps.name); 6387 final PackageParser.Package pkg = ps.pkg; 6388 if (pkg != null) { 6389 cleanPackageDataStructuresLILPw(pkg, chatty); 6390 } 6391 } 6392 } 6393 6394 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 6395 if (DEBUG_INSTALL) { 6396 if (chatty) 6397 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 6398 } 6399 6400 // writer 6401 synchronized (mPackages) { 6402 mPackages.remove(pkg.applicationInfo.packageName); 6403 cleanPackageDataStructuresLILPw(pkg, chatty); 6404 } 6405 } 6406 6407 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 6408 int N = pkg.providers.size(); 6409 StringBuilder r = null; 6410 int i; 6411 for (i=0; i<N; i++) { 6412 PackageParser.Provider p = pkg.providers.get(i); 6413 mProviders.removeProvider(p); 6414 if (p.info.authority == null) { 6415 6416 /* There was another ContentProvider with this authority when 6417 * this app was installed so this authority is null, 6418 * Ignore it as we don't have to unregister the provider. 6419 */ 6420 continue; 6421 } 6422 String names[] = p.info.authority.split(";"); 6423 for (int j = 0; j < names.length; j++) { 6424 if (mProvidersByAuthority.get(names[j]) == p) { 6425 mProvidersByAuthority.remove(names[j]); 6426 if (DEBUG_REMOVE) { 6427 if (chatty) 6428 Log.d(TAG, "Unregistered content provider: " + names[j] 6429 + ", className = " + p.info.name + ", isSyncable = " 6430 + p.info.isSyncable); 6431 } 6432 } 6433 } 6434 if (DEBUG_REMOVE && chatty) { 6435 if (r == null) { 6436 r = new StringBuilder(256); 6437 } else { 6438 r.append(' '); 6439 } 6440 r.append(p.info.name); 6441 } 6442 } 6443 if (r != null) { 6444 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 6445 } 6446 6447 N = pkg.services.size(); 6448 r = null; 6449 for (i=0; i<N; i++) { 6450 PackageParser.Service s = pkg.services.get(i); 6451 mServices.removeService(s); 6452 if (chatty) { 6453 if (r == null) { 6454 r = new StringBuilder(256); 6455 } else { 6456 r.append(' '); 6457 } 6458 r.append(s.info.name); 6459 } 6460 } 6461 if (r != null) { 6462 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 6463 } 6464 6465 N = pkg.receivers.size(); 6466 r = null; 6467 for (i=0; i<N; i++) { 6468 PackageParser.Activity a = pkg.receivers.get(i); 6469 mReceivers.removeActivity(a, "receiver"); 6470 if (DEBUG_REMOVE && chatty) { 6471 if (r == null) { 6472 r = new StringBuilder(256); 6473 } else { 6474 r.append(' '); 6475 } 6476 r.append(a.info.name); 6477 } 6478 } 6479 if (r != null) { 6480 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 6481 } 6482 6483 N = pkg.activities.size(); 6484 r = null; 6485 for (i=0; i<N; i++) { 6486 PackageParser.Activity a = pkg.activities.get(i); 6487 mActivities.removeActivity(a, "activity"); 6488 if (DEBUG_REMOVE && chatty) { 6489 if (r == null) { 6490 r = new StringBuilder(256); 6491 } else { 6492 r.append(' '); 6493 } 6494 r.append(a.info.name); 6495 } 6496 } 6497 if (r != null) { 6498 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 6499 } 6500 6501 N = pkg.permissions.size(); 6502 r = null; 6503 for (i=0; i<N; i++) { 6504 PackageParser.Permission p = pkg.permissions.get(i); 6505 BasePermission bp = mSettings.mPermissions.get(p.info.name); 6506 if (bp == null) { 6507 bp = mSettings.mPermissionTrees.get(p.info.name); 6508 } 6509 if (bp != null && bp.perm == p) { 6510 bp.perm = null; 6511 if (DEBUG_REMOVE && chatty) { 6512 if (r == null) { 6513 r = new StringBuilder(256); 6514 } else { 6515 r.append(' '); 6516 } 6517 r.append(p.info.name); 6518 } 6519 } 6520 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6521 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 6522 if (appOpPerms != null) { 6523 appOpPerms.remove(pkg.packageName); 6524 } 6525 } 6526 } 6527 if (r != null) { 6528 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6529 } 6530 6531 N = pkg.requestedPermissions.size(); 6532 r = null; 6533 for (i=0; i<N; i++) { 6534 String perm = pkg.requestedPermissions.get(i); 6535 BasePermission bp = mSettings.mPermissions.get(perm); 6536 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6537 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 6538 if (appOpPerms != null) { 6539 appOpPerms.remove(pkg.packageName); 6540 if (appOpPerms.isEmpty()) { 6541 mAppOpPermissionPackages.remove(perm); 6542 } 6543 } 6544 } 6545 } 6546 if (r != null) { 6547 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6548 } 6549 6550 N = pkg.instrumentation.size(); 6551 r = null; 6552 for (i=0; i<N; i++) { 6553 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6554 mInstrumentation.remove(a.getComponentName()); 6555 if (DEBUG_REMOVE && chatty) { 6556 if (r == null) { 6557 r = new StringBuilder(256); 6558 } else { 6559 r.append(' '); 6560 } 6561 r.append(a.info.name); 6562 } 6563 } 6564 if (r != null) { 6565 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 6566 } 6567 6568 r = null; 6569 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6570 // Only system apps can hold shared libraries. 6571 if (pkg.libraryNames != null) { 6572 for (i=0; i<pkg.libraryNames.size(); i++) { 6573 String name = pkg.libraryNames.get(i); 6574 SharedLibraryEntry cur = mSharedLibraries.get(name); 6575 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 6576 mSharedLibraries.remove(name); 6577 if (DEBUG_REMOVE && chatty) { 6578 if (r == null) { 6579 r = new StringBuilder(256); 6580 } else { 6581 r.append(' '); 6582 } 6583 r.append(name); 6584 } 6585 } 6586 } 6587 } 6588 } 6589 if (r != null) { 6590 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 6591 } 6592 } 6593 6594 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 6595 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 6596 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 6597 return true; 6598 } 6599 } 6600 return false; 6601 } 6602 6603 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 6604 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 6605 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 6606 6607 private void updatePermissionsLPw(String changingPkg, 6608 PackageParser.Package pkgInfo, int flags) { 6609 // Make sure there are no dangling permission trees. 6610 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 6611 while (it.hasNext()) { 6612 final BasePermission bp = it.next(); 6613 if (bp.packageSetting == null) { 6614 // We may not yet have parsed the package, so just see if 6615 // we still know about its settings. 6616 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6617 } 6618 if (bp.packageSetting == null) { 6619 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 6620 + " from package " + bp.sourcePackage); 6621 it.remove(); 6622 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6623 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6624 Slog.i(TAG, "Removing old permission tree: " + bp.name 6625 + " from package " + bp.sourcePackage); 6626 flags |= UPDATE_PERMISSIONS_ALL; 6627 it.remove(); 6628 } 6629 } 6630 } 6631 6632 // Make sure all dynamic permissions have been assigned to a package, 6633 // and make sure there are no dangling permissions. 6634 it = mSettings.mPermissions.values().iterator(); 6635 while (it.hasNext()) { 6636 final BasePermission bp = it.next(); 6637 if (bp.type == BasePermission.TYPE_DYNAMIC) { 6638 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 6639 + bp.name + " pkg=" + bp.sourcePackage 6640 + " info=" + bp.pendingInfo); 6641 if (bp.packageSetting == null && bp.pendingInfo != null) { 6642 final BasePermission tree = findPermissionTreeLP(bp.name); 6643 if (tree != null && tree.perm != null) { 6644 bp.packageSetting = tree.packageSetting; 6645 bp.perm = new PackageParser.Permission(tree.perm.owner, 6646 new PermissionInfo(bp.pendingInfo)); 6647 bp.perm.info.packageName = tree.perm.info.packageName; 6648 bp.perm.info.name = bp.name; 6649 bp.uid = tree.uid; 6650 } 6651 } 6652 } 6653 if (bp.packageSetting == null) { 6654 // We may not yet have parsed the package, so just see if 6655 // we still know about its settings. 6656 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6657 } 6658 if (bp.packageSetting == null) { 6659 Slog.w(TAG, "Removing dangling permission: " + bp.name 6660 + " from package " + bp.sourcePackage); 6661 it.remove(); 6662 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6663 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6664 Slog.i(TAG, "Removing old permission: " + bp.name 6665 + " from package " + bp.sourcePackage); 6666 flags |= UPDATE_PERMISSIONS_ALL; 6667 it.remove(); 6668 } 6669 } 6670 } 6671 6672 // Now update the permissions for all packages, in particular 6673 // replace the granted permissions of the system packages. 6674 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 6675 for (PackageParser.Package pkg : mPackages.values()) { 6676 if (pkg != pkgInfo) { 6677 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0); 6678 } 6679 } 6680 } 6681 6682 if (pkgInfo != null) { 6683 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0); 6684 } 6685 } 6686 6687 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) { 6688 final PackageSetting ps = (PackageSetting) pkg.mExtras; 6689 if (ps == null) { 6690 return; 6691 } 6692 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 6693 HashSet<String> origPermissions = gp.grantedPermissions; 6694 boolean changedPermission = false; 6695 6696 if (replace) { 6697 ps.permissionsFixed = false; 6698 if (gp == ps) { 6699 origPermissions = new HashSet<String>(gp.grantedPermissions); 6700 gp.grantedPermissions.clear(); 6701 gp.gids = mGlobalGids; 6702 } 6703 } 6704 6705 if (gp.gids == null) { 6706 gp.gids = mGlobalGids; 6707 } 6708 6709 final int N = pkg.requestedPermissions.size(); 6710 for (int i=0; i<N; i++) { 6711 final String name = pkg.requestedPermissions.get(i); 6712 final boolean required = pkg.requestedPermissionsRequired.get(i); 6713 final BasePermission bp = mSettings.mPermissions.get(name); 6714 if (DEBUG_INSTALL) { 6715 if (gp != ps) { 6716 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 6717 } 6718 } 6719 6720 if (bp == null || bp.packageSetting == null) { 6721 Slog.w(TAG, "Unknown permission " + name 6722 + " in package " + pkg.packageName); 6723 continue; 6724 } 6725 6726 final String perm = bp.name; 6727 boolean allowed; 6728 boolean allowedSig = false; 6729 if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6730 // Keep track of app op permissions. 6731 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 6732 if (pkgs == null) { 6733 pkgs = new ArraySet<>(); 6734 mAppOpPermissionPackages.put(bp.name, pkgs); 6735 } 6736 pkgs.add(pkg.packageName); 6737 } 6738 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 6739 if (level == PermissionInfo.PROTECTION_NORMAL 6740 || level == PermissionInfo.PROTECTION_DANGEROUS) { 6741 // We grant a normal or dangerous permission if any of the following 6742 // are true: 6743 // 1) The permission is required 6744 // 2) The permission is optional, but was granted in the past 6745 // 3) The permission is optional, but was requested by an 6746 // app in /system (not /data) 6747 // 6748 // Otherwise, reject the permission. 6749 allowed = (required || origPermissions.contains(perm) 6750 || (isSystemApp(ps) && !isUpdatedSystemApp(ps))); 6751 } else if (bp.packageSetting == null) { 6752 // This permission is invalid; skip it. 6753 allowed = false; 6754 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 6755 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions); 6756 if (allowed) { 6757 allowedSig = true; 6758 } 6759 } else { 6760 allowed = false; 6761 } 6762 if (DEBUG_INSTALL) { 6763 if (gp != ps) { 6764 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 6765 } 6766 } 6767 if (allowed) { 6768 if (!isSystemApp(ps) && ps.permissionsFixed) { 6769 // If this is an existing, non-system package, then 6770 // we can't add any new permissions to it. 6771 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 6772 // Except... if this is a permission that was added 6773 // to the platform (note: need to only do this when 6774 // updating the platform). 6775 allowed = isNewPlatformPermissionForPackage(perm, pkg); 6776 } 6777 } 6778 if (allowed) { 6779 if (!gp.grantedPermissions.contains(perm)) { 6780 changedPermission = true; 6781 gp.grantedPermissions.add(perm); 6782 gp.gids = appendInts(gp.gids, bp.gids); 6783 } else if (!ps.haveGids) { 6784 gp.gids = appendInts(gp.gids, bp.gids); 6785 } 6786 } else { 6787 Slog.w(TAG, "Not granting permission " + perm 6788 + " to package " + pkg.packageName 6789 + " because it was previously installed without"); 6790 } 6791 } else { 6792 if (gp.grantedPermissions.remove(perm)) { 6793 changedPermission = true; 6794 gp.gids = removeInts(gp.gids, bp.gids); 6795 Slog.i(TAG, "Un-granting permission " + perm 6796 + " from package " + pkg.packageName 6797 + " (protectionLevel=" + bp.protectionLevel 6798 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6799 + ")"); 6800 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 6801 // Don't print warning for app op permissions, since it is fine for them 6802 // not to be granted, there is a UI for the user to decide. 6803 Slog.w(TAG, "Not granting permission " + perm 6804 + " to package " + pkg.packageName 6805 + " (protectionLevel=" + bp.protectionLevel 6806 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6807 + ")"); 6808 } 6809 } 6810 } 6811 6812 if ((changedPermission || replace) && !ps.permissionsFixed && 6813 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 6814 // This is the first that we have heard about this package, so the 6815 // permissions we have now selected are fixed until explicitly 6816 // changed. 6817 ps.permissionsFixed = true; 6818 } 6819 ps.haveGids = true; 6820 } 6821 6822 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 6823 boolean allowed = false; 6824 final int NP = PackageParser.NEW_PERMISSIONS.length; 6825 for (int ip=0; ip<NP; ip++) { 6826 final PackageParser.NewPermissionInfo npi 6827 = PackageParser.NEW_PERMISSIONS[ip]; 6828 if (npi.name.equals(perm) 6829 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 6830 allowed = true; 6831 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 6832 + pkg.packageName); 6833 break; 6834 } 6835 } 6836 return allowed; 6837 } 6838 6839 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 6840 BasePermission bp, HashSet<String> origPermissions) { 6841 boolean allowed; 6842 allowed = (compareSignatures( 6843 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 6844 == PackageManager.SIGNATURE_MATCH) 6845 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 6846 == PackageManager.SIGNATURE_MATCH); 6847 if (!allowed && (bp.protectionLevel 6848 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 6849 if (isSystemApp(pkg)) { 6850 // For updated system applications, a system permission 6851 // is granted only if it had been defined by the original application. 6852 if (isUpdatedSystemApp(pkg)) { 6853 final PackageSetting sysPs = mSettings 6854 .getDisabledSystemPkgLPr(pkg.packageName); 6855 final GrantedPermissions origGp = sysPs.sharedUser != null 6856 ? sysPs.sharedUser : sysPs; 6857 6858 if (origGp.grantedPermissions.contains(perm)) { 6859 // If the original was granted this permission, we take 6860 // that grant decision as read and propagate it to the 6861 // update. 6862 allowed = true; 6863 } else { 6864 // The system apk may have been updated with an older 6865 // version of the one on the data partition, but which 6866 // granted a new system permission that it didn't have 6867 // before. In this case we do want to allow the app to 6868 // now get the new permission if the ancestral apk is 6869 // privileged to get it. 6870 if (sysPs.pkg != null && sysPs.isPrivileged()) { 6871 for (int j=0; 6872 j<sysPs.pkg.requestedPermissions.size(); j++) { 6873 if (perm.equals( 6874 sysPs.pkg.requestedPermissions.get(j))) { 6875 allowed = true; 6876 break; 6877 } 6878 } 6879 } 6880 } 6881 } else { 6882 allowed = isPrivilegedApp(pkg); 6883 } 6884 } 6885 } 6886 if (!allowed && (bp.protectionLevel 6887 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 6888 // For development permissions, a development permission 6889 // is granted only if it was already granted. 6890 allowed = origPermissions.contains(perm); 6891 } 6892 return allowed; 6893 } 6894 6895 final class ActivityIntentResolver 6896 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 6897 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 6898 boolean defaultOnly, int userId) { 6899 if (!sUserManager.exists(userId)) return null; 6900 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 6901 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 6902 } 6903 6904 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 6905 int userId) { 6906 if (!sUserManager.exists(userId)) return null; 6907 mFlags = flags; 6908 return super.queryIntent(intent, resolvedType, 6909 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 6910 } 6911 6912 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 6913 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 6914 if (!sUserManager.exists(userId)) return null; 6915 if (packageActivities == null) { 6916 return null; 6917 } 6918 mFlags = flags; 6919 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 6920 final int N = packageActivities.size(); 6921 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 6922 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 6923 6924 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 6925 for (int i = 0; i < N; ++i) { 6926 intentFilters = packageActivities.get(i).intents; 6927 if (intentFilters != null && intentFilters.size() > 0) { 6928 PackageParser.ActivityIntentInfo[] array = 6929 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 6930 intentFilters.toArray(array); 6931 listCut.add(array); 6932 } 6933 } 6934 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 6935 } 6936 6937 public final void addActivity(PackageParser.Activity a, String type) { 6938 final boolean systemApp = isSystemApp(a.info.applicationInfo); 6939 mActivities.put(a.getComponentName(), a); 6940 if (DEBUG_SHOW_INFO) 6941 Log.v( 6942 TAG, " " + type + " " + 6943 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 6944 if (DEBUG_SHOW_INFO) 6945 Log.v(TAG, " Class=" + a.info.name); 6946 final int NI = a.intents.size(); 6947 for (int j=0; j<NI; j++) { 6948 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 6949 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 6950 intent.setPriority(0); 6951 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 6952 + a.className + " with priority > 0, forcing to 0"); 6953 } 6954 if (DEBUG_SHOW_INFO) { 6955 Log.v(TAG, " IntentFilter:"); 6956 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6957 } 6958 if (!intent.debugCheck()) { 6959 Log.w(TAG, "==> For Activity " + a.info.name); 6960 } 6961 addFilter(intent); 6962 } 6963 } 6964 6965 public final void removeActivity(PackageParser.Activity a, String type) { 6966 mActivities.remove(a.getComponentName()); 6967 if (DEBUG_SHOW_INFO) { 6968 Log.v(TAG, " " + type + " " 6969 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 6970 : a.info.name) + ":"); 6971 Log.v(TAG, " Class=" + a.info.name); 6972 } 6973 final int NI = a.intents.size(); 6974 for (int j=0; j<NI; j++) { 6975 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 6976 if (DEBUG_SHOW_INFO) { 6977 Log.v(TAG, " IntentFilter:"); 6978 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6979 } 6980 removeFilter(intent); 6981 } 6982 } 6983 6984 @Override 6985 protected boolean allowFilterResult( 6986 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 6987 ActivityInfo filterAi = filter.activity.info; 6988 for (int i=dest.size()-1; i>=0; i--) { 6989 ActivityInfo destAi = dest.get(i).activityInfo; 6990 if (destAi.name == filterAi.name 6991 && destAi.packageName == filterAi.packageName) { 6992 return false; 6993 } 6994 } 6995 return true; 6996 } 6997 6998 @Override 6999 protected ActivityIntentInfo[] newArray(int size) { 7000 return new ActivityIntentInfo[size]; 7001 } 7002 7003 @Override 7004 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 7005 if (!sUserManager.exists(userId)) return true; 7006 PackageParser.Package p = filter.activity.owner; 7007 if (p != null) { 7008 PackageSetting ps = (PackageSetting)p.mExtras; 7009 if (ps != null) { 7010 // System apps are never considered stopped for purposes of 7011 // filtering, because there may be no way for the user to 7012 // actually re-launch them. 7013 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 7014 && ps.getStopped(userId); 7015 } 7016 } 7017 return false; 7018 } 7019 7020 @Override 7021 protected boolean isPackageForFilter(String packageName, 7022 PackageParser.ActivityIntentInfo info) { 7023 return packageName.equals(info.activity.owner.packageName); 7024 } 7025 7026 @Override 7027 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7028 int match, int userId) { 7029 if (!sUserManager.exists(userId)) return null; 7030 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7031 return null; 7032 } 7033 final PackageParser.Activity activity = info.activity; 7034 if (mSafeMode && (activity.info.applicationInfo.flags 7035 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7036 return null; 7037 } 7038 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7039 if (ps == null) { 7040 return null; 7041 } 7042 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7043 ps.readUserState(userId), userId); 7044 if (ai == null) { 7045 return null; 7046 } 7047 final ResolveInfo res = new ResolveInfo(); 7048 res.activityInfo = ai; 7049 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7050 res.filter = info; 7051 } 7052 res.priority = info.getPriority(); 7053 res.preferredOrder = activity.owner.mPreferredOrder; 7054 //System.out.println("Result: " + res.activityInfo.className + 7055 // " = " + res.priority); 7056 res.match = match; 7057 res.isDefault = info.hasDefault; 7058 res.labelRes = info.labelRes; 7059 res.nonLocalizedLabel = info.nonLocalizedLabel; 7060 if (userNeedsBadging(userId)) { 7061 res.noResourceId = true; 7062 } else { 7063 res.icon = info.icon; 7064 } 7065 res.system = isSystemApp(res.activityInfo.applicationInfo); 7066 return res; 7067 } 7068 7069 @Override 7070 protected void sortResults(List<ResolveInfo> results) { 7071 Collections.sort(results, mResolvePrioritySorter); 7072 } 7073 7074 @Override 7075 protected void dumpFilter(PrintWriter out, String prefix, 7076 PackageParser.ActivityIntentInfo filter) { 7077 out.print(prefix); out.print( 7078 Integer.toHexString(System.identityHashCode(filter.activity))); 7079 out.print(' '); 7080 filter.activity.printComponentShortName(out); 7081 out.print(" filter "); 7082 out.println(Integer.toHexString(System.identityHashCode(filter))); 7083 } 7084 7085// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7086// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7087// final List<ResolveInfo> retList = Lists.newArrayList(); 7088// while (i.hasNext()) { 7089// final ResolveInfo resolveInfo = i.next(); 7090// if (isEnabledLP(resolveInfo.activityInfo)) { 7091// retList.add(resolveInfo); 7092// } 7093// } 7094// return retList; 7095// } 7096 7097 // Keys are String (activity class name), values are Activity. 7098 private final HashMap<ComponentName, PackageParser.Activity> mActivities 7099 = new HashMap<ComponentName, PackageParser.Activity>(); 7100 private int mFlags; 7101 } 7102 7103 private final class ServiceIntentResolver 7104 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 7105 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7106 boolean defaultOnly, int userId) { 7107 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7108 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7109 } 7110 7111 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7112 int userId) { 7113 if (!sUserManager.exists(userId)) return null; 7114 mFlags = flags; 7115 return super.queryIntent(intent, resolvedType, 7116 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7117 } 7118 7119 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7120 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 7121 if (!sUserManager.exists(userId)) return null; 7122 if (packageServices == null) { 7123 return null; 7124 } 7125 mFlags = flags; 7126 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7127 final int N = packageServices.size(); 7128 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 7129 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 7130 7131 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 7132 for (int i = 0; i < N; ++i) { 7133 intentFilters = packageServices.get(i).intents; 7134 if (intentFilters != null && intentFilters.size() > 0) { 7135 PackageParser.ServiceIntentInfo[] array = 7136 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 7137 intentFilters.toArray(array); 7138 listCut.add(array); 7139 } 7140 } 7141 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7142 } 7143 7144 public final void addService(PackageParser.Service s) { 7145 mServices.put(s.getComponentName(), s); 7146 if (DEBUG_SHOW_INFO) { 7147 Log.v(TAG, " " 7148 + (s.info.nonLocalizedLabel != null 7149 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7150 Log.v(TAG, " Class=" + s.info.name); 7151 } 7152 final int NI = s.intents.size(); 7153 int j; 7154 for (j=0; j<NI; j++) { 7155 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7156 if (DEBUG_SHOW_INFO) { 7157 Log.v(TAG, " IntentFilter:"); 7158 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7159 } 7160 if (!intent.debugCheck()) { 7161 Log.w(TAG, "==> For Service " + s.info.name); 7162 } 7163 addFilter(intent); 7164 } 7165 } 7166 7167 public final void removeService(PackageParser.Service s) { 7168 mServices.remove(s.getComponentName()); 7169 if (DEBUG_SHOW_INFO) { 7170 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 7171 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7172 Log.v(TAG, " Class=" + s.info.name); 7173 } 7174 final int NI = s.intents.size(); 7175 int j; 7176 for (j=0; j<NI; j++) { 7177 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7178 if (DEBUG_SHOW_INFO) { 7179 Log.v(TAG, " IntentFilter:"); 7180 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7181 } 7182 removeFilter(intent); 7183 } 7184 } 7185 7186 @Override 7187 protected boolean allowFilterResult( 7188 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 7189 ServiceInfo filterSi = filter.service.info; 7190 for (int i=dest.size()-1; i>=0; i--) { 7191 ServiceInfo destAi = dest.get(i).serviceInfo; 7192 if (destAi.name == filterSi.name 7193 && destAi.packageName == filterSi.packageName) { 7194 return false; 7195 } 7196 } 7197 return true; 7198 } 7199 7200 @Override 7201 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 7202 return new PackageParser.ServiceIntentInfo[size]; 7203 } 7204 7205 @Override 7206 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 7207 if (!sUserManager.exists(userId)) return true; 7208 PackageParser.Package p = filter.service.owner; 7209 if (p != null) { 7210 PackageSetting ps = (PackageSetting)p.mExtras; 7211 if (ps != null) { 7212 // System apps are never considered stopped for purposes of 7213 // filtering, because there may be no way for the user to 7214 // actually re-launch them. 7215 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7216 && ps.getStopped(userId); 7217 } 7218 } 7219 return false; 7220 } 7221 7222 @Override 7223 protected boolean isPackageForFilter(String packageName, 7224 PackageParser.ServiceIntentInfo info) { 7225 return packageName.equals(info.service.owner.packageName); 7226 } 7227 7228 @Override 7229 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 7230 int match, int userId) { 7231 if (!sUserManager.exists(userId)) return null; 7232 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 7233 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 7234 return null; 7235 } 7236 final PackageParser.Service service = info.service; 7237 if (mSafeMode && (service.info.applicationInfo.flags 7238 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7239 return null; 7240 } 7241 PackageSetting ps = (PackageSetting) service.owner.mExtras; 7242 if (ps == null) { 7243 return null; 7244 } 7245 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 7246 ps.readUserState(userId), userId); 7247 if (si == null) { 7248 return null; 7249 } 7250 final ResolveInfo res = new ResolveInfo(); 7251 res.serviceInfo = si; 7252 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7253 res.filter = filter; 7254 } 7255 res.priority = info.getPriority(); 7256 res.preferredOrder = service.owner.mPreferredOrder; 7257 //System.out.println("Result: " + res.activityInfo.className + 7258 // " = " + res.priority); 7259 res.match = match; 7260 res.isDefault = info.hasDefault; 7261 res.labelRes = info.labelRes; 7262 res.nonLocalizedLabel = info.nonLocalizedLabel; 7263 res.icon = info.icon; 7264 res.system = isSystemApp(res.serviceInfo.applicationInfo); 7265 return res; 7266 } 7267 7268 @Override 7269 protected void sortResults(List<ResolveInfo> results) { 7270 Collections.sort(results, mResolvePrioritySorter); 7271 } 7272 7273 @Override 7274 protected void dumpFilter(PrintWriter out, String prefix, 7275 PackageParser.ServiceIntentInfo filter) { 7276 out.print(prefix); out.print( 7277 Integer.toHexString(System.identityHashCode(filter.service))); 7278 out.print(' '); 7279 filter.service.printComponentShortName(out); 7280 out.print(" filter "); 7281 out.println(Integer.toHexString(System.identityHashCode(filter))); 7282 } 7283 7284// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7285// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7286// final List<ResolveInfo> retList = Lists.newArrayList(); 7287// while (i.hasNext()) { 7288// final ResolveInfo resolveInfo = (ResolveInfo) i; 7289// if (isEnabledLP(resolveInfo.serviceInfo)) { 7290// retList.add(resolveInfo); 7291// } 7292// } 7293// return retList; 7294// } 7295 7296 // Keys are String (activity class name), values are Activity. 7297 private final HashMap<ComponentName, PackageParser.Service> mServices 7298 = new HashMap<ComponentName, PackageParser.Service>(); 7299 private int mFlags; 7300 }; 7301 7302 private final class ProviderIntentResolver 7303 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 7304 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7305 boolean defaultOnly, int userId) { 7306 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7307 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7308 } 7309 7310 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7311 int userId) { 7312 if (!sUserManager.exists(userId)) 7313 return null; 7314 mFlags = flags; 7315 return super.queryIntent(intent, resolvedType, 7316 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7317 } 7318 7319 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7320 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 7321 if (!sUserManager.exists(userId)) 7322 return null; 7323 if (packageProviders == null) { 7324 return null; 7325 } 7326 mFlags = flags; 7327 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 7328 final int N = packageProviders.size(); 7329 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 7330 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 7331 7332 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 7333 for (int i = 0; i < N; ++i) { 7334 intentFilters = packageProviders.get(i).intents; 7335 if (intentFilters != null && intentFilters.size() > 0) { 7336 PackageParser.ProviderIntentInfo[] array = 7337 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 7338 intentFilters.toArray(array); 7339 listCut.add(array); 7340 } 7341 } 7342 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7343 } 7344 7345 public final void addProvider(PackageParser.Provider p) { 7346 if (mProviders.containsKey(p.getComponentName())) { 7347 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 7348 return; 7349 } 7350 7351 mProviders.put(p.getComponentName(), p); 7352 if (DEBUG_SHOW_INFO) { 7353 Log.v(TAG, " " 7354 + (p.info.nonLocalizedLabel != null 7355 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7356 Log.v(TAG, " Class=" + p.info.name); 7357 } 7358 final int NI = p.intents.size(); 7359 int j; 7360 for (j = 0; j < NI; j++) { 7361 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7362 if (DEBUG_SHOW_INFO) { 7363 Log.v(TAG, " IntentFilter:"); 7364 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7365 } 7366 if (!intent.debugCheck()) { 7367 Log.w(TAG, "==> For Provider " + p.info.name); 7368 } 7369 addFilter(intent); 7370 } 7371 } 7372 7373 public final void removeProvider(PackageParser.Provider p) { 7374 mProviders.remove(p.getComponentName()); 7375 if (DEBUG_SHOW_INFO) { 7376 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 7377 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7378 Log.v(TAG, " Class=" + p.info.name); 7379 } 7380 final int NI = p.intents.size(); 7381 int j; 7382 for (j = 0; j < NI; j++) { 7383 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7384 if (DEBUG_SHOW_INFO) { 7385 Log.v(TAG, " IntentFilter:"); 7386 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7387 } 7388 removeFilter(intent); 7389 } 7390 } 7391 7392 @Override 7393 protected boolean allowFilterResult( 7394 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 7395 ProviderInfo filterPi = filter.provider.info; 7396 for (int i = dest.size() - 1; i >= 0; i--) { 7397 ProviderInfo destPi = dest.get(i).providerInfo; 7398 if (destPi.name == filterPi.name 7399 && destPi.packageName == filterPi.packageName) { 7400 return false; 7401 } 7402 } 7403 return true; 7404 } 7405 7406 @Override 7407 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 7408 return new PackageParser.ProviderIntentInfo[size]; 7409 } 7410 7411 @Override 7412 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 7413 if (!sUserManager.exists(userId)) 7414 return true; 7415 PackageParser.Package p = filter.provider.owner; 7416 if (p != null) { 7417 PackageSetting ps = (PackageSetting) p.mExtras; 7418 if (ps != null) { 7419 // System apps are never considered stopped for purposes of 7420 // filtering, because there may be no way for the user to 7421 // actually re-launch them. 7422 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7423 && ps.getStopped(userId); 7424 } 7425 } 7426 return false; 7427 } 7428 7429 @Override 7430 protected boolean isPackageForFilter(String packageName, 7431 PackageParser.ProviderIntentInfo info) { 7432 return packageName.equals(info.provider.owner.packageName); 7433 } 7434 7435 @Override 7436 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 7437 int match, int userId) { 7438 if (!sUserManager.exists(userId)) 7439 return null; 7440 final PackageParser.ProviderIntentInfo info = filter; 7441 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 7442 return null; 7443 } 7444 final PackageParser.Provider provider = info.provider; 7445 if (mSafeMode && (provider.info.applicationInfo.flags 7446 & ApplicationInfo.FLAG_SYSTEM) == 0) { 7447 return null; 7448 } 7449 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 7450 if (ps == null) { 7451 return null; 7452 } 7453 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 7454 ps.readUserState(userId), userId); 7455 if (pi == null) { 7456 return null; 7457 } 7458 final ResolveInfo res = new ResolveInfo(); 7459 res.providerInfo = pi; 7460 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 7461 res.filter = filter; 7462 } 7463 res.priority = info.getPriority(); 7464 res.preferredOrder = provider.owner.mPreferredOrder; 7465 res.match = match; 7466 res.isDefault = info.hasDefault; 7467 res.labelRes = info.labelRes; 7468 res.nonLocalizedLabel = info.nonLocalizedLabel; 7469 res.icon = info.icon; 7470 res.system = isSystemApp(res.providerInfo.applicationInfo); 7471 return res; 7472 } 7473 7474 @Override 7475 protected void sortResults(List<ResolveInfo> results) { 7476 Collections.sort(results, mResolvePrioritySorter); 7477 } 7478 7479 @Override 7480 protected void dumpFilter(PrintWriter out, String prefix, 7481 PackageParser.ProviderIntentInfo filter) { 7482 out.print(prefix); 7483 out.print( 7484 Integer.toHexString(System.identityHashCode(filter.provider))); 7485 out.print(' '); 7486 filter.provider.printComponentShortName(out); 7487 out.print(" filter "); 7488 out.println(Integer.toHexString(System.identityHashCode(filter))); 7489 } 7490 7491 private final HashMap<ComponentName, PackageParser.Provider> mProviders 7492 = new HashMap<ComponentName, PackageParser.Provider>(); 7493 private int mFlags; 7494 }; 7495 7496 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 7497 new Comparator<ResolveInfo>() { 7498 public int compare(ResolveInfo r1, ResolveInfo r2) { 7499 int v1 = r1.priority; 7500 int v2 = r2.priority; 7501 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 7502 if (v1 != v2) { 7503 return (v1 > v2) ? -1 : 1; 7504 } 7505 v1 = r1.preferredOrder; 7506 v2 = r2.preferredOrder; 7507 if (v1 != v2) { 7508 return (v1 > v2) ? -1 : 1; 7509 } 7510 if (r1.isDefault != r2.isDefault) { 7511 return r1.isDefault ? -1 : 1; 7512 } 7513 v1 = r1.match; 7514 v2 = r2.match; 7515 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 7516 if (v1 != v2) { 7517 return (v1 > v2) ? -1 : 1; 7518 } 7519 if (r1.system != r2.system) { 7520 return r1.system ? -1 : 1; 7521 } 7522 return 0; 7523 } 7524 }; 7525 7526 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 7527 new Comparator<ProviderInfo>() { 7528 public int compare(ProviderInfo p1, ProviderInfo p2) { 7529 final int v1 = p1.initOrder; 7530 final int v2 = p2.initOrder; 7531 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 7532 } 7533 }; 7534 7535 static final void sendPackageBroadcast(String action, String pkg, 7536 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 7537 int[] userIds) { 7538 IActivityManager am = ActivityManagerNative.getDefault(); 7539 if (am != null) { 7540 try { 7541 if (userIds == null) { 7542 userIds = am.getRunningUserIds(); 7543 } 7544 for (int id : userIds) { 7545 final Intent intent = new Intent(action, 7546 pkg != null ? Uri.fromParts("package", pkg, null) : null); 7547 if (extras != null) { 7548 intent.putExtras(extras); 7549 } 7550 if (targetPkg != null) { 7551 intent.setPackage(targetPkg); 7552 } 7553 // Modify the UID when posting to other users 7554 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 7555 if (uid > 0 && UserHandle.getUserId(uid) != id) { 7556 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 7557 intent.putExtra(Intent.EXTRA_UID, uid); 7558 } 7559 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 7560 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 7561 if (DEBUG_BROADCASTS) { 7562 RuntimeException here = new RuntimeException("here"); 7563 here.fillInStackTrace(); 7564 Slog.d(TAG, "Sending to user " + id + ": " 7565 + intent.toShortString(false, true, false, false) 7566 + " " + intent.getExtras(), here); 7567 } 7568 am.broadcastIntent(null, intent, null, finishedReceiver, 7569 0, null, null, null, android.app.AppOpsManager.OP_NONE, 7570 finishedReceiver != null, false, id); 7571 } 7572 } catch (RemoteException ex) { 7573 } 7574 } 7575 } 7576 7577 /** 7578 * Check if the external storage media is available. This is true if there 7579 * is a mounted external storage medium or if the external storage is 7580 * emulated. 7581 */ 7582 private boolean isExternalMediaAvailable() { 7583 return mMediaMounted || Environment.isExternalStorageEmulated(); 7584 } 7585 7586 @Override 7587 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 7588 // writer 7589 synchronized (mPackages) { 7590 if (!isExternalMediaAvailable()) { 7591 // If the external storage is no longer mounted at this point, 7592 // the caller may not have been able to delete all of this 7593 // packages files and can not delete any more. Bail. 7594 return null; 7595 } 7596 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 7597 if (lastPackage != null) { 7598 pkgs.remove(lastPackage); 7599 } 7600 if (pkgs.size() > 0) { 7601 return pkgs.get(0); 7602 } 7603 } 7604 return null; 7605 } 7606 7607 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 7608 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 7609 userId, andCode ? 1 : 0, packageName); 7610 if (mSystemReady) { 7611 msg.sendToTarget(); 7612 } else { 7613 if (mPostSystemReadyMessages == null) { 7614 mPostSystemReadyMessages = new ArrayList<>(); 7615 } 7616 mPostSystemReadyMessages.add(msg); 7617 } 7618 } 7619 7620 void startCleaningPackages() { 7621 // reader 7622 synchronized (mPackages) { 7623 if (!isExternalMediaAvailable()) { 7624 return; 7625 } 7626 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 7627 return; 7628 } 7629 } 7630 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 7631 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 7632 IActivityManager am = ActivityManagerNative.getDefault(); 7633 if (am != null) { 7634 try { 7635 am.startService(null, intent, null, UserHandle.USER_OWNER); 7636 } catch (RemoteException e) { 7637 } 7638 } 7639 } 7640 7641 @Override 7642 public void installPackage(String originPath, IPackageInstallObserver2 observer, 7643 int installFlags, String installerPackageName, VerificationParams verificationParams, 7644 String packageAbiOverride) { 7645 installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams, 7646 packageAbiOverride, UserHandle.getCallingUserId()); 7647 } 7648 7649 @Override 7650 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 7651 int installFlags, String installerPackageName, VerificationParams verificationParams, 7652 String packageAbiOverride, int userId) { 7653 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7654 null); 7655 if (UserHandle.getCallingUserId() != userId) { 7656 mContext.enforceCallingOrSelfPermission( 7657 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 7658 "installPackage " + userId); 7659 } 7660 7661 final File originFile = new File(originPath); 7662 final int uid = Binder.getCallingUid(); 7663 if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) { 7664 try { 7665 if (observer != null) { 7666 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 7667 } 7668 } catch (RemoteException re) { 7669 } 7670 return; 7671 } 7672 7673 UserHandle user; 7674 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 7675 user = UserHandle.ALL; 7676 } else { 7677 user = new UserHandle(userId); 7678 } 7679 7680 final int filteredInstallFlags; 7681 if (uid == Process.SHELL_UID || uid == 0) { 7682 if (DEBUG_INSTALL) { 7683 Slog.v(TAG, "Install from ADB"); 7684 } 7685 filteredInstallFlags = installFlags | PackageManager.INSTALL_FROM_ADB; 7686 } else { 7687 filteredInstallFlags = installFlags & ~PackageManager.INSTALL_FROM_ADB; 7688 } 7689 7690 verificationParams.setInstallerUid(uid); 7691 7692 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 7693 7694 final Message msg = mHandler.obtainMessage(INIT_COPY); 7695 msg.obj = new InstallParams(origin, observer, filteredInstallFlags, 7696 installerPackageName, verificationParams, user, packageAbiOverride); 7697 mHandler.sendMessage(msg); 7698 } 7699 7700 void installStage(String packageName, File stagedDir, String stagedCid, 7701 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 7702 String installerPackageName, int installerUid, UserHandle user) { 7703 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 7704 params.referrerUri, installerUid, null); 7705 7706 final OriginInfo origin; 7707 if (stagedDir != null) { 7708 origin = OriginInfo.fromStagedFile(stagedDir); 7709 } else { 7710 origin = OriginInfo.fromStagedContainer(stagedCid); 7711 } 7712 7713 final Message msg = mHandler.obtainMessage(INIT_COPY); 7714 msg.obj = new InstallParams(origin, observer, params.installFlags, 7715 installerPackageName, verifParams, user, params.abiOverride); 7716 mHandler.sendMessage(msg); 7717 } 7718 7719 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 7720 Bundle extras = new Bundle(1); 7721 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 7722 7723 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 7724 packageName, extras, null, null, new int[] {userId}); 7725 try { 7726 IActivityManager am = ActivityManagerNative.getDefault(); 7727 final boolean isSystem = 7728 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 7729 if (isSystem && am.isUserRunning(userId, false)) { 7730 // The just-installed/enabled app is bundled on the system, so presumed 7731 // to be able to run automatically without needing an explicit launch. 7732 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 7733 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 7734 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 7735 .setPackage(packageName); 7736 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 7737 android.app.AppOpsManager.OP_NONE, false, false, userId); 7738 } 7739 } catch (RemoteException e) { 7740 // shouldn't happen 7741 Slog.w(TAG, "Unable to bootstrap installed package", e); 7742 } 7743 } 7744 7745 @Override 7746 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 7747 int userId) { 7748 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7749 PackageSetting pkgSetting; 7750 final int uid = Binder.getCallingUid(); 7751 if (UserHandle.getUserId(uid) != userId) { 7752 mContext.enforceCallingOrSelfPermission( 7753 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 7754 "setApplicationHiddenSetting for user " + userId); 7755 } 7756 7757 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 7758 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 7759 return false; 7760 } 7761 7762 long callingId = Binder.clearCallingIdentity(); 7763 try { 7764 boolean sendAdded = false; 7765 boolean sendRemoved = false; 7766 // writer 7767 synchronized (mPackages) { 7768 pkgSetting = mSettings.mPackages.get(packageName); 7769 if (pkgSetting == null) { 7770 return false; 7771 } 7772 if (pkgSetting.getHidden(userId) != hidden) { 7773 pkgSetting.setHidden(hidden, userId); 7774 mSettings.writePackageRestrictionsLPr(userId); 7775 if (hidden) { 7776 sendRemoved = true; 7777 } else { 7778 sendAdded = true; 7779 } 7780 } 7781 } 7782 if (sendAdded) { 7783 sendPackageAddedForUser(packageName, pkgSetting, userId); 7784 return true; 7785 } 7786 if (sendRemoved) { 7787 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 7788 "hiding pkg"); 7789 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 7790 } 7791 } finally { 7792 Binder.restoreCallingIdentity(callingId); 7793 } 7794 return false; 7795 } 7796 7797 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 7798 int userId) { 7799 final PackageRemovedInfo info = new PackageRemovedInfo(); 7800 info.removedPackage = packageName; 7801 info.removedUsers = new int[] {userId}; 7802 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 7803 info.sendBroadcast(false, false, false); 7804 } 7805 7806 /** 7807 * Returns true if application is not found or there was an error. Otherwise it returns 7808 * the hidden state of the package for the given user. 7809 */ 7810 @Override 7811 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 7812 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7813 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 7814 "getApplicationHidden for user " + userId); 7815 PackageSetting pkgSetting; 7816 long callingId = Binder.clearCallingIdentity(); 7817 try { 7818 // writer 7819 synchronized (mPackages) { 7820 pkgSetting = mSettings.mPackages.get(packageName); 7821 if (pkgSetting == null) { 7822 return true; 7823 } 7824 return pkgSetting.getHidden(userId); 7825 } 7826 } finally { 7827 Binder.restoreCallingIdentity(callingId); 7828 } 7829 } 7830 7831 /** 7832 * @hide 7833 */ 7834 @Override 7835 public int installExistingPackageAsUser(String packageName, int userId) { 7836 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7837 null); 7838 PackageSetting pkgSetting; 7839 final int uid = Binder.getCallingUid(); 7840 enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId); 7841 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 7842 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 7843 } 7844 7845 long callingId = Binder.clearCallingIdentity(); 7846 try { 7847 boolean sendAdded = false; 7848 Bundle extras = new Bundle(1); 7849 7850 // writer 7851 synchronized (mPackages) { 7852 pkgSetting = mSettings.mPackages.get(packageName); 7853 if (pkgSetting == null) { 7854 return PackageManager.INSTALL_FAILED_INVALID_URI; 7855 } 7856 if (!pkgSetting.getInstalled(userId)) { 7857 pkgSetting.setInstalled(true, userId); 7858 pkgSetting.setHidden(false, userId); 7859 mSettings.writePackageRestrictionsLPr(userId); 7860 sendAdded = true; 7861 } 7862 } 7863 7864 if (sendAdded) { 7865 sendPackageAddedForUser(packageName, pkgSetting, userId); 7866 } 7867 } finally { 7868 Binder.restoreCallingIdentity(callingId); 7869 } 7870 7871 return PackageManager.INSTALL_SUCCEEDED; 7872 } 7873 7874 boolean isUserRestricted(int userId, String restrictionKey) { 7875 Bundle restrictions = sUserManager.getUserRestrictions(userId); 7876 if (restrictions.getBoolean(restrictionKey, false)) { 7877 Log.w(TAG, "User is restricted: " + restrictionKey); 7878 return true; 7879 } 7880 return false; 7881 } 7882 7883 @Override 7884 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 7885 mContext.enforceCallingOrSelfPermission( 7886 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7887 "Only package verification agents can verify applications"); 7888 7889 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7890 final PackageVerificationResponse response = new PackageVerificationResponse( 7891 verificationCode, Binder.getCallingUid()); 7892 msg.arg1 = id; 7893 msg.obj = response; 7894 mHandler.sendMessage(msg); 7895 } 7896 7897 @Override 7898 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 7899 long millisecondsToDelay) { 7900 mContext.enforceCallingOrSelfPermission( 7901 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7902 "Only package verification agents can extend verification timeouts"); 7903 7904 final PackageVerificationState state = mPendingVerification.get(id); 7905 final PackageVerificationResponse response = new PackageVerificationResponse( 7906 verificationCodeAtTimeout, Binder.getCallingUid()); 7907 7908 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 7909 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 7910 } 7911 if (millisecondsToDelay < 0) { 7912 millisecondsToDelay = 0; 7913 } 7914 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 7915 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 7916 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 7917 } 7918 7919 if ((state != null) && !state.timeoutExtended()) { 7920 state.extendTimeout(); 7921 7922 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7923 msg.arg1 = id; 7924 msg.obj = response; 7925 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 7926 } 7927 } 7928 7929 private void broadcastPackageVerified(int verificationId, Uri packageUri, 7930 int verificationCode, UserHandle user) { 7931 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 7932 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 7933 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 7934 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 7935 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 7936 7937 mContext.sendBroadcastAsUser(intent, user, 7938 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 7939 } 7940 7941 private ComponentName matchComponentForVerifier(String packageName, 7942 List<ResolveInfo> receivers) { 7943 ActivityInfo targetReceiver = null; 7944 7945 final int NR = receivers.size(); 7946 for (int i = 0; i < NR; i++) { 7947 final ResolveInfo info = receivers.get(i); 7948 if (info.activityInfo == null) { 7949 continue; 7950 } 7951 7952 if (packageName.equals(info.activityInfo.packageName)) { 7953 targetReceiver = info.activityInfo; 7954 break; 7955 } 7956 } 7957 7958 if (targetReceiver == null) { 7959 return null; 7960 } 7961 7962 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 7963 } 7964 7965 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 7966 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 7967 if (pkgInfo.verifiers.length == 0) { 7968 return null; 7969 } 7970 7971 final int N = pkgInfo.verifiers.length; 7972 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 7973 for (int i = 0; i < N; i++) { 7974 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 7975 7976 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 7977 receivers); 7978 if (comp == null) { 7979 continue; 7980 } 7981 7982 final int verifierUid = getUidForVerifier(verifierInfo); 7983 if (verifierUid == -1) { 7984 continue; 7985 } 7986 7987 if (DEBUG_VERIFY) { 7988 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 7989 + " with the correct signature"); 7990 } 7991 sufficientVerifiers.add(comp); 7992 verificationState.addSufficientVerifier(verifierUid); 7993 } 7994 7995 return sufficientVerifiers; 7996 } 7997 7998 private int getUidForVerifier(VerifierInfo verifierInfo) { 7999 synchronized (mPackages) { 8000 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8001 if (pkg == null) { 8002 return -1; 8003 } else if (pkg.mSignatures.length != 1) { 8004 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8005 + " has more than one signature; ignoring"); 8006 return -1; 8007 } 8008 8009 /* 8010 * If the public key of the package's signature does not match 8011 * our expected public key, then this is a different package and 8012 * we should skip. 8013 */ 8014 8015 final byte[] expectedPublicKey; 8016 try { 8017 final Signature verifierSig = pkg.mSignatures[0]; 8018 final PublicKey publicKey = verifierSig.getPublicKey(); 8019 expectedPublicKey = publicKey.getEncoded(); 8020 } catch (CertificateException e) { 8021 return -1; 8022 } 8023 8024 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8025 8026 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8027 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8028 + " does not have the expected public key; ignoring"); 8029 return -1; 8030 } 8031 8032 return pkg.applicationInfo.uid; 8033 } 8034 } 8035 8036 @Override 8037 public void finishPackageInstall(int token) { 8038 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8039 8040 if (DEBUG_INSTALL) { 8041 Slog.v(TAG, "BM finishing package install for " + token); 8042 } 8043 8044 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8045 mHandler.sendMessage(msg); 8046 } 8047 8048 /** 8049 * Get the verification agent timeout. 8050 * 8051 * @return verification timeout in milliseconds 8052 */ 8053 private long getVerificationTimeout() { 8054 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8055 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8056 DEFAULT_VERIFICATION_TIMEOUT); 8057 } 8058 8059 /** 8060 * Get the default verification agent response code. 8061 * 8062 * @return default verification response code 8063 */ 8064 private int getDefaultVerificationResponse() { 8065 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8066 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8067 DEFAULT_VERIFICATION_RESPONSE); 8068 } 8069 8070 /** 8071 * Check whether or not package verification has been enabled. 8072 * 8073 * @return true if verification should be performed 8074 */ 8075 private boolean isVerificationEnabled(int userId, int installFlags) { 8076 if (!DEFAULT_VERIFY_ENABLE) { 8077 return false; 8078 } 8079 8080 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 8081 8082 // Check if installing from ADB 8083 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 8084 // Do not run verification in a test harness environment 8085 if (ActivityManager.isRunningInTestHarness()) { 8086 return false; 8087 } 8088 if (ensureVerifyAppsEnabled) { 8089 return true; 8090 } 8091 // Check if the developer does not want package verification for ADB installs 8092 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8093 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8094 return false; 8095 } 8096 } 8097 8098 if (ensureVerifyAppsEnabled) { 8099 return true; 8100 } 8101 8102 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8103 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8104 } 8105 8106 /** 8107 * Get the "allow unknown sources" setting. 8108 * 8109 * @return the current "allow unknown sources" setting 8110 */ 8111 private int getUnknownSourcesSettings() { 8112 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8113 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 8114 -1); 8115 } 8116 8117 @Override 8118 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 8119 final int uid = Binder.getCallingUid(); 8120 // writer 8121 synchronized (mPackages) { 8122 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 8123 if (targetPackageSetting == null) { 8124 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 8125 } 8126 8127 PackageSetting installerPackageSetting; 8128 if (installerPackageName != null) { 8129 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 8130 if (installerPackageSetting == null) { 8131 throw new IllegalArgumentException("Unknown installer package: " 8132 + installerPackageName); 8133 } 8134 } else { 8135 installerPackageSetting = null; 8136 } 8137 8138 Signature[] callerSignature; 8139 Object obj = mSettings.getUserIdLPr(uid); 8140 if (obj != null) { 8141 if (obj instanceof SharedUserSetting) { 8142 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 8143 } else if (obj instanceof PackageSetting) { 8144 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 8145 } else { 8146 throw new SecurityException("Bad object " + obj + " for uid " + uid); 8147 } 8148 } else { 8149 throw new SecurityException("Unknown calling uid " + uid); 8150 } 8151 8152 // Verify: can't set installerPackageName to a package that is 8153 // not signed with the same cert as the caller. 8154 if (installerPackageSetting != null) { 8155 if (compareSignatures(callerSignature, 8156 installerPackageSetting.signatures.mSignatures) 8157 != PackageManager.SIGNATURE_MATCH) { 8158 throw new SecurityException( 8159 "Caller does not have same cert as new installer package " 8160 + installerPackageName); 8161 } 8162 } 8163 8164 // Verify: if target already has an installer package, it must 8165 // be signed with the same cert as the caller. 8166 if (targetPackageSetting.installerPackageName != null) { 8167 PackageSetting setting = mSettings.mPackages.get( 8168 targetPackageSetting.installerPackageName); 8169 // If the currently set package isn't valid, then it's always 8170 // okay to change it. 8171 if (setting != null) { 8172 if (compareSignatures(callerSignature, 8173 setting.signatures.mSignatures) 8174 != PackageManager.SIGNATURE_MATCH) { 8175 throw new SecurityException( 8176 "Caller does not have same cert as old installer package " 8177 + targetPackageSetting.installerPackageName); 8178 } 8179 } 8180 } 8181 8182 // Okay! 8183 targetPackageSetting.installerPackageName = installerPackageName; 8184 scheduleWriteSettingsLocked(); 8185 } 8186 } 8187 8188 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 8189 // Queue up an async operation since the package installation may take a little while. 8190 mHandler.post(new Runnable() { 8191 public void run() { 8192 mHandler.removeCallbacks(this); 8193 // Result object to be returned 8194 PackageInstalledInfo res = new PackageInstalledInfo(); 8195 res.returnCode = currentStatus; 8196 res.uid = -1; 8197 res.pkg = null; 8198 res.removedInfo = new PackageRemovedInfo(); 8199 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 8200 args.doPreInstall(res.returnCode); 8201 synchronized (mInstallLock) { 8202 installPackageLI(args, res); 8203 } 8204 args.doPostInstall(res.returnCode, res.uid); 8205 } 8206 8207 // A restore should be performed at this point if (a) the install 8208 // succeeded, (b) the operation is not an update, and (c) the new 8209 // package has not opted out of backup participation. 8210 final boolean update = res.removedInfo.removedPackage != null; 8211 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 8212 boolean doRestore = !update 8213 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 8214 8215 // Set up the post-install work request bookkeeping. This will be used 8216 // and cleaned up by the post-install event handling regardless of whether 8217 // there's a restore pass performed. Token values are >= 1. 8218 int token; 8219 if (mNextInstallToken < 0) mNextInstallToken = 1; 8220 token = mNextInstallToken++; 8221 8222 PostInstallData data = new PostInstallData(args, res); 8223 mRunningInstalls.put(token, data); 8224 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 8225 8226 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 8227 // Pass responsibility to the Backup Manager. It will perform a 8228 // restore if appropriate, then pass responsibility back to the 8229 // Package Manager to run the post-install observer callbacks 8230 // and broadcasts. 8231 IBackupManager bm = IBackupManager.Stub.asInterface( 8232 ServiceManager.getService(Context.BACKUP_SERVICE)); 8233 if (bm != null) { 8234 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 8235 + " to BM for possible restore"); 8236 try { 8237 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 8238 } catch (RemoteException e) { 8239 // can't happen; the backup manager is local 8240 } catch (Exception e) { 8241 Slog.e(TAG, "Exception trying to enqueue restore", e); 8242 doRestore = false; 8243 } 8244 } else { 8245 Slog.e(TAG, "Backup Manager not found!"); 8246 doRestore = false; 8247 } 8248 } 8249 8250 if (!doRestore) { 8251 // No restore possible, or the Backup Manager was mysteriously not 8252 // available -- just fire the post-install work request directly. 8253 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 8254 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8255 mHandler.sendMessage(msg); 8256 } 8257 } 8258 }); 8259 } 8260 8261 private abstract class HandlerParams { 8262 private static final int MAX_RETRIES = 4; 8263 8264 /** 8265 * Number of times startCopy() has been attempted and had a non-fatal 8266 * error. 8267 */ 8268 private int mRetries = 0; 8269 8270 /** User handle for the user requesting the information or installation. */ 8271 private final UserHandle mUser; 8272 8273 HandlerParams(UserHandle user) { 8274 mUser = user; 8275 } 8276 8277 UserHandle getUser() { 8278 return mUser; 8279 } 8280 8281 final boolean startCopy() { 8282 boolean res; 8283 try { 8284 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 8285 8286 if (++mRetries > MAX_RETRIES) { 8287 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 8288 mHandler.sendEmptyMessage(MCS_GIVE_UP); 8289 handleServiceError(); 8290 return false; 8291 } else { 8292 handleStartCopy(); 8293 res = true; 8294 } 8295 } catch (RemoteException e) { 8296 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 8297 mHandler.sendEmptyMessage(MCS_RECONNECT); 8298 res = false; 8299 } 8300 handleReturnCode(); 8301 return res; 8302 } 8303 8304 final void serviceError() { 8305 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 8306 handleServiceError(); 8307 handleReturnCode(); 8308 } 8309 8310 abstract void handleStartCopy() throws RemoteException; 8311 abstract void handleServiceError(); 8312 abstract void handleReturnCode(); 8313 } 8314 8315 class MeasureParams extends HandlerParams { 8316 private final PackageStats mStats; 8317 private boolean mSuccess; 8318 8319 private final IPackageStatsObserver mObserver; 8320 8321 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 8322 super(new UserHandle(stats.userHandle)); 8323 mObserver = observer; 8324 mStats = stats; 8325 } 8326 8327 @Override 8328 public String toString() { 8329 return "MeasureParams{" 8330 + Integer.toHexString(System.identityHashCode(this)) 8331 + " " + mStats.packageName + "}"; 8332 } 8333 8334 @Override 8335 void handleStartCopy() throws RemoteException { 8336 synchronized (mInstallLock) { 8337 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 8338 } 8339 8340 if (mSuccess) { 8341 final boolean mounted; 8342 if (Environment.isExternalStorageEmulated()) { 8343 mounted = true; 8344 } else { 8345 final String status = Environment.getExternalStorageState(); 8346 mounted = (Environment.MEDIA_MOUNTED.equals(status) 8347 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 8348 } 8349 8350 if (mounted) { 8351 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 8352 8353 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 8354 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 8355 8356 mStats.externalDataSize = calculateDirectorySize(mContainerService, 8357 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 8358 8359 // Always subtract cache size, since it's a subdirectory 8360 mStats.externalDataSize -= mStats.externalCacheSize; 8361 8362 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 8363 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 8364 8365 mStats.externalObbSize = calculateDirectorySize(mContainerService, 8366 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 8367 } 8368 } 8369 } 8370 8371 @Override 8372 void handleReturnCode() { 8373 if (mObserver != null) { 8374 try { 8375 mObserver.onGetStatsCompleted(mStats, mSuccess); 8376 } catch (RemoteException e) { 8377 Slog.i(TAG, "Observer no longer exists."); 8378 } 8379 } 8380 } 8381 8382 @Override 8383 void handleServiceError() { 8384 Slog.e(TAG, "Could not measure application " + mStats.packageName 8385 + " external storage"); 8386 } 8387 } 8388 8389 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 8390 throws RemoteException { 8391 long result = 0; 8392 for (File path : paths) { 8393 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 8394 } 8395 return result; 8396 } 8397 8398 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 8399 for (File path : paths) { 8400 try { 8401 mcs.clearDirectory(path.getAbsolutePath()); 8402 } catch (RemoteException e) { 8403 } 8404 } 8405 } 8406 8407 static class OriginInfo { 8408 /** 8409 * Location where install is coming from, before it has been 8410 * copied/renamed into place. This could be a single monolithic APK 8411 * file, or a cluster directory. This location may be untrusted. 8412 */ 8413 final File file; 8414 final String cid; 8415 8416 /** 8417 * Flag indicating that {@link #file} or {@link #cid} has already been 8418 * staged, meaning downstream users don't need to defensively copy the 8419 * contents. 8420 */ 8421 final boolean staged; 8422 8423 /** 8424 * Flag indicating that {@link #file} or {@link #cid} is an already 8425 * installed app that is being moved. 8426 */ 8427 final boolean existing; 8428 8429 final String resolvedPath; 8430 final File resolvedFile; 8431 8432 static OriginInfo fromNothing() { 8433 return new OriginInfo(null, null, false, false); 8434 } 8435 8436 static OriginInfo fromUntrustedFile(File file) { 8437 return new OriginInfo(file, null, false, false); 8438 } 8439 8440 static OriginInfo fromExistingFile(File file) { 8441 return new OriginInfo(file, null, false, true); 8442 } 8443 8444 static OriginInfo fromStagedFile(File file) { 8445 return new OriginInfo(file, null, true, false); 8446 } 8447 8448 static OriginInfo fromStagedContainer(String cid) { 8449 return new OriginInfo(null, cid, true, false); 8450 } 8451 8452 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 8453 this.file = file; 8454 this.cid = cid; 8455 this.staged = staged; 8456 this.existing = existing; 8457 8458 if (cid != null) { 8459 resolvedPath = PackageHelper.getSdDir(cid); 8460 resolvedFile = new File(resolvedPath); 8461 } else if (file != null) { 8462 resolvedPath = file.getAbsolutePath(); 8463 resolvedFile = file; 8464 } else { 8465 resolvedPath = null; 8466 resolvedFile = null; 8467 } 8468 } 8469 } 8470 8471 class InstallParams extends HandlerParams { 8472 final OriginInfo origin; 8473 final IPackageInstallObserver2 observer; 8474 int installFlags; 8475 final String installerPackageName; 8476 final VerificationParams verificationParams; 8477 private InstallArgs mArgs; 8478 private int mRet; 8479 final String packageAbiOverride; 8480 8481 InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 8482 String installerPackageName, VerificationParams verificationParams, UserHandle user, 8483 String packageAbiOverride) { 8484 super(user); 8485 this.origin = origin; 8486 this.observer = observer; 8487 this.installFlags = installFlags; 8488 this.installerPackageName = installerPackageName; 8489 this.verificationParams = verificationParams; 8490 this.packageAbiOverride = packageAbiOverride; 8491 } 8492 8493 @Override 8494 public String toString() { 8495 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 8496 + " file=" + origin.file + " cid=" + origin.cid + "}"; 8497 } 8498 8499 public ManifestDigest getManifestDigest() { 8500 if (verificationParams == null) { 8501 return null; 8502 } 8503 return verificationParams.getManifestDigest(); 8504 } 8505 8506 private int installLocationPolicy(PackageInfoLite pkgLite) { 8507 String packageName = pkgLite.packageName; 8508 int installLocation = pkgLite.installLocation; 8509 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 8510 // reader 8511 synchronized (mPackages) { 8512 PackageParser.Package pkg = mPackages.get(packageName); 8513 if (pkg != null) { 8514 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 8515 // Check for downgrading. 8516 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 8517 if (pkgLite.versionCode < pkg.mVersionCode) { 8518 Slog.w(TAG, "Can't install update of " + packageName 8519 + " update version " + pkgLite.versionCode 8520 + " is older than installed version " 8521 + pkg.mVersionCode); 8522 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 8523 } 8524 } 8525 // Check for updated system application. 8526 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8527 if (onSd) { 8528 Slog.w(TAG, "Cannot install update to system app on sdcard"); 8529 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 8530 } 8531 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8532 } else { 8533 if (onSd) { 8534 // Install flag overrides everything. 8535 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8536 } 8537 // If current upgrade specifies particular preference 8538 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 8539 // Application explicitly specified internal. 8540 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8541 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 8542 // App explictly prefers external. Let policy decide 8543 } else { 8544 // Prefer previous location 8545 if (isExternal(pkg)) { 8546 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8547 } 8548 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8549 } 8550 } 8551 } else { 8552 // Invalid install. Return error code 8553 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 8554 } 8555 } 8556 } 8557 // All the special cases have been taken care of. 8558 // Return result based on recommended install location. 8559 if (onSd) { 8560 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8561 } 8562 return pkgLite.recommendedInstallLocation; 8563 } 8564 8565 /* 8566 * Invoke remote method to get package information and install 8567 * location values. Override install location based on default 8568 * policy if needed and then create install arguments based 8569 * on the install location. 8570 */ 8571 public void handleStartCopy() throws RemoteException { 8572 int ret = PackageManager.INSTALL_SUCCEEDED; 8573 8574 // If we're already staged, we've firmly committed to an install location 8575 if (origin.staged) { 8576 if (origin.file != null) { 8577 installFlags |= PackageManager.INSTALL_INTERNAL; 8578 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 8579 } else if (origin.cid != null) { 8580 installFlags |= PackageManager.INSTALL_EXTERNAL; 8581 installFlags &= ~PackageManager.INSTALL_INTERNAL; 8582 } else { 8583 throw new IllegalStateException("Invalid stage location"); 8584 } 8585 } 8586 8587 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 8588 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 8589 8590 PackageInfoLite pkgLite = null; 8591 8592 if (onInt && onSd) { 8593 // Check if both bits are set. 8594 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 8595 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8596 } else { 8597 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 8598 packageAbiOverride); 8599 8600 /* 8601 * If we have too little free space, try to free cache 8602 * before giving up. 8603 */ 8604 if (!origin.staged && pkgLite.recommendedInstallLocation 8605 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8606 // TODO: focus freeing disk space on the target device 8607 final StorageManager storage = StorageManager.from(mContext); 8608 final long lowThreshold = storage.getStorageLowBytes( 8609 Environment.getDataDirectory()); 8610 8611 final long sizeBytes = mContainerService.calculateInstalledSize( 8612 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 8613 8614 if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) { 8615 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 8616 installFlags, packageAbiOverride); 8617 } 8618 8619 /* 8620 * The cache free must have deleted the file we 8621 * downloaded to install. 8622 * 8623 * TODO: fix the "freeCache" call to not delete 8624 * the file we care about. 8625 */ 8626 if (pkgLite.recommendedInstallLocation 8627 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8628 pkgLite.recommendedInstallLocation 8629 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 8630 } 8631 } 8632 } 8633 8634 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8635 int loc = pkgLite.recommendedInstallLocation; 8636 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 8637 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8638 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 8639 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 8640 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8641 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8642 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 8643 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 8644 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8645 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 8646 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 8647 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 8648 } else { 8649 // Override with defaults if needed. 8650 loc = installLocationPolicy(pkgLite); 8651 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 8652 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 8653 } else if (!onSd && !onInt) { 8654 // Override install location with flags 8655 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 8656 // Set the flag to install on external media. 8657 installFlags |= PackageManager.INSTALL_EXTERNAL; 8658 installFlags &= ~PackageManager.INSTALL_INTERNAL; 8659 } else { 8660 // Make sure the flag for installing on external 8661 // media is unset 8662 installFlags |= PackageManager.INSTALL_INTERNAL; 8663 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 8664 } 8665 } 8666 } 8667 } 8668 8669 final InstallArgs args = createInstallArgs(this); 8670 mArgs = args; 8671 8672 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8673 /* 8674 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 8675 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 8676 */ 8677 int userIdentifier = getUser().getIdentifier(); 8678 if (userIdentifier == UserHandle.USER_ALL 8679 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 8680 userIdentifier = UserHandle.USER_OWNER; 8681 } 8682 8683 /* 8684 * Determine if we have any installed package verifiers. If we 8685 * do, then we'll defer to them to verify the packages. 8686 */ 8687 final int requiredUid = mRequiredVerifierPackage == null ? -1 8688 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 8689 if (!origin.existing && requiredUid != -1 8690 && isVerificationEnabled(userIdentifier, installFlags)) { 8691 final Intent verification = new Intent( 8692 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 8693 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 8694 PACKAGE_MIME_TYPE); 8695 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8696 8697 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 8698 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 8699 0 /* TODO: Which userId? */); 8700 8701 if (DEBUG_VERIFY) { 8702 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 8703 + verification.toString() + " with " + pkgLite.verifiers.length 8704 + " optional verifiers"); 8705 } 8706 8707 final int verificationId = mPendingVerificationToken++; 8708 8709 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8710 8711 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 8712 installerPackageName); 8713 8714 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 8715 installFlags); 8716 8717 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 8718 pkgLite.packageName); 8719 8720 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 8721 pkgLite.versionCode); 8722 8723 if (verificationParams != null) { 8724 if (verificationParams.getVerificationURI() != null) { 8725 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 8726 verificationParams.getVerificationURI()); 8727 } 8728 if (verificationParams.getOriginatingURI() != null) { 8729 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 8730 verificationParams.getOriginatingURI()); 8731 } 8732 if (verificationParams.getReferrer() != null) { 8733 verification.putExtra(Intent.EXTRA_REFERRER, 8734 verificationParams.getReferrer()); 8735 } 8736 if (verificationParams.getOriginatingUid() >= 0) { 8737 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 8738 verificationParams.getOriginatingUid()); 8739 } 8740 if (verificationParams.getInstallerUid() >= 0) { 8741 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 8742 verificationParams.getInstallerUid()); 8743 } 8744 } 8745 8746 final PackageVerificationState verificationState = new PackageVerificationState( 8747 requiredUid, args); 8748 8749 mPendingVerification.append(verificationId, verificationState); 8750 8751 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 8752 receivers, verificationState); 8753 8754 /* 8755 * If any sufficient verifiers were listed in the package 8756 * manifest, attempt to ask them. 8757 */ 8758 if (sufficientVerifiers != null) { 8759 final int N = sufficientVerifiers.size(); 8760 if (N == 0) { 8761 Slog.i(TAG, "Additional verifiers required, but none installed."); 8762 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 8763 } else { 8764 for (int i = 0; i < N; i++) { 8765 final ComponentName verifierComponent = sufficientVerifiers.get(i); 8766 8767 final Intent sufficientIntent = new Intent(verification); 8768 sufficientIntent.setComponent(verifierComponent); 8769 8770 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 8771 } 8772 } 8773 } 8774 8775 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 8776 mRequiredVerifierPackage, receivers); 8777 if (ret == PackageManager.INSTALL_SUCCEEDED 8778 && mRequiredVerifierPackage != null) { 8779 /* 8780 * Send the intent to the required verification agent, 8781 * but only start the verification timeout after the 8782 * target BroadcastReceivers have run. 8783 */ 8784 verification.setComponent(requiredVerifierComponent); 8785 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 8786 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8787 new BroadcastReceiver() { 8788 @Override 8789 public void onReceive(Context context, Intent intent) { 8790 final Message msg = mHandler 8791 .obtainMessage(CHECK_PENDING_VERIFICATION); 8792 msg.arg1 = verificationId; 8793 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 8794 } 8795 }, null, 0, null, null); 8796 8797 /* 8798 * We don't want the copy to proceed until verification 8799 * succeeds, so null out this field. 8800 */ 8801 mArgs = null; 8802 } 8803 } else { 8804 /* 8805 * No package verification is enabled, so immediately start 8806 * the remote call to initiate copy using temporary file. 8807 */ 8808 ret = args.copyApk(mContainerService, true); 8809 } 8810 } 8811 8812 mRet = ret; 8813 } 8814 8815 @Override 8816 void handleReturnCode() { 8817 // If mArgs is null, then MCS couldn't be reached. When it 8818 // reconnects, it will try again to install. At that point, this 8819 // will succeed. 8820 if (mArgs != null) { 8821 processPendingInstall(mArgs, mRet); 8822 } 8823 } 8824 8825 @Override 8826 void handleServiceError() { 8827 mArgs = createInstallArgs(this); 8828 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8829 } 8830 8831 public boolean isForwardLocked() { 8832 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8833 } 8834 } 8835 8836 /** 8837 * Used during creation of InstallArgs 8838 * 8839 * @param installFlags package installation flags 8840 * @return true if should be installed on external storage 8841 */ 8842 private static boolean installOnSd(int installFlags) { 8843 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 8844 return false; 8845 } 8846 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 8847 return true; 8848 } 8849 return false; 8850 } 8851 8852 /** 8853 * Used during creation of InstallArgs 8854 * 8855 * @param installFlags package installation flags 8856 * @return true if should be installed as forward locked 8857 */ 8858 private static boolean installForwardLocked(int installFlags) { 8859 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8860 } 8861 8862 private InstallArgs createInstallArgs(InstallParams params) { 8863 if (installOnSd(params.installFlags) || params.isForwardLocked()) { 8864 return new AsecInstallArgs(params); 8865 } else { 8866 return new FileInstallArgs(params); 8867 } 8868 } 8869 8870 /** 8871 * Create args that describe an existing installed package. Typically used 8872 * when cleaning up old installs, or used as a move source. 8873 */ 8874 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 8875 String resourcePath, String nativeLibraryRoot, String[] instructionSets) { 8876 final boolean isInAsec; 8877 if (installOnSd(installFlags)) { 8878 /* Apps on SD card are always in ASEC containers. */ 8879 isInAsec = true; 8880 } else if (installForwardLocked(installFlags) 8881 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 8882 /* 8883 * Forward-locked apps are only in ASEC containers if they're the 8884 * new style 8885 */ 8886 isInAsec = true; 8887 } else { 8888 isInAsec = false; 8889 } 8890 8891 if (isInAsec) { 8892 return new AsecInstallArgs(codePath, instructionSets, 8893 installOnSd(installFlags), installForwardLocked(installFlags)); 8894 } else { 8895 return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot, 8896 instructionSets); 8897 } 8898 } 8899 8900 static abstract class InstallArgs { 8901 /** @see InstallParams#origin */ 8902 final OriginInfo origin; 8903 8904 final IPackageInstallObserver2 observer; 8905 // Always refers to PackageManager flags only 8906 final int installFlags; 8907 final String installerPackageName; 8908 final ManifestDigest manifestDigest; 8909 final UserHandle user; 8910 final String abiOverride; 8911 8912 // The list of instruction sets supported by this app. This is currently 8913 // only used during the rmdex() phase to clean up resources. We can get rid of this 8914 // if we move dex files under the common app path. 8915 /* nullable */ String[] instructionSets; 8916 8917 InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 8918 String installerPackageName, ManifestDigest manifestDigest, UserHandle user, 8919 String[] instructionSets, String abiOverride) { 8920 this.origin = origin; 8921 this.installFlags = installFlags; 8922 this.observer = observer; 8923 this.installerPackageName = installerPackageName; 8924 this.manifestDigest = manifestDigest; 8925 this.user = user; 8926 this.instructionSets = instructionSets; 8927 this.abiOverride = abiOverride; 8928 } 8929 8930 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 8931 abstract int doPreInstall(int status); 8932 8933 /** 8934 * Rename package into final resting place. All paths on the given 8935 * scanned package should be updated to reflect the rename. 8936 */ 8937 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 8938 abstract int doPostInstall(int status, int uid); 8939 8940 /** @see PackageSettingBase#codePathString */ 8941 abstract String getCodePath(); 8942 /** @see PackageSettingBase#resourcePathString */ 8943 abstract String getResourcePath(); 8944 abstract String getLegacyNativeLibraryPath(); 8945 8946 // Need installer lock especially for dex file removal. 8947 abstract void cleanUpResourcesLI(); 8948 abstract boolean doPostDeleteLI(boolean delete); 8949 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 8950 8951 /** 8952 * Called before the source arguments are copied. This is used mostly 8953 * for MoveParams when it needs to read the source file to put it in the 8954 * destination. 8955 */ 8956 int doPreCopy() { 8957 return PackageManager.INSTALL_SUCCEEDED; 8958 } 8959 8960 /** 8961 * Called after the source arguments are copied. This is used mostly for 8962 * MoveParams when it needs to read the source file to put it in the 8963 * destination. 8964 * 8965 * @return 8966 */ 8967 int doPostCopy(int uid) { 8968 return PackageManager.INSTALL_SUCCEEDED; 8969 } 8970 8971 protected boolean isFwdLocked() { 8972 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8973 } 8974 8975 protected boolean isExternal() { 8976 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 8977 } 8978 8979 UserHandle getUser() { 8980 return user; 8981 } 8982 } 8983 8984 /** 8985 * Logic to handle installation of non-ASEC applications, including copying 8986 * and renaming logic. 8987 */ 8988 class FileInstallArgs extends InstallArgs { 8989 private File codeFile; 8990 private File resourceFile; 8991 private File legacyNativeLibraryPath; 8992 8993 // Example topology: 8994 // /data/app/com.example/base.apk 8995 // /data/app/com.example/split_foo.apk 8996 // /data/app/com.example/lib/arm/libfoo.so 8997 // /data/app/com.example/lib/arm64/libfoo.so 8998 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 8999 9000 /** New install */ 9001 FileInstallArgs(InstallParams params) { 9002 super(params.origin, params.observer, params.installFlags, 9003 params.installerPackageName, params.getManifestDigest(), params.getUser(), 9004 null /* instruction sets */, params.packageAbiOverride); 9005 if (isFwdLocked()) { 9006 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 9007 } 9008 } 9009 9010 /** Existing install */ 9011 FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath, 9012 String[] instructionSets) { 9013 super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null); 9014 this.codeFile = (codePath != null) ? new File(codePath) : null; 9015 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 9016 this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ? 9017 new File(legacyNativeLibraryPath) : null; 9018 } 9019 9020 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9021 final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(), 9022 isFwdLocked(), abiOverride); 9023 9024 final StorageManager storage = StorageManager.from(mContext); 9025 return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory())); 9026 } 9027 9028 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9029 if (origin.staged) { 9030 Slog.d(TAG, origin.file + " already staged; skipping copy"); 9031 codeFile = origin.file; 9032 resourceFile = origin.file; 9033 return PackageManager.INSTALL_SUCCEEDED; 9034 } 9035 9036 try { 9037 final File tempDir = mInstallerService.allocateInternalStageDirLegacy(); 9038 codeFile = tempDir; 9039 resourceFile = tempDir; 9040 } catch (IOException e) { 9041 Slog.w(TAG, "Failed to create copy file: " + e); 9042 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9043 } 9044 9045 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 9046 @Override 9047 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 9048 if (!FileUtils.isValidExtFilename(name)) { 9049 throw new IllegalArgumentException("Invalid filename: " + name); 9050 } 9051 try { 9052 final File file = new File(codeFile, name); 9053 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 9054 O_RDWR | O_CREAT, 0644); 9055 Os.chmod(file.getAbsolutePath(), 0644); 9056 return new ParcelFileDescriptor(fd); 9057 } catch (ErrnoException e) { 9058 throw new RemoteException("Failed to open: " + e.getMessage()); 9059 } 9060 } 9061 }; 9062 9063 int ret = PackageManager.INSTALL_SUCCEEDED; 9064 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 9065 if (ret != PackageManager.INSTALL_SUCCEEDED) { 9066 Slog.e(TAG, "Failed to copy package"); 9067 return ret; 9068 } 9069 9070 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 9071 NativeLibraryHelper.Handle handle = null; 9072 try { 9073 handle = NativeLibraryHelper.Handle.create(codeFile); 9074 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 9075 abiOverride); 9076 } catch (IOException e) { 9077 Slog.e(TAG, "Copying native libraries failed", e); 9078 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9079 } finally { 9080 IoUtils.closeQuietly(handle); 9081 } 9082 9083 return ret; 9084 } 9085 9086 int doPreInstall(int status) { 9087 if (status != PackageManager.INSTALL_SUCCEEDED) { 9088 cleanUp(); 9089 } 9090 return status; 9091 } 9092 9093 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9094 if (status != PackageManager.INSTALL_SUCCEEDED) { 9095 cleanUp(); 9096 return false; 9097 } else { 9098 final File beforeCodeFile = codeFile; 9099 final File afterCodeFile = getNextCodePath(pkg.packageName); 9100 9101 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 9102 try { 9103 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 9104 } catch (ErrnoException e) { 9105 Slog.d(TAG, "Failed to rename", e); 9106 return false; 9107 } 9108 9109 if (!SELinux.restoreconRecursive(afterCodeFile)) { 9110 Slog.d(TAG, "Failed to restorecon"); 9111 return false; 9112 } 9113 9114 // Reflect the rename internally 9115 codeFile = afterCodeFile; 9116 resourceFile = afterCodeFile; 9117 9118 // Reflect the rename in scanned details 9119 pkg.codePath = afterCodeFile.getAbsolutePath(); 9120 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9121 pkg.baseCodePath); 9122 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9123 pkg.splitCodePaths); 9124 9125 // Reflect the rename in app info 9126 pkg.applicationInfo.setCodePath(pkg.codePath); 9127 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9128 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9129 pkg.applicationInfo.setResourcePath(pkg.codePath); 9130 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9131 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9132 9133 return true; 9134 } 9135 } 9136 9137 int doPostInstall(int status, int uid) { 9138 if (status != PackageManager.INSTALL_SUCCEEDED) { 9139 cleanUp(); 9140 } 9141 return status; 9142 } 9143 9144 @Override 9145 String getCodePath() { 9146 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 9147 } 9148 9149 @Override 9150 String getResourcePath() { 9151 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 9152 } 9153 9154 @Override 9155 String getLegacyNativeLibraryPath() { 9156 return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null; 9157 } 9158 9159 private boolean cleanUp() { 9160 if (codeFile == null || !codeFile.exists()) { 9161 return false; 9162 } 9163 9164 if (codeFile.isDirectory()) { 9165 FileUtils.deleteContents(codeFile); 9166 } 9167 codeFile.delete(); 9168 9169 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 9170 resourceFile.delete(); 9171 } 9172 9173 if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) { 9174 if (!FileUtils.deleteContents(legacyNativeLibraryPath)) { 9175 Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath); 9176 } 9177 legacyNativeLibraryPath.delete(); 9178 } 9179 9180 return true; 9181 } 9182 9183 void cleanUpResourcesLI() { 9184 // Try enumerating all code paths before deleting 9185 List<String> allCodePaths = Collections.EMPTY_LIST; 9186 if (codeFile != null && codeFile.exists()) { 9187 try { 9188 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9189 allCodePaths = pkg.getAllCodePaths(); 9190 } catch (PackageParserException e) { 9191 // Ignored; we tried our best 9192 } 9193 } 9194 9195 cleanUp(); 9196 9197 if (!allCodePaths.isEmpty()) { 9198 if (instructionSets == null) { 9199 throw new IllegalStateException("instructionSet == null"); 9200 } 9201 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9202 for (String codePath : allCodePaths) { 9203 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9204 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9205 if (retCode < 0) { 9206 Slog.w(TAG, "Couldn't remove dex file for package: " 9207 + " at location " + codePath + ", retcode=" + retCode); 9208 // we don't consider this to be a failure of the core package deletion 9209 } 9210 } 9211 } 9212 } 9213 } 9214 9215 boolean doPostDeleteLI(boolean delete) { 9216 // XXX err, shouldn't we respect the delete flag? 9217 cleanUpResourcesLI(); 9218 return true; 9219 } 9220 } 9221 9222 private boolean isAsecExternal(String cid) { 9223 final String asecPath = PackageHelper.getSdFilesystem(cid); 9224 return !asecPath.startsWith(mAsecInternalPath); 9225 } 9226 9227 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 9228 PackageManagerException { 9229 if (copyRet < 0) { 9230 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 9231 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 9232 throw new PackageManagerException(copyRet, message); 9233 } 9234 } 9235 } 9236 9237 /** 9238 * Extract the MountService "container ID" from the full code path of an 9239 * .apk. 9240 */ 9241 static String cidFromCodePath(String fullCodePath) { 9242 int eidx = fullCodePath.lastIndexOf("/"); 9243 String subStr1 = fullCodePath.substring(0, eidx); 9244 int sidx = subStr1.lastIndexOf("/"); 9245 return subStr1.substring(sidx+1, eidx); 9246 } 9247 9248 /** 9249 * Logic to handle installation of ASEC applications, including copying and 9250 * renaming logic. 9251 */ 9252 class AsecInstallArgs extends InstallArgs { 9253 static final String RES_FILE_NAME = "pkg.apk"; 9254 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 9255 9256 String cid; 9257 String packagePath; 9258 String resourcePath; 9259 String legacyNativeLibraryDir; 9260 9261 /** New install */ 9262 AsecInstallArgs(InstallParams params) { 9263 super(params.origin, params.observer, params.installFlags, 9264 params.installerPackageName, params.getManifestDigest(), 9265 params.getUser(), null /* instruction sets */, 9266 params.packageAbiOverride); 9267 } 9268 9269 /** Existing install */ 9270 AsecInstallArgs(String fullCodePath, String[] instructionSets, 9271 boolean isExternal, boolean isForwardLocked) { 9272 super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0) 9273 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9274 instructionSets, null); 9275 // Hackily pretend we're still looking at a full code path 9276 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 9277 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 9278 } 9279 9280 // Extract cid from fullCodePath 9281 int eidx = fullCodePath.lastIndexOf("/"); 9282 String subStr1 = fullCodePath.substring(0, eidx); 9283 int sidx = subStr1.lastIndexOf("/"); 9284 cid = subStr1.substring(sidx+1, eidx); 9285 setMountPath(subStr1); 9286 } 9287 9288 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 9289 super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 9290 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9291 instructionSets, null); 9292 this.cid = cid; 9293 setMountPath(PackageHelper.getSdDir(cid)); 9294 } 9295 9296 void createCopyFile() { 9297 cid = mInstallerService.allocateExternalStageCidLegacy(); 9298 } 9299 9300 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9301 final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(), 9302 abiOverride); 9303 9304 final File target; 9305 if (isExternal()) { 9306 target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory(); 9307 } else { 9308 target = Environment.getDataDirectory(); 9309 } 9310 9311 final StorageManager storage = StorageManager.from(mContext); 9312 return (sizeBytes <= storage.getStorageBytesUntilLow(target)); 9313 } 9314 9315 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9316 if (origin.staged) { 9317 Slog.d(TAG, origin.cid + " already staged; skipping copy"); 9318 cid = origin.cid; 9319 setMountPath(PackageHelper.getSdDir(cid)); 9320 return PackageManager.INSTALL_SUCCEEDED; 9321 } 9322 9323 if (temp) { 9324 createCopyFile(); 9325 } else { 9326 /* 9327 * Pre-emptively destroy the container since it's destroyed if 9328 * copying fails due to it existing anyway. 9329 */ 9330 PackageHelper.destroySdDir(cid); 9331 } 9332 9333 final String newMountPath = imcs.copyPackageToContainer( 9334 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(), 9335 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 9336 9337 if (newMountPath != null) { 9338 setMountPath(newMountPath); 9339 return PackageManager.INSTALL_SUCCEEDED; 9340 } else { 9341 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9342 } 9343 } 9344 9345 @Override 9346 String getCodePath() { 9347 return packagePath; 9348 } 9349 9350 @Override 9351 String getResourcePath() { 9352 return resourcePath; 9353 } 9354 9355 @Override 9356 String getLegacyNativeLibraryPath() { 9357 return legacyNativeLibraryDir; 9358 } 9359 9360 int doPreInstall(int status) { 9361 if (status != PackageManager.INSTALL_SUCCEEDED) { 9362 // Destroy container 9363 PackageHelper.destroySdDir(cid); 9364 } else { 9365 boolean mounted = PackageHelper.isContainerMounted(cid); 9366 if (!mounted) { 9367 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 9368 Process.SYSTEM_UID); 9369 if (newMountPath != null) { 9370 setMountPath(newMountPath); 9371 } else { 9372 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9373 } 9374 } 9375 } 9376 return status; 9377 } 9378 9379 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9380 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 9381 String newMountPath = null; 9382 if (PackageHelper.isContainerMounted(cid)) { 9383 // Unmount the container 9384 if (!PackageHelper.unMountSdDir(cid)) { 9385 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9386 return false; 9387 } 9388 } 9389 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9390 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9391 " which might be stale. Will try to clean up."); 9392 // Clean up the stale container and proceed to recreate. 9393 if (!PackageHelper.destroySdDir(newCacheId)) { 9394 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9395 return false; 9396 } 9397 // Successfully cleaned up stale container. Try to rename again. 9398 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9399 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9400 + " inspite of cleaning it up."); 9401 return false; 9402 } 9403 } 9404 if (!PackageHelper.isContainerMounted(newCacheId)) { 9405 Slog.w(TAG, "Mounting container " + newCacheId); 9406 newMountPath = PackageHelper.mountSdDir(newCacheId, 9407 getEncryptKey(), Process.SYSTEM_UID); 9408 } else { 9409 newMountPath = PackageHelper.getSdDir(newCacheId); 9410 } 9411 if (newMountPath == null) { 9412 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9413 return false; 9414 } 9415 Log.i(TAG, "Succesfully renamed " + cid + 9416 " to " + newCacheId + 9417 " at new path: " + newMountPath); 9418 cid = newCacheId; 9419 9420 final File beforeCodeFile = new File(packagePath); 9421 setMountPath(newMountPath); 9422 final File afterCodeFile = new File(packagePath); 9423 9424 // Reflect the rename in scanned details 9425 pkg.codePath = afterCodeFile.getAbsolutePath(); 9426 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9427 pkg.baseCodePath); 9428 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9429 pkg.splitCodePaths); 9430 9431 // Reflect the rename in app info 9432 pkg.applicationInfo.setCodePath(pkg.codePath); 9433 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9434 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9435 pkg.applicationInfo.setResourcePath(pkg.codePath); 9436 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9437 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9438 9439 return true; 9440 } 9441 9442 private void setMountPath(String mountPath) { 9443 final File mountFile = new File(mountPath); 9444 9445 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 9446 if (monolithicFile.exists()) { 9447 packagePath = monolithicFile.getAbsolutePath(); 9448 if (isFwdLocked()) { 9449 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 9450 } else { 9451 resourcePath = packagePath; 9452 } 9453 } else { 9454 packagePath = mountFile.getAbsolutePath(); 9455 resourcePath = packagePath; 9456 } 9457 9458 legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath(); 9459 } 9460 9461 int doPostInstall(int status, int uid) { 9462 if (status != PackageManager.INSTALL_SUCCEEDED) { 9463 cleanUp(); 9464 } else { 9465 final int groupOwner; 9466 final String protectedFile; 9467 if (isFwdLocked()) { 9468 groupOwner = UserHandle.getSharedAppGid(uid); 9469 protectedFile = RES_FILE_NAME; 9470 } else { 9471 groupOwner = -1; 9472 protectedFile = null; 9473 } 9474 9475 if (uid < Process.FIRST_APPLICATION_UID 9476 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9477 Slog.e(TAG, "Failed to finalize " + cid); 9478 PackageHelper.destroySdDir(cid); 9479 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9480 } 9481 9482 boolean mounted = PackageHelper.isContainerMounted(cid); 9483 if (!mounted) { 9484 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9485 } 9486 } 9487 return status; 9488 } 9489 9490 private void cleanUp() { 9491 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9492 9493 // Destroy secure container 9494 PackageHelper.destroySdDir(cid); 9495 } 9496 9497 private List<String> getAllCodePaths() { 9498 final File codeFile = new File(getCodePath()); 9499 if (codeFile != null && codeFile.exists()) { 9500 try { 9501 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9502 return pkg.getAllCodePaths(); 9503 } catch (PackageParserException e) { 9504 // Ignored; we tried our best 9505 } 9506 } 9507 return Collections.EMPTY_LIST; 9508 } 9509 9510 void cleanUpResourcesLI() { 9511 // Enumerate all code paths before deleting 9512 cleanUpResourcesLI(getAllCodePaths()); 9513 } 9514 9515 private void cleanUpResourcesLI(List<String> allCodePaths) { 9516 cleanUp(); 9517 9518 if (!allCodePaths.isEmpty()) { 9519 if (instructionSets == null) { 9520 throw new IllegalStateException("instructionSet == null"); 9521 } 9522 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9523 for (String codePath : allCodePaths) { 9524 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9525 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9526 if (retCode < 0) { 9527 Slog.w(TAG, "Couldn't remove dex file for package: " 9528 + " at location " + codePath + ", retcode=" + retCode); 9529 // we don't consider this to be a failure of the core package deletion 9530 } 9531 } 9532 } 9533 } 9534 } 9535 9536 boolean matchContainer(String app) { 9537 if (cid.startsWith(app)) { 9538 return true; 9539 } 9540 return false; 9541 } 9542 9543 String getPackageName() { 9544 return getAsecPackageName(cid); 9545 } 9546 9547 boolean doPostDeleteLI(boolean delete) { 9548 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 9549 final List<String> allCodePaths = getAllCodePaths(); 9550 boolean mounted = PackageHelper.isContainerMounted(cid); 9551 if (mounted) { 9552 // Unmount first 9553 if (PackageHelper.unMountSdDir(cid)) { 9554 mounted = false; 9555 } 9556 } 9557 if (!mounted && delete) { 9558 cleanUpResourcesLI(allCodePaths); 9559 } 9560 return !mounted; 9561 } 9562 9563 @Override 9564 int doPreCopy() { 9565 if (isFwdLocked()) { 9566 if (!PackageHelper.fixSdPermissions(cid, 9567 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 9568 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9569 } 9570 } 9571 9572 return PackageManager.INSTALL_SUCCEEDED; 9573 } 9574 9575 @Override 9576 int doPostCopy(int uid) { 9577 if (isFwdLocked()) { 9578 if (uid < Process.FIRST_APPLICATION_UID 9579 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 9580 RES_FILE_NAME)) { 9581 Slog.e(TAG, "Failed to finalize " + cid); 9582 PackageHelper.destroySdDir(cid); 9583 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9584 } 9585 } 9586 9587 return PackageManager.INSTALL_SUCCEEDED; 9588 } 9589 } 9590 9591 static String getAsecPackageName(String packageCid) { 9592 int idx = packageCid.lastIndexOf("-"); 9593 if (idx == -1) { 9594 return packageCid; 9595 } 9596 return packageCid.substring(0, idx); 9597 } 9598 9599 // Utility method used to create code paths based on package name and available index. 9600 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 9601 String idxStr = ""; 9602 int idx = 1; 9603 // Fall back to default value of idx=1 if prefix is not 9604 // part of oldCodePath 9605 if (oldCodePath != null) { 9606 String subStr = oldCodePath; 9607 // Drop the suffix right away 9608 if (suffix != null && subStr.endsWith(suffix)) { 9609 subStr = subStr.substring(0, subStr.length() - suffix.length()); 9610 } 9611 // If oldCodePath already contains prefix find out the 9612 // ending index to either increment or decrement. 9613 int sidx = subStr.lastIndexOf(prefix); 9614 if (sidx != -1) { 9615 subStr = subStr.substring(sidx + prefix.length()); 9616 if (subStr != null) { 9617 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 9618 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 9619 } 9620 try { 9621 idx = Integer.parseInt(subStr); 9622 if (idx <= 1) { 9623 idx++; 9624 } else { 9625 idx--; 9626 } 9627 } catch(NumberFormatException e) { 9628 } 9629 } 9630 } 9631 } 9632 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 9633 return prefix + idxStr; 9634 } 9635 9636 private File getNextCodePath(String packageName) { 9637 int suffix = 1; 9638 File result; 9639 do { 9640 result = new File(mAppInstallDir, packageName + "-" + suffix); 9641 suffix++; 9642 } while (result.exists()); 9643 return result; 9644 } 9645 9646 // Utility method used to ignore ADD/REMOVE events 9647 // by directory observer. 9648 private static boolean ignoreCodePath(String fullPathStr) { 9649 String apkName = deriveCodePathName(fullPathStr); 9650 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 9651 if (idx != -1 && ((idx+1) < apkName.length())) { 9652 // Make sure the package ends with a numeral 9653 String version = apkName.substring(idx+1); 9654 try { 9655 Integer.parseInt(version); 9656 return true; 9657 } catch (NumberFormatException e) {} 9658 } 9659 return false; 9660 } 9661 9662 // Utility method that returns the relative package path with respect 9663 // to the installation directory. Like say for /data/data/com.test-1.apk 9664 // string com.test-1 is returned. 9665 static String deriveCodePathName(String codePath) { 9666 if (codePath == null) { 9667 return null; 9668 } 9669 final File codeFile = new File(codePath); 9670 final String name = codeFile.getName(); 9671 if (codeFile.isDirectory()) { 9672 return name; 9673 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 9674 final int lastDot = name.lastIndexOf('.'); 9675 return name.substring(0, lastDot); 9676 } else { 9677 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 9678 return null; 9679 } 9680 } 9681 9682 class PackageInstalledInfo { 9683 String name; 9684 int uid; 9685 // The set of users that originally had this package installed. 9686 int[] origUsers; 9687 // The set of users that now have this package installed. 9688 int[] newUsers; 9689 PackageParser.Package pkg; 9690 int returnCode; 9691 String returnMsg; 9692 PackageRemovedInfo removedInfo; 9693 9694 public void setError(int code, String msg) { 9695 returnCode = code; 9696 returnMsg = msg; 9697 Slog.w(TAG, msg); 9698 } 9699 9700 public void setError(String msg, PackageParserException e) { 9701 returnCode = e.error; 9702 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9703 Slog.w(TAG, msg, e); 9704 } 9705 9706 public void setError(String msg, PackageManagerException e) { 9707 returnCode = e.error; 9708 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9709 Slog.w(TAG, msg, e); 9710 } 9711 9712 // In some error cases we want to convey more info back to the observer 9713 String origPackage; 9714 String origPermission; 9715 } 9716 9717 /* 9718 * Install a non-existing package. 9719 */ 9720 private void installNewPackageLI(PackageParser.Package pkg, 9721 int parseFlags, int scanFlags, UserHandle user, 9722 String installerPackageName, PackageInstalledInfo res) { 9723 // Remember this for later, in case we need to rollback this install 9724 String pkgName = pkg.packageName; 9725 9726 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 9727 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 9728 synchronized(mPackages) { 9729 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 9730 // A package with the same name is already installed, though 9731 // it has been renamed to an older name. The package we 9732 // are trying to install should be installed as an update to 9733 // the existing one, but that has not been requested, so bail. 9734 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9735 + " without first uninstalling package running as " 9736 + mSettings.mRenamedPackages.get(pkgName)); 9737 return; 9738 } 9739 if (mPackages.containsKey(pkgName)) { 9740 // Don't allow installation over an existing package with the same name. 9741 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9742 + " without first uninstalling."); 9743 return; 9744 } 9745 } 9746 9747 try { 9748 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 9749 System.currentTimeMillis(), user); 9750 9751 updateSettingsLI(newPackage, installerPackageName, null, null, res); 9752 // delete the partially installed application. the data directory will have to be 9753 // restored if it was already existing 9754 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9755 // remove package from internal structures. Note that we want deletePackageX to 9756 // delete the package data and cache directories that it created in 9757 // scanPackageLocked, unless those directories existed before we even tried to 9758 // install. 9759 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 9760 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 9761 res.removedInfo, true); 9762 } 9763 9764 } catch (PackageManagerException e) { 9765 res.setError("Package couldn't be installed in " + pkg.codePath, e); 9766 } 9767 } 9768 9769 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 9770 // Upgrade keysets are being used. Determine if new package has a superset of the 9771 // required keys. 9772 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 9773 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9774 for (int i = 0; i < upgradeKeySets.length; i++) { 9775 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 9776 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 9777 return true; 9778 } 9779 } 9780 return false; 9781 } 9782 9783 private void replacePackageLI(PackageParser.Package pkg, 9784 int parseFlags, int scanFlags, UserHandle user, 9785 String installerPackageName, PackageInstalledInfo res) { 9786 PackageParser.Package oldPackage; 9787 String pkgName = pkg.packageName; 9788 int[] allUsers; 9789 boolean[] perUserInstalled; 9790 9791 // First find the old package info and check signatures 9792 synchronized(mPackages) { 9793 oldPackage = mPackages.get(pkgName); 9794 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 9795 PackageSetting ps = mSettings.mPackages.get(pkgName); 9796 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 9797 // default to original signature matching 9798 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 9799 != PackageManager.SIGNATURE_MATCH) { 9800 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9801 "New package has a different signature: " + pkgName); 9802 return; 9803 } 9804 } else { 9805 if(!checkUpgradeKeySetLP(ps, pkg)) { 9806 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9807 "New package not signed by keys specified by upgrade-keysets: " 9808 + pkgName); 9809 return; 9810 } 9811 } 9812 9813 // In case of rollback, remember per-user/profile install state 9814 allUsers = sUserManager.getUserIds(); 9815 perUserInstalled = new boolean[allUsers.length]; 9816 for (int i = 0; i < allUsers.length; i++) { 9817 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 9818 } 9819 } 9820 9821 boolean sysPkg = (isSystemApp(oldPackage)); 9822 if (sysPkg) { 9823 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 9824 user, allUsers, perUserInstalled, installerPackageName, res); 9825 } else { 9826 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 9827 user, allUsers, perUserInstalled, installerPackageName, res); 9828 } 9829 } 9830 9831 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 9832 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 9833 int[] allUsers, boolean[] perUserInstalled, 9834 String installerPackageName, PackageInstalledInfo res) { 9835 String pkgName = deletedPackage.packageName; 9836 boolean deletedPkg = true; 9837 boolean updatedSettings = false; 9838 9839 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 9840 + deletedPackage); 9841 long origUpdateTime; 9842 if (pkg.mExtras != null) { 9843 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 9844 } else { 9845 origUpdateTime = 0; 9846 } 9847 9848 // First delete the existing package while retaining the data directory 9849 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 9850 res.removedInfo, true)) { 9851 // If the existing package wasn't successfully deleted 9852 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 9853 deletedPkg = false; 9854 } else { 9855 // Successfully deleted the old package; proceed with replace. 9856 9857 // If deleted package lived in a container, give users a chance to 9858 // relinquish resources before killing. 9859 if (isForwardLocked(deletedPackage) || isExternal(deletedPackage)) { 9860 if (DEBUG_INSTALL) { 9861 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 9862 } 9863 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 9864 final ArrayList<String> pkgList = new ArrayList<String>(1); 9865 pkgList.add(deletedPackage.applicationInfo.packageName); 9866 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 9867 } 9868 9869 deleteCodeCacheDirsLI(pkgName); 9870 try { 9871 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 9872 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 9873 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 9874 updatedSettings = true; 9875 } catch (PackageManagerException e) { 9876 res.setError("Package couldn't be installed in " + pkg.codePath, e); 9877 } 9878 } 9879 9880 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9881 // remove package from internal structures. Note that we want deletePackageX to 9882 // delete the package data and cache directories that it created in 9883 // scanPackageLocked, unless those directories existed before we even tried to 9884 // install. 9885 if(updatedSettings) { 9886 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 9887 deletePackageLI( 9888 pkgName, null, true, allUsers, perUserInstalled, 9889 PackageManager.DELETE_KEEP_DATA, 9890 res.removedInfo, true); 9891 } 9892 // Since we failed to install the new package we need to restore the old 9893 // package that we deleted. 9894 if (deletedPkg) { 9895 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 9896 File restoreFile = new File(deletedPackage.codePath); 9897 // Parse old package 9898 boolean oldOnSd = isExternal(deletedPackage); 9899 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 9900 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) | 9901 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 9902 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 9903 try { 9904 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 9905 } catch (PackageManagerException e) { 9906 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 9907 + e.getMessage()); 9908 return; 9909 } 9910 // Restore of old package succeeded. Update permissions. 9911 // writer 9912 synchronized (mPackages) { 9913 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 9914 UPDATE_PERMISSIONS_ALL); 9915 // can downgrade to reader 9916 mSettings.writeLPr(); 9917 } 9918 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 9919 } 9920 } 9921 } 9922 9923 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 9924 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 9925 int[] allUsers, boolean[] perUserInstalled, 9926 String installerPackageName, PackageInstalledInfo res) { 9927 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 9928 + ", old=" + deletedPackage); 9929 boolean updatedSettings = false; 9930 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 9931 if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) { 9932 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 9933 } 9934 String packageName = deletedPackage.packageName; 9935 if (packageName == null) { 9936 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 9937 "Attempt to delete null packageName."); 9938 return; 9939 } 9940 PackageParser.Package oldPkg; 9941 PackageSetting oldPkgSetting; 9942 // reader 9943 synchronized (mPackages) { 9944 oldPkg = mPackages.get(packageName); 9945 oldPkgSetting = mSettings.mPackages.get(packageName); 9946 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 9947 (oldPkgSetting == null)) { 9948 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 9949 "Couldn't find package:" + packageName + " information"); 9950 return; 9951 } 9952 } 9953 9954 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 9955 9956 res.removedInfo.uid = oldPkg.applicationInfo.uid; 9957 res.removedInfo.removedPackage = packageName; 9958 // Remove existing system package 9959 removePackageLI(oldPkgSetting, true); 9960 // writer 9961 synchronized (mPackages) { 9962 if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) { 9963 // We didn't need to disable the .apk as a current system package, 9964 // which means we are replacing another update that is already 9965 // installed. We need to make sure to delete the older one's .apk. 9966 res.removedInfo.args = createInstallArgsForExisting(0, 9967 deletedPackage.applicationInfo.getCodePath(), 9968 deletedPackage.applicationInfo.getResourcePath(), 9969 deletedPackage.applicationInfo.nativeLibraryRootDir, 9970 getAppDexInstructionSets(deletedPackage.applicationInfo)); 9971 } else { 9972 res.removedInfo.args = null; 9973 } 9974 } 9975 9976 // Successfully disabled the old package. Now proceed with re-installation 9977 deleteCodeCacheDirsLI(packageName); 9978 9979 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 9980 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 9981 9982 PackageParser.Package newPackage = null; 9983 try { 9984 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 9985 if (newPackage.mExtras != null) { 9986 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 9987 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 9988 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 9989 9990 // is the update attempting to change shared user? that isn't going to work... 9991 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 9992 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 9993 "Forbidding shared user change from " + oldPkgSetting.sharedUser 9994 + " to " + newPkgSetting.sharedUser); 9995 updatedSettings = true; 9996 } 9997 } 9998 9999 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10000 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10001 updatedSettings = true; 10002 } 10003 10004 } catch (PackageManagerException e) { 10005 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10006 } 10007 10008 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10009 // Re installation failed. Restore old information 10010 // Remove new pkg information 10011 if (newPackage != null) { 10012 removeInstalledPackageLI(newPackage, true); 10013 } 10014 // Add back the old system package 10015 try { 10016 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 10017 } catch (PackageManagerException e) { 10018 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 10019 } 10020 // Restore the old system information in Settings 10021 synchronized(mPackages) { 10022 if (updatedSettings) { 10023 mSettings.enableSystemPackageLPw(packageName); 10024 mSettings.setInstallerPackageName(packageName, 10025 oldPkgSetting.installerPackageName); 10026 } 10027 mSettings.writeLPr(); 10028 } 10029 } 10030 } 10031 10032 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10033 int[] allUsers, boolean[] perUserInstalled, 10034 PackageInstalledInfo res) { 10035 String pkgName = newPackage.packageName; 10036 synchronized (mPackages) { 10037 //write settings. the installStatus will be incomplete at this stage. 10038 //note that the new package setting would have already been 10039 //added to mPackages. It hasn't been persisted yet. 10040 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10041 mSettings.writeLPr(); 10042 } 10043 10044 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10045 10046 synchronized (mPackages) { 10047 updatePermissionsLPw(newPackage.packageName, newPackage, 10048 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10049 ? UPDATE_PERMISSIONS_ALL : 0)); 10050 // For system-bundled packages, we assume that installing an upgraded version 10051 // of the package implies that the user actually wants to run that new code, 10052 // so we enable the package. 10053 if (isSystemApp(newPackage)) { 10054 // NB: implicit assumption that system package upgrades apply to all users 10055 if (DEBUG_INSTALL) { 10056 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10057 } 10058 PackageSetting ps = mSettings.mPackages.get(pkgName); 10059 if (ps != null) { 10060 if (res.origUsers != null) { 10061 for (int userHandle : res.origUsers) { 10062 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10063 userHandle, installerPackageName); 10064 } 10065 } 10066 // Also convey the prior install/uninstall state 10067 if (allUsers != null && perUserInstalled != null) { 10068 for (int i = 0; i < allUsers.length; i++) { 10069 if (DEBUG_INSTALL) { 10070 Slog.d(TAG, " user " + allUsers[i] 10071 + " => " + perUserInstalled[i]); 10072 } 10073 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10074 } 10075 // these install state changes will be persisted in the 10076 // upcoming call to mSettings.writeLPr(). 10077 } 10078 } 10079 } 10080 res.name = pkgName; 10081 res.uid = newPackage.applicationInfo.uid; 10082 res.pkg = newPackage; 10083 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10084 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10085 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10086 //to update install status 10087 mSettings.writeLPr(); 10088 } 10089 } 10090 10091 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 10092 final int installFlags = args.installFlags; 10093 String installerPackageName = args.installerPackageName; 10094 File tmpPackageFile = new File(args.getCodePath()); 10095 boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10096 boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0); 10097 boolean replace = false; 10098 final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE; 10099 // Result object to be returned 10100 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10101 10102 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10103 // Retrieve PackageSettings and parse package 10104 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10105 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10106 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 10107 PackageParser pp = new PackageParser(); 10108 pp.setSeparateProcesses(mSeparateProcesses); 10109 pp.setDisplayMetrics(mMetrics); 10110 10111 final PackageParser.Package pkg; 10112 try { 10113 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 10114 } catch (PackageParserException e) { 10115 res.setError("Failed parse during installPackageLI", e); 10116 return; 10117 } 10118 10119 // Mark that we have an install time CPU ABI override. 10120 pkg.cpuAbiOverride = args.abiOverride; 10121 10122 String pkgName = res.name = pkg.packageName; 10123 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 10124 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 10125 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 10126 return; 10127 } 10128 } 10129 10130 try { 10131 pp.collectCertificates(pkg, parseFlags); 10132 pp.collectManifestDigest(pkg); 10133 } catch (PackageParserException e) { 10134 res.setError("Failed collect during installPackageLI", e); 10135 return; 10136 } 10137 10138 /* If the installer passed in a manifest digest, compare it now. */ 10139 if (args.manifestDigest != null) { 10140 if (DEBUG_INSTALL) { 10141 final String parsedManifest = pkg.manifestDigest == null ? "null" 10142 : pkg.manifestDigest.toString(); 10143 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 10144 + parsedManifest); 10145 } 10146 10147 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 10148 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 10149 return; 10150 } 10151 } else if (DEBUG_INSTALL) { 10152 final String parsedManifest = pkg.manifestDigest == null 10153 ? "null" : pkg.manifestDigest.toString(); 10154 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 10155 } 10156 10157 // Get rid of all references to package scan path via parser. 10158 pp = null; 10159 String oldCodePath = null; 10160 boolean systemApp = false; 10161 synchronized (mPackages) { 10162 // Check whether the newly-scanned package wants to define an already-defined perm 10163 int N = pkg.permissions.size(); 10164 for (int i = N-1; i >= 0; i--) { 10165 PackageParser.Permission perm = pkg.permissions.get(i); 10166 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 10167 if (bp != null) { 10168 // If the defining package is signed with our cert, it's okay. This 10169 // also includes the "updating the same package" case, of course. 10170 // "updating same package" could also involve key-rotation. 10171 final boolean sigsOk; 10172 if (!bp.sourcePackage.equals(pkg.packageName) 10173 || !(bp.packageSetting instanceof PackageSetting) 10174 || !bp.packageSetting.keySetData.isUsingUpgradeKeySets() 10175 || ((PackageSetting) bp.packageSetting).sharedUser != null) { 10176 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 10177 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 10178 } else { 10179 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 10180 } 10181 if (!sigsOk) { 10182 // If the owning package is the system itself, we log but allow 10183 // install to proceed; we fail the install on all other permission 10184 // redefinitions. 10185 if (!bp.sourcePackage.equals("android")) { 10186 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 10187 + pkg.packageName + " attempting to redeclare permission " 10188 + perm.info.name + " already owned by " + bp.sourcePackage); 10189 res.origPermission = perm.info.name; 10190 res.origPackage = bp.sourcePackage; 10191 return; 10192 } else { 10193 Slog.w(TAG, "Package " + pkg.packageName 10194 + " attempting to redeclare system permission " 10195 + perm.info.name + "; ignoring new declaration"); 10196 pkg.permissions.remove(i); 10197 } 10198 } 10199 } 10200 } 10201 10202 // Check if installing already existing package 10203 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10204 String oldName = mSettings.mRenamedPackages.get(pkgName); 10205 if (pkg.mOriginalPackages != null 10206 && pkg.mOriginalPackages.contains(oldName) 10207 && mPackages.containsKey(oldName)) { 10208 // This package is derived from an original package, 10209 // and this device has been updating from that original 10210 // name. We must continue using the original name, so 10211 // rename the new package here. 10212 pkg.setPackageName(oldName); 10213 pkgName = pkg.packageName; 10214 replace = true; 10215 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 10216 + oldName + " pkgName=" + pkgName); 10217 } else if (mPackages.containsKey(pkgName)) { 10218 // This package, under its official name, already exists 10219 // on the device; we should replace it. 10220 replace = true; 10221 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 10222 } 10223 } 10224 PackageSetting ps = mSettings.mPackages.get(pkgName); 10225 if (ps != null) { 10226 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 10227 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 10228 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 10229 systemApp = (ps.pkg.applicationInfo.flags & 10230 ApplicationInfo.FLAG_SYSTEM) != 0; 10231 } 10232 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10233 } 10234 } 10235 10236 if (systemApp && onSd) { 10237 // Disable updates to system apps on sdcard 10238 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 10239 "Cannot install updates to system apps on sdcard"); 10240 return; 10241 } 10242 10243 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 10244 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 10245 return; 10246 } 10247 10248 if (replace) { 10249 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 10250 installerPackageName, res); 10251 } else { 10252 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 10253 args.user, installerPackageName, res); 10254 } 10255 synchronized (mPackages) { 10256 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10257 if (ps != null) { 10258 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10259 } 10260 } 10261 } 10262 10263 private static boolean isForwardLocked(PackageParser.Package pkg) { 10264 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10265 } 10266 10267 private static boolean isForwardLocked(ApplicationInfo info) { 10268 return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10269 } 10270 10271 private boolean isForwardLocked(PackageSetting ps) { 10272 return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10273 } 10274 10275 private static boolean isMultiArch(PackageSetting ps) { 10276 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10277 } 10278 10279 private static boolean isMultiArch(ApplicationInfo info) { 10280 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10281 } 10282 10283 private static boolean isExternal(PackageParser.Package pkg) { 10284 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10285 } 10286 10287 private static boolean isExternal(PackageSetting ps) { 10288 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10289 } 10290 10291 private static boolean isExternal(ApplicationInfo info) { 10292 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10293 } 10294 10295 private static boolean isSystemApp(PackageParser.Package pkg) { 10296 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10297 } 10298 10299 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 10300 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0; 10301 } 10302 10303 private static boolean isSystemApp(ApplicationInfo info) { 10304 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10305 } 10306 10307 private static boolean isSystemApp(PackageSetting ps) { 10308 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 10309 } 10310 10311 private static boolean isUpdatedSystemApp(PackageSetting ps) { 10312 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10313 } 10314 10315 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 10316 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10317 } 10318 10319 private static boolean isUpdatedSystemApp(ApplicationInfo info) { 10320 return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10321 } 10322 10323 private int packageFlagsToInstallFlags(PackageSetting ps) { 10324 int installFlags = 0; 10325 if (isExternal(ps)) { 10326 installFlags |= PackageManager.INSTALL_EXTERNAL; 10327 } 10328 if (isForwardLocked(ps)) { 10329 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 10330 } 10331 return installFlags; 10332 } 10333 10334 private void deleteTempPackageFiles() { 10335 final FilenameFilter filter = new FilenameFilter() { 10336 public boolean accept(File dir, String name) { 10337 return name.startsWith("vmdl") && name.endsWith(".tmp"); 10338 } 10339 }; 10340 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 10341 file.delete(); 10342 } 10343 } 10344 10345 @Override 10346 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 10347 int flags) { 10348 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 10349 flags); 10350 } 10351 10352 @Override 10353 public void deletePackage(final String packageName, 10354 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 10355 mContext.enforceCallingOrSelfPermission( 10356 android.Manifest.permission.DELETE_PACKAGES, null); 10357 final int uid = Binder.getCallingUid(); 10358 if (UserHandle.getUserId(uid) != userId) { 10359 mContext.enforceCallingPermission( 10360 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 10361 "deletePackage for user " + userId); 10362 } 10363 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 10364 try { 10365 observer.onPackageDeleted(packageName, 10366 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 10367 } catch (RemoteException re) { 10368 } 10369 return; 10370 } 10371 10372 boolean uninstallBlocked = false; 10373 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 10374 int[] users = sUserManager.getUserIds(); 10375 for (int i = 0; i < users.length; ++i) { 10376 if (getBlockUninstallForUser(packageName, users[i])) { 10377 uninstallBlocked = true; 10378 break; 10379 } 10380 } 10381 } else { 10382 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 10383 } 10384 if (uninstallBlocked) { 10385 try { 10386 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 10387 null); 10388 } catch (RemoteException re) { 10389 } 10390 return; 10391 } 10392 10393 if (DEBUG_REMOVE) { 10394 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 10395 } 10396 // Queue up an async operation since the package deletion may take a little while. 10397 mHandler.post(new Runnable() { 10398 public void run() { 10399 mHandler.removeCallbacks(this); 10400 final int returnCode = deletePackageX(packageName, userId, flags); 10401 if (observer != null) { 10402 try { 10403 observer.onPackageDeleted(packageName, returnCode, null); 10404 } catch (RemoteException e) { 10405 Log.i(TAG, "Observer no longer exists."); 10406 } //end catch 10407 } //end if 10408 } //end run 10409 }); 10410 } 10411 10412 private boolean isPackageDeviceAdmin(String packageName, int userId) { 10413 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 10414 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 10415 try { 10416 if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId) 10417 || dpm.isDeviceOwner(packageName))) { 10418 return true; 10419 } 10420 } catch (RemoteException e) { 10421 } 10422 return false; 10423 } 10424 10425 /** 10426 * This method is an internal method that could be get invoked either 10427 * to delete an installed package or to clean up a failed installation. 10428 * After deleting an installed package, a broadcast is sent to notify any 10429 * listeners that the package has been installed. For cleaning up a failed 10430 * installation, the broadcast is not necessary since the package's 10431 * installation wouldn't have sent the initial broadcast either 10432 * The key steps in deleting a package are 10433 * deleting the package information in internal structures like mPackages, 10434 * deleting the packages base directories through installd 10435 * updating mSettings to reflect current status 10436 * persisting settings for later use 10437 * sending a broadcast if necessary 10438 */ 10439 private int deletePackageX(String packageName, int userId, int flags) { 10440 final PackageRemovedInfo info = new PackageRemovedInfo(); 10441 final boolean res; 10442 10443 if (isPackageDeviceAdmin(packageName, userId)) { 10444 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 10445 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 10446 } 10447 10448 boolean removedForAllUsers = false; 10449 boolean systemUpdate = false; 10450 10451 // for the uninstall-updates case and restricted profiles, remember the per- 10452 // userhandle installed state 10453 int[] allUsers; 10454 boolean[] perUserInstalled; 10455 synchronized (mPackages) { 10456 PackageSetting ps = mSettings.mPackages.get(packageName); 10457 allUsers = sUserManager.getUserIds(); 10458 perUserInstalled = new boolean[allUsers.length]; 10459 for (int i = 0; i < allUsers.length; i++) { 10460 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10461 } 10462 } 10463 10464 synchronized (mInstallLock) { 10465 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 10466 res = deletePackageLI(packageName, 10467 (flags & PackageManager.DELETE_ALL_USERS) != 0 10468 ? UserHandle.ALL : new UserHandle(userId), 10469 true, allUsers, perUserInstalled, 10470 flags | REMOVE_CHATTY, info, true); 10471 systemUpdate = info.isRemovedPackageSystemUpdate; 10472 if (res && !systemUpdate && mPackages.get(packageName) == null) { 10473 removedForAllUsers = true; 10474 } 10475 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 10476 + " removedForAllUsers=" + removedForAllUsers); 10477 } 10478 10479 if (res) { 10480 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 10481 10482 // If the removed package was a system update, the old system package 10483 // was re-enabled; we need to broadcast this information 10484 if (systemUpdate) { 10485 Bundle extras = new Bundle(1); 10486 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 10487 ? info.removedAppId : info.uid); 10488 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10489 10490 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 10491 extras, null, null, null); 10492 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 10493 extras, null, null, null); 10494 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 10495 null, packageName, null, null); 10496 } 10497 } 10498 // Force a gc here. 10499 Runtime.getRuntime().gc(); 10500 // Delete the resources here after sending the broadcast to let 10501 // other processes clean up before deleting resources. 10502 if (info.args != null) { 10503 synchronized (mInstallLock) { 10504 info.args.doPostDeleteLI(true); 10505 } 10506 } 10507 10508 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10509 } 10510 10511 static class PackageRemovedInfo { 10512 String removedPackage; 10513 int uid = -1; 10514 int removedAppId = -1; 10515 int[] removedUsers = null; 10516 boolean isRemovedPackageSystemUpdate = false; 10517 // Clean up resources deleted packages. 10518 InstallArgs args = null; 10519 10520 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 10521 Bundle extras = new Bundle(1); 10522 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 10523 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 10524 if (replacing) { 10525 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10526 } 10527 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 10528 if (removedPackage != null) { 10529 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 10530 extras, null, null, removedUsers); 10531 if (fullRemove && !replacing) { 10532 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 10533 extras, null, null, removedUsers); 10534 } 10535 } 10536 if (removedAppId >= 0) { 10537 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 10538 removedUsers); 10539 } 10540 } 10541 } 10542 10543 /* 10544 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 10545 * flag is not set, the data directory is removed as well. 10546 * make sure this flag is set for partially installed apps. If not its meaningless to 10547 * delete a partially installed application. 10548 */ 10549 private void removePackageDataLI(PackageSetting ps, 10550 int[] allUserHandles, boolean[] perUserInstalled, 10551 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 10552 String packageName = ps.name; 10553 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 10554 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 10555 // Retrieve object to delete permissions for shared user later on 10556 final PackageSetting deletedPs; 10557 // reader 10558 synchronized (mPackages) { 10559 deletedPs = mSettings.mPackages.get(packageName); 10560 if (outInfo != null) { 10561 outInfo.removedPackage = packageName; 10562 outInfo.removedUsers = deletedPs != null 10563 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 10564 : null; 10565 } 10566 } 10567 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10568 removeDataDirsLI(packageName); 10569 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 10570 } 10571 // writer 10572 synchronized (mPackages) { 10573 if (deletedPs != null) { 10574 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10575 if (outInfo != null) { 10576 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 10577 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 10578 } 10579 if (deletedPs != null) { 10580 updatePermissionsLPw(deletedPs.name, null, 0); 10581 if (deletedPs.sharedUser != null) { 10582 // remove permissions associated with package 10583 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 10584 } 10585 } 10586 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 10587 } 10588 // make sure to preserve per-user disabled state if this removal was just 10589 // a downgrade of a system app to the factory package 10590 if (allUserHandles != null && perUserInstalled != null) { 10591 if (DEBUG_REMOVE) { 10592 Slog.d(TAG, "Propagating install state across downgrade"); 10593 } 10594 for (int i = 0; i < allUserHandles.length; i++) { 10595 if (DEBUG_REMOVE) { 10596 Slog.d(TAG, " user " + allUserHandles[i] 10597 + " => " + perUserInstalled[i]); 10598 } 10599 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10600 } 10601 } 10602 } 10603 // can downgrade to reader 10604 if (writeSettings) { 10605 // Save settings now 10606 mSettings.writeLPr(); 10607 } 10608 } 10609 if (outInfo != null) { 10610 // A user ID was deleted here. Go through all users and remove it 10611 // from KeyStore. 10612 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 10613 } 10614 } 10615 10616 static boolean locationIsPrivileged(File path) { 10617 try { 10618 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 10619 .getCanonicalPath(); 10620 return path.getCanonicalPath().startsWith(privilegedAppDir); 10621 } catch (IOException e) { 10622 Slog.e(TAG, "Unable to access code path " + path); 10623 } 10624 return false; 10625 } 10626 10627 /* 10628 * Tries to delete system package. 10629 */ 10630 private boolean deleteSystemPackageLI(PackageSetting newPs, 10631 int[] allUserHandles, boolean[] perUserInstalled, 10632 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 10633 final boolean applyUserRestrictions 10634 = (allUserHandles != null) && (perUserInstalled != null); 10635 PackageSetting disabledPs = null; 10636 // Confirm if the system package has been updated 10637 // An updated system app can be deleted. This will also have to restore 10638 // the system pkg from system partition 10639 // reader 10640 synchronized (mPackages) { 10641 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 10642 } 10643 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 10644 + " disabledPs=" + disabledPs); 10645 if (disabledPs == null) { 10646 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 10647 return false; 10648 } else if (DEBUG_REMOVE) { 10649 Slog.d(TAG, "Deleting system pkg from data partition"); 10650 } 10651 if (DEBUG_REMOVE) { 10652 if (applyUserRestrictions) { 10653 Slog.d(TAG, "Remembering install states:"); 10654 for (int i = 0; i < allUserHandles.length; i++) { 10655 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 10656 } 10657 } 10658 } 10659 // Delete the updated package 10660 outInfo.isRemovedPackageSystemUpdate = true; 10661 if (disabledPs.versionCode < newPs.versionCode) { 10662 // Delete data for downgrades 10663 flags &= ~PackageManager.DELETE_KEEP_DATA; 10664 } else { 10665 // Preserve data by setting flag 10666 flags |= PackageManager.DELETE_KEEP_DATA; 10667 } 10668 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 10669 allUserHandles, perUserInstalled, outInfo, writeSettings); 10670 if (!ret) { 10671 return false; 10672 } 10673 // writer 10674 synchronized (mPackages) { 10675 // Reinstate the old system package 10676 mSettings.enableSystemPackageLPw(newPs.name); 10677 // Remove any native libraries from the upgraded package. 10678 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 10679 } 10680 // Install the system package 10681 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 10682 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 10683 if (locationIsPrivileged(disabledPs.codePath)) { 10684 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10685 } 10686 10687 final PackageParser.Package newPkg; 10688 try { 10689 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 10690 } catch (PackageManagerException e) { 10691 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 10692 return false; 10693 } 10694 10695 // writer 10696 synchronized (mPackages) { 10697 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 10698 updatePermissionsLPw(newPkg.packageName, newPkg, 10699 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 10700 if (applyUserRestrictions) { 10701 if (DEBUG_REMOVE) { 10702 Slog.d(TAG, "Propagating install state across reinstall"); 10703 } 10704 for (int i = 0; i < allUserHandles.length; i++) { 10705 if (DEBUG_REMOVE) { 10706 Slog.d(TAG, " user " + allUserHandles[i] 10707 + " => " + perUserInstalled[i]); 10708 } 10709 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10710 } 10711 // Regardless of writeSettings we need to ensure that this restriction 10712 // state propagation is persisted 10713 mSettings.writeAllUsersPackageRestrictionsLPr(); 10714 } 10715 // can downgrade to reader here 10716 if (writeSettings) { 10717 mSettings.writeLPr(); 10718 } 10719 } 10720 return true; 10721 } 10722 10723 private boolean deleteInstalledPackageLI(PackageSetting ps, 10724 boolean deleteCodeAndResources, int flags, 10725 int[] allUserHandles, boolean[] perUserInstalled, 10726 PackageRemovedInfo outInfo, boolean writeSettings) { 10727 if (outInfo != null) { 10728 outInfo.uid = ps.appId; 10729 } 10730 10731 // Delete package data from internal structures and also remove data if flag is set 10732 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 10733 10734 // Delete application code and resources 10735 if (deleteCodeAndResources && (outInfo != null)) { 10736 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 10737 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 10738 getAppDexInstructionSets(ps)); 10739 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 10740 } 10741 return true; 10742 } 10743 10744 @Override 10745 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 10746 int userId) { 10747 mContext.enforceCallingOrSelfPermission( 10748 android.Manifest.permission.DELETE_PACKAGES, null); 10749 synchronized (mPackages) { 10750 PackageSetting ps = mSettings.mPackages.get(packageName); 10751 if (ps == null) { 10752 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 10753 return false; 10754 } 10755 if (!ps.getInstalled(userId)) { 10756 // Can't block uninstall for an app that is not installed or enabled. 10757 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 10758 return false; 10759 } 10760 ps.setBlockUninstall(blockUninstall, userId); 10761 mSettings.writePackageRestrictionsLPr(userId); 10762 } 10763 return true; 10764 } 10765 10766 @Override 10767 public boolean getBlockUninstallForUser(String packageName, int userId) { 10768 synchronized (mPackages) { 10769 PackageSetting ps = mSettings.mPackages.get(packageName); 10770 if (ps == null) { 10771 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 10772 return false; 10773 } 10774 return ps.getBlockUninstall(userId); 10775 } 10776 } 10777 10778 /* 10779 * This method handles package deletion in general 10780 */ 10781 private boolean deletePackageLI(String packageName, UserHandle user, 10782 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 10783 int flags, PackageRemovedInfo outInfo, 10784 boolean writeSettings) { 10785 if (packageName == null) { 10786 Slog.w(TAG, "Attempt to delete null packageName."); 10787 return false; 10788 } 10789 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 10790 PackageSetting ps; 10791 boolean dataOnly = false; 10792 int removeUser = -1; 10793 int appId = -1; 10794 synchronized (mPackages) { 10795 ps = mSettings.mPackages.get(packageName); 10796 if (ps == null) { 10797 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 10798 return false; 10799 } 10800 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 10801 && user.getIdentifier() != UserHandle.USER_ALL) { 10802 // The caller is asking that the package only be deleted for a single 10803 // user. To do this, we just mark its uninstalled state and delete 10804 // its data. If this is a system app, we only allow this to happen if 10805 // they have set the special DELETE_SYSTEM_APP which requests different 10806 // semantics than normal for uninstalling system apps. 10807 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 10808 ps.setUserState(user.getIdentifier(), 10809 COMPONENT_ENABLED_STATE_DEFAULT, 10810 false, //installed 10811 true, //stopped 10812 true, //notLaunched 10813 false, //hidden 10814 null, null, null, 10815 false // blockUninstall 10816 ); 10817 if (!isSystemApp(ps)) { 10818 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 10819 // Other user still have this package installed, so all 10820 // we need to do is clear this user's data and save that 10821 // it is uninstalled. 10822 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 10823 removeUser = user.getIdentifier(); 10824 appId = ps.appId; 10825 mSettings.writePackageRestrictionsLPr(removeUser); 10826 } else { 10827 // We need to set it back to 'installed' so the uninstall 10828 // broadcasts will be sent correctly. 10829 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 10830 ps.setInstalled(true, user.getIdentifier()); 10831 } 10832 } else { 10833 // This is a system app, so we assume that the 10834 // other users still have this package installed, so all 10835 // we need to do is clear this user's data and save that 10836 // it is uninstalled. 10837 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 10838 removeUser = user.getIdentifier(); 10839 appId = ps.appId; 10840 mSettings.writePackageRestrictionsLPr(removeUser); 10841 } 10842 } 10843 } 10844 10845 if (removeUser >= 0) { 10846 // From above, we determined that we are deleting this only 10847 // for a single user. Continue the work here. 10848 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 10849 if (outInfo != null) { 10850 outInfo.removedPackage = packageName; 10851 outInfo.removedAppId = appId; 10852 outInfo.removedUsers = new int[] {removeUser}; 10853 } 10854 mInstaller.clearUserData(packageName, removeUser); 10855 removeKeystoreDataIfNeeded(removeUser, appId); 10856 schedulePackageCleaning(packageName, removeUser, false); 10857 return true; 10858 } 10859 10860 if (dataOnly) { 10861 // Delete application data first 10862 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 10863 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 10864 return true; 10865 } 10866 10867 boolean ret = false; 10868 if (isSystemApp(ps)) { 10869 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 10870 // When an updated system application is deleted we delete the existing resources as well and 10871 // fall back to existing code in system partition 10872 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 10873 flags, outInfo, writeSettings); 10874 } else { 10875 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 10876 // Kill application pre-emptively especially for apps on sd. 10877 killApplication(packageName, ps.appId, "uninstall pkg"); 10878 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 10879 allUserHandles, perUserInstalled, 10880 outInfo, writeSettings); 10881 } 10882 10883 return ret; 10884 } 10885 10886 private final class ClearStorageConnection implements ServiceConnection { 10887 IMediaContainerService mContainerService; 10888 10889 @Override 10890 public void onServiceConnected(ComponentName name, IBinder service) { 10891 synchronized (this) { 10892 mContainerService = IMediaContainerService.Stub.asInterface(service); 10893 notifyAll(); 10894 } 10895 } 10896 10897 @Override 10898 public void onServiceDisconnected(ComponentName name) { 10899 } 10900 } 10901 10902 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 10903 final boolean mounted; 10904 if (Environment.isExternalStorageEmulated()) { 10905 mounted = true; 10906 } else { 10907 final String status = Environment.getExternalStorageState(); 10908 10909 mounted = status.equals(Environment.MEDIA_MOUNTED) 10910 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 10911 } 10912 10913 if (!mounted) { 10914 return; 10915 } 10916 10917 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 10918 int[] users; 10919 if (userId == UserHandle.USER_ALL) { 10920 users = sUserManager.getUserIds(); 10921 } else { 10922 users = new int[] { userId }; 10923 } 10924 final ClearStorageConnection conn = new ClearStorageConnection(); 10925 if (mContext.bindServiceAsUser( 10926 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 10927 try { 10928 for (int curUser : users) { 10929 long timeout = SystemClock.uptimeMillis() + 5000; 10930 synchronized (conn) { 10931 long now = SystemClock.uptimeMillis(); 10932 while (conn.mContainerService == null && now < timeout) { 10933 try { 10934 conn.wait(timeout - now); 10935 } catch (InterruptedException e) { 10936 } 10937 } 10938 } 10939 if (conn.mContainerService == null) { 10940 return; 10941 } 10942 10943 final UserEnvironment userEnv = new UserEnvironment(curUser); 10944 clearDirectory(conn.mContainerService, 10945 userEnv.buildExternalStorageAppCacheDirs(packageName)); 10946 if (allData) { 10947 clearDirectory(conn.mContainerService, 10948 userEnv.buildExternalStorageAppDataDirs(packageName)); 10949 clearDirectory(conn.mContainerService, 10950 userEnv.buildExternalStorageAppMediaDirs(packageName)); 10951 } 10952 } 10953 } finally { 10954 mContext.unbindService(conn); 10955 } 10956 } 10957 } 10958 10959 @Override 10960 public void clearApplicationUserData(final String packageName, 10961 final IPackageDataObserver observer, final int userId) { 10962 mContext.enforceCallingOrSelfPermission( 10963 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 10964 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data"); 10965 // Queue up an async operation since the package deletion may take a little while. 10966 mHandler.post(new Runnable() { 10967 public void run() { 10968 mHandler.removeCallbacks(this); 10969 final boolean succeeded; 10970 synchronized (mInstallLock) { 10971 succeeded = clearApplicationUserDataLI(packageName, userId); 10972 } 10973 clearExternalStorageDataSync(packageName, userId, true); 10974 if (succeeded) { 10975 // invoke DeviceStorageMonitor's update method to clear any notifications 10976 DeviceStorageMonitorInternal 10977 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 10978 if (dsm != null) { 10979 dsm.checkMemory(); 10980 } 10981 } 10982 if(observer != null) { 10983 try { 10984 observer.onRemoveCompleted(packageName, succeeded); 10985 } catch (RemoteException e) { 10986 Log.i(TAG, "Observer no longer exists."); 10987 } 10988 } //end if observer 10989 } //end run 10990 }); 10991 } 10992 10993 private boolean clearApplicationUserDataLI(String packageName, int userId) { 10994 if (packageName == null) { 10995 Slog.w(TAG, "Attempt to delete null packageName."); 10996 return false; 10997 } 10998 PackageParser.Package pkg; 10999 boolean dataOnly = false; 11000 final int appId; 11001 synchronized (mPackages) { 11002 pkg = mPackages.get(packageName); 11003 if (pkg == null) { 11004 dataOnly = true; 11005 PackageSetting ps = mSettings.mPackages.get(packageName); 11006 if ((ps == null) || (ps.pkg == null)) { 11007 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11008 return false; 11009 } 11010 pkg = ps.pkg; 11011 } 11012 if (!dataOnly) { 11013 // need to check this only for fully installed applications 11014 if (pkg == null) { 11015 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11016 return false; 11017 } 11018 final ApplicationInfo applicationInfo = pkg.applicationInfo; 11019 if (applicationInfo == null) { 11020 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11021 return false; 11022 } 11023 } 11024 if (pkg != null && pkg.applicationInfo != null) { 11025 appId = pkg.applicationInfo.uid; 11026 } else { 11027 appId = -1; 11028 } 11029 } 11030 int retCode = mInstaller.clearUserData(packageName, userId); 11031 if (retCode < 0) { 11032 Slog.w(TAG, "Couldn't remove cache files for package: " 11033 + packageName); 11034 return false; 11035 } 11036 removeKeystoreDataIfNeeded(userId, appId); 11037 11038 // Create a native library symlink only if we have native libraries 11039 // and if the native libraries are 32 bit libraries. We do not provide 11040 // this symlink for 64 bit libraries. 11041 if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null && 11042 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 11043 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 11044 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 11045 Slog.w(TAG, "Failed linking native library dir"); 11046 return false; 11047 } 11048 } 11049 11050 return true; 11051 } 11052 11053 /** 11054 * Remove entries from the keystore daemon. Will only remove it if the 11055 * {@code appId} is valid. 11056 */ 11057 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 11058 if (appId < 0) { 11059 return; 11060 } 11061 11062 final KeyStore keyStore = KeyStore.getInstance(); 11063 if (keyStore != null) { 11064 if (userId == UserHandle.USER_ALL) { 11065 for (final int individual : sUserManager.getUserIds()) { 11066 keyStore.clearUid(UserHandle.getUid(individual, appId)); 11067 } 11068 } else { 11069 keyStore.clearUid(UserHandle.getUid(userId, appId)); 11070 } 11071 } else { 11072 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 11073 } 11074 } 11075 11076 @Override 11077 public void deleteApplicationCacheFiles(final String packageName, 11078 final IPackageDataObserver observer) { 11079 mContext.enforceCallingOrSelfPermission( 11080 android.Manifest.permission.DELETE_CACHE_FILES, null); 11081 // Queue up an async operation since the package deletion may take a little while. 11082 final int userId = UserHandle.getCallingUserId(); 11083 mHandler.post(new Runnable() { 11084 public void run() { 11085 mHandler.removeCallbacks(this); 11086 final boolean succeded; 11087 synchronized (mInstallLock) { 11088 succeded = deleteApplicationCacheFilesLI(packageName, userId); 11089 } 11090 clearExternalStorageDataSync(packageName, userId, false); 11091 if(observer != null) { 11092 try { 11093 observer.onRemoveCompleted(packageName, succeded); 11094 } catch (RemoteException e) { 11095 Log.i(TAG, "Observer no longer exists."); 11096 } 11097 } //end if observer 11098 } //end run 11099 }); 11100 } 11101 11102 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 11103 if (packageName == null) { 11104 Slog.w(TAG, "Attempt to delete null packageName."); 11105 return false; 11106 } 11107 PackageParser.Package p; 11108 synchronized (mPackages) { 11109 p = mPackages.get(packageName); 11110 } 11111 if (p == null) { 11112 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11113 return false; 11114 } 11115 final ApplicationInfo applicationInfo = p.applicationInfo; 11116 if (applicationInfo == null) { 11117 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11118 return false; 11119 } 11120 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 11121 if (retCode < 0) { 11122 Slog.w(TAG, "Couldn't remove cache files for package: " 11123 + packageName + " u" + userId); 11124 return false; 11125 } 11126 return true; 11127 } 11128 11129 @Override 11130 public void getPackageSizeInfo(final String packageName, int userHandle, 11131 final IPackageStatsObserver observer) { 11132 mContext.enforceCallingOrSelfPermission( 11133 android.Manifest.permission.GET_PACKAGE_SIZE, null); 11134 if (packageName == null) { 11135 throw new IllegalArgumentException("Attempt to get size of null packageName"); 11136 } 11137 11138 PackageStats stats = new PackageStats(packageName, userHandle); 11139 11140 /* 11141 * Queue up an async operation since the package measurement may take a 11142 * little while. 11143 */ 11144 Message msg = mHandler.obtainMessage(INIT_COPY); 11145 msg.obj = new MeasureParams(stats, observer); 11146 mHandler.sendMessage(msg); 11147 } 11148 11149 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 11150 PackageStats pStats) { 11151 if (packageName == null) { 11152 Slog.w(TAG, "Attempt to get size of null packageName."); 11153 return false; 11154 } 11155 PackageParser.Package p; 11156 boolean dataOnly = false; 11157 String libDirRoot = null; 11158 String asecPath = null; 11159 PackageSetting ps = null; 11160 synchronized (mPackages) { 11161 p = mPackages.get(packageName); 11162 ps = mSettings.mPackages.get(packageName); 11163 if(p == null) { 11164 dataOnly = true; 11165 if((ps == null) || (ps.pkg == null)) { 11166 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11167 return false; 11168 } 11169 p = ps.pkg; 11170 } 11171 if (ps != null) { 11172 libDirRoot = ps.legacyNativeLibraryPathString; 11173 } 11174 if (p != null && (isExternal(p) || isForwardLocked(p))) { 11175 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 11176 if (secureContainerId != null) { 11177 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 11178 } 11179 } 11180 } 11181 String publicSrcDir = null; 11182 if(!dataOnly) { 11183 final ApplicationInfo applicationInfo = p.applicationInfo; 11184 if (applicationInfo == null) { 11185 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11186 return false; 11187 } 11188 if (isForwardLocked(p)) { 11189 publicSrcDir = applicationInfo.getBaseResourcePath(); 11190 } 11191 } 11192 // TODO: extend to measure size of split APKs 11193 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 11194 // not just the first level. 11195 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 11196 // just the primary. 11197 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 11198 int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot, 11199 publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 11200 if (res < 0) { 11201 return false; 11202 } 11203 11204 // Fix-up for forward-locked applications in ASEC containers. 11205 if (!isExternal(p)) { 11206 pStats.codeSize += pStats.externalCodeSize; 11207 pStats.externalCodeSize = 0L; 11208 } 11209 11210 return true; 11211 } 11212 11213 11214 @Override 11215 public void addPackageToPreferred(String packageName) { 11216 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 11217 } 11218 11219 @Override 11220 public void removePackageFromPreferred(String packageName) { 11221 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 11222 } 11223 11224 @Override 11225 public List<PackageInfo> getPreferredPackages(int flags) { 11226 return new ArrayList<PackageInfo>(); 11227 } 11228 11229 private int getUidTargetSdkVersionLockedLPr(int uid) { 11230 Object obj = mSettings.getUserIdLPr(uid); 11231 if (obj instanceof SharedUserSetting) { 11232 final SharedUserSetting sus = (SharedUserSetting) obj; 11233 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 11234 final Iterator<PackageSetting> it = sus.packages.iterator(); 11235 while (it.hasNext()) { 11236 final PackageSetting ps = it.next(); 11237 if (ps.pkg != null) { 11238 int v = ps.pkg.applicationInfo.targetSdkVersion; 11239 if (v < vers) vers = v; 11240 } 11241 } 11242 return vers; 11243 } else if (obj instanceof PackageSetting) { 11244 final PackageSetting ps = (PackageSetting) obj; 11245 if (ps.pkg != null) { 11246 return ps.pkg.applicationInfo.targetSdkVersion; 11247 } 11248 } 11249 return Build.VERSION_CODES.CUR_DEVELOPMENT; 11250 } 11251 11252 @Override 11253 public void addPreferredActivity(IntentFilter filter, int match, 11254 ComponentName[] set, ComponentName activity, int userId) { 11255 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11256 "Adding preferred"); 11257 } 11258 11259 private void addPreferredActivityInternal(IntentFilter filter, int match, 11260 ComponentName[] set, ComponentName activity, boolean always, int userId, 11261 String opname) { 11262 // writer 11263 int callingUid = Binder.getCallingUid(); 11264 enforceCrossUserPermission(callingUid, userId, true, "add preferred activity"); 11265 if (filter.countActions() == 0) { 11266 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11267 return; 11268 } 11269 synchronized (mPackages) { 11270 if (mContext.checkCallingOrSelfPermission( 11271 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11272 != PackageManager.PERMISSION_GRANTED) { 11273 if (getUidTargetSdkVersionLockedLPr(callingUid) 11274 < Build.VERSION_CODES.FROYO) { 11275 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 11276 + callingUid); 11277 return; 11278 } 11279 mContext.enforceCallingOrSelfPermission( 11280 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11281 } 11282 11283 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 11284 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 11285 + userId + ":"); 11286 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11287 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 11288 mSettings.writePackageRestrictionsLPr(userId); 11289 } 11290 } 11291 11292 @Override 11293 public void replacePreferredActivity(IntentFilter filter, int match, 11294 ComponentName[] set, ComponentName activity, int userId) { 11295 if (filter.countActions() != 1) { 11296 throw new IllegalArgumentException( 11297 "replacePreferredActivity expects filter to have only 1 action."); 11298 } 11299 if (filter.countDataAuthorities() != 0 11300 || filter.countDataPaths() != 0 11301 || filter.countDataSchemes() > 1 11302 || filter.countDataTypes() != 0) { 11303 throw new IllegalArgumentException( 11304 "replacePreferredActivity expects filter to have no data authorities, " + 11305 "paths, or types; and at most one scheme."); 11306 } 11307 11308 final int callingUid = Binder.getCallingUid(); 11309 enforceCrossUserPermission(callingUid, userId, true, "replace preferred activity"); 11310 synchronized (mPackages) { 11311 if (mContext.checkCallingOrSelfPermission( 11312 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11313 != PackageManager.PERMISSION_GRANTED) { 11314 if (getUidTargetSdkVersionLockedLPr(callingUid) 11315 < Build.VERSION_CODES.FROYO) { 11316 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 11317 + Binder.getCallingUid()); 11318 return; 11319 } 11320 mContext.enforceCallingOrSelfPermission( 11321 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11322 } 11323 11324 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11325 if (pir != null) { 11326 // Get all of the existing entries that exactly match this filter. 11327 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 11328 if (existing != null && existing.size() == 1) { 11329 PreferredActivity cur = existing.get(0); 11330 if (DEBUG_PREFERRED) { 11331 Slog.i(TAG, "Checking replace of preferred:"); 11332 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11333 if (!cur.mPref.mAlways) { 11334 Slog.i(TAG, " -- CUR; not mAlways!"); 11335 } else { 11336 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 11337 Slog.i(TAG, " -- CUR: mSet=" 11338 + Arrays.toString(cur.mPref.mSetComponents)); 11339 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 11340 Slog.i(TAG, " -- NEW: mMatch=" 11341 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 11342 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 11343 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 11344 } 11345 } 11346 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 11347 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 11348 && cur.mPref.sameSet(set)) { 11349 if (DEBUG_PREFERRED) { 11350 Slog.i(TAG, "Replacing with same preferred activity " 11351 + cur.mPref.mShortComponent + " for user " 11352 + userId + ":"); 11353 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11354 } else { 11355 Slog.i(TAG, "Replacing with same preferred activity " 11356 + cur.mPref.mShortComponent + " for user " 11357 + userId); 11358 } 11359 return; 11360 } 11361 } 11362 11363 if (existing != null) { 11364 if (DEBUG_PREFERRED) { 11365 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 11366 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11367 } 11368 for (int i = 0; i < existing.size(); i++) { 11369 PreferredActivity pa = existing.get(i); 11370 if (DEBUG_PREFERRED) { 11371 Slog.i(TAG, "Removing existing preferred activity " 11372 + pa.mPref.mComponent + ":"); 11373 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 11374 } 11375 pir.removeFilter(pa); 11376 } 11377 } 11378 } 11379 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11380 "Replacing preferred"); 11381 } 11382 } 11383 11384 @Override 11385 public void clearPackagePreferredActivities(String packageName) { 11386 final int uid = Binder.getCallingUid(); 11387 // writer 11388 synchronized (mPackages) { 11389 PackageParser.Package pkg = mPackages.get(packageName); 11390 if (pkg == null || pkg.applicationInfo.uid != uid) { 11391 if (mContext.checkCallingOrSelfPermission( 11392 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11393 != PackageManager.PERMISSION_GRANTED) { 11394 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11395 < Build.VERSION_CODES.FROYO) { 11396 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 11397 + Binder.getCallingUid()); 11398 return; 11399 } 11400 mContext.enforceCallingOrSelfPermission( 11401 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11402 } 11403 } 11404 11405 int user = UserHandle.getCallingUserId(); 11406 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 11407 mSettings.writePackageRestrictionsLPr(user); 11408 scheduleWriteSettingsLocked(); 11409 } 11410 } 11411 } 11412 11413 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 11414 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 11415 ArrayList<PreferredActivity> removed = null; 11416 boolean changed = false; 11417 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11418 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 11419 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11420 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 11421 continue; 11422 } 11423 Iterator<PreferredActivity> it = pir.filterIterator(); 11424 while (it.hasNext()) { 11425 PreferredActivity pa = it.next(); 11426 // Mark entry for removal only if it matches the package name 11427 // and the entry is of type "always". 11428 if (packageName == null || 11429 (pa.mPref.mComponent.getPackageName().equals(packageName) 11430 && pa.mPref.mAlways)) { 11431 if (removed == null) { 11432 removed = new ArrayList<PreferredActivity>(); 11433 } 11434 removed.add(pa); 11435 } 11436 } 11437 if (removed != null) { 11438 for (int j=0; j<removed.size(); j++) { 11439 PreferredActivity pa = removed.get(j); 11440 pir.removeFilter(pa); 11441 } 11442 changed = true; 11443 } 11444 } 11445 return changed; 11446 } 11447 11448 @Override 11449 public void resetPreferredActivities(int userId) { 11450 mContext.enforceCallingOrSelfPermission( 11451 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11452 // writer 11453 synchronized (mPackages) { 11454 int user = UserHandle.getCallingUserId(); 11455 clearPackagePreferredActivitiesLPw(null, user); 11456 mSettings.readDefaultPreferredAppsLPw(this, user); 11457 mSettings.writePackageRestrictionsLPr(user); 11458 scheduleWriteSettingsLocked(); 11459 } 11460 } 11461 11462 @Override 11463 public int getPreferredActivities(List<IntentFilter> outFilters, 11464 List<ComponentName> outActivities, String packageName) { 11465 11466 int num = 0; 11467 final int userId = UserHandle.getCallingUserId(); 11468 // reader 11469 synchronized (mPackages) { 11470 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11471 if (pir != null) { 11472 final Iterator<PreferredActivity> it = pir.filterIterator(); 11473 while (it.hasNext()) { 11474 final PreferredActivity pa = it.next(); 11475 if (packageName == null 11476 || (pa.mPref.mComponent.getPackageName().equals(packageName) 11477 && pa.mPref.mAlways)) { 11478 if (outFilters != null) { 11479 outFilters.add(new IntentFilter(pa)); 11480 } 11481 if (outActivities != null) { 11482 outActivities.add(pa.mPref.mComponent); 11483 } 11484 } 11485 } 11486 } 11487 } 11488 11489 return num; 11490 } 11491 11492 @Override 11493 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 11494 int userId) { 11495 int callingUid = Binder.getCallingUid(); 11496 if (callingUid != Process.SYSTEM_UID) { 11497 throw new SecurityException( 11498 "addPersistentPreferredActivity can only be run by the system"); 11499 } 11500 if (filter.countActions() == 0) { 11501 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11502 return; 11503 } 11504 synchronized (mPackages) { 11505 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 11506 " :"); 11507 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11508 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 11509 new PersistentPreferredActivity(filter, activity)); 11510 mSettings.writePackageRestrictionsLPr(userId); 11511 } 11512 } 11513 11514 @Override 11515 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 11516 int callingUid = Binder.getCallingUid(); 11517 if (callingUid != Process.SYSTEM_UID) { 11518 throw new SecurityException( 11519 "clearPackagePersistentPreferredActivities can only be run by the system"); 11520 } 11521 ArrayList<PersistentPreferredActivity> removed = null; 11522 boolean changed = false; 11523 synchronized (mPackages) { 11524 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 11525 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 11526 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 11527 .valueAt(i); 11528 if (userId != thisUserId) { 11529 continue; 11530 } 11531 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 11532 while (it.hasNext()) { 11533 PersistentPreferredActivity ppa = it.next(); 11534 // Mark entry for removal only if it matches the package name. 11535 if (ppa.mComponent.getPackageName().equals(packageName)) { 11536 if (removed == null) { 11537 removed = new ArrayList<PersistentPreferredActivity>(); 11538 } 11539 removed.add(ppa); 11540 } 11541 } 11542 if (removed != null) { 11543 for (int j=0; j<removed.size(); j++) { 11544 PersistentPreferredActivity ppa = removed.get(j); 11545 ppir.removeFilter(ppa); 11546 } 11547 changed = true; 11548 } 11549 } 11550 11551 if (changed) { 11552 mSettings.writePackageRestrictionsLPr(userId); 11553 } 11554 } 11555 } 11556 11557 @Override 11558 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 11559 int ownerUserId, int sourceUserId, int targetUserId, int flags) { 11560 mContext.enforceCallingOrSelfPermission( 11561 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11562 int callingUid = Binder.getCallingUid(); 11563 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11564 if (intentFilter.countActions() == 0) { 11565 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 11566 return; 11567 } 11568 synchronized (mPackages) { 11569 CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter, 11570 ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags); 11571 mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter); 11572 mSettings.writePackageRestrictionsLPr(sourceUserId); 11573 } 11574 } 11575 11576 @Override 11577 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage, 11578 int ownerUserId) { 11579 mContext.enforceCallingOrSelfPermission( 11580 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11581 int callingUid = Binder.getCallingUid(); 11582 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11583 int callingUserId = UserHandle.getUserId(callingUid); 11584 synchronized (mPackages) { 11585 CrossProfileIntentResolver resolver = 11586 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11587 HashSet<CrossProfileIntentFilter> set = 11588 new HashSet<CrossProfileIntentFilter>(resolver.filterSet()); 11589 for (CrossProfileIntentFilter filter : set) { 11590 if (filter.getOwnerPackage().equals(ownerPackage) 11591 && filter.getOwnerUserId() == callingUserId) { 11592 resolver.removeFilter(filter); 11593 } 11594 } 11595 mSettings.writePackageRestrictionsLPr(sourceUserId); 11596 } 11597 } 11598 11599 // Enforcing that callingUid is owning pkg on userId 11600 private void enforceOwnerRights(String pkg, int userId, int callingUid) { 11601 // The system owns everything. 11602 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 11603 return; 11604 } 11605 int callingUserId = UserHandle.getUserId(callingUid); 11606 if (callingUserId != userId) { 11607 throw new SecurityException("calling uid " + callingUid 11608 + " pretends to own " + pkg + " on user " + userId + " but belongs to user " 11609 + callingUserId); 11610 } 11611 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 11612 if (pi == null) { 11613 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 11614 + callingUserId); 11615 } 11616 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 11617 throw new SecurityException("Calling uid " + callingUid 11618 + " does not own package " + pkg); 11619 } 11620 } 11621 11622 @Override 11623 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 11624 Intent intent = new Intent(Intent.ACTION_MAIN); 11625 intent.addCategory(Intent.CATEGORY_HOME); 11626 11627 final int callingUserId = UserHandle.getCallingUserId(); 11628 List<ResolveInfo> list = queryIntentActivities(intent, null, 11629 PackageManager.GET_META_DATA, callingUserId); 11630 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 11631 true, false, false, callingUserId); 11632 11633 allHomeCandidates.clear(); 11634 if (list != null) { 11635 for (ResolveInfo ri : list) { 11636 allHomeCandidates.add(ri); 11637 } 11638 } 11639 return (preferred == null || preferred.activityInfo == null) 11640 ? null 11641 : new ComponentName(preferred.activityInfo.packageName, 11642 preferred.activityInfo.name); 11643 } 11644 11645 @Override 11646 public void setApplicationEnabledSetting(String appPackageName, 11647 int newState, int flags, int userId, String callingPackage) { 11648 if (!sUserManager.exists(userId)) return; 11649 if (callingPackage == null) { 11650 callingPackage = Integer.toString(Binder.getCallingUid()); 11651 } 11652 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 11653 } 11654 11655 @Override 11656 public void setComponentEnabledSetting(ComponentName componentName, 11657 int newState, int flags, int userId) { 11658 if (!sUserManager.exists(userId)) return; 11659 setEnabledSetting(componentName.getPackageName(), 11660 componentName.getClassName(), newState, flags, userId, null); 11661 } 11662 11663 private void setEnabledSetting(final String packageName, String className, int newState, 11664 final int flags, int userId, String callingPackage) { 11665 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 11666 || newState == COMPONENT_ENABLED_STATE_ENABLED 11667 || newState == COMPONENT_ENABLED_STATE_DISABLED 11668 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 11669 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 11670 throw new IllegalArgumentException("Invalid new component state: " 11671 + newState); 11672 } 11673 PackageSetting pkgSetting; 11674 final int uid = Binder.getCallingUid(); 11675 final int permission = mContext.checkCallingOrSelfPermission( 11676 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11677 enforceCrossUserPermission(uid, userId, false, "set enabled"); 11678 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11679 boolean sendNow = false; 11680 boolean isApp = (className == null); 11681 String componentName = isApp ? packageName : className; 11682 int packageUid = -1; 11683 ArrayList<String> components; 11684 11685 // writer 11686 synchronized (mPackages) { 11687 pkgSetting = mSettings.mPackages.get(packageName); 11688 if (pkgSetting == null) { 11689 if (className == null) { 11690 throw new IllegalArgumentException( 11691 "Unknown package: " + packageName); 11692 } 11693 throw new IllegalArgumentException( 11694 "Unknown component: " + packageName 11695 + "/" + className); 11696 } 11697 // Allow root and verify that userId is not being specified by a different user 11698 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 11699 throw new SecurityException( 11700 "Permission Denial: attempt to change component state from pid=" 11701 + Binder.getCallingPid() 11702 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 11703 } 11704 if (className == null) { 11705 // We're dealing with an application/package level state change 11706 if (pkgSetting.getEnabled(userId) == newState) { 11707 // Nothing to do 11708 return; 11709 } 11710 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 11711 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 11712 // Don't care about who enables an app. 11713 callingPackage = null; 11714 } 11715 pkgSetting.setEnabled(newState, userId, callingPackage); 11716 // pkgSetting.pkg.mSetEnabled = newState; 11717 } else { 11718 // We're dealing with a component level state change 11719 // First, verify that this is a valid class name. 11720 PackageParser.Package pkg = pkgSetting.pkg; 11721 if (pkg == null || !pkg.hasComponentClassName(className)) { 11722 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 11723 throw new IllegalArgumentException("Component class " + className 11724 + " does not exist in " + packageName); 11725 } else { 11726 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 11727 + className + " does not exist in " + packageName); 11728 } 11729 } 11730 switch (newState) { 11731 case COMPONENT_ENABLED_STATE_ENABLED: 11732 if (!pkgSetting.enableComponentLPw(className, userId)) { 11733 return; 11734 } 11735 break; 11736 case COMPONENT_ENABLED_STATE_DISABLED: 11737 if (!pkgSetting.disableComponentLPw(className, userId)) { 11738 return; 11739 } 11740 break; 11741 case COMPONENT_ENABLED_STATE_DEFAULT: 11742 if (!pkgSetting.restoreComponentLPw(className, userId)) { 11743 return; 11744 } 11745 break; 11746 default: 11747 Slog.e(TAG, "Invalid new component state: " + newState); 11748 return; 11749 } 11750 } 11751 mSettings.writePackageRestrictionsLPr(userId); 11752 components = mPendingBroadcasts.get(userId, packageName); 11753 final boolean newPackage = components == null; 11754 if (newPackage) { 11755 components = new ArrayList<String>(); 11756 } 11757 if (!components.contains(componentName)) { 11758 components.add(componentName); 11759 } 11760 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 11761 sendNow = true; 11762 // Purge entry from pending broadcast list if another one exists already 11763 // since we are sending one right away. 11764 mPendingBroadcasts.remove(userId, packageName); 11765 } else { 11766 if (newPackage) { 11767 mPendingBroadcasts.put(userId, packageName, components); 11768 } 11769 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 11770 // Schedule a message 11771 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 11772 } 11773 } 11774 } 11775 11776 long callingId = Binder.clearCallingIdentity(); 11777 try { 11778 if (sendNow) { 11779 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 11780 sendPackageChangedBroadcast(packageName, 11781 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 11782 } 11783 } finally { 11784 Binder.restoreCallingIdentity(callingId); 11785 } 11786 } 11787 11788 private void sendPackageChangedBroadcast(String packageName, 11789 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 11790 if (DEBUG_INSTALL) 11791 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 11792 + componentNames); 11793 Bundle extras = new Bundle(4); 11794 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 11795 String nameList[] = new String[componentNames.size()]; 11796 componentNames.toArray(nameList); 11797 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 11798 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 11799 extras.putInt(Intent.EXTRA_UID, packageUid); 11800 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 11801 new int[] {UserHandle.getUserId(packageUid)}); 11802 } 11803 11804 @Override 11805 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 11806 if (!sUserManager.exists(userId)) return; 11807 final int uid = Binder.getCallingUid(); 11808 final int permission = mContext.checkCallingOrSelfPermission( 11809 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11810 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11811 enforceCrossUserPermission(uid, userId, true, "stop package"); 11812 // writer 11813 synchronized (mPackages) { 11814 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 11815 uid, userId)) { 11816 scheduleWritePackageRestrictionsLocked(userId); 11817 } 11818 } 11819 } 11820 11821 @Override 11822 public String getInstallerPackageName(String packageName) { 11823 // reader 11824 synchronized (mPackages) { 11825 return mSettings.getInstallerPackageNameLPr(packageName); 11826 } 11827 } 11828 11829 @Override 11830 public int getApplicationEnabledSetting(String packageName, int userId) { 11831 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11832 int uid = Binder.getCallingUid(); 11833 enforceCrossUserPermission(uid, userId, false, "get enabled"); 11834 // reader 11835 synchronized (mPackages) { 11836 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 11837 } 11838 } 11839 11840 @Override 11841 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 11842 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11843 int uid = Binder.getCallingUid(); 11844 enforceCrossUserPermission(uid, userId, false, "get component enabled"); 11845 // reader 11846 synchronized (mPackages) { 11847 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 11848 } 11849 } 11850 11851 @Override 11852 public void enterSafeMode() { 11853 enforceSystemOrRoot("Only the system can request entering safe mode"); 11854 11855 if (!mSystemReady) { 11856 mSafeMode = true; 11857 } 11858 } 11859 11860 @Override 11861 public void systemReady() { 11862 mSystemReady = true; 11863 11864 // Read the compatibilty setting when the system is ready. 11865 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 11866 mContext.getContentResolver(), 11867 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 11868 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 11869 if (DEBUG_SETTINGS) { 11870 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 11871 } 11872 11873 synchronized (mPackages) { 11874 // Verify that all of the preferred activity components actually 11875 // exist. It is possible for applications to be updated and at 11876 // that point remove a previously declared activity component that 11877 // had been set as a preferred activity. We try to clean this up 11878 // the next time we encounter that preferred activity, but it is 11879 // possible for the user flow to never be able to return to that 11880 // situation so here we do a sanity check to make sure we haven't 11881 // left any junk around. 11882 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 11883 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11884 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11885 removed.clear(); 11886 for (PreferredActivity pa : pir.filterSet()) { 11887 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 11888 removed.add(pa); 11889 } 11890 } 11891 if (removed.size() > 0) { 11892 for (int r=0; r<removed.size(); r++) { 11893 PreferredActivity pa = removed.get(r); 11894 Slog.w(TAG, "Removing dangling preferred activity: " 11895 + pa.mPref.mComponent); 11896 pir.removeFilter(pa); 11897 } 11898 mSettings.writePackageRestrictionsLPr( 11899 mSettings.mPreferredActivities.keyAt(i)); 11900 } 11901 } 11902 } 11903 sUserManager.systemReady(); 11904 11905 // Kick off any messages waiting for system ready 11906 if (mPostSystemReadyMessages != null) { 11907 for (Message msg : mPostSystemReadyMessages) { 11908 msg.sendToTarget(); 11909 } 11910 mPostSystemReadyMessages = null; 11911 } 11912 } 11913 11914 @Override 11915 public boolean isSafeMode() { 11916 return mSafeMode; 11917 } 11918 11919 @Override 11920 public boolean hasSystemUidErrors() { 11921 return mHasSystemUidErrors; 11922 } 11923 11924 static String arrayToString(int[] array) { 11925 StringBuffer buf = new StringBuffer(128); 11926 buf.append('['); 11927 if (array != null) { 11928 for (int i=0; i<array.length; i++) { 11929 if (i > 0) buf.append(", "); 11930 buf.append(array[i]); 11931 } 11932 } 11933 buf.append(']'); 11934 return buf.toString(); 11935 } 11936 11937 static class DumpState { 11938 public static final int DUMP_LIBS = 1 << 0; 11939 public static final int DUMP_FEATURES = 1 << 1; 11940 public static final int DUMP_RESOLVERS = 1 << 2; 11941 public static final int DUMP_PERMISSIONS = 1 << 3; 11942 public static final int DUMP_PACKAGES = 1 << 4; 11943 public static final int DUMP_SHARED_USERS = 1 << 5; 11944 public static final int DUMP_MESSAGES = 1 << 6; 11945 public static final int DUMP_PROVIDERS = 1 << 7; 11946 public static final int DUMP_VERIFIERS = 1 << 8; 11947 public static final int DUMP_PREFERRED = 1 << 9; 11948 public static final int DUMP_PREFERRED_XML = 1 << 10; 11949 public static final int DUMP_KEYSETS = 1 << 11; 11950 public static final int DUMP_VERSION = 1 << 12; 11951 public static final int DUMP_INSTALLS = 1 << 13; 11952 11953 public static final int OPTION_SHOW_FILTERS = 1 << 0; 11954 11955 private int mTypes; 11956 11957 private int mOptions; 11958 11959 private boolean mTitlePrinted; 11960 11961 private SharedUserSetting mSharedUser; 11962 11963 public boolean isDumping(int type) { 11964 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 11965 return true; 11966 } 11967 11968 return (mTypes & type) != 0; 11969 } 11970 11971 public void setDump(int type) { 11972 mTypes |= type; 11973 } 11974 11975 public boolean isOptionEnabled(int option) { 11976 return (mOptions & option) != 0; 11977 } 11978 11979 public void setOptionEnabled(int option) { 11980 mOptions |= option; 11981 } 11982 11983 public boolean onTitlePrinted() { 11984 final boolean printed = mTitlePrinted; 11985 mTitlePrinted = true; 11986 return printed; 11987 } 11988 11989 public boolean getTitlePrinted() { 11990 return mTitlePrinted; 11991 } 11992 11993 public void setTitlePrinted(boolean enabled) { 11994 mTitlePrinted = enabled; 11995 } 11996 11997 public SharedUserSetting getSharedUser() { 11998 return mSharedUser; 11999 } 12000 12001 public void setSharedUser(SharedUserSetting user) { 12002 mSharedUser = user; 12003 } 12004 } 12005 12006 @Override 12007 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 12008 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 12009 != PackageManager.PERMISSION_GRANTED) { 12010 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 12011 + Binder.getCallingPid() 12012 + ", uid=" + Binder.getCallingUid() 12013 + " without permission " 12014 + android.Manifest.permission.DUMP); 12015 return; 12016 } 12017 12018 DumpState dumpState = new DumpState(); 12019 boolean fullPreferred = false; 12020 boolean checkin = false; 12021 12022 String packageName = null; 12023 12024 int opti = 0; 12025 while (opti < args.length) { 12026 String opt = args[opti]; 12027 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 12028 break; 12029 } 12030 opti++; 12031 if ("-a".equals(opt)) { 12032 // Right now we only know how to print all. 12033 } else if ("-h".equals(opt)) { 12034 pw.println("Package manager dump options:"); 12035 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 12036 pw.println(" --checkin: dump for a checkin"); 12037 pw.println(" -f: print details of intent filters"); 12038 pw.println(" -h: print this help"); 12039 pw.println(" cmd may be one of:"); 12040 pw.println(" l[ibraries]: list known shared libraries"); 12041 pw.println(" f[ibraries]: list device features"); 12042 pw.println(" k[eysets]: print known keysets"); 12043 pw.println(" r[esolvers]: dump intent resolvers"); 12044 pw.println(" perm[issions]: dump permissions"); 12045 pw.println(" pref[erred]: print preferred package settings"); 12046 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 12047 pw.println(" prov[iders]: dump content providers"); 12048 pw.println(" p[ackages]: dump installed packages"); 12049 pw.println(" s[hared-users]: dump shared user IDs"); 12050 pw.println(" m[essages]: print collected runtime messages"); 12051 pw.println(" v[erifiers]: print package verifier info"); 12052 pw.println(" version: print database version info"); 12053 pw.println(" write: write current settings now"); 12054 pw.println(" <package.name>: info about given package"); 12055 pw.println(" installs: details about install sessions"); 12056 return; 12057 } else if ("--checkin".equals(opt)) { 12058 checkin = true; 12059 } else if ("-f".equals(opt)) { 12060 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12061 } else { 12062 pw.println("Unknown argument: " + opt + "; use -h for help"); 12063 } 12064 } 12065 12066 // Is the caller requesting to dump a particular piece of data? 12067 if (opti < args.length) { 12068 String cmd = args[opti]; 12069 opti++; 12070 // Is this a package name? 12071 if ("android".equals(cmd) || cmd.contains(".")) { 12072 packageName = cmd; 12073 // When dumping a single package, we always dump all of its 12074 // filter information since the amount of data will be reasonable. 12075 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12076 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 12077 dumpState.setDump(DumpState.DUMP_LIBS); 12078 } else if ("f".equals(cmd) || "features".equals(cmd)) { 12079 dumpState.setDump(DumpState.DUMP_FEATURES); 12080 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 12081 dumpState.setDump(DumpState.DUMP_RESOLVERS); 12082 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 12083 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 12084 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 12085 dumpState.setDump(DumpState.DUMP_PREFERRED); 12086 } else if ("preferred-xml".equals(cmd)) { 12087 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 12088 if (opti < args.length && "--full".equals(args[opti])) { 12089 fullPreferred = true; 12090 opti++; 12091 } 12092 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 12093 dumpState.setDump(DumpState.DUMP_PACKAGES); 12094 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 12095 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 12096 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 12097 dumpState.setDump(DumpState.DUMP_PROVIDERS); 12098 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 12099 dumpState.setDump(DumpState.DUMP_MESSAGES); 12100 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 12101 dumpState.setDump(DumpState.DUMP_VERIFIERS); 12102 } else if ("version".equals(cmd)) { 12103 dumpState.setDump(DumpState.DUMP_VERSION); 12104 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 12105 dumpState.setDump(DumpState.DUMP_KEYSETS); 12106 } else if ("write".equals(cmd)) { 12107 synchronized (mPackages) { 12108 mSettings.writeLPr(); 12109 pw.println("Settings written."); 12110 return; 12111 } 12112 } else if ("installs".equals(cmd)) { 12113 dumpState.setDump(DumpState.DUMP_INSTALLS); 12114 } 12115 } 12116 12117 if (checkin) { 12118 pw.println("vers,1"); 12119 } 12120 12121 // reader 12122 synchronized (mPackages) { 12123 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 12124 if (!checkin) { 12125 if (dumpState.onTitlePrinted()) 12126 pw.println(); 12127 pw.println("Database versions:"); 12128 pw.print(" SDK Version:"); 12129 pw.print(" internal="); 12130 pw.print(mSettings.mInternalSdkPlatform); 12131 pw.print(" external="); 12132 pw.println(mSettings.mExternalSdkPlatform); 12133 pw.print(" DB Version:"); 12134 pw.print(" internal="); 12135 pw.print(mSettings.mInternalDatabaseVersion); 12136 pw.print(" external="); 12137 pw.println(mSettings.mExternalDatabaseVersion); 12138 } 12139 } 12140 12141 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 12142 if (!checkin) { 12143 if (dumpState.onTitlePrinted()) 12144 pw.println(); 12145 pw.println("Verifiers:"); 12146 pw.print(" Required: "); 12147 pw.print(mRequiredVerifierPackage); 12148 pw.print(" (uid="); 12149 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 12150 pw.println(")"); 12151 } else if (mRequiredVerifierPackage != null) { 12152 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 12153 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 12154 } 12155 } 12156 12157 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 12158 boolean printedHeader = false; 12159 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 12160 while (it.hasNext()) { 12161 String name = it.next(); 12162 SharedLibraryEntry ent = mSharedLibraries.get(name); 12163 if (!checkin) { 12164 if (!printedHeader) { 12165 if (dumpState.onTitlePrinted()) 12166 pw.println(); 12167 pw.println("Libraries:"); 12168 printedHeader = true; 12169 } 12170 pw.print(" "); 12171 } else { 12172 pw.print("lib,"); 12173 } 12174 pw.print(name); 12175 if (!checkin) { 12176 pw.print(" -> "); 12177 } 12178 if (ent.path != null) { 12179 if (!checkin) { 12180 pw.print("(jar) "); 12181 pw.print(ent.path); 12182 } else { 12183 pw.print(",jar,"); 12184 pw.print(ent.path); 12185 } 12186 } else { 12187 if (!checkin) { 12188 pw.print("(apk) "); 12189 pw.print(ent.apk); 12190 } else { 12191 pw.print(",apk,"); 12192 pw.print(ent.apk); 12193 } 12194 } 12195 pw.println(); 12196 } 12197 } 12198 12199 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 12200 if (dumpState.onTitlePrinted()) 12201 pw.println(); 12202 if (!checkin) { 12203 pw.println("Features:"); 12204 } 12205 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 12206 while (it.hasNext()) { 12207 String name = it.next(); 12208 if (!checkin) { 12209 pw.print(" "); 12210 } else { 12211 pw.print("feat,"); 12212 } 12213 pw.println(name); 12214 } 12215 } 12216 12217 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 12218 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 12219 : "Activity Resolver Table:", " ", packageName, 12220 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12221 dumpState.setTitlePrinted(true); 12222 } 12223 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 12224 : "Receiver Resolver Table:", " ", packageName, 12225 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12226 dumpState.setTitlePrinted(true); 12227 } 12228 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 12229 : "Service Resolver Table:", " ", packageName, 12230 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12231 dumpState.setTitlePrinted(true); 12232 } 12233 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 12234 : "Provider Resolver Table:", " ", packageName, 12235 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12236 dumpState.setTitlePrinted(true); 12237 } 12238 } 12239 12240 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 12241 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12242 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12243 int user = mSettings.mPreferredActivities.keyAt(i); 12244 if (pir.dump(pw, 12245 dumpState.getTitlePrinted() 12246 ? "\nPreferred Activities User " + user + ":" 12247 : "Preferred Activities User " + user + ":", " ", 12248 packageName, true)) { 12249 dumpState.setTitlePrinted(true); 12250 } 12251 } 12252 } 12253 12254 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 12255 pw.flush(); 12256 FileOutputStream fout = new FileOutputStream(fd); 12257 BufferedOutputStream str = new BufferedOutputStream(fout); 12258 XmlSerializer serializer = new FastXmlSerializer(); 12259 try { 12260 serializer.setOutput(str, "utf-8"); 12261 serializer.startDocument(null, true); 12262 serializer.setFeature( 12263 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 12264 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 12265 serializer.endDocument(); 12266 serializer.flush(); 12267 } catch (IllegalArgumentException e) { 12268 pw.println("Failed writing: " + e); 12269 } catch (IllegalStateException e) { 12270 pw.println("Failed writing: " + e); 12271 } catch (IOException e) { 12272 pw.println("Failed writing: " + e); 12273 } 12274 } 12275 12276 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 12277 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 12278 if (packageName == null) { 12279 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 12280 if (iperm == 0) { 12281 if (dumpState.onTitlePrinted()) 12282 pw.println(); 12283 pw.println("AppOp Permissions:"); 12284 } 12285 pw.print(" AppOp Permission "); 12286 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 12287 pw.println(":"); 12288 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 12289 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 12290 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 12291 } 12292 } 12293 } 12294 } 12295 12296 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 12297 boolean printedSomething = false; 12298 for (PackageParser.Provider p : mProviders.mProviders.values()) { 12299 if (packageName != null && !packageName.equals(p.info.packageName)) { 12300 continue; 12301 } 12302 if (!printedSomething) { 12303 if (dumpState.onTitlePrinted()) 12304 pw.println(); 12305 pw.println("Registered ContentProviders:"); 12306 printedSomething = true; 12307 } 12308 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 12309 pw.print(" "); pw.println(p.toString()); 12310 } 12311 printedSomething = false; 12312 for (Map.Entry<String, PackageParser.Provider> entry : 12313 mProvidersByAuthority.entrySet()) { 12314 PackageParser.Provider p = entry.getValue(); 12315 if (packageName != null && !packageName.equals(p.info.packageName)) { 12316 continue; 12317 } 12318 if (!printedSomething) { 12319 if (dumpState.onTitlePrinted()) 12320 pw.println(); 12321 pw.println("ContentProvider Authorities:"); 12322 printedSomething = true; 12323 } 12324 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 12325 pw.print(" "); pw.println(p.toString()); 12326 if (p.info != null && p.info.applicationInfo != null) { 12327 final String appInfo = p.info.applicationInfo.toString(); 12328 pw.print(" applicationInfo="); pw.println(appInfo); 12329 } 12330 } 12331 } 12332 12333 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 12334 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 12335 } 12336 12337 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 12338 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 12339 } 12340 12341 if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 12342 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState); 12343 } 12344 12345 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS)) { 12346 if (dumpState.onTitlePrinted()) pw.println(); 12347 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 12348 } 12349 12350 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 12351 if (dumpState.onTitlePrinted()) pw.println(); 12352 mSettings.dumpReadMessagesLPr(pw, dumpState); 12353 12354 pw.println(); 12355 pw.println("Package warning messages:"); 12356 final File fname = getSettingsProblemFile(); 12357 FileInputStream in = null; 12358 try { 12359 in = new FileInputStream(fname); 12360 final int avail = in.available(); 12361 final byte[] data = new byte[avail]; 12362 in.read(data); 12363 pw.print(new String(data)); 12364 } catch (FileNotFoundException e) { 12365 } catch (IOException e) { 12366 } finally { 12367 if (in != null) { 12368 try { 12369 in.close(); 12370 } catch (IOException e) { 12371 } 12372 } 12373 } 12374 } 12375 } 12376 } 12377 12378 // ------- apps on sdcard specific code ------- 12379 static final boolean DEBUG_SD_INSTALL = false; 12380 12381 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 12382 12383 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 12384 12385 private boolean mMediaMounted = false; 12386 12387 static String getEncryptKey() { 12388 try { 12389 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 12390 SD_ENCRYPTION_KEYSTORE_NAME); 12391 if (sdEncKey == null) { 12392 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 12393 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 12394 if (sdEncKey == null) { 12395 Slog.e(TAG, "Failed to create encryption keys"); 12396 return null; 12397 } 12398 } 12399 return sdEncKey; 12400 } catch (NoSuchAlgorithmException nsae) { 12401 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 12402 return null; 12403 } catch (IOException ioe) { 12404 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 12405 return null; 12406 } 12407 } 12408 12409 /* 12410 * Update media status on PackageManager. 12411 */ 12412 @Override 12413 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 12414 int callingUid = Binder.getCallingUid(); 12415 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 12416 throw new SecurityException("Media status can only be updated by the system"); 12417 } 12418 // reader; this apparently protects mMediaMounted, but should probably 12419 // be a different lock in that case. 12420 synchronized (mPackages) { 12421 Log.i(TAG, "Updating external media status from " 12422 + (mMediaMounted ? "mounted" : "unmounted") + " to " 12423 + (mediaStatus ? "mounted" : "unmounted")); 12424 if (DEBUG_SD_INSTALL) 12425 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 12426 + ", mMediaMounted=" + mMediaMounted); 12427 if (mediaStatus == mMediaMounted) { 12428 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 12429 : 0, -1); 12430 mHandler.sendMessage(msg); 12431 return; 12432 } 12433 mMediaMounted = mediaStatus; 12434 } 12435 // Queue up an async operation since the package installation may take a 12436 // little while. 12437 mHandler.post(new Runnable() { 12438 public void run() { 12439 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 12440 } 12441 }); 12442 } 12443 12444 /** 12445 * Called by MountService when the initial ASECs to scan are available. 12446 * Should block until all the ASEC containers are finished being scanned. 12447 */ 12448 public void scanAvailableAsecs() { 12449 updateExternalMediaStatusInner(true, false, false); 12450 if (mShouldRestoreconData) { 12451 SELinuxMMAC.setRestoreconDone(); 12452 mShouldRestoreconData = false; 12453 } 12454 } 12455 12456 /* 12457 * Collect information of applications on external media, map them against 12458 * existing containers and update information based on current mount status. 12459 * Please note that we always have to report status if reportStatus has been 12460 * set to true especially when unloading packages. 12461 */ 12462 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 12463 boolean externalStorage) { 12464 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 12465 int[] uidArr = EmptyArray.INT; 12466 12467 final String[] list = PackageHelper.getSecureContainerList(); 12468 if (ArrayUtils.isEmpty(list)) { 12469 Log.i(TAG, "No secure containers found"); 12470 } else { 12471 // Process list of secure containers and categorize them 12472 // as active or stale based on their package internal state. 12473 12474 // reader 12475 synchronized (mPackages) { 12476 for (String cid : list) { 12477 // Leave stages untouched for now; installer service owns them 12478 if (PackageInstallerService.isStageName(cid)) continue; 12479 12480 if (DEBUG_SD_INSTALL) 12481 Log.i(TAG, "Processing container " + cid); 12482 String pkgName = getAsecPackageName(cid); 12483 if (pkgName == null) { 12484 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 12485 continue; 12486 } 12487 if (DEBUG_SD_INSTALL) 12488 Log.i(TAG, "Looking for pkg : " + pkgName); 12489 12490 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12491 if (ps == null) { 12492 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 12493 continue; 12494 } 12495 12496 /* 12497 * Skip packages that are not external if we're unmounting 12498 * external storage. 12499 */ 12500 if (externalStorage && !isMounted && !isExternal(ps)) { 12501 continue; 12502 } 12503 12504 final AsecInstallArgs args = new AsecInstallArgs(cid, 12505 getAppDexInstructionSets(ps), isForwardLocked(ps)); 12506 // The package status is changed only if the code path 12507 // matches between settings and the container id. 12508 if (ps.codePathString != null 12509 && ps.codePathString.startsWith(args.getCodePath())) { 12510 if (DEBUG_SD_INSTALL) { 12511 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 12512 + " at code path: " + ps.codePathString); 12513 } 12514 12515 // We do have a valid package installed on sdcard 12516 processCids.put(args, ps.codePathString); 12517 final int uid = ps.appId; 12518 if (uid != -1) { 12519 uidArr = ArrayUtils.appendInt(uidArr, uid); 12520 } 12521 } else { 12522 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 12523 + ps.codePathString); 12524 } 12525 } 12526 } 12527 12528 Arrays.sort(uidArr); 12529 } 12530 12531 // Process packages with valid entries. 12532 if (isMounted) { 12533 if (DEBUG_SD_INSTALL) 12534 Log.i(TAG, "Loading packages"); 12535 loadMediaPackages(processCids, uidArr); 12536 startCleaningPackages(); 12537 mInstallerService.onSecureContainersAvailable(); 12538 } else { 12539 if (DEBUG_SD_INSTALL) 12540 Log.i(TAG, "Unloading packages"); 12541 unloadMediaPackages(processCids, uidArr, reportStatus); 12542 } 12543 } 12544 12545 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 12546 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 12547 int size = pkgList.size(); 12548 if (size > 0) { 12549 // Send broadcasts here 12550 Bundle extras = new Bundle(); 12551 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 12552 .toArray(new String[size])); 12553 if (uidArr != null) { 12554 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 12555 } 12556 if (replacing) { 12557 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 12558 } 12559 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 12560 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 12561 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 12562 } 12563 } 12564 12565 /* 12566 * Look at potentially valid container ids from processCids If package 12567 * information doesn't match the one on record or package scanning fails, 12568 * the cid is added to list of removeCids. We currently don't delete stale 12569 * containers. 12570 */ 12571 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 12572 ArrayList<String> pkgList = new ArrayList<String>(); 12573 Set<AsecInstallArgs> keys = processCids.keySet(); 12574 12575 for (AsecInstallArgs args : keys) { 12576 String codePath = processCids.get(args); 12577 if (DEBUG_SD_INSTALL) 12578 Log.i(TAG, "Loading container : " + args.cid); 12579 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12580 try { 12581 // Make sure there are no container errors first. 12582 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 12583 Slog.e(TAG, "Failed to mount cid : " + args.cid 12584 + " when installing from sdcard"); 12585 continue; 12586 } 12587 // Check code path here. 12588 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 12589 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 12590 + " does not match one in settings " + codePath); 12591 continue; 12592 } 12593 // Parse package 12594 int parseFlags = mDefParseFlags; 12595 if (args.isExternal()) { 12596 parseFlags |= PackageParser.PARSE_ON_SDCARD; 12597 } 12598 if (args.isFwdLocked()) { 12599 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 12600 } 12601 12602 synchronized (mInstallLock) { 12603 PackageParser.Package pkg = null; 12604 try { 12605 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 12606 } catch (PackageManagerException e) { 12607 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 12608 } 12609 // Scan the package 12610 if (pkg != null) { 12611 /* 12612 * TODO why is the lock being held? doPostInstall is 12613 * called in other places without the lock. This needs 12614 * to be straightened out. 12615 */ 12616 // writer 12617 synchronized (mPackages) { 12618 retCode = PackageManager.INSTALL_SUCCEEDED; 12619 pkgList.add(pkg.packageName); 12620 // Post process args 12621 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 12622 pkg.applicationInfo.uid); 12623 } 12624 } else { 12625 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 12626 } 12627 } 12628 12629 } finally { 12630 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 12631 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 12632 } 12633 } 12634 } 12635 // writer 12636 synchronized (mPackages) { 12637 // If the platform SDK has changed since the last time we booted, 12638 // we need to re-grant app permission to catch any new ones that 12639 // appear. This is really a hack, and means that apps can in some 12640 // cases get permissions that the user didn't initially explicitly 12641 // allow... it would be nice to have some better way to handle 12642 // this situation. 12643 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 12644 if (regrantPermissions) 12645 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 12646 + mSdkVersion + "; regranting permissions for external storage"); 12647 mSettings.mExternalSdkPlatform = mSdkVersion; 12648 12649 // Make sure group IDs have been assigned, and any permission 12650 // changes in other apps are accounted for 12651 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 12652 | (regrantPermissions 12653 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 12654 : 0)); 12655 12656 mSettings.updateExternalDatabaseVersion(); 12657 12658 // can downgrade to reader 12659 // Persist settings 12660 mSettings.writeLPr(); 12661 } 12662 // Send a broadcast to let everyone know we are done processing 12663 if (pkgList.size() > 0) { 12664 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12665 } 12666 } 12667 12668 /* 12669 * Utility method to unload a list of specified containers 12670 */ 12671 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 12672 // Just unmount all valid containers. 12673 for (AsecInstallArgs arg : cidArgs) { 12674 synchronized (mInstallLock) { 12675 arg.doPostDeleteLI(false); 12676 } 12677 } 12678 } 12679 12680 /* 12681 * Unload packages mounted on external media. This involves deleting package 12682 * data from internal structures, sending broadcasts about diabled packages, 12683 * gc'ing to free up references, unmounting all secure containers 12684 * corresponding to packages on external media, and posting a 12685 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 12686 * that we always have to post this message if status has been requested no 12687 * matter what. 12688 */ 12689 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 12690 final boolean reportStatus) { 12691 if (DEBUG_SD_INSTALL) 12692 Log.i(TAG, "unloading media packages"); 12693 ArrayList<String> pkgList = new ArrayList<String>(); 12694 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 12695 final Set<AsecInstallArgs> keys = processCids.keySet(); 12696 for (AsecInstallArgs args : keys) { 12697 String pkgName = args.getPackageName(); 12698 if (DEBUG_SD_INSTALL) 12699 Log.i(TAG, "Trying to unload pkg : " + pkgName); 12700 // Delete package internally 12701 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 12702 synchronized (mInstallLock) { 12703 boolean res = deletePackageLI(pkgName, null, false, null, null, 12704 PackageManager.DELETE_KEEP_DATA, outInfo, false); 12705 if (res) { 12706 pkgList.add(pkgName); 12707 } else { 12708 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 12709 failedList.add(args); 12710 } 12711 } 12712 } 12713 12714 // reader 12715 synchronized (mPackages) { 12716 // We didn't update the settings after removing each package; 12717 // write them now for all packages. 12718 mSettings.writeLPr(); 12719 } 12720 12721 // We have to absolutely send UPDATED_MEDIA_STATUS only 12722 // after confirming that all the receivers processed the ordered 12723 // broadcast when packages get disabled, force a gc to clean things up. 12724 // and unload all the containers. 12725 if (pkgList.size() > 0) { 12726 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 12727 new IIntentReceiver.Stub() { 12728 public void performReceive(Intent intent, int resultCode, String data, 12729 Bundle extras, boolean ordered, boolean sticky, 12730 int sendingUser) throws RemoteException { 12731 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 12732 reportStatus ? 1 : 0, 1, keys); 12733 mHandler.sendMessage(msg); 12734 } 12735 }); 12736 } else { 12737 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 12738 keys); 12739 mHandler.sendMessage(msg); 12740 } 12741 } 12742 12743 /** Binder call */ 12744 @Override 12745 public void movePackage(final String packageName, final IPackageMoveObserver observer, 12746 final int flags) { 12747 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 12748 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 12749 int returnCode = PackageManager.MOVE_SUCCEEDED; 12750 int currInstallFlags = 0; 12751 int newInstallFlags = 0; 12752 12753 File codeFile = null; 12754 String installerPackageName = null; 12755 String packageAbiOverride = null; 12756 12757 // reader 12758 synchronized (mPackages) { 12759 final PackageParser.Package pkg = mPackages.get(packageName); 12760 final PackageSetting ps = mSettings.mPackages.get(packageName); 12761 if (pkg == null || ps == null) { 12762 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12763 } else { 12764 // Disable moving fwd locked apps and system packages 12765 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 12766 Slog.w(TAG, "Cannot move system application"); 12767 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 12768 } else if (pkg.mOperationPending) { 12769 Slog.w(TAG, "Attempt to move package which has pending operations"); 12770 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 12771 } else { 12772 // Find install location first 12773 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 12774 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 12775 Slog.w(TAG, "Ambigous flags specified for move location."); 12776 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12777 } else { 12778 newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 12779 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 12780 currInstallFlags = isExternal(pkg) 12781 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 12782 12783 if (newInstallFlags == currInstallFlags) { 12784 Slog.w(TAG, "No move required. Trying to move to same location"); 12785 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12786 } else { 12787 if (isForwardLocked(pkg)) { 12788 currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12789 newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12790 } 12791 } 12792 } 12793 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12794 pkg.mOperationPending = true; 12795 } 12796 } 12797 12798 codeFile = new File(pkg.codePath); 12799 installerPackageName = ps.installerPackageName; 12800 packageAbiOverride = ps.cpuAbiOverrideString; 12801 } 12802 } 12803 12804 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 12805 try { 12806 observer.packageMoved(packageName, returnCode); 12807 } catch (RemoteException ignored) { 12808 } 12809 return; 12810 } 12811 12812 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 12813 @Override 12814 public void onUserActionRequired(Intent intent) throws RemoteException { 12815 throw new IllegalStateException(); 12816 } 12817 12818 @Override 12819 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 12820 Bundle extras) throws RemoteException { 12821 Slog.d(TAG, "Install result for move: " 12822 + PackageManager.installStatusToString(returnCode, msg)); 12823 12824 // We usually have a new package now after the install, but if 12825 // we failed we need to clear the pending flag on the original 12826 // package object. 12827 synchronized (mPackages) { 12828 final PackageParser.Package pkg = mPackages.get(packageName); 12829 if (pkg != null) { 12830 pkg.mOperationPending = false; 12831 } 12832 } 12833 12834 final int status = PackageManager.installStatusToPublicStatus(returnCode); 12835 switch (status) { 12836 case PackageInstaller.STATUS_SUCCESS: 12837 observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED); 12838 break; 12839 case PackageInstaller.STATUS_FAILURE_STORAGE: 12840 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 12841 break; 12842 default: 12843 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR); 12844 break; 12845 } 12846 } 12847 }; 12848 12849 // Treat a move like reinstalling an existing app, which ensures that we 12850 // process everythign uniformly, like unpacking native libraries. 12851 newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 12852 12853 final Message msg = mHandler.obtainMessage(INIT_COPY); 12854 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 12855 msg.obj = new InstallParams(origin, installObserver, newInstallFlags, 12856 installerPackageName, null, user, packageAbiOverride); 12857 mHandler.sendMessage(msg); 12858 } 12859 12860 @Override 12861 public boolean setInstallLocation(int loc) { 12862 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 12863 null); 12864 if (getInstallLocation() == loc) { 12865 return true; 12866 } 12867 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 12868 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 12869 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 12870 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 12871 return true; 12872 } 12873 return false; 12874 } 12875 12876 @Override 12877 public int getInstallLocation() { 12878 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12879 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 12880 PackageHelper.APP_INSTALL_AUTO); 12881 } 12882 12883 /** Called by UserManagerService */ 12884 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 12885 mDirtyUsers.remove(userHandle); 12886 mSettings.removeUserLPw(userHandle); 12887 mPendingBroadcasts.remove(userHandle); 12888 if (mInstaller != null) { 12889 // Technically, we shouldn't be doing this with the package lock 12890 // held. However, this is very rare, and there is already so much 12891 // other disk I/O going on, that we'll let it slide for now. 12892 mInstaller.removeUserDataDirs(userHandle); 12893 } 12894 mUserNeedsBadging.delete(userHandle); 12895 removeUnusedPackagesLILPw(userManager, userHandle); 12896 } 12897 12898 /** 12899 * We're removing userHandle and would like to remove any downloaded packages 12900 * that are no longer in use by any other user. 12901 * @param userHandle the user being removed 12902 */ 12903 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 12904 final boolean DEBUG_CLEAN_APKS = false; 12905 int [] users = userManager.getUserIdsLPr(); 12906 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 12907 while (psit.hasNext()) { 12908 PackageSetting ps = psit.next(); 12909 if (ps.pkg == null) { 12910 continue; 12911 } 12912 final String packageName = ps.pkg.packageName; 12913 // Skip over if system app 12914 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12915 continue; 12916 } 12917 if (DEBUG_CLEAN_APKS) { 12918 Slog.i(TAG, "Checking package " + packageName); 12919 } 12920 boolean keep = false; 12921 for (int i = 0; i < users.length; i++) { 12922 if (users[i] != userHandle && ps.getInstalled(users[i])) { 12923 keep = true; 12924 if (DEBUG_CLEAN_APKS) { 12925 Slog.i(TAG, " Keeping package " + packageName + " for user " 12926 + users[i]); 12927 } 12928 break; 12929 } 12930 } 12931 if (!keep) { 12932 if (DEBUG_CLEAN_APKS) { 12933 Slog.i(TAG, " Removing package " + packageName); 12934 } 12935 mHandler.post(new Runnable() { 12936 public void run() { 12937 deletePackageX(packageName, userHandle, 0); 12938 } //end run 12939 }); 12940 } 12941 } 12942 } 12943 12944 /** Called by UserManagerService */ 12945 void createNewUserLILPw(int userHandle, File path) { 12946 if (mInstaller != null) { 12947 mInstaller.createUserConfig(userHandle); 12948 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 12949 } 12950 } 12951 12952 @Override 12953 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 12954 mContext.enforceCallingOrSelfPermission( 12955 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12956 "Only package verification agents can read the verifier device identity"); 12957 12958 synchronized (mPackages) { 12959 return mSettings.getVerifierDeviceIdentityLPw(); 12960 } 12961 } 12962 12963 @Override 12964 public void setPermissionEnforced(String permission, boolean enforced) { 12965 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 12966 if (READ_EXTERNAL_STORAGE.equals(permission)) { 12967 synchronized (mPackages) { 12968 if (mSettings.mReadExternalStorageEnforced == null 12969 || mSettings.mReadExternalStorageEnforced != enforced) { 12970 mSettings.mReadExternalStorageEnforced = enforced; 12971 mSettings.writeLPr(); 12972 } 12973 } 12974 // kill any non-foreground processes so we restart them and 12975 // grant/revoke the GID. 12976 final IActivityManager am = ActivityManagerNative.getDefault(); 12977 if (am != null) { 12978 final long token = Binder.clearCallingIdentity(); 12979 try { 12980 am.killProcessesBelowForeground("setPermissionEnforcement"); 12981 } catch (RemoteException e) { 12982 } finally { 12983 Binder.restoreCallingIdentity(token); 12984 } 12985 } 12986 } else { 12987 throw new IllegalArgumentException("No selective enforcement for " + permission); 12988 } 12989 } 12990 12991 @Override 12992 @Deprecated 12993 public boolean isPermissionEnforced(String permission) { 12994 return true; 12995 } 12996 12997 @Override 12998 public boolean isStorageLow() { 12999 final long token = Binder.clearCallingIdentity(); 13000 try { 13001 final DeviceStorageMonitorInternal 13002 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13003 if (dsm != null) { 13004 return dsm.isMemoryLow(); 13005 } else { 13006 return false; 13007 } 13008 } finally { 13009 Binder.restoreCallingIdentity(token); 13010 } 13011 } 13012 13013 @Override 13014 public IPackageInstaller getPackageInstaller() { 13015 return mInstallerService; 13016 } 13017 13018 private boolean userNeedsBadging(int userId) { 13019 int index = mUserNeedsBadging.indexOfKey(userId); 13020 if (index < 0) { 13021 final UserInfo userInfo; 13022 final long token = Binder.clearCallingIdentity(); 13023 try { 13024 userInfo = sUserManager.getUserInfo(userId); 13025 } finally { 13026 Binder.restoreCallingIdentity(token); 13027 } 13028 final boolean b; 13029 if (userInfo != null && userInfo.isManagedProfile()) { 13030 b = true; 13031 } else { 13032 b = false; 13033 } 13034 mUserNeedsBadging.put(userId, b); 13035 return b; 13036 } 13037 return mUserNeedsBadging.valueAt(index); 13038 } 13039 13040 @Override 13041 public KeySet getKeySetByAlias(String packageName, String alias) { 13042 if (packageName == null || alias == null) { 13043 return null; 13044 } 13045 synchronized(mPackages) { 13046 final PackageParser.Package pkg = mPackages.get(packageName); 13047 if (pkg == null) { 13048 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13049 throw new IllegalArgumentException("Unknown package: " + packageName); 13050 } 13051 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13052 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 13053 } 13054 } 13055 13056 @Override 13057 public KeySet getSigningKeySet(String packageName) { 13058 if (packageName == null) { 13059 return null; 13060 } 13061 synchronized(mPackages) { 13062 final PackageParser.Package pkg = mPackages.get(packageName); 13063 if (pkg == null) { 13064 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13065 throw new IllegalArgumentException("Unknown package: " + packageName); 13066 } 13067 if (pkg.applicationInfo.uid != Binder.getCallingUid() 13068 && Process.SYSTEM_UID != Binder.getCallingUid()) { 13069 throw new SecurityException("May not access signing KeySet of other apps."); 13070 } 13071 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13072 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 13073 } 13074 } 13075 13076 @Override 13077 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 13078 if (packageName == null || ks == null) { 13079 return false; 13080 } 13081 synchronized(mPackages) { 13082 final PackageParser.Package pkg = mPackages.get(packageName); 13083 if (pkg == null) { 13084 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13085 throw new IllegalArgumentException("Unknown package: " + packageName); 13086 } 13087 IBinder ksh = ks.getToken(); 13088 if (ksh instanceof KeySetHandle) { 13089 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13090 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 13091 } 13092 return false; 13093 } 13094 } 13095 13096 @Override 13097 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 13098 if (packageName == null || ks == null) { 13099 return false; 13100 } 13101 synchronized(mPackages) { 13102 final PackageParser.Package pkg = mPackages.get(packageName); 13103 if (pkg == null) { 13104 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13105 throw new IllegalArgumentException("Unknown package: " + packageName); 13106 } 13107 IBinder ksh = ks.getToken(); 13108 if (ksh instanceof KeySetHandle) { 13109 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13110 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 13111 } 13112 return false; 13113 } 13114 } 13115} 13116