PackageManagerService.java revision 742e790294b3441b79f715fe447069b63c6065db
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS; 20import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 21import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 26import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 27import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 28import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 29import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 30import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 32import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 33import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 34import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 36import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 37import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 38import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 39import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 41import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 42import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 44import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 45import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 46import static android.content.pm.PackageParser.isApkFile; 47import static android.os.Process.PACKAGE_INFO_GID; 48import static android.os.Process.SYSTEM_UID; 49import static android.system.OsConstants.O_CREAT; 50import static android.system.OsConstants.O_RDWR; 51import static android.system.OsConstants.S_IRGRP; 52import static android.system.OsConstants.S_IROTH; 53import static android.system.OsConstants.S_IRWXU; 54import static android.system.OsConstants.S_IXGRP; 55import static android.system.OsConstants.S_IXOTH; 56import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 57import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 58import static com.android.internal.util.ArrayUtils.appendInt; 59import static com.android.internal.util.ArrayUtils.removeInt; 60 61import android.util.ArrayMap; 62 63import com.android.internal.R; 64import com.android.internal.app.IMediaContainerService; 65import com.android.internal.app.ResolverActivity; 66import com.android.internal.content.NativeLibraryHelper; 67import com.android.internal.content.PackageHelper; 68import com.android.internal.os.IParcelFileDescriptorFactory; 69import com.android.internal.util.ArrayUtils; 70import com.android.internal.util.FastPrintWriter; 71import com.android.internal.util.FastXmlSerializer; 72import com.android.internal.util.IndentingPrintWriter; 73import com.android.internal.util.Preconditions; 74import com.android.server.EventLogTags; 75import com.android.server.IntentResolver; 76import com.android.server.LocalServices; 77import com.android.server.ServiceThread; 78import com.android.server.SystemConfig; 79import com.android.server.Watchdog; 80import com.android.server.pm.Settings.DatabaseVersion; 81import com.android.server.storage.DeviceStorageMonitorInternal; 82 83import org.xmlpull.v1.XmlSerializer; 84 85import android.app.ActivityManager; 86import android.app.ActivityManagerNative; 87import android.app.IActivityManager; 88import android.app.admin.IDevicePolicyManager; 89import android.app.backup.IBackupManager; 90import android.content.BroadcastReceiver; 91import android.content.ComponentName; 92import android.content.Context; 93import android.content.IIntentReceiver; 94import android.content.Intent; 95import android.content.IntentFilter; 96import android.content.IntentSender; 97import android.content.IntentSender.SendIntentException; 98import android.content.ServiceConnection; 99import android.content.pm.ActivityInfo; 100import android.content.pm.ApplicationInfo; 101import android.content.pm.FeatureInfo; 102import android.content.pm.IPackageDataObserver; 103import android.content.pm.IPackageDeleteObserver; 104import android.content.pm.IPackageDeleteObserver2; 105import android.content.pm.IPackageInstallObserver2; 106import android.content.pm.IPackageInstaller; 107import android.content.pm.IPackageManager; 108import android.content.pm.IPackageMoveObserver; 109import android.content.pm.IPackageStatsObserver; 110import android.content.pm.InstrumentationInfo; 111import android.content.pm.ManifestDigest; 112import android.content.pm.PackageCleanItem; 113import android.content.pm.PackageInfo; 114import android.content.pm.PackageInfoLite; 115import android.content.pm.PackageInstaller; 116import android.content.pm.PackageManager; 117import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 118import android.content.pm.PackageParser.ActivityIntentInfo; 119import android.content.pm.PackageParser.PackageLite; 120import android.content.pm.PackageParser.PackageParserException; 121import android.content.pm.PackageParser; 122import android.content.pm.PackageStats; 123import android.content.pm.PackageUserState; 124import android.content.pm.ParceledListSlice; 125import android.content.pm.PermissionGroupInfo; 126import android.content.pm.PermissionInfo; 127import android.content.pm.ProviderInfo; 128import android.content.pm.ResolveInfo; 129import android.content.pm.ServiceInfo; 130import android.content.pm.Signature; 131import android.content.pm.UserInfo; 132import android.content.pm.VerificationParams; 133import android.content.pm.VerifierDeviceIdentity; 134import android.content.pm.VerifierInfo; 135import android.content.res.Resources; 136import android.hardware.display.DisplayManager; 137import android.net.Uri; 138import android.os.Binder; 139import android.os.Build; 140import android.os.Bundle; 141import android.os.Environment; 142import android.os.Environment.UserEnvironment; 143import android.os.storage.StorageManager; 144import android.os.FileUtils; 145import android.os.Handler; 146import android.os.IBinder; 147import android.os.Looper; 148import android.os.Message; 149import android.os.Parcel; 150import android.os.ParcelFileDescriptor; 151import android.os.Process; 152import android.os.RemoteException; 153import android.os.SELinux; 154import android.os.ServiceManager; 155import android.os.SystemClock; 156import android.os.SystemProperties; 157import android.os.UserHandle; 158import android.os.UserManager; 159import android.security.KeyStore; 160import android.security.SystemKeyStore; 161import android.system.ErrnoException; 162import android.system.Os; 163import android.system.StructStat; 164import android.text.TextUtils; 165import android.util.ArraySet; 166import android.util.AtomicFile; 167import android.util.DisplayMetrics; 168import android.util.EventLog; 169import android.util.ExceptionUtils; 170import android.util.Log; 171import android.util.LogPrinter; 172import android.util.PrintStreamPrinter; 173import android.util.Slog; 174import android.util.SparseArray; 175import android.util.SparseBooleanArray; 176import android.view.Display; 177 178import java.io.BufferedInputStream; 179import java.io.BufferedOutputStream; 180import java.io.File; 181import java.io.FileDescriptor; 182import java.io.FileInputStream; 183import java.io.FileNotFoundException; 184import java.io.FileOutputStream; 185import java.io.FilenameFilter; 186import java.io.IOException; 187import java.io.InputStream; 188import java.io.PrintWriter; 189import java.nio.charset.StandardCharsets; 190import java.security.NoSuchAlgorithmException; 191import java.security.PublicKey; 192import java.security.cert.CertificateEncodingException; 193import java.security.cert.CertificateException; 194import java.text.SimpleDateFormat; 195import java.util.ArrayList; 196import java.util.Arrays; 197import java.util.Collection; 198import java.util.Collections; 199import java.util.Comparator; 200import java.util.Date; 201import java.util.HashMap; 202import java.util.HashSet; 203import java.util.Iterator; 204import java.util.List; 205import java.util.Map; 206import java.util.Set; 207import java.util.concurrent.atomic.AtomicBoolean; 208import java.util.concurrent.atomic.AtomicLong; 209 210import dalvik.system.DexFile; 211import dalvik.system.StaleDexCacheError; 212import dalvik.system.VMRuntime; 213 214import libcore.io.IoUtils; 215import libcore.util.EmptyArray; 216 217/** 218 * Keep track of all those .apks everywhere. 219 * 220 * This is very central to the platform's security; please run the unit 221 * tests whenever making modifications here: 222 * 223mmm frameworks/base/tests/AndroidTests 224adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 225adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 226 * 227 * {@hide} 228 */ 229public class PackageManagerService extends IPackageManager.Stub { 230 static final String TAG = "PackageManager"; 231 static final boolean DEBUG_SETTINGS = false; 232 static final boolean DEBUG_PREFERRED = false; 233 static final boolean DEBUG_UPGRADE = false; 234 private static final boolean DEBUG_INSTALL = false; 235 private static final boolean DEBUG_REMOVE = false; 236 private static final boolean DEBUG_BROADCASTS = false; 237 private static final boolean DEBUG_SHOW_INFO = false; 238 private static final boolean DEBUG_PACKAGE_INFO = false; 239 private static final boolean DEBUG_INTENT_MATCHING = false; 240 private static final boolean DEBUG_PACKAGE_SCANNING = false; 241 private static final boolean DEBUG_VERIFY = false; 242 private static final boolean DEBUG_DEXOPT = false; 243 private static final boolean DEBUG_ABI_SELECTION = false; 244 245 private static final int RADIO_UID = Process.PHONE_UID; 246 private static final int LOG_UID = Process.LOG_UID; 247 private static final int NFC_UID = Process.NFC_UID; 248 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 249 private static final int SHELL_UID = Process.SHELL_UID; 250 251 // Cap the size of permission trees that 3rd party apps can define 252 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 253 254 // Suffix used during package installation when copying/moving 255 // package apks to install directory. 256 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 257 258 // Special value for {@code PackageParser.Package#cpuAbiOverride} to indicate 259 // that the cpuAbiOverride must be clear. 260 private static final String CLEAR_ABI_OVERRIDE = "-"; 261 262 static final int SCAN_MONITOR = 1<<0; 263 static final int SCAN_NO_DEX = 1<<1; 264 static final int SCAN_FORCE_DEX = 1<<2; 265 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 266 static final int SCAN_NEW_INSTALL = 1<<4; 267 static final int SCAN_NO_PATHS = 1<<5; 268 static final int SCAN_UPDATE_TIME = 1<<6; 269 static final int SCAN_DEFER_DEX = 1<<7; 270 static final int SCAN_BOOTING = 1<<8; 271 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 272 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 273 274 static final int REMOVE_CHATTY = 1<<16; 275 276 /** 277 * Timeout (in milliseconds) after which the watchdog should declare that 278 * our handler thread is wedged. The usual default for such things is one 279 * minute but we sometimes do very lengthy I/O operations on this thread, 280 * such as installing multi-gigabyte applications, so ours needs to be longer. 281 */ 282 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 283 284 /** 285 * Whether verification is enabled by default. 286 */ 287 private static final boolean DEFAULT_VERIFY_ENABLE = true; 288 289 /** 290 * The default maximum time to wait for the verification agent to return in 291 * milliseconds. 292 */ 293 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 294 295 /** 296 * The default response for package verification timeout. 297 * 298 * This can be either PackageManager.VERIFICATION_ALLOW or 299 * PackageManager.VERIFICATION_REJECT. 300 */ 301 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 302 303 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 304 305 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 306 DEFAULT_CONTAINER_PACKAGE, 307 "com.android.defcontainer.DefaultContainerService"); 308 309 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 310 311 private static final String LIB_DIR_NAME = "lib"; 312 private static final String LIB64_DIR_NAME = "lib64"; 313 314 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 315 316 private static String sPreferredInstructionSet; 317 318 final ServiceThread mHandlerThread; 319 320 private static final String IDMAP_PREFIX = "/data/resource-cache/"; 321 private static final String IDMAP_SUFFIX = "@idmap"; 322 323 final PackageHandler mHandler; 324 325 final int mSdkVersion = Build.VERSION.SDK_INT; 326 327 final Context mContext; 328 final boolean mFactoryTest; 329 final boolean mOnlyCore; 330 final DisplayMetrics mMetrics; 331 final int mDefParseFlags; 332 final String[] mSeparateProcesses; 333 334 // This is where all application persistent data goes. 335 final File mAppDataDir; 336 337 // This is where all application persistent data goes for secondary users. 338 final File mUserAppDataDir; 339 340 /** The location for ASEC container files on internal storage. */ 341 final String mAsecInternalPath; 342 343 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 344 // LOCK HELD. Can be called with mInstallLock held. 345 final Installer mInstaller; 346 347 /** Directory where installed third-party apps stored */ 348 final File mAppInstallDir; 349 350 /** 351 * Directory to which applications installed internally have their 352 * 32 bit native libraries copied. 353 */ 354 private File mAppLib32InstallDir; 355 356 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 357 // apps. 358 final File mDrmAppPrivateInstallDir; 359 360 // ---------------------------------------------------------------- 361 362 // Lock for state used when installing and doing other long running 363 // operations. Methods that must be called with this lock held have 364 // the suffix "LI". 365 final Object mInstallLock = new Object(); 366 367 // These are the directories in the 3rd party applications installed dir 368 // that we have currently loaded packages from. Keys are the application's 369 // installed zip file (absolute codePath), and values are Package. 370 final HashMap<String, PackageParser.Package> mAppDirs = 371 new HashMap<String, PackageParser.Package>(); 372 373 // ---------------------------------------------------------------- 374 375 // Keys are String (package name), values are Package. This also serves 376 // as the lock for the global state. Methods that must be called with 377 // this lock held have the prefix "LP". 378 final HashMap<String, PackageParser.Package> mPackages = 379 new HashMap<String, PackageParser.Package>(); 380 381 // Tracks available target package names -> overlay package paths. 382 final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays = 383 new HashMap<String, HashMap<String, PackageParser.Package>>(); 384 385 final Settings mSettings; 386 boolean mRestoredSettings; 387 388 // System configuration read by SystemConfig. 389 final int[] mGlobalGids; 390 final SparseArray<HashSet<String>> mSystemPermissions; 391 final HashMap<String, FeatureInfo> mAvailableFeatures; 392 393 // If mac_permissions.xml was found for seinfo labeling. 394 boolean mFoundPolicyFile; 395 396 // If a recursive restorecon of /data/data/<pkg> is needed. 397 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 398 399 public static final class SharedLibraryEntry { 400 public final String path; 401 public final String apk; 402 403 SharedLibraryEntry(String _path, String _apk) { 404 path = _path; 405 apk = _apk; 406 } 407 } 408 409 // Currently known shared libraries. 410 final HashMap<String, SharedLibraryEntry> mSharedLibraries = 411 new HashMap<String, SharedLibraryEntry>(); 412 413 // All available activities, for your resolving pleasure. 414 final ActivityIntentResolver mActivities = 415 new ActivityIntentResolver(); 416 417 // All available receivers, for your resolving pleasure. 418 final ActivityIntentResolver mReceivers = 419 new ActivityIntentResolver(); 420 421 // All available services, for your resolving pleasure. 422 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 423 424 // All available providers, for your resolving pleasure. 425 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 426 427 // Mapping from provider base names (first directory in content URI codePath) 428 // to the provider information. 429 final HashMap<String, PackageParser.Provider> mProvidersByAuthority = 430 new HashMap<String, PackageParser.Provider>(); 431 432 // Mapping from instrumentation class names to info about them. 433 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 434 new HashMap<ComponentName, PackageParser.Instrumentation>(); 435 436 // Mapping from permission names to info about them. 437 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups = 438 new HashMap<String, PackageParser.PermissionGroup>(); 439 440 // Packages whose data we have transfered into another package, thus 441 // should no longer exist. 442 final HashSet<String> mTransferedPackages = new HashSet<String>(); 443 444 // Broadcast actions that are only available to the system. 445 final HashSet<String> mProtectedBroadcasts = new HashSet<String>(); 446 447 /** List of packages waiting for verification. */ 448 final SparseArray<PackageVerificationState> mPendingVerification 449 = new SparseArray<PackageVerificationState>(); 450 451 /** Set of packages associated with each app op permission. */ 452 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 453 454 final PackageInstallerService mInstallerService; 455 456 HashSet<PackageParser.Package> mDeferredDexOpt = null; 457 458 // Cache of users who need badging. 459 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 460 461 /** Token for keys in mPendingVerification. */ 462 private int mPendingVerificationToken = 0; 463 464 boolean mSystemReady; 465 boolean mSafeMode; 466 boolean mHasSystemUidErrors; 467 468 ApplicationInfo mAndroidApplication; 469 final ActivityInfo mResolveActivity = new ActivityInfo(); 470 final ResolveInfo mResolveInfo = new ResolveInfo(); 471 ComponentName mResolveComponentName; 472 PackageParser.Package mPlatformPackage; 473 ComponentName mCustomResolverComponentName; 474 475 boolean mResolverReplaced = false; 476 477 // Set of pending broadcasts for aggregating enable/disable of components. 478 static class PendingPackageBroadcasts { 479 // for each user id, a map of <package name -> components within that package> 480 final SparseArray<HashMap<String, ArrayList<String>>> mUidMap; 481 482 public PendingPackageBroadcasts() { 483 mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2); 484 } 485 486 public ArrayList<String> get(int userId, String packageName) { 487 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 488 return packages.get(packageName); 489 } 490 491 public void put(int userId, String packageName, ArrayList<String> components) { 492 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 493 packages.put(packageName, components); 494 } 495 496 public void remove(int userId, String packageName) { 497 HashMap<String, ArrayList<String>> packages = mUidMap.get(userId); 498 if (packages != null) { 499 packages.remove(packageName); 500 } 501 } 502 503 public void remove(int userId) { 504 mUidMap.remove(userId); 505 } 506 507 public int userIdCount() { 508 return mUidMap.size(); 509 } 510 511 public int userIdAt(int n) { 512 return mUidMap.keyAt(n); 513 } 514 515 public HashMap<String, ArrayList<String>> packagesForUserId(int userId) { 516 return mUidMap.get(userId); 517 } 518 519 public int size() { 520 // total number of pending broadcast entries across all userIds 521 int num = 0; 522 for (int i = 0; i< mUidMap.size(); i++) { 523 num += mUidMap.valueAt(i).size(); 524 } 525 return num; 526 } 527 528 public void clear() { 529 mUidMap.clear(); 530 } 531 532 private HashMap<String, ArrayList<String>> getOrAllocate(int userId) { 533 HashMap<String, ArrayList<String>> map = mUidMap.get(userId); 534 if (map == null) { 535 map = new HashMap<String, ArrayList<String>>(); 536 mUidMap.put(userId, map); 537 } 538 return map; 539 } 540 } 541 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 542 543 // Service Connection to remote media container service to copy 544 // package uri's from external media onto secure containers 545 // or internal storage. 546 private IMediaContainerService mContainerService = null; 547 548 static final int SEND_PENDING_BROADCAST = 1; 549 static final int MCS_BOUND = 3; 550 static final int END_COPY = 4; 551 static final int INIT_COPY = 5; 552 static final int MCS_UNBIND = 6; 553 static final int START_CLEANING_PACKAGE = 7; 554 static final int FIND_INSTALL_LOC = 8; 555 static final int POST_INSTALL = 9; 556 static final int MCS_RECONNECT = 10; 557 static final int MCS_GIVE_UP = 11; 558 static final int UPDATED_MEDIA_STATUS = 12; 559 static final int WRITE_SETTINGS = 13; 560 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 561 static final int PACKAGE_VERIFIED = 15; 562 static final int CHECK_PENDING_VERIFICATION = 16; 563 564 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 565 566 // Delay time in millisecs 567 static final int BROADCAST_DELAY = 10 * 1000; 568 569 static UserManagerService sUserManager; 570 571 // Stores a list of users whose package restrictions file needs to be updated 572 private HashSet<Integer> mDirtyUsers = new HashSet<Integer>(); 573 574 final private DefaultContainerConnection mDefContainerConn = 575 new DefaultContainerConnection(); 576 class DefaultContainerConnection implements ServiceConnection { 577 public void onServiceConnected(ComponentName name, IBinder service) { 578 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 579 IMediaContainerService imcs = 580 IMediaContainerService.Stub.asInterface(service); 581 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 582 } 583 584 public void onServiceDisconnected(ComponentName name) { 585 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 586 } 587 }; 588 589 // Recordkeeping of restore-after-install operations that are currently in flight 590 // between the Package Manager and the Backup Manager 591 class PostInstallData { 592 public InstallArgs args; 593 public PackageInstalledInfo res; 594 595 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 596 args = _a; 597 res = _r; 598 } 599 }; 600 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 601 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 602 603 private final String mRequiredVerifierPackage; 604 605 private final PackageUsage mPackageUsage = new PackageUsage(); 606 607 private class PackageUsage { 608 private static final int WRITE_INTERVAL 609 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 610 611 private final Object mFileLock = new Object(); 612 private final AtomicLong mLastWritten = new AtomicLong(0); 613 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 614 615 private boolean mIsHistoricalPackageUsageAvailable = true; 616 617 boolean isHistoricalPackageUsageAvailable() { 618 return mIsHistoricalPackageUsageAvailable; 619 } 620 621 void write(boolean force) { 622 if (force) { 623 writeInternal(); 624 return; 625 } 626 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 627 && !DEBUG_DEXOPT) { 628 return; 629 } 630 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 631 new Thread("PackageUsage_DiskWriter") { 632 @Override 633 public void run() { 634 try { 635 writeInternal(); 636 } finally { 637 mBackgroundWriteRunning.set(false); 638 } 639 } 640 }.start(); 641 } 642 } 643 644 private void writeInternal() { 645 synchronized (mPackages) { 646 synchronized (mFileLock) { 647 AtomicFile file = getFile(); 648 FileOutputStream f = null; 649 try { 650 f = file.startWrite(); 651 BufferedOutputStream out = new BufferedOutputStream(f); 652 FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID); 653 StringBuilder sb = new StringBuilder(); 654 for (PackageParser.Package pkg : mPackages.values()) { 655 if (pkg.mLastPackageUsageTimeInMills == 0) { 656 continue; 657 } 658 sb.setLength(0); 659 sb.append(pkg.packageName); 660 sb.append(' '); 661 sb.append((long)pkg.mLastPackageUsageTimeInMills); 662 sb.append('\n'); 663 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 664 } 665 out.flush(); 666 file.finishWrite(f); 667 } catch (IOException e) { 668 if (f != null) { 669 file.failWrite(f); 670 } 671 Log.e(TAG, "Failed to write package usage times", e); 672 } 673 } 674 } 675 mLastWritten.set(SystemClock.elapsedRealtime()); 676 } 677 678 void readLP() { 679 synchronized (mFileLock) { 680 AtomicFile file = getFile(); 681 BufferedInputStream in = null; 682 try { 683 in = new BufferedInputStream(file.openRead()); 684 StringBuffer sb = new StringBuffer(); 685 while (true) { 686 String packageName = readToken(in, sb, ' '); 687 if (packageName == null) { 688 break; 689 } 690 String timeInMillisString = readToken(in, sb, '\n'); 691 if (timeInMillisString == null) { 692 throw new IOException("Failed to find last usage time for package " 693 + packageName); 694 } 695 PackageParser.Package pkg = mPackages.get(packageName); 696 if (pkg == null) { 697 continue; 698 } 699 long timeInMillis; 700 try { 701 timeInMillis = Long.parseLong(timeInMillisString.toString()); 702 } catch (NumberFormatException e) { 703 throw new IOException("Failed to parse " + timeInMillisString 704 + " as a long.", e); 705 } 706 pkg.mLastPackageUsageTimeInMills = timeInMillis; 707 } 708 } catch (FileNotFoundException expected) { 709 mIsHistoricalPackageUsageAvailable = false; 710 } catch (IOException e) { 711 Log.w(TAG, "Failed to read package usage times", e); 712 } finally { 713 IoUtils.closeQuietly(in); 714 } 715 } 716 mLastWritten.set(SystemClock.elapsedRealtime()); 717 } 718 719 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 720 throws IOException { 721 sb.setLength(0); 722 while (true) { 723 int ch = in.read(); 724 if (ch == -1) { 725 if (sb.length() == 0) { 726 return null; 727 } 728 throw new IOException("Unexpected EOF"); 729 } 730 if (ch == endOfToken) { 731 return sb.toString(); 732 } 733 sb.append((char)ch); 734 } 735 } 736 737 private AtomicFile getFile() { 738 File dataDir = Environment.getDataDirectory(); 739 File systemDir = new File(dataDir, "system"); 740 File fname = new File(systemDir, "package-usage.list"); 741 return new AtomicFile(fname); 742 } 743 } 744 745 class PackageHandler extends Handler { 746 private boolean mBound = false; 747 final ArrayList<HandlerParams> mPendingInstalls = 748 new ArrayList<HandlerParams>(); 749 750 private boolean connectToService() { 751 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 752 " DefaultContainerService"); 753 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 754 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 755 if (mContext.bindServiceAsUser(service, mDefContainerConn, 756 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 757 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 758 mBound = true; 759 return true; 760 } 761 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 762 return false; 763 } 764 765 private void disconnectService() { 766 mContainerService = null; 767 mBound = false; 768 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 769 mContext.unbindService(mDefContainerConn); 770 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 771 } 772 773 PackageHandler(Looper looper) { 774 super(looper); 775 } 776 777 public void handleMessage(Message msg) { 778 try { 779 doHandleMessage(msg); 780 } finally { 781 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 782 } 783 } 784 785 void doHandleMessage(Message msg) { 786 switch (msg.what) { 787 case INIT_COPY: { 788 HandlerParams params = (HandlerParams) msg.obj; 789 int idx = mPendingInstalls.size(); 790 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 791 // If a bind was already initiated we dont really 792 // need to do anything. The pending install 793 // will be processed later on. 794 if (!mBound) { 795 // If this is the only one pending we might 796 // have to bind to the service again. 797 if (!connectToService()) { 798 Slog.e(TAG, "Failed to bind to media container service"); 799 params.serviceError(); 800 return; 801 } else { 802 // Once we bind to the service, the first 803 // pending request will be processed. 804 mPendingInstalls.add(idx, params); 805 } 806 } else { 807 mPendingInstalls.add(idx, params); 808 // Already bound to the service. Just make 809 // sure we trigger off processing the first request. 810 if (idx == 0) { 811 mHandler.sendEmptyMessage(MCS_BOUND); 812 } 813 } 814 break; 815 } 816 case MCS_BOUND: { 817 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 818 if (msg.obj != null) { 819 mContainerService = (IMediaContainerService) msg.obj; 820 } 821 if (mContainerService == null) { 822 // Something seriously wrong. Bail out 823 Slog.e(TAG, "Cannot bind to media container service"); 824 for (HandlerParams params : mPendingInstalls) { 825 // Indicate service bind error 826 params.serviceError(); 827 } 828 mPendingInstalls.clear(); 829 } else if (mPendingInstalls.size() > 0) { 830 HandlerParams params = mPendingInstalls.get(0); 831 if (params != null) { 832 if (params.startCopy()) { 833 // We are done... look for more work or to 834 // go idle. 835 if (DEBUG_SD_INSTALL) Log.i(TAG, 836 "Checking for more work or unbind..."); 837 // Delete pending install 838 if (mPendingInstalls.size() > 0) { 839 mPendingInstalls.remove(0); 840 } 841 if (mPendingInstalls.size() == 0) { 842 if (mBound) { 843 if (DEBUG_SD_INSTALL) Log.i(TAG, 844 "Posting delayed MCS_UNBIND"); 845 removeMessages(MCS_UNBIND); 846 Message ubmsg = obtainMessage(MCS_UNBIND); 847 // Unbind after a little delay, to avoid 848 // continual thrashing. 849 sendMessageDelayed(ubmsg, 10000); 850 } 851 } else { 852 // There are more pending requests in queue. 853 // Just post MCS_BOUND message to trigger processing 854 // of next pending install. 855 if (DEBUG_SD_INSTALL) Log.i(TAG, 856 "Posting MCS_BOUND for next work"); 857 mHandler.sendEmptyMessage(MCS_BOUND); 858 } 859 } 860 } 861 } else { 862 // Should never happen ideally. 863 Slog.w(TAG, "Empty queue"); 864 } 865 break; 866 } 867 case MCS_RECONNECT: { 868 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 869 if (mPendingInstalls.size() > 0) { 870 if (mBound) { 871 disconnectService(); 872 } 873 if (!connectToService()) { 874 Slog.e(TAG, "Failed to bind to media container service"); 875 for (HandlerParams params : mPendingInstalls) { 876 // Indicate service bind error 877 params.serviceError(); 878 } 879 mPendingInstalls.clear(); 880 } 881 } 882 break; 883 } 884 case MCS_UNBIND: { 885 // If there is no actual work left, then time to unbind. 886 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 887 888 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 889 if (mBound) { 890 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 891 892 disconnectService(); 893 } 894 } else if (mPendingInstalls.size() > 0) { 895 // There are more pending requests in queue. 896 // Just post MCS_BOUND message to trigger processing 897 // of next pending install. 898 mHandler.sendEmptyMessage(MCS_BOUND); 899 } 900 901 break; 902 } 903 case MCS_GIVE_UP: { 904 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 905 mPendingInstalls.remove(0); 906 break; 907 } 908 case SEND_PENDING_BROADCAST: { 909 String packages[]; 910 ArrayList<String> components[]; 911 int size = 0; 912 int uids[]; 913 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 914 synchronized (mPackages) { 915 if (mPendingBroadcasts == null) { 916 return; 917 } 918 size = mPendingBroadcasts.size(); 919 if (size <= 0) { 920 // Nothing to be done. Just return 921 return; 922 } 923 packages = new String[size]; 924 components = new ArrayList[size]; 925 uids = new int[size]; 926 int i = 0; // filling out the above arrays 927 928 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 929 int packageUserId = mPendingBroadcasts.userIdAt(n); 930 Iterator<Map.Entry<String, ArrayList<String>>> it 931 = mPendingBroadcasts.packagesForUserId(packageUserId) 932 .entrySet().iterator(); 933 while (it.hasNext() && i < size) { 934 Map.Entry<String, ArrayList<String>> ent = it.next(); 935 packages[i] = ent.getKey(); 936 components[i] = ent.getValue(); 937 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 938 uids[i] = (ps != null) 939 ? UserHandle.getUid(packageUserId, ps.appId) 940 : -1; 941 i++; 942 } 943 } 944 size = i; 945 mPendingBroadcasts.clear(); 946 } 947 // Send broadcasts 948 for (int i = 0; i < size; i++) { 949 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 950 } 951 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 952 break; 953 } 954 case START_CLEANING_PACKAGE: { 955 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 956 final String packageName = (String)msg.obj; 957 final int userId = msg.arg1; 958 final boolean andCode = msg.arg2 != 0; 959 synchronized (mPackages) { 960 if (userId == UserHandle.USER_ALL) { 961 int[] users = sUserManager.getUserIds(); 962 for (int user : users) { 963 mSettings.addPackageToCleanLPw( 964 new PackageCleanItem(user, packageName, andCode)); 965 } 966 } else { 967 mSettings.addPackageToCleanLPw( 968 new PackageCleanItem(userId, packageName, andCode)); 969 } 970 } 971 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 972 startCleaningPackages(); 973 } break; 974 case POST_INSTALL: { 975 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 976 PostInstallData data = mRunningInstalls.get(msg.arg1); 977 mRunningInstalls.delete(msg.arg1); 978 boolean deleteOld = false; 979 980 if (data != null) { 981 InstallArgs args = data.args; 982 PackageInstalledInfo res = data.res; 983 984 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 985 res.removedInfo.sendBroadcast(false, true, false); 986 Bundle extras = new Bundle(1); 987 extras.putInt(Intent.EXTRA_UID, res.uid); 988 // Determine the set of users who are adding this 989 // package for the first time vs. those who are seeing 990 // an update. 991 int[] firstUsers; 992 int[] updateUsers = new int[0]; 993 if (res.origUsers == null || res.origUsers.length == 0) { 994 firstUsers = res.newUsers; 995 } else { 996 firstUsers = new int[0]; 997 for (int i=0; i<res.newUsers.length; i++) { 998 int user = res.newUsers[i]; 999 boolean isNew = true; 1000 for (int j=0; j<res.origUsers.length; j++) { 1001 if (res.origUsers[j] == user) { 1002 isNew = false; 1003 break; 1004 } 1005 } 1006 if (isNew) { 1007 int[] newFirst = new int[firstUsers.length+1]; 1008 System.arraycopy(firstUsers, 0, newFirst, 0, 1009 firstUsers.length); 1010 newFirst[firstUsers.length] = user; 1011 firstUsers = newFirst; 1012 } else { 1013 int[] newUpdate = new int[updateUsers.length+1]; 1014 System.arraycopy(updateUsers, 0, newUpdate, 0, 1015 updateUsers.length); 1016 newUpdate[updateUsers.length] = user; 1017 updateUsers = newUpdate; 1018 } 1019 } 1020 } 1021 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1022 res.pkg.applicationInfo.packageName, 1023 extras, null, null, firstUsers); 1024 final boolean update = res.removedInfo.removedPackage != null; 1025 if (update) { 1026 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1027 } 1028 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1029 res.pkg.applicationInfo.packageName, 1030 extras, null, null, updateUsers); 1031 if (update) { 1032 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1033 res.pkg.applicationInfo.packageName, 1034 extras, null, null, updateUsers); 1035 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1036 null, null, 1037 res.pkg.applicationInfo.packageName, null, updateUsers); 1038 1039 // treat asec-hosted packages like removable media on upgrade 1040 if (isForwardLocked(res.pkg) || isExternal(res.pkg)) { 1041 if (DEBUG_INSTALL) { 1042 Slog.i(TAG, "upgrading pkg " + res.pkg 1043 + " is ASEC-hosted -> AVAILABLE"); 1044 } 1045 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1046 ArrayList<String> pkgList = new ArrayList<String>(1); 1047 pkgList.add(res.pkg.applicationInfo.packageName); 1048 sendResourcesChangedBroadcast(true, true, 1049 pkgList,uidArray, null); 1050 } 1051 } 1052 if (res.removedInfo.args != null) { 1053 // Remove the replaced package's older resources safely now 1054 deleteOld = true; 1055 } 1056 1057 // Log current value of "unknown sources" setting 1058 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1059 getUnknownSourcesSettings()); 1060 } 1061 // Force a gc to clear up things 1062 Runtime.getRuntime().gc(); 1063 // We delete after a gc for applications on sdcard. 1064 if (deleteOld) { 1065 synchronized (mInstallLock) { 1066 res.removedInfo.args.doPostDeleteLI(true); 1067 } 1068 } 1069 if (args.observer != null) { 1070 try { 1071 Bundle extras = extrasForInstallResult(res); 1072 args.observer.onPackageInstalled(res.name, res.returnCode, 1073 res.returnMsg, extras); 1074 } catch (RemoteException e) { 1075 Slog.i(TAG, "Observer no longer exists."); 1076 } 1077 } 1078 } else { 1079 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1080 } 1081 } break; 1082 case UPDATED_MEDIA_STATUS: { 1083 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1084 boolean reportStatus = msg.arg1 == 1; 1085 boolean doGc = msg.arg2 == 1; 1086 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1087 if (doGc) { 1088 // Force a gc to clear up stale containers. 1089 Runtime.getRuntime().gc(); 1090 } 1091 if (msg.obj != null) { 1092 @SuppressWarnings("unchecked") 1093 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1094 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1095 // Unload containers 1096 unloadAllContainers(args); 1097 } 1098 if (reportStatus) { 1099 try { 1100 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1101 PackageHelper.getMountService().finishMediaUpdate(); 1102 } catch (RemoteException e) { 1103 Log.e(TAG, "MountService not running?"); 1104 } 1105 } 1106 } break; 1107 case WRITE_SETTINGS: { 1108 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1109 synchronized (mPackages) { 1110 removeMessages(WRITE_SETTINGS); 1111 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1112 mSettings.writeLPr(); 1113 mDirtyUsers.clear(); 1114 } 1115 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1116 } break; 1117 case WRITE_PACKAGE_RESTRICTIONS: { 1118 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1119 synchronized (mPackages) { 1120 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1121 for (int userId : mDirtyUsers) { 1122 mSettings.writePackageRestrictionsLPr(userId); 1123 } 1124 mDirtyUsers.clear(); 1125 } 1126 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1127 } break; 1128 case CHECK_PENDING_VERIFICATION: { 1129 final int verificationId = msg.arg1; 1130 final PackageVerificationState state = mPendingVerification.get(verificationId); 1131 1132 if ((state != null) && !state.timeoutExtended()) { 1133 final InstallArgs args = state.getInstallArgs(); 1134 final Uri originUri = Uri.fromFile(args.originFile); 1135 1136 Slog.i(TAG, "Verification timed out for " + originUri); 1137 mPendingVerification.remove(verificationId); 1138 1139 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1140 1141 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1142 Slog.i(TAG, "Continuing with installation of " + originUri); 1143 state.setVerifierResponse(Binder.getCallingUid(), 1144 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1145 broadcastPackageVerified(verificationId, originUri, 1146 PackageManager.VERIFICATION_ALLOW, 1147 state.getInstallArgs().getUser()); 1148 try { 1149 ret = args.copyApk(mContainerService, true); 1150 } catch (RemoteException e) { 1151 Slog.e(TAG, "Could not contact the ContainerService"); 1152 } 1153 } else { 1154 broadcastPackageVerified(verificationId, originUri, 1155 PackageManager.VERIFICATION_REJECT, 1156 state.getInstallArgs().getUser()); 1157 } 1158 1159 processPendingInstall(args, ret); 1160 mHandler.sendEmptyMessage(MCS_UNBIND); 1161 } 1162 break; 1163 } 1164 case PACKAGE_VERIFIED: { 1165 final int verificationId = msg.arg1; 1166 1167 final PackageVerificationState state = mPendingVerification.get(verificationId); 1168 if (state == null) { 1169 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1170 break; 1171 } 1172 1173 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1174 1175 state.setVerifierResponse(response.callerUid, response.code); 1176 1177 if (state.isVerificationComplete()) { 1178 mPendingVerification.remove(verificationId); 1179 1180 final InstallArgs args = state.getInstallArgs(); 1181 final Uri originUri = Uri.fromFile(args.originFile); 1182 1183 int ret; 1184 if (state.isInstallAllowed()) { 1185 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1186 broadcastPackageVerified(verificationId, originUri, 1187 response.code, state.getInstallArgs().getUser()); 1188 try { 1189 ret = args.copyApk(mContainerService, true); 1190 } catch (RemoteException e) { 1191 Slog.e(TAG, "Could not contact the ContainerService"); 1192 } 1193 } else { 1194 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1195 } 1196 1197 processPendingInstall(args, ret); 1198 1199 mHandler.sendEmptyMessage(MCS_UNBIND); 1200 } 1201 1202 break; 1203 } 1204 } 1205 } 1206 } 1207 1208 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1209 Bundle extras = null; 1210 switch (res.returnCode) { 1211 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1212 extras = new Bundle(); 1213 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1214 res.origPermission); 1215 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1216 res.origPackage); 1217 break; 1218 } 1219 } 1220 return extras; 1221 } 1222 1223 void scheduleWriteSettingsLocked() { 1224 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1225 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1226 } 1227 } 1228 1229 void scheduleWritePackageRestrictionsLocked(int userId) { 1230 if (!sUserManager.exists(userId)) return; 1231 mDirtyUsers.add(userId); 1232 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1233 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1234 } 1235 } 1236 1237 public static final PackageManagerService main(Context context, Installer installer, 1238 boolean factoryTest, boolean onlyCore) { 1239 PackageManagerService m = new PackageManagerService(context, installer, 1240 factoryTest, onlyCore); 1241 ServiceManager.addService("package", m); 1242 return m; 1243 } 1244 1245 static String[] splitString(String str, char sep) { 1246 int count = 1; 1247 int i = 0; 1248 while ((i=str.indexOf(sep, i)) >= 0) { 1249 count++; 1250 i++; 1251 } 1252 1253 String[] res = new String[count]; 1254 i=0; 1255 count = 0; 1256 int lastI=0; 1257 while ((i=str.indexOf(sep, i)) >= 0) { 1258 res[count] = str.substring(lastI, i); 1259 count++; 1260 i++; 1261 lastI = i; 1262 } 1263 res[count] = str.substring(lastI, str.length()); 1264 return res; 1265 } 1266 1267 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1268 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1269 Context.DISPLAY_SERVICE); 1270 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1271 } 1272 1273 public PackageManagerService(Context context, Installer installer, 1274 boolean factoryTest, boolean onlyCore) { 1275 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1276 SystemClock.uptimeMillis()); 1277 1278 if (mSdkVersion <= 0) { 1279 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1280 } 1281 1282 mContext = context; 1283 mFactoryTest = factoryTest; 1284 mOnlyCore = onlyCore; 1285 mMetrics = new DisplayMetrics(); 1286 mSettings = new Settings(context); 1287 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1288 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1289 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1290 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1291 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1292 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1293 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1294 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1295 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1296 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1297 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1298 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1299 1300 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1301 if (separateProcesses != null && separateProcesses.length() > 0) { 1302 if ("*".equals(separateProcesses)) { 1303 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1304 mSeparateProcesses = null; 1305 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1306 } else { 1307 mDefParseFlags = 0; 1308 mSeparateProcesses = separateProcesses.split(","); 1309 Slog.w(TAG, "Running with debug.separate_processes: " 1310 + separateProcesses); 1311 } 1312 } else { 1313 mDefParseFlags = 0; 1314 mSeparateProcesses = null; 1315 } 1316 1317 mInstaller = installer; 1318 1319 getDefaultDisplayMetrics(context, mMetrics); 1320 1321 SystemConfig systemConfig = SystemConfig.getInstance(); 1322 mGlobalGids = systemConfig.getGlobalGids(); 1323 mSystemPermissions = systemConfig.getSystemPermissions(); 1324 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1325 1326 synchronized (mInstallLock) { 1327 // writer 1328 synchronized (mPackages) { 1329 mHandlerThread = new ServiceThread(TAG, 1330 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1331 mHandlerThread.start(); 1332 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1333 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1334 1335 File dataDir = Environment.getDataDirectory(); 1336 mAppDataDir = new File(dataDir, "data"); 1337 mAppInstallDir = new File(dataDir, "app"); 1338 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1339 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1340 mUserAppDataDir = new File(dataDir, "user"); 1341 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1342 1343 sUserManager = new UserManagerService(context, this, 1344 mInstallLock, mPackages); 1345 1346 // Propagate permission configuration in to package manager. 1347 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1348 = systemConfig.getPermissions(); 1349 for (int i=0; i<permConfig.size(); i++) { 1350 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1351 BasePermission bp = mSettings.mPermissions.get(perm.name); 1352 if (bp == null) { 1353 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1354 mSettings.mPermissions.put(perm.name, bp); 1355 } 1356 if (perm.gids != null) { 1357 bp.gids = appendInts(bp.gids, perm.gids); 1358 } 1359 } 1360 1361 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1362 for (int i=0; i<libConfig.size(); i++) { 1363 mSharedLibraries.put(libConfig.keyAt(i), 1364 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1365 } 1366 1367 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1368 1369 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1370 mSdkVersion, mOnlyCore); 1371 1372 String customResolverActivity = Resources.getSystem().getString( 1373 R.string.config_customResolverActivity); 1374 if (TextUtils.isEmpty(customResolverActivity)) { 1375 customResolverActivity = null; 1376 } else { 1377 mCustomResolverComponentName = ComponentName.unflattenFromString( 1378 customResolverActivity); 1379 } 1380 1381 long startTime = SystemClock.uptimeMillis(); 1382 1383 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1384 startTime); 1385 1386 // Set flag to monitor and not change apk file paths when 1387 // scanning install directories. 1388 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1389 1390 final HashSet<String> alreadyDexOpted = new HashSet<String>(); 1391 1392 /** 1393 * Add everything in the in the boot class path to the 1394 * list of process files because dexopt will have been run 1395 * if necessary during zygote startup. 1396 */ 1397 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1398 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1399 1400 if (bootClassPath != null) { 1401 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1402 for (String element : bootClassPathElements) { 1403 alreadyDexOpted.add(element); 1404 } 1405 } else { 1406 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1407 } 1408 1409 if (systemServerClassPath != null) { 1410 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1411 for (String element : systemServerClassPathElements) { 1412 alreadyDexOpted.add(element); 1413 } 1414 } else { 1415 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1416 } 1417 1418 boolean didDexOptLibraryOrTool = false; 1419 1420 final List<String> allInstructionSets = getAllInstructionSets(); 1421 final String[] dexCodeInstructionSets = 1422 getDexCodeInstructionSets(allInstructionSets.toArray(new String[allInstructionSets.size()])); 1423 1424 /** 1425 * Ensure all external libraries have had dexopt run on them. 1426 */ 1427 if (mSharedLibraries.size() > 0) { 1428 // NOTE: For now, we're compiling these system "shared libraries" 1429 // (and framework jars) into all available architectures. It's possible 1430 // to compile them only when we come across an app that uses them (there's 1431 // already logic for that in scanPackageLI) but that adds some complexity. 1432 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1433 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1434 final String lib = libEntry.path; 1435 if (lib == null) { 1436 continue; 1437 } 1438 1439 try { 1440 byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null, 1441 dexCodeInstructionSet, 1442 false); 1443 if (dexoptRequired != DexFile.UP_TO_DATE) { 1444 alreadyDexOpted.add(lib); 1445 1446 // The list of "shared libraries" we have at this point is 1447 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1448 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1449 } else { 1450 mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1451 } 1452 didDexOptLibraryOrTool = true; 1453 } 1454 } catch (FileNotFoundException e) { 1455 Slog.w(TAG, "Library not found: " + lib); 1456 } catch (IOException e) { 1457 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1458 + e.getMessage()); 1459 } 1460 } 1461 } 1462 } 1463 1464 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1465 1466 // Gross hack for now: we know this file doesn't contain any 1467 // code, so don't dexopt it to avoid the resulting log spew. 1468 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1469 1470 // Gross hack for now: we know this file is only part of 1471 // the boot class path for art, so don't dexopt it to 1472 // avoid the resulting log spew. 1473 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1474 1475 /** 1476 * And there are a number of commands implemented in Java, which 1477 * we currently need to do the dexopt on so that they can be 1478 * run from a non-root shell. 1479 */ 1480 String[] frameworkFiles = frameworkDir.list(); 1481 if (frameworkFiles != null) { 1482 // TODO: We could compile these only for the most preferred ABI. We should 1483 // first double check that the dex files for these commands are not referenced 1484 // by other system apps. 1485 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1486 for (int i=0; i<frameworkFiles.length; i++) { 1487 File libPath = new File(frameworkDir, frameworkFiles[i]); 1488 String path = libPath.getPath(); 1489 // Skip the file if we already did it. 1490 if (alreadyDexOpted.contains(path)) { 1491 continue; 1492 } 1493 // Skip the file if it is not a type we want to dexopt. 1494 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1495 continue; 1496 } 1497 try { 1498 byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null, 1499 dexCodeInstructionSet, 1500 false); 1501 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1502 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1503 didDexOptLibraryOrTool = true; 1504 } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) { 1505 mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1506 didDexOptLibraryOrTool = true; 1507 } 1508 } catch (FileNotFoundException e) { 1509 Slog.w(TAG, "Jar not found: " + path); 1510 } catch (IOException e) { 1511 Slog.w(TAG, "Exception reading jar: " + path, e); 1512 } 1513 } 1514 } 1515 } 1516 1517 if (didDexOptLibraryOrTool) { 1518 // If we dexopted a library or tool, then something on the system has 1519 // changed. Consider this significant, and wipe away all other 1520 // existing dexopt files to ensure we don't leave any dangling around. 1521 // 1522 // TODO: This should be revisited because it isn't as good an indicator 1523 // as it used to be. It used to include the boot classpath but at some point 1524 // DexFile.isDexOptNeeded started returning false for the boot 1525 // class path files in all cases. It is very possible in a 1526 // small maintenance release update that the library and tool 1527 // jars may be unchanged but APK could be removed resulting in 1528 // unused dalvik-cache files. 1529 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1530 mInstaller.pruneDexCache(dexCodeInstructionSet); 1531 } 1532 1533 // Additionally, delete all dex files from the root directory 1534 // since there shouldn't be any there anyway, unless we're upgrading 1535 // from an older OS version or a build that contained the "old" style 1536 // flat scheme. 1537 mInstaller.pruneDexCache("."); 1538 } 1539 1540 // Collect vendor overlay packages. 1541 // (Do this before scanning any apps.) 1542 // For security and version matching reason, only consider 1543 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1544 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1545 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1546 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode | SCAN_TRUSTED_OVERLAY, 0); 1547 1548 // Find base frameworks (resource packages without code). 1549 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1550 | PackageParser.PARSE_IS_SYSTEM_DIR 1551 | PackageParser.PARSE_IS_PRIVILEGED, 1552 scanMode | SCAN_NO_DEX, 0); 1553 1554 // Collected privileged system packages. 1555 File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1556 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1557 | PackageParser.PARSE_IS_SYSTEM_DIR 1558 | PackageParser.PARSE_IS_PRIVILEGED, scanMode, 0); 1559 1560 // Collect ordinary system packages. 1561 File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1562 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1563 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1564 1565 // Collect all vendor packages. 1566 File vendorAppDir = new File("/vendor/app"); 1567 try { 1568 vendorAppDir = vendorAppDir.getCanonicalFile(); 1569 } catch (IOException e) { 1570 // failed to look up canonical path, continue with original one 1571 } 1572 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1573 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1574 1575 // Collect all OEM packages. 1576 File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1577 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1578 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1579 1580 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1581 mInstaller.moveFiles(); 1582 1583 // Prune any system packages that no longer exist. 1584 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1585 if (!mOnlyCore) { 1586 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1587 while (psit.hasNext()) { 1588 PackageSetting ps = psit.next(); 1589 1590 /* 1591 * If this is not a system app, it can't be a 1592 * disable system app. 1593 */ 1594 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1595 continue; 1596 } 1597 1598 /* 1599 * If the package is scanned, it's not erased. 1600 */ 1601 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1602 if (scannedPkg != null) { 1603 /* 1604 * If the system app is both scanned and in the 1605 * disabled packages list, then it must have been 1606 * added via OTA. Remove it from the currently 1607 * scanned package so the previously user-installed 1608 * application can be scanned. 1609 */ 1610 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1611 Slog.i(TAG, "Expecting better updatd system app for " + ps.name 1612 + "; removing system app"); 1613 removePackageLI(ps, true); 1614 } 1615 1616 continue; 1617 } 1618 1619 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1620 psit.remove(); 1621 String msg = "System package " + ps.name 1622 + " no longer exists; wiping its data"; 1623 reportSettingsProblem(Log.WARN, msg); 1624 removeDataDirsLI(ps.name); 1625 } else { 1626 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1627 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1628 possiblyDeletedUpdatedSystemApps.add(ps.name); 1629 } 1630 } 1631 } 1632 } 1633 1634 //look for any incomplete package installations 1635 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1636 //clean up list 1637 for(int i = 0; i < deletePkgsList.size(); i++) { 1638 //clean up here 1639 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1640 } 1641 //delete tmp files 1642 deleteTempPackageFiles(); 1643 1644 // Remove any shared userIDs that have no associated packages 1645 mSettings.pruneSharedUsersLPw(); 1646 1647 if (!mOnlyCore) { 1648 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 1649 SystemClock.uptimeMillis()); 1650 scanDirLI(mAppInstallDir, 0, scanMode, 0); 1651 1652 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 1653 scanMode, 0); 1654 1655 /** 1656 * Remove disable package settings for any updated system 1657 * apps that were removed via an OTA. If they're not a 1658 * previously-updated app, remove them completely. 1659 * Otherwise, just revoke their system-level permissions. 1660 */ 1661 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 1662 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 1663 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 1664 1665 String msg; 1666 if (deletedPkg == null) { 1667 msg = "Updated system package " + deletedAppName 1668 + " no longer exists; wiping its data"; 1669 removeDataDirsLI(deletedAppName); 1670 } else { 1671 msg = "Updated system app + " + deletedAppName 1672 + " no longer present; removing system privileges for " 1673 + deletedAppName; 1674 1675 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 1676 1677 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 1678 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 1679 } 1680 reportSettingsProblem(Log.WARN, msg); 1681 } 1682 } 1683 1684 // Now that we know all of the shared libraries, update all clients to have 1685 // the correct library paths. 1686 updateAllSharedLibrariesLPw(); 1687 1688 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 1689 // NOTE: We ignore potential failures here during a system scan (like 1690 // the rest of the commands above) because there's precious little we 1691 // can do about it. A settings error is reported, though. 1692 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 1693 false /* force dexopt */, false /* defer dexopt */); 1694 } 1695 1696 // Now that we know all the packages we are keeping, 1697 // read and update their last usage times. 1698 mPackageUsage.readLP(); 1699 1700 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 1701 SystemClock.uptimeMillis()); 1702 Slog.i(TAG, "Time to scan packages: " 1703 + ((SystemClock.uptimeMillis()-startTime)/1000f) 1704 + " seconds"); 1705 1706 // If the platform SDK has changed since the last time we booted, 1707 // we need to re-grant app permission to catch any new ones that 1708 // appear. This is really a hack, and means that apps can in some 1709 // cases get permissions that the user didn't initially explicitly 1710 // allow... it would be nice to have some better way to handle 1711 // this situation. 1712 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 1713 != mSdkVersion; 1714 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 1715 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 1716 + "; regranting permissions for internal storage"); 1717 mSettings.mInternalSdkPlatform = mSdkVersion; 1718 1719 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 1720 | (regrantPermissions 1721 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 1722 : 0)); 1723 1724 // If this is the first boot, and it is a normal boot, then 1725 // we need to initialize the default preferred apps. 1726 if (!mRestoredSettings && !onlyCore) { 1727 mSettings.readDefaultPreferredAppsLPw(this, 0); 1728 } 1729 1730 // If this is first boot after an OTA, and a normal boot, then 1731 // we need to clear code cache directories. 1732 if (!Build.FINGERPRINT.equals(mSettings.mFingerprint) && !onlyCore) { 1733 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 1734 for (String pkgName : mSettings.mPackages.keySet()) { 1735 deleteCodeCacheDirsLI(pkgName); 1736 } 1737 mSettings.mFingerprint = Build.FINGERPRINT; 1738 } 1739 1740 // All the changes are done during package scanning. 1741 mSettings.updateInternalDatabaseVersion(); 1742 1743 // can downgrade to reader 1744 mSettings.writeLPr(); 1745 1746 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 1747 SystemClock.uptimeMillis()); 1748 1749 1750 mRequiredVerifierPackage = getRequiredVerifierLPr(); 1751 } // synchronized (mPackages) 1752 } // synchronized (mInstallLock) 1753 1754 mInstallerService = new PackageInstallerService(context, this, mAppInstallDir); 1755 1756 // Now after opening every single application zip, make sure they 1757 // are all flushed. Not really needed, but keeps things nice and 1758 // tidy. 1759 Runtime.getRuntime().gc(); 1760 } 1761 1762 @Override 1763 public boolean isFirstBoot() { 1764 return !mRestoredSettings; 1765 } 1766 1767 @Override 1768 public boolean isOnlyCoreApps() { 1769 return mOnlyCore; 1770 } 1771 1772 private String getRequiredVerifierLPr() { 1773 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 1774 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 1775 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 1776 1777 String requiredVerifier = null; 1778 1779 final int N = receivers.size(); 1780 for (int i = 0; i < N; i++) { 1781 final ResolveInfo info = receivers.get(i); 1782 1783 if (info.activityInfo == null) { 1784 continue; 1785 } 1786 1787 final String packageName = info.activityInfo.packageName; 1788 1789 final PackageSetting ps = mSettings.mPackages.get(packageName); 1790 if (ps == null) { 1791 continue; 1792 } 1793 1794 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1795 if (!gp.grantedPermissions 1796 .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) { 1797 continue; 1798 } 1799 1800 if (requiredVerifier != null) { 1801 throw new RuntimeException("There can be only one required verifier"); 1802 } 1803 1804 requiredVerifier = packageName; 1805 } 1806 1807 return requiredVerifier; 1808 } 1809 1810 @Override 1811 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 1812 throws RemoteException { 1813 try { 1814 return super.onTransact(code, data, reply, flags); 1815 } catch (RuntimeException e) { 1816 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 1817 Slog.wtf(TAG, "Package Manager Crash", e); 1818 } 1819 throw e; 1820 } 1821 } 1822 1823 void cleanupInstallFailedPackage(PackageSetting ps) { 1824 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name); 1825 removeDataDirsLI(ps.name); 1826 1827 // TODO: try cleaning up codePath directory contents first, since it 1828 // might be a cluster 1829 1830 if (ps.codePath != null) { 1831 if (!ps.codePath.delete()) { 1832 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath); 1833 } 1834 } 1835 if (ps.resourcePath != null) { 1836 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) { 1837 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath); 1838 } 1839 } 1840 mSettings.removePackageLPw(ps.name); 1841 } 1842 1843 static int[] appendInts(int[] cur, int[] add) { 1844 if (add == null) return cur; 1845 if (cur == null) return add; 1846 final int N = add.length; 1847 for (int i=0; i<N; i++) { 1848 cur = appendInt(cur, add[i]); 1849 } 1850 return cur; 1851 } 1852 1853 static int[] removeInts(int[] cur, int[] rem) { 1854 if (rem == null) return cur; 1855 if (cur == null) return cur; 1856 final int N = rem.length; 1857 for (int i=0; i<N; i++) { 1858 cur = removeInt(cur, rem[i]); 1859 } 1860 return cur; 1861 } 1862 1863 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 1864 if (!sUserManager.exists(userId)) return null; 1865 final PackageSetting ps = (PackageSetting) p.mExtras; 1866 if (ps == null) { 1867 return null; 1868 } 1869 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1870 final PackageUserState state = ps.readUserState(userId); 1871 return PackageParser.generatePackageInfo(p, gp.gids, flags, 1872 ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions, 1873 state, userId); 1874 } 1875 1876 @Override 1877 public boolean isPackageAvailable(String packageName, int userId) { 1878 if (!sUserManager.exists(userId)) return false; 1879 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available"); 1880 synchronized (mPackages) { 1881 PackageParser.Package p = mPackages.get(packageName); 1882 if (p != null) { 1883 final PackageSetting ps = (PackageSetting) p.mExtras; 1884 if (ps != null) { 1885 final PackageUserState state = ps.readUserState(userId); 1886 if (state != null) { 1887 return PackageParser.isAvailable(state); 1888 } 1889 } 1890 } 1891 } 1892 return false; 1893 } 1894 1895 @Override 1896 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 1897 if (!sUserManager.exists(userId)) return null; 1898 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info"); 1899 // reader 1900 synchronized (mPackages) { 1901 PackageParser.Package p = mPackages.get(packageName); 1902 if (DEBUG_PACKAGE_INFO) 1903 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 1904 if (p != null) { 1905 return generatePackageInfo(p, flags, userId); 1906 } 1907 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 1908 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 1909 } 1910 } 1911 return null; 1912 } 1913 1914 @Override 1915 public String[] currentToCanonicalPackageNames(String[] names) { 1916 String[] out = new String[names.length]; 1917 // reader 1918 synchronized (mPackages) { 1919 for (int i=names.length-1; i>=0; i--) { 1920 PackageSetting ps = mSettings.mPackages.get(names[i]); 1921 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 1922 } 1923 } 1924 return out; 1925 } 1926 1927 @Override 1928 public String[] canonicalToCurrentPackageNames(String[] names) { 1929 String[] out = new String[names.length]; 1930 // reader 1931 synchronized (mPackages) { 1932 for (int i=names.length-1; i>=0; i--) { 1933 String cur = mSettings.mRenamedPackages.get(names[i]); 1934 out[i] = cur != null ? cur : names[i]; 1935 } 1936 } 1937 return out; 1938 } 1939 1940 @Override 1941 public int getPackageUid(String packageName, int userId) { 1942 if (!sUserManager.exists(userId)) return -1; 1943 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid"); 1944 // reader 1945 synchronized (mPackages) { 1946 PackageParser.Package p = mPackages.get(packageName); 1947 if(p != null) { 1948 return UserHandle.getUid(userId, p.applicationInfo.uid); 1949 } 1950 PackageSetting ps = mSettings.mPackages.get(packageName); 1951 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 1952 return -1; 1953 } 1954 p = ps.pkg; 1955 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 1956 } 1957 } 1958 1959 @Override 1960 public int[] getPackageGids(String packageName) { 1961 // reader 1962 synchronized (mPackages) { 1963 PackageParser.Package p = mPackages.get(packageName); 1964 if (DEBUG_PACKAGE_INFO) 1965 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 1966 if (p != null) { 1967 final PackageSetting ps = (PackageSetting)p.mExtras; 1968 return ps.getGids(); 1969 } 1970 } 1971 // stupid thing to indicate an error. 1972 return new int[0]; 1973 } 1974 1975 static final PermissionInfo generatePermissionInfo( 1976 BasePermission bp, int flags) { 1977 if (bp.perm != null) { 1978 return PackageParser.generatePermissionInfo(bp.perm, flags); 1979 } 1980 PermissionInfo pi = new PermissionInfo(); 1981 pi.name = bp.name; 1982 pi.packageName = bp.sourcePackage; 1983 pi.nonLocalizedLabel = bp.name; 1984 pi.protectionLevel = bp.protectionLevel; 1985 return pi; 1986 } 1987 1988 @Override 1989 public PermissionInfo getPermissionInfo(String name, int flags) { 1990 // reader 1991 synchronized (mPackages) { 1992 final BasePermission p = mSettings.mPermissions.get(name); 1993 if (p != null) { 1994 return generatePermissionInfo(p, flags); 1995 } 1996 return null; 1997 } 1998 } 1999 2000 @Override 2001 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2002 // reader 2003 synchronized (mPackages) { 2004 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2005 for (BasePermission p : mSettings.mPermissions.values()) { 2006 if (group == null) { 2007 if (p.perm == null || p.perm.info.group == null) { 2008 out.add(generatePermissionInfo(p, flags)); 2009 } 2010 } else { 2011 if (p.perm != null && group.equals(p.perm.info.group)) { 2012 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2013 } 2014 } 2015 } 2016 2017 if (out.size() > 0) { 2018 return out; 2019 } 2020 return mPermissionGroups.containsKey(group) ? out : null; 2021 } 2022 } 2023 2024 @Override 2025 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2026 // reader 2027 synchronized (mPackages) { 2028 return PackageParser.generatePermissionGroupInfo( 2029 mPermissionGroups.get(name), flags); 2030 } 2031 } 2032 2033 @Override 2034 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2035 // reader 2036 synchronized (mPackages) { 2037 final int N = mPermissionGroups.size(); 2038 ArrayList<PermissionGroupInfo> out 2039 = new ArrayList<PermissionGroupInfo>(N); 2040 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2041 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2042 } 2043 return out; 2044 } 2045 } 2046 2047 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2048 int userId) { 2049 if (!sUserManager.exists(userId)) return null; 2050 PackageSetting ps = mSettings.mPackages.get(packageName); 2051 if (ps != null) { 2052 if (ps.pkg == null) { 2053 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2054 flags, userId); 2055 if (pInfo != null) { 2056 return pInfo.applicationInfo; 2057 } 2058 return null; 2059 } 2060 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2061 ps.readUserState(userId), userId); 2062 } 2063 return null; 2064 } 2065 2066 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2067 int userId) { 2068 if (!sUserManager.exists(userId)) return null; 2069 PackageSetting ps = mSettings.mPackages.get(packageName); 2070 if (ps != null) { 2071 PackageParser.Package pkg = ps.pkg; 2072 if (pkg == null) { 2073 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2074 return null; 2075 } 2076 // Only data remains, so we aren't worried about code paths 2077 pkg = new PackageParser.Package(packageName); 2078 pkg.applicationInfo.packageName = packageName; 2079 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2080 pkg.applicationInfo.dataDir = 2081 getDataPathForPackage(packageName, 0).getPath(); 2082 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2083 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2084 } 2085 return generatePackageInfo(pkg, flags, userId); 2086 } 2087 return null; 2088 } 2089 2090 @Override 2091 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2092 if (!sUserManager.exists(userId)) return null; 2093 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info"); 2094 // writer 2095 synchronized (mPackages) { 2096 PackageParser.Package p = mPackages.get(packageName); 2097 if (DEBUG_PACKAGE_INFO) Log.v( 2098 TAG, "getApplicationInfo " + packageName 2099 + ": " + p); 2100 if (p != null) { 2101 PackageSetting ps = mSettings.mPackages.get(packageName); 2102 if (ps == null) return null; 2103 // Note: isEnabledLP() does not apply here - always return info 2104 return PackageParser.generateApplicationInfo( 2105 p, flags, ps.readUserState(userId), userId); 2106 } 2107 if ("android".equals(packageName)||"system".equals(packageName)) { 2108 return mAndroidApplication; 2109 } 2110 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2111 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2112 } 2113 } 2114 return null; 2115 } 2116 2117 2118 @Override 2119 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2120 mContext.enforceCallingOrSelfPermission( 2121 android.Manifest.permission.CLEAR_APP_CACHE, null); 2122 // Queue up an async operation since clearing cache may take a little while. 2123 mHandler.post(new Runnable() { 2124 public void run() { 2125 mHandler.removeCallbacks(this); 2126 int retCode = -1; 2127 synchronized (mInstallLock) { 2128 retCode = mInstaller.freeCache(freeStorageSize); 2129 if (retCode < 0) { 2130 Slog.w(TAG, "Couldn't clear application caches"); 2131 } 2132 } 2133 if (observer != null) { 2134 try { 2135 observer.onRemoveCompleted(null, (retCode >= 0)); 2136 } catch (RemoteException e) { 2137 Slog.w(TAG, "RemoveException when invoking call back"); 2138 } 2139 } 2140 } 2141 }); 2142 } 2143 2144 @Override 2145 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2146 mContext.enforceCallingOrSelfPermission( 2147 android.Manifest.permission.CLEAR_APP_CACHE, null); 2148 // Queue up an async operation since clearing cache may take a little while. 2149 mHandler.post(new Runnable() { 2150 public void run() { 2151 mHandler.removeCallbacks(this); 2152 int retCode = -1; 2153 synchronized (mInstallLock) { 2154 retCode = mInstaller.freeCache(freeStorageSize); 2155 if (retCode < 0) { 2156 Slog.w(TAG, "Couldn't clear application caches"); 2157 } 2158 } 2159 if(pi != null) { 2160 try { 2161 // Callback via pending intent 2162 int code = (retCode >= 0) ? 1 : 0; 2163 pi.sendIntent(null, code, null, 2164 null, null); 2165 } catch (SendIntentException e1) { 2166 Slog.i(TAG, "Failed to send pending intent"); 2167 } 2168 } 2169 } 2170 }); 2171 } 2172 2173 void freeStorage(long freeStorageSize) throws IOException { 2174 synchronized (mInstallLock) { 2175 if (mInstaller.freeCache(freeStorageSize) < 0) { 2176 throw new IOException("Failed to free enough space"); 2177 } 2178 } 2179 } 2180 2181 @Override 2182 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2183 if (!sUserManager.exists(userId)) return null; 2184 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info"); 2185 synchronized (mPackages) { 2186 PackageParser.Activity a = mActivities.mActivities.get(component); 2187 2188 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2189 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2190 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2191 if (ps == null) return null; 2192 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2193 userId); 2194 } 2195 if (mResolveComponentName.equals(component)) { 2196 return mResolveActivity; 2197 } 2198 } 2199 return null; 2200 } 2201 2202 @Override 2203 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2204 String resolvedType) { 2205 synchronized (mPackages) { 2206 PackageParser.Activity a = mActivities.mActivities.get(component); 2207 if (a == null) { 2208 return false; 2209 } 2210 for (int i=0; i<a.intents.size(); i++) { 2211 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2212 intent.getData(), intent.getCategories(), TAG) >= 0) { 2213 return true; 2214 } 2215 } 2216 return false; 2217 } 2218 } 2219 2220 @Override 2221 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2222 if (!sUserManager.exists(userId)) return null; 2223 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info"); 2224 synchronized (mPackages) { 2225 PackageParser.Activity a = mReceivers.mActivities.get(component); 2226 if (DEBUG_PACKAGE_INFO) Log.v( 2227 TAG, "getReceiverInfo " + component + ": " + a); 2228 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2229 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2230 if (ps == null) return null; 2231 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2232 userId); 2233 } 2234 } 2235 return null; 2236 } 2237 2238 @Override 2239 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2240 if (!sUserManager.exists(userId)) return null; 2241 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info"); 2242 synchronized (mPackages) { 2243 PackageParser.Service s = mServices.mServices.get(component); 2244 if (DEBUG_PACKAGE_INFO) Log.v( 2245 TAG, "getServiceInfo " + component + ": " + s); 2246 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2247 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2248 if (ps == null) return null; 2249 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2250 userId); 2251 } 2252 } 2253 return null; 2254 } 2255 2256 @Override 2257 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2258 if (!sUserManager.exists(userId)) return null; 2259 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info"); 2260 synchronized (mPackages) { 2261 PackageParser.Provider p = mProviders.mProviders.get(component); 2262 if (DEBUG_PACKAGE_INFO) Log.v( 2263 TAG, "getProviderInfo " + component + ": " + p); 2264 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2265 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2266 if (ps == null) return null; 2267 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2268 userId); 2269 } 2270 } 2271 return null; 2272 } 2273 2274 @Override 2275 public String[] getSystemSharedLibraryNames() { 2276 Set<String> libSet; 2277 synchronized (mPackages) { 2278 libSet = mSharedLibraries.keySet(); 2279 int size = libSet.size(); 2280 if (size > 0) { 2281 String[] libs = new String[size]; 2282 libSet.toArray(libs); 2283 return libs; 2284 } 2285 } 2286 return null; 2287 } 2288 2289 @Override 2290 public FeatureInfo[] getSystemAvailableFeatures() { 2291 Collection<FeatureInfo> featSet; 2292 synchronized (mPackages) { 2293 featSet = mAvailableFeatures.values(); 2294 int size = featSet.size(); 2295 if (size > 0) { 2296 FeatureInfo[] features = new FeatureInfo[size+1]; 2297 featSet.toArray(features); 2298 FeatureInfo fi = new FeatureInfo(); 2299 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2300 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2301 features[size] = fi; 2302 return features; 2303 } 2304 } 2305 return null; 2306 } 2307 2308 @Override 2309 public boolean hasSystemFeature(String name) { 2310 synchronized (mPackages) { 2311 return mAvailableFeatures.containsKey(name); 2312 } 2313 } 2314 2315 private void checkValidCaller(int uid, int userId) { 2316 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2317 return; 2318 2319 throw new SecurityException("Caller uid=" + uid 2320 + " is not privileged to communicate with user=" + userId); 2321 } 2322 2323 @Override 2324 public int checkPermission(String permName, String pkgName) { 2325 synchronized (mPackages) { 2326 PackageParser.Package p = mPackages.get(pkgName); 2327 if (p != null && p.mExtras != null) { 2328 PackageSetting ps = (PackageSetting)p.mExtras; 2329 if (ps.sharedUser != null) { 2330 if (ps.sharedUser.grantedPermissions.contains(permName)) { 2331 return PackageManager.PERMISSION_GRANTED; 2332 } 2333 } else if (ps.grantedPermissions.contains(permName)) { 2334 return PackageManager.PERMISSION_GRANTED; 2335 } 2336 } 2337 } 2338 return PackageManager.PERMISSION_DENIED; 2339 } 2340 2341 @Override 2342 public int checkUidPermission(String permName, int uid) { 2343 synchronized (mPackages) { 2344 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2345 if (obj != null) { 2346 GrantedPermissions gp = (GrantedPermissions)obj; 2347 if (gp.grantedPermissions.contains(permName)) { 2348 return PackageManager.PERMISSION_GRANTED; 2349 } 2350 } else { 2351 HashSet<String> perms = mSystemPermissions.get(uid); 2352 if (perms != null && perms.contains(permName)) { 2353 return PackageManager.PERMISSION_GRANTED; 2354 } 2355 } 2356 } 2357 return PackageManager.PERMISSION_DENIED; 2358 } 2359 2360 /** 2361 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2362 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2363 * @param message the message to log on security exception 2364 */ 2365 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2366 String message) { 2367 if (userId < 0) { 2368 throw new IllegalArgumentException("Invalid userId " + userId); 2369 } 2370 if (userId == UserHandle.getUserId(callingUid)) return; 2371 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2372 if (requireFullPermission) { 2373 mContext.enforceCallingOrSelfPermission( 2374 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2375 } else { 2376 try { 2377 mContext.enforceCallingOrSelfPermission( 2378 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2379 } catch (SecurityException se) { 2380 mContext.enforceCallingOrSelfPermission( 2381 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2382 } 2383 } 2384 } 2385 } 2386 2387 private BasePermission findPermissionTreeLP(String permName) { 2388 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2389 if (permName.startsWith(bp.name) && 2390 permName.length() > bp.name.length() && 2391 permName.charAt(bp.name.length()) == '.') { 2392 return bp; 2393 } 2394 } 2395 return null; 2396 } 2397 2398 private BasePermission checkPermissionTreeLP(String permName) { 2399 if (permName != null) { 2400 BasePermission bp = findPermissionTreeLP(permName); 2401 if (bp != null) { 2402 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2403 return bp; 2404 } 2405 throw new SecurityException("Calling uid " 2406 + Binder.getCallingUid() 2407 + " is not allowed to add to permission tree " 2408 + bp.name + " owned by uid " + bp.uid); 2409 } 2410 } 2411 throw new SecurityException("No permission tree found for " + permName); 2412 } 2413 2414 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2415 if (s1 == null) { 2416 return s2 == null; 2417 } 2418 if (s2 == null) { 2419 return false; 2420 } 2421 if (s1.getClass() != s2.getClass()) { 2422 return false; 2423 } 2424 return s1.equals(s2); 2425 } 2426 2427 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2428 if (pi1.icon != pi2.icon) return false; 2429 if (pi1.logo != pi2.logo) return false; 2430 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2431 if (!compareStrings(pi1.name, pi2.name)) return false; 2432 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2433 // We'll take care of setting this one. 2434 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2435 // These are not currently stored in settings. 2436 //if (!compareStrings(pi1.group, pi2.group)) return false; 2437 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2438 //if (pi1.labelRes != pi2.labelRes) return false; 2439 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2440 return true; 2441 } 2442 2443 int permissionInfoFootprint(PermissionInfo info) { 2444 int size = info.name.length(); 2445 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2446 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2447 return size; 2448 } 2449 2450 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2451 int size = 0; 2452 for (BasePermission perm : mSettings.mPermissions.values()) { 2453 if (perm.uid == tree.uid) { 2454 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2455 } 2456 } 2457 return size; 2458 } 2459 2460 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2461 // We calculate the max size of permissions defined by this uid and throw 2462 // if that plus the size of 'info' would exceed our stated maximum. 2463 if (tree.uid != Process.SYSTEM_UID) { 2464 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2465 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2466 throw new SecurityException("Permission tree size cap exceeded"); 2467 } 2468 } 2469 } 2470 2471 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2472 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2473 throw new SecurityException("Label must be specified in permission"); 2474 } 2475 BasePermission tree = checkPermissionTreeLP(info.name); 2476 BasePermission bp = mSettings.mPermissions.get(info.name); 2477 boolean added = bp == null; 2478 boolean changed = true; 2479 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2480 if (added) { 2481 enforcePermissionCapLocked(info, tree); 2482 bp = new BasePermission(info.name, tree.sourcePackage, 2483 BasePermission.TYPE_DYNAMIC); 2484 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2485 throw new SecurityException( 2486 "Not allowed to modify non-dynamic permission " 2487 + info.name); 2488 } else { 2489 if (bp.protectionLevel == fixedLevel 2490 && bp.perm.owner.equals(tree.perm.owner) 2491 && bp.uid == tree.uid 2492 && comparePermissionInfos(bp.perm.info, info)) { 2493 changed = false; 2494 } 2495 } 2496 bp.protectionLevel = fixedLevel; 2497 info = new PermissionInfo(info); 2498 info.protectionLevel = fixedLevel; 2499 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 2500 bp.perm.info.packageName = tree.perm.info.packageName; 2501 bp.uid = tree.uid; 2502 if (added) { 2503 mSettings.mPermissions.put(info.name, bp); 2504 } 2505 if (changed) { 2506 if (!async) { 2507 mSettings.writeLPr(); 2508 } else { 2509 scheduleWriteSettingsLocked(); 2510 } 2511 } 2512 return added; 2513 } 2514 2515 @Override 2516 public boolean addPermission(PermissionInfo info) { 2517 synchronized (mPackages) { 2518 return addPermissionLocked(info, false); 2519 } 2520 } 2521 2522 @Override 2523 public boolean addPermissionAsync(PermissionInfo info) { 2524 synchronized (mPackages) { 2525 return addPermissionLocked(info, true); 2526 } 2527 } 2528 2529 @Override 2530 public void removePermission(String name) { 2531 synchronized (mPackages) { 2532 checkPermissionTreeLP(name); 2533 BasePermission bp = mSettings.mPermissions.get(name); 2534 if (bp != null) { 2535 if (bp.type != BasePermission.TYPE_DYNAMIC) { 2536 throw new SecurityException( 2537 "Not allowed to modify non-dynamic permission " 2538 + name); 2539 } 2540 mSettings.mPermissions.remove(name); 2541 mSettings.writeLPr(); 2542 } 2543 } 2544 } 2545 2546 private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) { 2547 int index = pkg.requestedPermissions.indexOf(bp.name); 2548 if (index == -1) { 2549 throw new SecurityException("Package " + pkg.packageName 2550 + " has not requested permission " + bp.name); 2551 } 2552 boolean isNormal = 2553 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2554 == PermissionInfo.PROTECTION_NORMAL); 2555 boolean isDangerous = 2556 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2557 == PermissionInfo.PROTECTION_DANGEROUS); 2558 boolean isDevelopment = 2559 ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0); 2560 2561 if (!isNormal && !isDangerous && !isDevelopment) { 2562 throw new SecurityException("Permission " + bp.name 2563 + " is not a changeable permission type"); 2564 } 2565 2566 if (isNormal || isDangerous) { 2567 if (pkg.requestedPermissionsRequired.get(index)) { 2568 throw new SecurityException("Can't change " + bp.name 2569 + ". It is required by the application"); 2570 } 2571 } 2572 } 2573 2574 @Override 2575 public void grantPermission(String packageName, String permissionName) { 2576 mContext.enforceCallingOrSelfPermission( 2577 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2578 synchronized (mPackages) { 2579 final PackageParser.Package pkg = mPackages.get(packageName); 2580 if (pkg == null) { 2581 throw new IllegalArgumentException("Unknown package: " + packageName); 2582 } 2583 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2584 if (bp == null) { 2585 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2586 } 2587 2588 checkGrantRevokePermissions(pkg, bp); 2589 2590 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2591 if (ps == null) { 2592 return; 2593 } 2594 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2595 if (gp.grantedPermissions.add(permissionName)) { 2596 if (ps.haveGids) { 2597 gp.gids = appendInts(gp.gids, bp.gids); 2598 } 2599 mSettings.writeLPr(); 2600 } 2601 } 2602 } 2603 2604 @Override 2605 public void revokePermission(String packageName, String permissionName) { 2606 int changedAppId = -1; 2607 2608 synchronized (mPackages) { 2609 final PackageParser.Package pkg = mPackages.get(packageName); 2610 if (pkg == null) { 2611 throw new IllegalArgumentException("Unknown package: " + packageName); 2612 } 2613 if (pkg.applicationInfo.uid != Binder.getCallingUid()) { 2614 mContext.enforceCallingOrSelfPermission( 2615 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2616 } 2617 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2618 if (bp == null) { 2619 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2620 } 2621 2622 checkGrantRevokePermissions(pkg, bp); 2623 2624 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2625 if (ps == null) { 2626 return; 2627 } 2628 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2629 if (gp.grantedPermissions.remove(permissionName)) { 2630 gp.grantedPermissions.remove(permissionName); 2631 if (ps.haveGids) { 2632 gp.gids = removeInts(gp.gids, bp.gids); 2633 } 2634 mSettings.writeLPr(); 2635 changedAppId = ps.appId; 2636 } 2637 } 2638 2639 if (changedAppId >= 0) { 2640 // We changed the perm on someone, kill its processes. 2641 IActivityManager am = ActivityManagerNative.getDefault(); 2642 if (am != null) { 2643 final int callingUserId = UserHandle.getCallingUserId(); 2644 final long ident = Binder.clearCallingIdentity(); 2645 try { 2646 //XXX we should only revoke for the calling user's app permissions, 2647 // but for now we impact all users. 2648 //am.killUid(UserHandle.getUid(callingUserId, changedAppId), 2649 // "revoke " + permissionName); 2650 int[] users = sUserManager.getUserIds(); 2651 for (int user : users) { 2652 am.killUid(UserHandle.getUid(user, changedAppId), 2653 "revoke " + permissionName); 2654 } 2655 } catch (RemoteException e) { 2656 } finally { 2657 Binder.restoreCallingIdentity(ident); 2658 } 2659 } 2660 } 2661 } 2662 2663 @Override 2664 public boolean isProtectedBroadcast(String actionName) { 2665 synchronized (mPackages) { 2666 return mProtectedBroadcasts.contains(actionName); 2667 } 2668 } 2669 2670 @Override 2671 public int checkSignatures(String pkg1, String pkg2) { 2672 synchronized (mPackages) { 2673 final PackageParser.Package p1 = mPackages.get(pkg1); 2674 final PackageParser.Package p2 = mPackages.get(pkg2); 2675 if (p1 == null || p1.mExtras == null 2676 || p2 == null || p2.mExtras == null) { 2677 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2678 } 2679 return compareSignatures(p1.mSignatures, p2.mSignatures); 2680 } 2681 } 2682 2683 @Override 2684 public int checkUidSignatures(int uid1, int uid2) { 2685 // Map to base uids. 2686 uid1 = UserHandle.getAppId(uid1); 2687 uid2 = UserHandle.getAppId(uid2); 2688 // reader 2689 synchronized (mPackages) { 2690 Signature[] s1; 2691 Signature[] s2; 2692 Object obj = mSettings.getUserIdLPr(uid1); 2693 if (obj != null) { 2694 if (obj instanceof SharedUserSetting) { 2695 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 2696 } else if (obj instanceof PackageSetting) { 2697 s1 = ((PackageSetting)obj).signatures.mSignatures; 2698 } else { 2699 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2700 } 2701 } else { 2702 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2703 } 2704 obj = mSettings.getUserIdLPr(uid2); 2705 if (obj != null) { 2706 if (obj instanceof SharedUserSetting) { 2707 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 2708 } else if (obj instanceof PackageSetting) { 2709 s2 = ((PackageSetting)obj).signatures.mSignatures; 2710 } else { 2711 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2712 } 2713 } else { 2714 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2715 } 2716 return compareSignatures(s1, s2); 2717 } 2718 } 2719 2720 /** 2721 * Compares two sets of signatures. Returns: 2722 * <br /> 2723 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 2724 * <br /> 2725 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 2726 * <br /> 2727 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 2728 * <br /> 2729 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 2730 * <br /> 2731 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 2732 */ 2733 static int compareSignatures(Signature[] s1, Signature[] s2) { 2734 if (s1 == null) { 2735 return s2 == null 2736 ? PackageManager.SIGNATURE_NEITHER_SIGNED 2737 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 2738 } 2739 2740 if (s2 == null) { 2741 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 2742 } 2743 2744 if (s1.length != s2.length) { 2745 return PackageManager.SIGNATURE_NO_MATCH; 2746 } 2747 2748 // Since both signature sets are of size 1, we can compare without HashSets. 2749 if (s1.length == 1) { 2750 return s1[0].equals(s2[0]) ? 2751 PackageManager.SIGNATURE_MATCH : 2752 PackageManager.SIGNATURE_NO_MATCH; 2753 } 2754 2755 HashSet<Signature> set1 = new HashSet<Signature>(); 2756 for (Signature sig : s1) { 2757 set1.add(sig); 2758 } 2759 HashSet<Signature> set2 = new HashSet<Signature>(); 2760 for (Signature sig : s2) { 2761 set2.add(sig); 2762 } 2763 // Make sure s2 contains all signatures in s1. 2764 if (set1.equals(set2)) { 2765 return PackageManager.SIGNATURE_MATCH; 2766 } 2767 return PackageManager.SIGNATURE_NO_MATCH; 2768 } 2769 2770 /** 2771 * If the database version for this type of package (internal storage or 2772 * external storage) is less than the version where package signatures 2773 * were updated, return true. 2774 */ 2775 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2776 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 2777 DatabaseVersion.SIGNATURE_END_ENTITY)) 2778 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 2779 DatabaseVersion.SIGNATURE_END_ENTITY)); 2780 } 2781 2782 /** 2783 * Used for backward compatibility to make sure any packages with 2784 * certificate chains get upgraded to the new style. {@code existingSigs} 2785 * will be in the old format (since they were stored on disk from before the 2786 * system upgrade) and {@code scannedSigs} will be in the newer format. 2787 */ 2788 private int compareSignaturesCompat(PackageSignatures existingSigs, 2789 PackageParser.Package scannedPkg) { 2790 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 2791 return PackageManager.SIGNATURE_NO_MATCH; 2792 } 2793 2794 HashSet<Signature> existingSet = new HashSet<Signature>(); 2795 for (Signature sig : existingSigs.mSignatures) { 2796 existingSet.add(sig); 2797 } 2798 HashSet<Signature> scannedCompatSet = new HashSet<Signature>(); 2799 for (Signature sig : scannedPkg.mSignatures) { 2800 try { 2801 Signature[] chainSignatures = sig.getChainSignatures(); 2802 for (Signature chainSig : chainSignatures) { 2803 scannedCompatSet.add(chainSig); 2804 } 2805 } catch (CertificateEncodingException e) { 2806 scannedCompatSet.add(sig); 2807 } 2808 } 2809 /* 2810 * Make sure the expanded scanned set contains all signatures in the 2811 * existing one. 2812 */ 2813 if (scannedCompatSet.equals(existingSet)) { 2814 // Migrate the old signatures to the new scheme. 2815 existingSigs.assignSignatures(scannedPkg.mSignatures); 2816 // The new KeySets will be re-added later in the scanning process. 2817 synchronized (mPackages) { 2818 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 2819 } 2820 return PackageManager.SIGNATURE_MATCH; 2821 } 2822 return PackageManager.SIGNATURE_NO_MATCH; 2823 } 2824 2825 @Override 2826 public String[] getPackagesForUid(int uid) { 2827 uid = UserHandle.getAppId(uid); 2828 // reader 2829 synchronized (mPackages) { 2830 Object obj = mSettings.getUserIdLPr(uid); 2831 if (obj instanceof SharedUserSetting) { 2832 final SharedUserSetting sus = (SharedUserSetting) obj; 2833 final int N = sus.packages.size(); 2834 final String[] res = new String[N]; 2835 final Iterator<PackageSetting> it = sus.packages.iterator(); 2836 int i = 0; 2837 while (it.hasNext()) { 2838 res[i++] = it.next().name; 2839 } 2840 return res; 2841 } else if (obj instanceof PackageSetting) { 2842 final PackageSetting ps = (PackageSetting) obj; 2843 return new String[] { ps.name }; 2844 } 2845 } 2846 return null; 2847 } 2848 2849 @Override 2850 public String getNameForUid(int uid) { 2851 // reader 2852 synchronized (mPackages) { 2853 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2854 if (obj instanceof SharedUserSetting) { 2855 final SharedUserSetting sus = (SharedUserSetting) obj; 2856 return sus.name + ":" + sus.userId; 2857 } else if (obj instanceof PackageSetting) { 2858 final PackageSetting ps = (PackageSetting) obj; 2859 return ps.name; 2860 } 2861 } 2862 return null; 2863 } 2864 2865 @Override 2866 public int getUidForSharedUser(String sharedUserName) { 2867 if(sharedUserName == null) { 2868 return -1; 2869 } 2870 // reader 2871 synchronized (mPackages) { 2872 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false); 2873 if (suid == null) { 2874 return -1; 2875 } 2876 return suid.userId; 2877 } 2878 } 2879 2880 @Override 2881 public int getFlagsForUid(int uid) { 2882 synchronized (mPackages) { 2883 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2884 if (obj instanceof SharedUserSetting) { 2885 final SharedUserSetting sus = (SharedUserSetting) obj; 2886 return sus.pkgFlags; 2887 } else if (obj instanceof PackageSetting) { 2888 final PackageSetting ps = (PackageSetting) obj; 2889 return ps.pkgFlags; 2890 } 2891 } 2892 return 0; 2893 } 2894 2895 @Override 2896 public String[] getAppOpPermissionPackages(String permissionName) { 2897 synchronized (mPackages) { 2898 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 2899 if (pkgs == null) { 2900 return null; 2901 } 2902 return pkgs.toArray(new String[pkgs.size()]); 2903 } 2904 } 2905 2906 @Override 2907 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 2908 int flags, int userId) { 2909 if (!sUserManager.exists(userId)) return null; 2910 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent"); 2911 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2912 return chooseBestActivity(intent, resolvedType, flags, query, userId); 2913 } 2914 2915 @Override 2916 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 2917 IntentFilter filter, int match, ComponentName activity) { 2918 final int userId = UserHandle.getCallingUserId(); 2919 if (DEBUG_PREFERRED) { 2920 Log.v(TAG, "setLastChosenActivity intent=" + intent 2921 + " resolvedType=" + resolvedType 2922 + " flags=" + flags 2923 + " filter=" + filter 2924 + " match=" + match 2925 + " activity=" + activity); 2926 filter.dump(new PrintStreamPrinter(System.out), " "); 2927 } 2928 intent.setComponent(null); 2929 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2930 // Find any earlier preferred or last chosen entries and nuke them 2931 findPreferredActivity(intent, resolvedType, 2932 flags, query, 0, false, true, false, userId); 2933 // Add the new activity as the last chosen for this filter 2934 addPreferredActivityInternal(filter, match, null, activity, false, userId, 2935 "Setting last chosen"); 2936 } 2937 2938 @Override 2939 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 2940 final int userId = UserHandle.getCallingUserId(); 2941 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 2942 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2943 return findPreferredActivity(intent, resolvedType, flags, query, 0, 2944 false, false, false, userId); 2945 } 2946 2947 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 2948 int flags, List<ResolveInfo> query, int userId) { 2949 if (query != null) { 2950 final int N = query.size(); 2951 if (N == 1) { 2952 return query.get(0); 2953 } else if (N > 1) { 2954 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 2955 // If there is more than one activity with the same priority, 2956 // then let the user decide between them. 2957 ResolveInfo r0 = query.get(0); 2958 ResolveInfo r1 = query.get(1); 2959 if (DEBUG_INTENT_MATCHING || debug) { 2960 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 2961 + r1.activityInfo.name + "=" + r1.priority); 2962 } 2963 // If the first activity has a higher priority, or a different 2964 // default, then it is always desireable to pick it. 2965 if (r0.priority != r1.priority 2966 || r0.preferredOrder != r1.preferredOrder 2967 || r0.isDefault != r1.isDefault) { 2968 return query.get(0); 2969 } 2970 // If we have saved a preference for a preferred activity for 2971 // this Intent, use that. 2972 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 2973 flags, query, r0.priority, true, false, debug, userId); 2974 if (ri != null) { 2975 return ri; 2976 } 2977 if (userId != 0) { 2978 ri = new ResolveInfo(mResolveInfo); 2979 ri.activityInfo = new ActivityInfo(ri.activityInfo); 2980 ri.activityInfo.applicationInfo = new ApplicationInfo( 2981 ri.activityInfo.applicationInfo); 2982 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 2983 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 2984 return ri; 2985 } 2986 return mResolveInfo; 2987 } 2988 } 2989 return null; 2990 } 2991 2992 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 2993 int flags, List<ResolveInfo> query, boolean debug, int userId) { 2994 final int N = query.size(); 2995 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 2996 .get(userId); 2997 // Get the list of persistent preferred activities that handle the intent 2998 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 2999 List<PersistentPreferredActivity> pprefs = ppir != null 3000 ? ppir.queryIntent(intent, resolvedType, 3001 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3002 : null; 3003 if (pprefs != null && pprefs.size() > 0) { 3004 final int M = pprefs.size(); 3005 for (int i=0; i<M; i++) { 3006 final PersistentPreferredActivity ppa = pprefs.get(i); 3007 if (DEBUG_PREFERRED || debug) { 3008 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3009 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3010 + "\n component=" + ppa.mComponent); 3011 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3012 } 3013 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3014 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3015 if (DEBUG_PREFERRED || debug) { 3016 Slog.v(TAG, "Found persistent preferred activity:"); 3017 if (ai != null) { 3018 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3019 } else { 3020 Slog.v(TAG, " null"); 3021 } 3022 } 3023 if (ai == null) { 3024 // This previously registered persistent preferred activity 3025 // component is no longer known. Ignore it and do NOT remove it. 3026 continue; 3027 } 3028 for (int j=0; j<N; j++) { 3029 final ResolveInfo ri = query.get(j); 3030 if (!ri.activityInfo.applicationInfo.packageName 3031 .equals(ai.applicationInfo.packageName)) { 3032 continue; 3033 } 3034 if (!ri.activityInfo.name.equals(ai.name)) { 3035 continue; 3036 } 3037 // Found a persistent preference that can handle the intent. 3038 if (DEBUG_PREFERRED || debug) { 3039 Slog.v(TAG, "Returning persistent preferred activity: " + 3040 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3041 } 3042 return ri; 3043 } 3044 } 3045 } 3046 return null; 3047 } 3048 3049 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3050 List<ResolveInfo> query, int priority, boolean always, 3051 boolean removeMatches, boolean debug, int userId) { 3052 if (!sUserManager.exists(userId)) return null; 3053 // writer 3054 synchronized (mPackages) { 3055 if (intent.getSelector() != null) { 3056 intent = intent.getSelector(); 3057 } 3058 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3059 3060 // Try to find a matching persistent preferred activity. 3061 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3062 debug, userId); 3063 3064 // If a persistent preferred activity matched, use it. 3065 if (pri != null) { 3066 return pri; 3067 } 3068 3069 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3070 // Get the list of preferred activities that handle the intent 3071 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3072 List<PreferredActivity> prefs = pir != null 3073 ? pir.queryIntent(intent, resolvedType, 3074 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3075 : null; 3076 if (prefs != null && prefs.size() > 0) { 3077 // First figure out how good the original match set is. 3078 // We will only allow preferred activities that came 3079 // from the same match quality. 3080 int match = 0; 3081 3082 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3083 3084 final int N = query.size(); 3085 for (int j=0; j<N; j++) { 3086 final ResolveInfo ri = query.get(j); 3087 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3088 + ": 0x" + Integer.toHexString(match)); 3089 if (ri.match > match) { 3090 match = ri.match; 3091 } 3092 } 3093 3094 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3095 + Integer.toHexString(match)); 3096 3097 match &= IntentFilter.MATCH_CATEGORY_MASK; 3098 final int M = prefs.size(); 3099 for (int i=0; i<M; i++) { 3100 final PreferredActivity pa = prefs.get(i); 3101 if (DEBUG_PREFERRED || debug) { 3102 Slog.v(TAG, "Checking PreferredActivity ds=" 3103 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3104 + "\n component=" + pa.mPref.mComponent); 3105 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3106 } 3107 if (pa.mPref.mMatch != match) { 3108 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3109 + Integer.toHexString(pa.mPref.mMatch)); 3110 continue; 3111 } 3112 // If it's not an "always" type preferred activity and that's what we're 3113 // looking for, skip it. 3114 if (always && !pa.mPref.mAlways) { 3115 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3116 continue; 3117 } 3118 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3119 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3120 if (DEBUG_PREFERRED || debug) { 3121 Slog.v(TAG, "Found preferred activity:"); 3122 if (ai != null) { 3123 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3124 } else { 3125 Slog.v(TAG, " null"); 3126 } 3127 } 3128 if (ai == null) { 3129 // This previously registered preferred activity 3130 // component is no longer known. Most likely an update 3131 // to the app was installed and in the new version this 3132 // component no longer exists. Clean it up by removing 3133 // it from the preferred activities list, and skip it. 3134 Slog.w(TAG, "Removing dangling preferred activity: " 3135 + pa.mPref.mComponent); 3136 pir.removeFilter(pa); 3137 continue; 3138 } 3139 for (int j=0; j<N; j++) { 3140 final ResolveInfo ri = query.get(j); 3141 if (!ri.activityInfo.applicationInfo.packageName 3142 .equals(ai.applicationInfo.packageName)) { 3143 continue; 3144 } 3145 if (!ri.activityInfo.name.equals(ai.name)) { 3146 continue; 3147 } 3148 3149 if (removeMatches) { 3150 pir.removeFilter(pa); 3151 if (DEBUG_PREFERRED) { 3152 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3153 } 3154 break; 3155 } 3156 3157 // Okay we found a previously set preferred or last chosen app. 3158 // If the result set is different from when this 3159 // was created, we need to clear it and re-ask the 3160 // user their preference, if we're looking for an "always" type entry. 3161 if (always && !pa.mPref.sameSet(query, priority)) { 3162 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3163 + intent + " type " + resolvedType); 3164 if (DEBUG_PREFERRED) { 3165 Slog.v(TAG, "Removing preferred activity since set changed " 3166 + pa.mPref.mComponent); 3167 } 3168 pir.removeFilter(pa); 3169 // Re-add the filter as a "last chosen" entry (!always) 3170 PreferredActivity lastChosen = new PreferredActivity( 3171 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3172 pir.addFilter(lastChosen); 3173 mSettings.writePackageRestrictionsLPr(userId); 3174 return null; 3175 } 3176 3177 // Yay! Either the set matched or we're looking for the last chosen 3178 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3179 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3180 mSettings.writePackageRestrictionsLPr(userId); 3181 return ri; 3182 } 3183 } 3184 } 3185 mSettings.writePackageRestrictionsLPr(userId); 3186 } 3187 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3188 return null; 3189 } 3190 3191 /* 3192 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3193 */ 3194 @Override 3195 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3196 int targetUserId) { 3197 mContext.enforceCallingOrSelfPermission( 3198 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3199 List<CrossProfileIntentFilter> matches = 3200 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3201 if (matches != null) { 3202 int size = matches.size(); 3203 for (int i = 0; i < size; i++) { 3204 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3205 } 3206 } 3207 ArrayList<String> packageNames = null; 3208 SparseArray<ArrayList<String>> fromSource = 3209 mSettings.mCrossProfilePackageInfo.get(sourceUserId); 3210 if (fromSource != null) { 3211 packageNames = fromSource.get(targetUserId); 3212 if (packageNames != null) { 3213 // We need the package name, so we try to resolve with the loosest flags possible 3214 List<ResolveInfo> resolveInfos = mActivities.queryIntent(intent, resolvedType, 3215 PackageManager.GET_UNINSTALLED_PACKAGES, targetUserId); 3216 int count = resolveInfos.size(); 3217 for (int i = 0; i < count; i++) { 3218 ResolveInfo resolveInfo = resolveInfos.get(i); 3219 if (packageNames.contains(resolveInfo.activityInfo.packageName)) { 3220 return true; 3221 } 3222 } 3223 } 3224 } 3225 return false; 3226 } 3227 3228 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3229 String resolvedType, int userId) { 3230 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3231 if (resolver != null) { 3232 return resolver.queryIntent(intent, resolvedType, false, userId); 3233 } 3234 return null; 3235 } 3236 3237 @Override 3238 public List<ResolveInfo> queryIntentActivities(Intent intent, 3239 String resolvedType, int flags, int userId) { 3240 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3241 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities"); 3242 ComponentName comp = intent.getComponent(); 3243 if (comp == null) { 3244 if (intent.getSelector() != null) { 3245 intent = intent.getSelector(); 3246 comp = intent.getComponent(); 3247 } 3248 } 3249 3250 if (comp != null) { 3251 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3252 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3253 if (ai != null) { 3254 final ResolveInfo ri = new ResolveInfo(); 3255 ri.activityInfo = ai; 3256 list.add(ri); 3257 } 3258 return list; 3259 } 3260 3261 // reader 3262 synchronized (mPackages) { 3263 final String pkgName = intent.getPackage(); 3264 boolean queryCrossProfile = (flags & PackageManager.NO_CROSS_PROFILE) == 0; 3265 if (pkgName == null) { 3266 ResolveInfo resolveInfo = null; 3267 if (queryCrossProfile) { 3268 // Check if the intent needs to be forwarded to another user for this package 3269 ArrayList<ResolveInfo> crossProfileResult = 3270 queryIntentActivitiesCrossProfilePackage( 3271 intent, resolvedType, flags, userId); 3272 if (!crossProfileResult.isEmpty()) { 3273 // Skip the current profile 3274 return crossProfileResult; 3275 } 3276 List<CrossProfileIntentFilter> matchingFilters = 3277 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3278 // Check for results that need to skip the current profile. 3279 resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3280 resolvedType, flags, userId); 3281 if (resolveInfo != null) { 3282 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3283 result.add(resolveInfo); 3284 return result; 3285 } 3286 // Check for cross profile results. 3287 resolveInfo = queryCrossProfileIntents( 3288 matchingFilters, intent, resolvedType, flags, userId); 3289 } 3290 // Check for results in the current profile. 3291 List<ResolveInfo> result = mActivities.queryIntent( 3292 intent, resolvedType, flags, userId); 3293 if (resolveInfo != null) { 3294 result.add(resolveInfo); 3295 } 3296 return result; 3297 } 3298 final PackageParser.Package pkg = mPackages.get(pkgName); 3299 if (pkg != null) { 3300 if (queryCrossProfile) { 3301 ArrayList<ResolveInfo> crossProfileResult = 3302 queryIntentActivitiesCrossProfilePackage( 3303 intent, resolvedType, flags, userId, pkg, pkgName); 3304 if (!crossProfileResult.isEmpty()) { 3305 // Skip the current profile 3306 return crossProfileResult; 3307 } 3308 } 3309 return mActivities.queryIntentForPackage(intent, resolvedType, flags, 3310 pkg.activities, userId); 3311 } 3312 return new ArrayList<ResolveInfo>(); 3313 } 3314 } 3315 3316 private ResolveInfo querySkipCurrentProfileIntents( 3317 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3318 int flags, int sourceUserId) { 3319 if (matchingFilters != null) { 3320 int size = matchingFilters.size(); 3321 for (int i = 0; i < size; i ++) { 3322 CrossProfileIntentFilter filter = matchingFilters.get(i); 3323 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 3324 // Checking if there are activities in the target user that can handle the 3325 // intent. 3326 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3327 flags, sourceUserId); 3328 if (resolveInfo != null) { 3329 return resolveInfo; 3330 } 3331 } 3332 } 3333 } 3334 return null; 3335 } 3336 3337 private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage( 3338 Intent intent, String resolvedType, int flags, int userId) { 3339 ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>(); 3340 SparseArray<ArrayList<String>> sourceForwardingInfo = 3341 mSettings.mCrossProfilePackageInfo.get(userId); 3342 if (sourceForwardingInfo != null) { 3343 int NI = sourceForwardingInfo.size(); 3344 for (int i = 0; i < NI; i++) { 3345 int targetUserId = sourceForwardingInfo.keyAt(i); 3346 ArrayList<String> packageNames = sourceForwardingInfo.valueAt(i); 3347 List<ResolveInfo> resolveInfos = mActivities.queryIntent( 3348 intent, resolvedType, flags, targetUserId); 3349 int NJ = resolveInfos.size(); 3350 for (int j = 0; j < NJ; j++) { 3351 ResolveInfo resolveInfo = resolveInfos.get(j); 3352 if (packageNames.contains(resolveInfo.activityInfo.packageName)) { 3353 matchingResolveInfos.add(createForwardingResolveInfo( 3354 resolveInfo.filter, userId, targetUserId)); 3355 } 3356 } 3357 } 3358 } 3359 return matchingResolveInfos; 3360 } 3361 3362 private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage( 3363 Intent intent, String resolvedType, int flags, int userId, PackageParser.Package pkg, 3364 String packageName) { 3365 ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>(); 3366 SparseArray<ArrayList<String>> sourceForwardingInfo = 3367 mSettings.mCrossProfilePackageInfo.get(userId); 3368 if (sourceForwardingInfo != null) { 3369 int NI = sourceForwardingInfo.size(); 3370 for (int i = 0; i < NI; i++) { 3371 int targetUserId = sourceForwardingInfo.keyAt(i); 3372 if (sourceForwardingInfo.valueAt(i).contains(packageName)) { 3373 List<ResolveInfo> resolveInfos = mActivities.queryIntentForPackage( 3374 intent, resolvedType, flags, pkg.activities, targetUserId); 3375 int NJ = resolveInfos.size(); 3376 for (int j = 0; j < NJ; j++) { 3377 ResolveInfo resolveInfo = resolveInfos.get(j); 3378 matchingResolveInfos.add(createForwardingResolveInfo( 3379 resolveInfo.filter, userId, targetUserId)); 3380 } 3381 } 3382 } 3383 } 3384 return matchingResolveInfos; 3385 } 3386 3387 // Return matching ResolveInfo if any for skip current profile intent filters. 3388 private ResolveInfo queryCrossProfileIntents( 3389 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3390 int flags, int sourceUserId) { 3391 if (matchingFilters != null) { 3392 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 3393 // match the same intent. For performance reasons, it is better not to 3394 // run queryIntent twice for the same userId 3395 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 3396 int size = matchingFilters.size(); 3397 for (int i = 0; i < size; i++) { 3398 CrossProfileIntentFilter filter = matchingFilters.get(i); 3399 int targetUserId = filter.getTargetUserId(); 3400 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 3401 && !alreadyTriedUserIds.get(targetUserId)) { 3402 // Checking if there are activities in the target user that can handle the 3403 // intent. 3404 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3405 flags, sourceUserId); 3406 if (resolveInfo != null) return resolveInfo; 3407 alreadyTriedUserIds.put(targetUserId, true); 3408 } 3409 } 3410 } 3411 return null; 3412 } 3413 3414 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 3415 String resolvedType, int flags, int sourceUserId) { 3416 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 3417 resolvedType, flags, filter.getTargetUserId()); 3418 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 3419 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 3420 } 3421 return null; 3422 } 3423 3424 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 3425 int sourceUserId, int targetUserId) { 3426 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 3427 String className; 3428 if (targetUserId == UserHandle.USER_OWNER) { 3429 className = FORWARD_INTENT_TO_USER_OWNER; 3430 } else { 3431 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 3432 } 3433 ComponentName forwardingActivityComponentName = new ComponentName( 3434 mAndroidApplication.packageName, className); 3435 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 3436 sourceUserId); 3437 if (targetUserId == UserHandle.USER_OWNER) { 3438 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 3439 forwardingResolveInfo.noResourceId = true; 3440 } 3441 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 3442 forwardingResolveInfo.priority = 0; 3443 forwardingResolveInfo.preferredOrder = 0; 3444 forwardingResolveInfo.match = 0; 3445 forwardingResolveInfo.isDefault = true; 3446 forwardingResolveInfo.filter = filter; 3447 forwardingResolveInfo.targetUserId = targetUserId; 3448 return forwardingResolveInfo; 3449 } 3450 3451 @Override 3452 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 3453 Intent[] specifics, String[] specificTypes, Intent intent, 3454 String resolvedType, int flags, int userId) { 3455 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3456 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 3457 "query intent activity options"); 3458 final String resultsAction = intent.getAction(); 3459 3460 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 3461 | PackageManager.GET_RESOLVED_FILTER, userId); 3462 3463 if (DEBUG_INTENT_MATCHING) { 3464 Log.v(TAG, "Query " + intent + ": " + results); 3465 } 3466 3467 int specificsPos = 0; 3468 int N; 3469 3470 // todo: note that the algorithm used here is O(N^2). This 3471 // isn't a problem in our current environment, but if we start running 3472 // into situations where we have more than 5 or 10 matches then this 3473 // should probably be changed to something smarter... 3474 3475 // First we go through and resolve each of the specific items 3476 // that were supplied, taking care of removing any corresponding 3477 // duplicate items in the generic resolve list. 3478 if (specifics != null) { 3479 for (int i=0; i<specifics.length; i++) { 3480 final Intent sintent = specifics[i]; 3481 if (sintent == null) { 3482 continue; 3483 } 3484 3485 if (DEBUG_INTENT_MATCHING) { 3486 Log.v(TAG, "Specific #" + i + ": " + sintent); 3487 } 3488 3489 String action = sintent.getAction(); 3490 if (resultsAction != null && resultsAction.equals(action)) { 3491 // If this action was explicitly requested, then don't 3492 // remove things that have it. 3493 action = null; 3494 } 3495 3496 ResolveInfo ri = null; 3497 ActivityInfo ai = null; 3498 3499 ComponentName comp = sintent.getComponent(); 3500 if (comp == null) { 3501 ri = resolveIntent( 3502 sintent, 3503 specificTypes != null ? specificTypes[i] : null, 3504 flags, userId); 3505 if (ri == null) { 3506 continue; 3507 } 3508 if (ri == mResolveInfo) { 3509 // ACK! Must do something better with this. 3510 } 3511 ai = ri.activityInfo; 3512 comp = new ComponentName(ai.applicationInfo.packageName, 3513 ai.name); 3514 } else { 3515 ai = getActivityInfo(comp, flags, userId); 3516 if (ai == null) { 3517 continue; 3518 } 3519 } 3520 3521 // Look for any generic query activities that are duplicates 3522 // of this specific one, and remove them from the results. 3523 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 3524 N = results.size(); 3525 int j; 3526 for (j=specificsPos; j<N; j++) { 3527 ResolveInfo sri = results.get(j); 3528 if ((sri.activityInfo.name.equals(comp.getClassName()) 3529 && sri.activityInfo.applicationInfo.packageName.equals( 3530 comp.getPackageName())) 3531 || (action != null && sri.filter.matchAction(action))) { 3532 results.remove(j); 3533 if (DEBUG_INTENT_MATCHING) Log.v( 3534 TAG, "Removing duplicate item from " + j 3535 + " due to specific " + specificsPos); 3536 if (ri == null) { 3537 ri = sri; 3538 } 3539 j--; 3540 N--; 3541 } 3542 } 3543 3544 // Add this specific item to its proper place. 3545 if (ri == null) { 3546 ri = new ResolveInfo(); 3547 ri.activityInfo = ai; 3548 } 3549 results.add(specificsPos, ri); 3550 ri.specificIndex = i; 3551 specificsPos++; 3552 } 3553 } 3554 3555 // Now we go through the remaining generic results and remove any 3556 // duplicate actions that are found here. 3557 N = results.size(); 3558 for (int i=specificsPos; i<N-1; i++) { 3559 final ResolveInfo rii = results.get(i); 3560 if (rii.filter == null) { 3561 continue; 3562 } 3563 3564 // Iterate over all of the actions of this result's intent 3565 // filter... typically this should be just one. 3566 final Iterator<String> it = rii.filter.actionsIterator(); 3567 if (it == null) { 3568 continue; 3569 } 3570 while (it.hasNext()) { 3571 final String action = it.next(); 3572 if (resultsAction != null && resultsAction.equals(action)) { 3573 // If this action was explicitly requested, then don't 3574 // remove things that have it. 3575 continue; 3576 } 3577 for (int j=i+1; j<N; j++) { 3578 final ResolveInfo rij = results.get(j); 3579 if (rij.filter != null && rij.filter.hasAction(action)) { 3580 results.remove(j); 3581 if (DEBUG_INTENT_MATCHING) Log.v( 3582 TAG, "Removing duplicate item from " + j 3583 + " due to action " + action + " at " + i); 3584 j--; 3585 N--; 3586 } 3587 } 3588 } 3589 3590 // If the caller didn't request filter information, drop it now 3591 // so we don't have to marshall/unmarshall it. 3592 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3593 rii.filter = null; 3594 } 3595 } 3596 3597 // Filter out the caller activity if so requested. 3598 if (caller != null) { 3599 N = results.size(); 3600 for (int i=0; i<N; i++) { 3601 ActivityInfo ainfo = results.get(i).activityInfo; 3602 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 3603 && caller.getClassName().equals(ainfo.name)) { 3604 results.remove(i); 3605 break; 3606 } 3607 } 3608 } 3609 3610 // If the caller didn't request filter information, 3611 // drop them now so we don't have to 3612 // marshall/unmarshall it. 3613 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3614 N = results.size(); 3615 for (int i=0; i<N; i++) { 3616 results.get(i).filter = null; 3617 } 3618 } 3619 3620 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 3621 return results; 3622 } 3623 3624 @Override 3625 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 3626 int userId) { 3627 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3628 ComponentName comp = intent.getComponent(); 3629 if (comp == null) { 3630 if (intent.getSelector() != null) { 3631 intent = intent.getSelector(); 3632 comp = intent.getComponent(); 3633 } 3634 } 3635 if (comp != null) { 3636 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3637 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 3638 if (ai != null) { 3639 ResolveInfo ri = new ResolveInfo(); 3640 ri.activityInfo = ai; 3641 list.add(ri); 3642 } 3643 return list; 3644 } 3645 3646 // reader 3647 synchronized (mPackages) { 3648 String pkgName = intent.getPackage(); 3649 if (pkgName == null) { 3650 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 3651 } 3652 final PackageParser.Package pkg = mPackages.get(pkgName); 3653 if (pkg != null) { 3654 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 3655 userId); 3656 } 3657 return null; 3658 } 3659 } 3660 3661 @Override 3662 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 3663 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 3664 if (!sUserManager.exists(userId)) return null; 3665 if (query != null) { 3666 if (query.size() >= 1) { 3667 // If there is more than one service with the same priority, 3668 // just arbitrarily pick the first one. 3669 return query.get(0); 3670 } 3671 } 3672 return null; 3673 } 3674 3675 @Override 3676 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 3677 int userId) { 3678 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3679 ComponentName comp = intent.getComponent(); 3680 if (comp == null) { 3681 if (intent.getSelector() != null) { 3682 intent = intent.getSelector(); 3683 comp = intent.getComponent(); 3684 } 3685 } 3686 if (comp != null) { 3687 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3688 final ServiceInfo si = getServiceInfo(comp, flags, userId); 3689 if (si != null) { 3690 final ResolveInfo ri = new ResolveInfo(); 3691 ri.serviceInfo = si; 3692 list.add(ri); 3693 } 3694 return list; 3695 } 3696 3697 // reader 3698 synchronized (mPackages) { 3699 String pkgName = intent.getPackage(); 3700 if (pkgName == null) { 3701 return mServices.queryIntent(intent, resolvedType, flags, userId); 3702 } 3703 final PackageParser.Package pkg = mPackages.get(pkgName); 3704 if (pkg != null) { 3705 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 3706 userId); 3707 } 3708 return null; 3709 } 3710 } 3711 3712 @Override 3713 public List<ResolveInfo> queryIntentContentProviders( 3714 Intent intent, String resolvedType, int flags, int userId) { 3715 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3716 ComponentName comp = intent.getComponent(); 3717 if (comp == null) { 3718 if (intent.getSelector() != null) { 3719 intent = intent.getSelector(); 3720 comp = intent.getComponent(); 3721 } 3722 } 3723 if (comp != null) { 3724 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3725 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 3726 if (pi != null) { 3727 final ResolveInfo ri = new ResolveInfo(); 3728 ri.providerInfo = pi; 3729 list.add(ri); 3730 } 3731 return list; 3732 } 3733 3734 // reader 3735 synchronized (mPackages) { 3736 String pkgName = intent.getPackage(); 3737 if (pkgName == null) { 3738 return mProviders.queryIntent(intent, resolvedType, flags, userId); 3739 } 3740 final PackageParser.Package pkg = mPackages.get(pkgName); 3741 if (pkg != null) { 3742 return mProviders.queryIntentForPackage( 3743 intent, resolvedType, flags, pkg.providers, userId); 3744 } 3745 return null; 3746 } 3747 } 3748 3749 @Override 3750 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 3751 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3752 3753 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages"); 3754 3755 // writer 3756 synchronized (mPackages) { 3757 ArrayList<PackageInfo> list; 3758 if (listUninstalled) { 3759 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 3760 for (PackageSetting ps : mSettings.mPackages.values()) { 3761 PackageInfo pi; 3762 if (ps.pkg != null) { 3763 pi = generatePackageInfo(ps.pkg, flags, userId); 3764 } else { 3765 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3766 } 3767 if (pi != null) { 3768 list.add(pi); 3769 } 3770 } 3771 } else { 3772 list = new ArrayList<PackageInfo>(mPackages.size()); 3773 for (PackageParser.Package p : mPackages.values()) { 3774 PackageInfo pi = generatePackageInfo(p, flags, userId); 3775 if (pi != null) { 3776 list.add(pi); 3777 } 3778 } 3779 } 3780 3781 return new ParceledListSlice<PackageInfo>(list); 3782 } 3783 } 3784 3785 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 3786 String[] permissions, boolean[] tmp, int flags, int userId) { 3787 int numMatch = 0; 3788 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 3789 for (int i=0; i<permissions.length; i++) { 3790 if (gp.grantedPermissions.contains(permissions[i])) { 3791 tmp[i] = true; 3792 numMatch++; 3793 } else { 3794 tmp[i] = false; 3795 } 3796 } 3797 if (numMatch == 0) { 3798 return; 3799 } 3800 PackageInfo pi; 3801 if (ps.pkg != null) { 3802 pi = generatePackageInfo(ps.pkg, flags, userId); 3803 } else { 3804 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3805 } 3806 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 3807 if (numMatch == permissions.length) { 3808 pi.requestedPermissions = permissions; 3809 } else { 3810 pi.requestedPermissions = new String[numMatch]; 3811 numMatch = 0; 3812 for (int i=0; i<permissions.length; i++) { 3813 if (tmp[i]) { 3814 pi.requestedPermissions[numMatch] = permissions[i]; 3815 numMatch++; 3816 } 3817 } 3818 } 3819 } 3820 list.add(pi); 3821 } 3822 3823 @Override 3824 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 3825 String[] permissions, int flags, int userId) { 3826 if (!sUserManager.exists(userId)) return null; 3827 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3828 3829 // writer 3830 synchronized (mPackages) { 3831 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 3832 boolean[] tmpBools = new boolean[permissions.length]; 3833 if (listUninstalled) { 3834 for (PackageSetting ps : mSettings.mPackages.values()) { 3835 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 3836 } 3837 } else { 3838 for (PackageParser.Package pkg : mPackages.values()) { 3839 PackageSetting ps = (PackageSetting)pkg.mExtras; 3840 if (ps != null) { 3841 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 3842 userId); 3843 } 3844 } 3845 } 3846 3847 return new ParceledListSlice<PackageInfo>(list); 3848 } 3849 } 3850 3851 @Override 3852 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 3853 if (!sUserManager.exists(userId)) return null; 3854 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3855 3856 // writer 3857 synchronized (mPackages) { 3858 ArrayList<ApplicationInfo> list; 3859 if (listUninstalled) { 3860 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 3861 for (PackageSetting ps : mSettings.mPackages.values()) { 3862 ApplicationInfo ai; 3863 if (ps.pkg != null) { 3864 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3865 ps.readUserState(userId), userId); 3866 } else { 3867 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 3868 } 3869 if (ai != null) { 3870 list.add(ai); 3871 } 3872 } 3873 } else { 3874 list = new ArrayList<ApplicationInfo>(mPackages.size()); 3875 for (PackageParser.Package p : mPackages.values()) { 3876 if (p.mExtras != null) { 3877 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3878 ((PackageSetting)p.mExtras).readUserState(userId), userId); 3879 if (ai != null) { 3880 list.add(ai); 3881 } 3882 } 3883 } 3884 } 3885 3886 return new ParceledListSlice<ApplicationInfo>(list); 3887 } 3888 } 3889 3890 public List<ApplicationInfo> getPersistentApplications(int flags) { 3891 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 3892 3893 // reader 3894 synchronized (mPackages) { 3895 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 3896 final int userId = UserHandle.getCallingUserId(); 3897 while (i.hasNext()) { 3898 final PackageParser.Package p = i.next(); 3899 if (p.applicationInfo != null 3900 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 3901 && (!mSafeMode || isSystemApp(p))) { 3902 PackageSetting ps = mSettings.mPackages.get(p.packageName); 3903 if (ps != null) { 3904 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3905 ps.readUserState(userId), userId); 3906 if (ai != null) { 3907 finalList.add(ai); 3908 } 3909 } 3910 } 3911 } 3912 } 3913 3914 return finalList; 3915 } 3916 3917 @Override 3918 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 3919 if (!sUserManager.exists(userId)) return null; 3920 // reader 3921 synchronized (mPackages) { 3922 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 3923 PackageSetting ps = provider != null 3924 ? mSettings.mPackages.get(provider.owner.packageName) 3925 : null; 3926 return ps != null 3927 && mSettings.isEnabledLPr(provider.info, flags, userId) 3928 && (!mSafeMode || (provider.info.applicationInfo.flags 3929 &ApplicationInfo.FLAG_SYSTEM) != 0) 3930 ? PackageParser.generateProviderInfo(provider, flags, 3931 ps.readUserState(userId), userId) 3932 : null; 3933 } 3934 } 3935 3936 /** 3937 * @deprecated 3938 */ 3939 @Deprecated 3940 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 3941 // reader 3942 synchronized (mPackages) { 3943 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 3944 .entrySet().iterator(); 3945 final int userId = UserHandle.getCallingUserId(); 3946 while (i.hasNext()) { 3947 Map.Entry<String, PackageParser.Provider> entry = i.next(); 3948 PackageParser.Provider p = entry.getValue(); 3949 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3950 3951 if (ps != null && p.syncable 3952 && (!mSafeMode || (p.info.applicationInfo.flags 3953 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 3954 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 3955 ps.readUserState(userId), userId); 3956 if (info != null) { 3957 outNames.add(entry.getKey()); 3958 outInfo.add(info); 3959 } 3960 } 3961 } 3962 } 3963 } 3964 3965 @Override 3966 public List<ProviderInfo> queryContentProviders(String processName, 3967 int uid, int flags) { 3968 ArrayList<ProviderInfo> finalList = null; 3969 // reader 3970 synchronized (mPackages) { 3971 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 3972 final int userId = processName != null ? 3973 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 3974 while (i.hasNext()) { 3975 final PackageParser.Provider p = i.next(); 3976 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3977 if (ps != null && p.info.authority != null 3978 && (processName == null 3979 || (p.info.processName.equals(processName) 3980 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 3981 && mSettings.isEnabledLPr(p.info, flags, userId) 3982 && (!mSafeMode 3983 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 3984 if (finalList == null) { 3985 finalList = new ArrayList<ProviderInfo>(3); 3986 } 3987 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 3988 ps.readUserState(userId), userId); 3989 if (info != null) { 3990 finalList.add(info); 3991 } 3992 } 3993 } 3994 } 3995 3996 if (finalList != null) { 3997 Collections.sort(finalList, mProviderInitOrderSorter); 3998 } 3999 4000 return finalList; 4001 } 4002 4003 @Override 4004 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4005 int flags) { 4006 // reader 4007 synchronized (mPackages) { 4008 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4009 return PackageParser.generateInstrumentationInfo(i, flags); 4010 } 4011 } 4012 4013 @Override 4014 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4015 int flags) { 4016 ArrayList<InstrumentationInfo> finalList = 4017 new ArrayList<InstrumentationInfo>(); 4018 4019 // reader 4020 synchronized (mPackages) { 4021 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4022 while (i.hasNext()) { 4023 final PackageParser.Instrumentation p = i.next(); 4024 if (targetPackage == null 4025 || targetPackage.equals(p.info.targetPackage)) { 4026 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4027 flags); 4028 if (ii != null) { 4029 finalList.add(ii); 4030 } 4031 } 4032 } 4033 } 4034 4035 return finalList; 4036 } 4037 4038 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4039 HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4040 if (overlays == null) { 4041 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4042 return; 4043 } 4044 for (PackageParser.Package opkg : overlays.values()) { 4045 // Not much to do if idmap fails: we already logged the error 4046 // and we certainly don't want to abort installation of pkg simply 4047 // because an overlay didn't fit properly. For these reasons, 4048 // ignore the return value of createIdmapForPackagePairLI. 4049 createIdmapForPackagePairLI(pkg, opkg); 4050 } 4051 } 4052 4053 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4054 PackageParser.Package opkg) { 4055 if (!opkg.mTrustedOverlay) { 4056 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4057 opkg.baseCodePath + ": overlay not trusted"); 4058 return false; 4059 } 4060 HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4061 if (overlaySet == null) { 4062 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4063 opkg.baseCodePath + " but target package has no known overlays"); 4064 return false; 4065 } 4066 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4067 // TODO: generate idmap for split APKs 4068 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4069 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4070 + opkg.baseCodePath); 4071 return false; 4072 } 4073 PackageParser.Package[] overlayArray = 4074 overlaySet.values().toArray(new PackageParser.Package[0]); 4075 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4076 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4077 return p1.mOverlayPriority - p2.mOverlayPriority; 4078 } 4079 }; 4080 Arrays.sort(overlayArray, cmp); 4081 4082 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4083 int i = 0; 4084 for (PackageParser.Package p : overlayArray) { 4085 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4086 } 4087 return true; 4088 } 4089 4090 private void scanDirLI(File dir, int flags, int scanMode, long currentTime) { 4091 final File[] files = dir.listFiles(); 4092 if (ArrayUtils.isEmpty(files)) { 4093 Log.d(TAG, "No files in app dir " + dir); 4094 return; 4095 } 4096 4097 if (DEBUG_PACKAGE_SCANNING) { 4098 Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode 4099 + " flags=0x" + Integer.toHexString(flags)); 4100 } 4101 4102 for (File file : files) { 4103 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 4104 && !PackageInstallerService.isStageName(file.getName()); 4105 if (!isPackage) { 4106 // Ignore entries which are not packages 4107 continue; 4108 } 4109 try { 4110 scanPackageLI(file, flags | PackageParser.PARSE_MUST_BE_APK, 4111 scanMode, currentTime, null); 4112 } catch (PackageManagerException e) { 4113 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4114 4115 // Delete invalid userdata apps 4116 if ((flags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4117 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4118 Slog.w(TAG, "Deleting invalid package at " + file); 4119 if (file.isDirectory()) { 4120 FileUtils.deleteContents(file); 4121 } 4122 file.delete(); 4123 } 4124 } 4125 } 4126 } 4127 4128 private static File getSettingsProblemFile() { 4129 File dataDir = Environment.getDataDirectory(); 4130 File systemDir = new File(dataDir, "system"); 4131 File fname = new File(systemDir, "uiderrors.txt"); 4132 return fname; 4133 } 4134 4135 static void reportSettingsProblem(int priority, String msg) { 4136 try { 4137 File fname = getSettingsProblemFile(); 4138 FileOutputStream out = new FileOutputStream(fname, true); 4139 PrintWriter pw = new FastPrintWriter(out); 4140 SimpleDateFormat formatter = new SimpleDateFormat(); 4141 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4142 pw.println(dateString + ": " + msg); 4143 pw.close(); 4144 FileUtils.setPermissions( 4145 fname.toString(), 4146 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4147 -1, -1); 4148 } catch (java.io.IOException e) { 4149 } 4150 Slog.println(priority, TAG, msg); 4151 } 4152 4153 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 4154 PackageParser.Package pkg, File srcFile, int parseFlags) 4155 throws PackageManagerException { 4156 if (ps != null 4157 && ps.codePath.equals(srcFile) 4158 && ps.timeStamp == srcFile.lastModified() 4159 && !isCompatSignatureUpdateNeeded(pkg)) { 4160 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4161 if (ps.signatures.mSignatures != null 4162 && ps.signatures.mSignatures.length != 0 4163 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4164 // Optimization: reuse the existing cached certificates 4165 // if the package appears to be unchanged. 4166 pkg.mSignatures = ps.signatures.mSignatures; 4167 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4168 synchronized (mPackages) { 4169 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 4170 } 4171 return; 4172 } 4173 4174 Slog.w(TAG, "PackageSetting for " + ps.name 4175 + " is missing signatures. Collecting certs again to recover them."); 4176 } else { 4177 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4178 } 4179 4180 try { 4181 pp.collectCertificates(pkg, parseFlags); 4182 pp.collectManifestDigest(pkg); 4183 } catch (PackageParserException e) { 4184 throw new PackageManagerException(e.error, "Failed to collect certificates for " 4185 + pkg.packageName + ": " + e.getMessage()); 4186 } 4187 } 4188 4189 /* 4190 * Scan a package and return the newly parsed package. 4191 * Returns null in case of errors and the error code is stored in mLastScanError 4192 */ 4193 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanMode, 4194 long currentTime, UserHandle user) throws PackageManagerException { 4195 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4196 parseFlags |= mDefParseFlags; 4197 PackageParser pp = new PackageParser(); 4198 pp.setSeparateProcesses(mSeparateProcesses); 4199 pp.setOnlyCoreApps(mOnlyCore); 4200 pp.setDisplayMetrics(mMetrics); 4201 4202 if ((scanMode & SCAN_TRUSTED_OVERLAY) != 0) { 4203 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4204 } 4205 4206 final PackageParser.Package pkg; 4207 try { 4208 pkg = pp.parsePackage(scanFile, parseFlags); 4209 } catch (PackageParserException e) { 4210 throw new PackageManagerException(e.error, 4211 "Failed to scan " + scanFile + ": " + e.getMessage()); 4212 } 4213 4214 PackageSetting ps = null; 4215 PackageSetting updatedPkg; 4216 // reader 4217 synchronized (mPackages) { 4218 // Look to see if we already know about this package. 4219 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4220 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4221 // This package has been renamed to its original name. Let's 4222 // use that. 4223 ps = mSettings.peekPackageLPr(oldName); 4224 } 4225 // If there was no original package, see one for the real package name. 4226 if (ps == null) { 4227 ps = mSettings.peekPackageLPr(pkg.packageName); 4228 } 4229 // Check to see if this package could be hiding/updating a system 4230 // package. Must look for it either under the original or real 4231 // package name depending on our state. 4232 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4233 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4234 } 4235 boolean updatedPkgBetter = false; 4236 // First check if this is a system package that may involve an update 4237 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4238 if (ps != null && !ps.codePath.equals(scanFile)) { 4239 // The path has changed from what was last scanned... check the 4240 // version of the new path against what we have stored to determine 4241 // what to do. 4242 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4243 if (pkg.mVersionCode < ps.versionCode) { 4244 // The system package has been updated and the code path does not match 4245 // Ignore entry. Skip it. 4246 Log.i(TAG, "Package " + ps.name + " at " + scanFile 4247 + " ignored: updated version " + ps.versionCode 4248 + " better than this " + pkg.mVersionCode); 4249 if (!updatedPkg.codePath.equals(scanFile)) { 4250 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4251 + ps.name + " changing from " + updatedPkg.codePathString 4252 + " to " + scanFile); 4253 updatedPkg.codePath = scanFile; 4254 updatedPkg.codePathString = scanFile.toString(); 4255 // This is the point at which we know that the system-disk APK 4256 // for this package has moved during a reboot (e.g. due to an OTA), 4257 // so we need to reevaluate it for privilege policy. 4258 if (locationIsPrivileged(scanFile)) { 4259 updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED; 4260 } 4261 } 4262 updatedPkg.pkg = pkg; 4263 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 4264 } else { 4265 // The current app on the system partition is better than 4266 // what we have updated to on the data partition; switch 4267 // back to the system partition version. 4268 // At this point, its safely assumed that package installation for 4269 // apps in system partition will go through. If not there won't be a working 4270 // version of the app 4271 // writer 4272 synchronized (mPackages) { 4273 // Just remove the loaded entries from package lists. 4274 mPackages.remove(ps.name); 4275 } 4276 Slog.w(TAG, "Package " + ps.name + " at " + scanFile 4277 + "reverting from " + ps.codePathString 4278 + ": new version " + pkg.mVersionCode 4279 + " better than installed " + ps.versionCode); 4280 4281 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4282 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4283 getAppDexInstructionSets(ps), isMultiArch(ps)); 4284 synchronized (mInstallLock) { 4285 args.cleanUpResourcesLI(); 4286 } 4287 synchronized (mPackages) { 4288 mSettings.enableSystemPackageLPw(ps.name); 4289 } 4290 updatedPkgBetter = true; 4291 } 4292 } 4293 } 4294 4295 if (updatedPkg != null) { 4296 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4297 // initially 4298 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4299 4300 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4301 // flag set initially 4302 if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) { 4303 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4304 } 4305 } 4306 4307 // Verify certificates against what was last scanned 4308 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 4309 4310 /* 4311 * A new system app appeared, but we already had a non-system one of the 4312 * same name installed earlier. 4313 */ 4314 boolean shouldHideSystemApp = false; 4315 if (updatedPkg == null && ps != null 4316 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4317 /* 4318 * Check to make sure the signatures match first. If they don't, 4319 * wipe the installed application and its data. 4320 */ 4321 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4322 != PackageManager.SIGNATURE_MATCH) { 4323 if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!"); 4324 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4325 ps = null; 4326 } else { 4327 /* 4328 * If the newly-added system app is an older version than the 4329 * already installed version, hide it. It will be scanned later 4330 * and re-added like an update. 4331 */ 4332 if (pkg.mVersionCode < ps.versionCode) { 4333 shouldHideSystemApp = true; 4334 } else { 4335 /* 4336 * The newly found system app is a newer version that the 4337 * one previously installed. Simply remove the 4338 * already-installed application and replace it with our own 4339 * while keeping the application data. 4340 */ 4341 Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from " 4342 + ps.codePathString + ": new version " + pkg.mVersionCode 4343 + " better than installed " + ps.versionCode); 4344 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4345 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4346 getAppDexInstructionSets(ps), isMultiArch(ps)); 4347 synchronized (mInstallLock) { 4348 args.cleanUpResourcesLI(); 4349 } 4350 } 4351 } 4352 } 4353 4354 // The apk is forward locked (not public) if its code and resources 4355 // are kept in different files. (except for app in either system or 4356 // vendor path). 4357 // TODO grab this value from PackageSettings 4358 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4359 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4360 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 4361 } 4362 } 4363 4364 // TODO: extend to support forward-locked splits 4365 String resourcePath = null; 4366 String baseResourcePath = null; 4367 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 4368 if (ps != null && ps.resourcePathString != null) { 4369 resourcePath = ps.resourcePathString; 4370 baseResourcePath = ps.resourcePathString; 4371 } else { 4372 // Should not happen at all. Just log an error. 4373 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 4374 } 4375 } else { 4376 resourcePath = pkg.codePath; 4377 baseResourcePath = pkg.baseCodePath; 4378 } 4379 4380 // Set application objects path explicitly. 4381 pkg.applicationInfo.setCodePath(pkg.codePath); 4382 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 4383 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 4384 pkg.applicationInfo.setResourcePath(resourcePath); 4385 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 4386 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 4387 4388 // Note that we invoke the following method only if we are about to unpack an application 4389 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode 4390 | SCAN_UPDATE_SIGNATURE, currentTime, user); 4391 4392 /* 4393 * If the system app should be overridden by a previously installed 4394 * data, hide the system app now and let the /data/app scan pick it up 4395 * again. 4396 */ 4397 if (shouldHideSystemApp) { 4398 synchronized (mPackages) { 4399 /* 4400 * We have to grant systems permissions before we hide, because 4401 * grantPermissions will assume the package update is trying to 4402 * expand its permissions. 4403 */ 4404 grantPermissionsLPw(pkg, true); 4405 mSettings.disableSystemPackageLPw(pkg.packageName); 4406 } 4407 } 4408 4409 return scannedPkg; 4410 } 4411 4412 private static String fixProcessName(String defProcessName, 4413 String processName, int uid) { 4414 if (processName == null) { 4415 return defProcessName; 4416 } 4417 return processName; 4418 } 4419 4420 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 4421 throws PackageManagerException { 4422 if (pkgSetting.signatures.mSignatures != null) { 4423 // Already existing package. Make sure signatures match 4424 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 4425 == PackageManager.SIGNATURE_MATCH; 4426 if (!match) { 4427 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 4428 == PackageManager.SIGNATURE_MATCH; 4429 } 4430 if (!match) { 4431 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 4432 + pkg.packageName + " signatures do not match the " 4433 + "previously installed version; ignoring!"); 4434 } 4435 } 4436 4437 // Check for shared user signatures 4438 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 4439 // Already existing package. Make sure signatures match 4440 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4441 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 4442 if (!match) { 4443 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 4444 == PackageManager.SIGNATURE_MATCH; 4445 } 4446 if (!match) { 4447 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 4448 "Package " + pkg.packageName 4449 + " has no signatures that match those in shared user " 4450 + pkgSetting.sharedUser.name + "; ignoring!"); 4451 } 4452 } 4453 } 4454 4455 /** 4456 * Enforces that only the system UID or root's UID can call a method exposed 4457 * via Binder. 4458 * 4459 * @param message used as message if SecurityException is thrown 4460 * @throws SecurityException if the caller is not system or root 4461 */ 4462 private static final void enforceSystemOrRoot(String message) { 4463 final int uid = Binder.getCallingUid(); 4464 if (uid != Process.SYSTEM_UID && uid != 0) { 4465 throw new SecurityException(message); 4466 } 4467 } 4468 4469 @Override 4470 public void performBootDexOpt() { 4471 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4472 4473 final HashSet<PackageParser.Package> pkgs; 4474 synchronized (mPackages) { 4475 pkgs = mDeferredDexOpt; 4476 mDeferredDexOpt = null; 4477 } 4478 4479 if (pkgs != null) { 4480 // Filter out packages that aren't recently used. 4481 // 4482 // The exception is first boot of a non-eng device, which 4483 // should do a full dexopt. 4484 boolean eng = "eng".equals(SystemProperties.get("ro.build.type")); 4485 if (eng || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 4486 // TODO: add a property to control this? 4487 long dexOptLRUThresholdInMinutes; 4488 if (eng) { 4489 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 4490 } else { 4491 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 4492 } 4493 long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 4494 4495 int total = pkgs.size(); 4496 int skipped = 0; 4497 long now = System.currentTimeMillis(); 4498 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 4499 PackageParser.Package pkg = i.next(); 4500 long then = pkg.mLastPackageUsageTimeInMills; 4501 if (then + dexOptLRUThresholdInMills < now) { 4502 if (DEBUG_DEXOPT) { 4503 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 4504 ((then == 0) ? "never" : new Date(then))); 4505 } 4506 i.remove(); 4507 skipped++; 4508 } 4509 } 4510 if (DEBUG_DEXOPT) { 4511 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 4512 } 4513 } 4514 4515 int i = 0; 4516 for (PackageParser.Package pkg : pkgs) { 4517 i++; 4518 if (DEBUG_DEXOPT) { 4519 Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size() 4520 + ": " + pkg.packageName); 4521 } 4522 if (!isFirstBoot()) { 4523 try { 4524 ActivityManagerNative.getDefault().showBootMessage( 4525 mContext.getResources().getString( 4526 R.string.android_upgrading_apk, 4527 i, pkgs.size()), true); 4528 } catch (RemoteException e) { 4529 } 4530 } 4531 PackageParser.Package p = pkg; 4532 synchronized (mInstallLock) { 4533 performDexOptLI(p, null /* instruction sets */, false /* force dex */, false /* defer */, 4534 true /* include dependencies */); 4535 } 4536 } 4537 } 4538 } 4539 4540 @Override 4541 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 4542 return performDexOpt(packageName, instructionSet, true); 4543 } 4544 4545 private static String getPrimaryInstructionSet(ApplicationInfo info) { 4546 if (info.primaryCpuAbi == null) { 4547 return getPreferredInstructionSet(); 4548 } 4549 4550 return VMRuntime.getInstructionSet(info.primaryCpuAbi); 4551 } 4552 4553 public boolean performDexOpt(String packageName, String instructionSet, boolean updateUsage) { 4554 PackageParser.Package p; 4555 final String targetInstructionSet; 4556 synchronized (mPackages) { 4557 p = mPackages.get(packageName); 4558 if (p == null) { 4559 return false; 4560 } 4561 if (updateUsage) { 4562 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 4563 } 4564 mPackageUsage.write(false); 4565 4566 targetInstructionSet = instructionSet != null ? instructionSet : 4567 getPrimaryInstructionSet(p.applicationInfo); 4568 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 4569 return false; 4570 } 4571 } 4572 4573 synchronized (mInstallLock) { 4574 final String[] instructionSets = new String[] { targetInstructionSet }; 4575 return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */, 4576 true /* include dependencies */) == DEX_OPT_PERFORMED; 4577 } 4578 } 4579 4580 public HashSet<String> getPackagesThatNeedDexOpt() { 4581 HashSet<String> pkgs = null; 4582 synchronized (mPackages) { 4583 for (PackageParser.Package p : mPackages.values()) { 4584 if (DEBUG_DEXOPT) { 4585 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 4586 } 4587 if (!p.mDexOptPerformed.isEmpty()) { 4588 continue; 4589 } 4590 if (pkgs == null) { 4591 pkgs = new HashSet<String>(); 4592 } 4593 pkgs.add(p.packageName); 4594 } 4595 } 4596 return pkgs; 4597 } 4598 4599 public void shutdown() { 4600 mPackageUsage.write(true); 4601 } 4602 4603 private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets, 4604 boolean forceDex, boolean defer, HashSet<String> done) { 4605 for (int i=0; i<libs.size(); i++) { 4606 PackageParser.Package libPkg; 4607 String libName; 4608 synchronized (mPackages) { 4609 libName = libs.get(i); 4610 SharedLibraryEntry lib = mSharedLibraries.get(libName); 4611 if (lib != null && lib.apk != null) { 4612 libPkg = mPackages.get(lib.apk); 4613 } else { 4614 libPkg = null; 4615 } 4616 } 4617 if (libPkg != null && !done.contains(libName)) { 4618 performDexOptLI(libPkg, instructionSets, forceDex, defer, done); 4619 } 4620 } 4621 } 4622 4623 static final int DEX_OPT_SKIPPED = 0; 4624 static final int DEX_OPT_PERFORMED = 1; 4625 static final int DEX_OPT_DEFERRED = 2; 4626 static final int DEX_OPT_FAILED = -1; 4627 4628 private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets, 4629 boolean forceDex, boolean defer, HashSet<String> done) { 4630 final String[] instructionSets = targetInstructionSets != null ? 4631 targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo); 4632 4633 if (done != null) { 4634 done.add(pkg.packageName); 4635 if (pkg.usesLibraries != null) { 4636 performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done); 4637 } 4638 if (pkg.usesOptionalLibraries != null) { 4639 performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done); 4640 } 4641 } 4642 4643 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) { 4644 return DEX_OPT_SKIPPED; 4645 } 4646 4647 final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly(); 4648 boolean performedDexOpt = false; 4649 // There are three basic cases here: 4650 // 1.) we need to dexopt, either because we are forced or it is needed 4651 // 2.) we are defering a needed dexopt 4652 // 3.) we are skipping an unneeded dexopt 4653 final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 4654 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 4655 if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) { 4656 continue; 4657 } 4658 4659 for (String path : paths) { 4660 try { 4661 // This will return DEXOPT_NEEDED if we either cannot find any odex file for this 4662 // patckage or the one we find does not match the image checksum (i.e. it was 4663 // compiled against an old image). It will return PATCHOAT_NEEDED if we can find a 4664 // odex file and it matches the checksum of the image but not its base address, 4665 // meaning we need to move it. 4666 final byte isDexOptNeeded = DexFile.isDexOptNeededInternal(path, 4667 pkg.packageName, dexCodeInstructionSet, defer); 4668 if (forceDex || (!defer && isDexOptNeeded == DexFile.DEXOPT_NEEDED)) { 4669 Log.i(TAG, "Running dexopt on: " + path + " pkg=" 4670 + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet); 4671 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4672 final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg), 4673 pkg.packageName, dexCodeInstructionSet); 4674 4675 if (ret < 0) { 4676 // Don't bother running dexopt again if we failed, it will probably 4677 // just result in an error again. Also, don't bother dexopting for other 4678 // paths & ISAs. 4679 return DEX_OPT_FAILED; 4680 } 4681 4682 performedDexOpt = true; 4683 } else if (!defer && isDexOptNeeded == DexFile.PATCHOAT_NEEDED) { 4684 Log.i(TAG, "Running patchoat on: " + pkg.applicationInfo.packageName); 4685 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4686 final int ret = mInstaller.patchoat(path, sharedGid, !isForwardLocked(pkg), 4687 pkg.packageName, dexCodeInstructionSet); 4688 4689 if (ret < 0) { 4690 // Don't bother running patchoat again if we failed, it will probably 4691 // just result in an error again. Also, don't bother dexopting for other 4692 // paths & ISAs. 4693 return DEX_OPT_FAILED; 4694 } 4695 4696 performedDexOpt = true; 4697 } 4698 4699 // We're deciding to defer a needed dexopt. Don't bother dexopting for other 4700 // paths and instruction sets. We'll deal with them all together when we process 4701 // our list of deferred dexopts. 4702 if (defer && isDexOptNeeded != DexFile.UP_TO_DATE) { 4703 if (mDeferredDexOpt == null) { 4704 mDeferredDexOpt = new HashSet<PackageParser.Package>(); 4705 } 4706 mDeferredDexOpt.add(pkg); 4707 return DEX_OPT_DEFERRED; 4708 } 4709 } catch (FileNotFoundException e) { 4710 Slog.w(TAG, "Apk not found for dexopt: " + path); 4711 return DEX_OPT_FAILED; 4712 } catch (IOException e) { 4713 Slog.w(TAG, "IOException reading apk: " + path, e); 4714 return DEX_OPT_FAILED; 4715 } catch (StaleDexCacheError e) { 4716 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e); 4717 return DEX_OPT_FAILED; 4718 } catch (Exception e) { 4719 Slog.w(TAG, "Exception when doing dexopt : ", e); 4720 return DEX_OPT_FAILED; 4721 } 4722 } 4723 4724 // At this point we haven't failed dexopt and we haven't deferred dexopt. We must 4725 // either have either succeeded dexopt, or have had isDexOptNeededInternal tell us 4726 // it isn't required. We therefore mark that this package doesn't need dexopt unless 4727 // it's forced. performedDexOpt will tell us whether we performed dex-opt or skipped 4728 // it. 4729 pkg.mDexOptPerformed.add(dexCodeInstructionSet); 4730 } 4731 4732 // If we've gotten here, we're sure that no error occurred and that we haven't 4733 // deferred dex-opt. We've either dex-opted one more paths or instruction sets or 4734 // we've skipped all of them because they are up to date. In both cases this 4735 // package doesn't need dexopt any longer. 4736 return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED; 4737 } 4738 4739 private static String[] getAppDexInstructionSets(ApplicationInfo info) { 4740 if (info.primaryCpuAbi != null) { 4741 if (info.secondaryCpuAbi != null) { 4742 return new String[] { 4743 VMRuntime.getInstructionSet(info.primaryCpuAbi), 4744 VMRuntime.getInstructionSet(info.secondaryCpuAbi) }; 4745 } else { 4746 return new String[] { 4747 VMRuntime.getInstructionSet(info.primaryCpuAbi) }; 4748 } 4749 } 4750 4751 return new String[] { getPreferredInstructionSet() }; 4752 } 4753 4754 private static String[] getAppDexInstructionSets(PackageSetting ps) { 4755 if (ps.primaryCpuAbiString != null) { 4756 if (ps.secondaryCpuAbiString != null) { 4757 return new String[] { 4758 VMRuntime.getInstructionSet(ps.primaryCpuAbiString), 4759 VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) }; 4760 } else { 4761 return new String[] { 4762 VMRuntime.getInstructionSet(ps.primaryCpuAbiString) }; 4763 } 4764 } 4765 4766 return new String[] { getPreferredInstructionSet() }; 4767 } 4768 4769 private static String getPreferredInstructionSet() { 4770 if (sPreferredInstructionSet == null) { 4771 sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]); 4772 } 4773 4774 return sPreferredInstructionSet; 4775 } 4776 4777 private static List<String> getAllInstructionSets() { 4778 final String[] allAbis = Build.SUPPORTED_ABIS; 4779 final List<String> allInstructionSets = new ArrayList<String>(allAbis.length); 4780 4781 for (String abi : allAbis) { 4782 final String instructionSet = VMRuntime.getInstructionSet(abi); 4783 if (!allInstructionSets.contains(instructionSet)) { 4784 allInstructionSets.add(instructionSet); 4785 } 4786 } 4787 4788 return allInstructionSets; 4789 } 4790 4791 /** 4792 * Returns the instruction set that should be used to compile dex code. In the presence of 4793 * a native bridge this might be different than the one shared libraries use. 4794 */ 4795 private static String getDexCodeInstructionSet(String sharedLibraryIsa) { 4796 String dexCodeIsa = SystemProperties.get("ro.dalvik.vm.isa." + sharedLibraryIsa); 4797 return (dexCodeIsa.isEmpty() ? sharedLibraryIsa : dexCodeIsa); 4798 } 4799 4800 private static String[] getDexCodeInstructionSets(String[] instructionSets) { 4801 HashSet<String> dexCodeInstructionSets = new HashSet<String>(instructionSets.length); 4802 for (String instructionSet : instructionSets) { 4803 dexCodeInstructionSets.add(getDexCodeInstructionSet(instructionSet)); 4804 } 4805 return dexCodeInstructionSets.toArray(new String[dexCodeInstructionSets.size()]); 4806 } 4807 4808 @Override 4809 public void forceDexOpt(String packageName) { 4810 enforceSystemOrRoot("forceDexOpt"); 4811 4812 PackageParser.Package pkg; 4813 synchronized (mPackages) { 4814 pkg = mPackages.get(packageName); 4815 if (pkg == null) { 4816 throw new IllegalArgumentException("Missing package: " + packageName); 4817 } 4818 } 4819 4820 synchronized (mInstallLock) { 4821 final String[] instructionSets = new String[] { 4822 getPrimaryInstructionSet(pkg.applicationInfo) }; 4823 final int res = performDexOptLI(pkg, instructionSets, true, false, true); 4824 if (res != DEX_OPT_PERFORMED) { 4825 throw new IllegalStateException("Failed to dexopt: " + res); 4826 } 4827 } 4828 } 4829 4830 private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets, 4831 boolean forceDex, boolean defer, boolean inclDependencies) { 4832 HashSet<String> done; 4833 if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) { 4834 done = new HashSet<String>(); 4835 done.add(pkg.packageName); 4836 } else { 4837 done = null; 4838 } 4839 return performDexOptLI(pkg, instructionSets, forceDex, defer, done); 4840 } 4841 4842 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 4843 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 4844 Slog.w(TAG, "Unable to update from " + oldPkg.name 4845 + " to " + newPkg.packageName 4846 + ": old package not in system partition"); 4847 return false; 4848 } else if (mPackages.get(oldPkg.name) != null) { 4849 Slog.w(TAG, "Unable to update from " + oldPkg.name 4850 + " to " + newPkg.packageName 4851 + ": old package still exists"); 4852 return false; 4853 } 4854 return true; 4855 } 4856 4857 File getDataPathForUser(int userId) { 4858 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId); 4859 } 4860 4861 private File getDataPathForPackage(String packageName, int userId) { 4862 /* 4863 * Until we fully support multiple users, return the directory we 4864 * previously would have. The PackageManagerTests will need to be 4865 * revised when this is changed back.. 4866 */ 4867 if (userId == 0) { 4868 return new File(mAppDataDir, packageName); 4869 } else { 4870 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 4871 + File.separator + packageName); 4872 } 4873 } 4874 4875 private int createDataDirsLI(String packageName, int uid, String seinfo) { 4876 int[] users = sUserManager.getUserIds(); 4877 int res = mInstaller.install(packageName, uid, uid, seinfo); 4878 if (res < 0) { 4879 return res; 4880 } 4881 for (int user : users) { 4882 if (user != 0) { 4883 res = mInstaller.createUserData(packageName, 4884 UserHandle.getUid(user, uid), user, seinfo); 4885 if (res < 0) { 4886 return res; 4887 } 4888 } 4889 } 4890 return res; 4891 } 4892 4893 private int removeDataDirsLI(String packageName) { 4894 int[] users = sUserManager.getUserIds(); 4895 int res = 0; 4896 for (int user : users) { 4897 int resInner = mInstaller.remove(packageName, user); 4898 if (resInner < 0) { 4899 res = resInner; 4900 } 4901 } 4902 4903 return res; 4904 } 4905 4906 private int deleteCodeCacheDirsLI(String packageName) { 4907 int[] users = sUserManager.getUserIds(); 4908 int res = 0; 4909 for (int user : users) { 4910 int resInner = mInstaller.deleteCodeCacheFiles(packageName, user); 4911 if (resInner < 0) { 4912 res = resInner; 4913 } 4914 } 4915 return res; 4916 } 4917 4918 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 4919 PackageParser.Package changingLib) { 4920 if (file.path != null) { 4921 usesLibraryFiles.add(file.path); 4922 return; 4923 } 4924 PackageParser.Package p = mPackages.get(file.apk); 4925 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 4926 // If we are doing this while in the middle of updating a library apk, 4927 // then we need to make sure to use that new apk for determining the 4928 // dependencies here. (We haven't yet finished committing the new apk 4929 // to the package manager state.) 4930 if (p == null || p.packageName.equals(changingLib.packageName)) { 4931 p = changingLib; 4932 } 4933 } 4934 if (p != null) { 4935 usesLibraryFiles.addAll(p.getAllCodePaths()); 4936 } 4937 } 4938 4939 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 4940 PackageParser.Package changingLib) throws PackageManagerException { 4941 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 4942 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 4943 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 4944 for (int i=0; i<N; i++) { 4945 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 4946 if (file == null) { 4947 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 4948 "Package " + pkg.packageName + " requires unavailable shared library " 4949 + pkg.usesLibraries.get(i) + "; failing!"); 4950 } 4951 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4952 } 4953 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 4954 for (int i=0; i<N; i++) { 4955 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 4956 if (file == null) { 4957 Slog.w(TAG, "Package " + pkg.packageName 4958 + " desires unavailable shared library " 4959 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 4960 } else { 4961 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4962 } 4963 } 4964 N = usesLibraryFiles.size(); 4965 if (N > 0) { 4966 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 4967 } else { 4968 pkg.usesLibraryFiles = null; 4969 } 4970 } 4971 } 4972 4973 private static boolean hasString(List<String> list, List<String> which) { 4974 if (list == null) { 4975 return false; 4976 } 4977 for (int i=list.size()-1; i>=0; i--) { 4978 for (int j=which.size()-1; j>=0; j--) { 4979 if (which.get(j).equals(list.get(i))) { 4980 return true; 4981 } 4982 } 4983 } 4984 return false; 4985 } 4986 4987 private void updateAllSharedLibrariesLPw() { 4988 for (PackageParser.Package pkg : mPackages.values()) { 4989 try { 4990 updateSharedLibrariesLPw(pkg, null); 4991 } catch (PackageManagerException e) { 4992 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 4993 } 4994 } 4995 } 4996 4997 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 4998 PackageParser.Package changingPkg) { 4999 ArrayList<PackageParser.Package> res = null; 5000 for (PackageParser.Package pkg : mPackages.values()) { 5001 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 5002 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 5003 if (res == null) { 5004 res = new ArrayList<PackageParser.Package>(); 5005 } 5006 res.add(pkg); 5007 try { 5008 updateSharedLibrariesLPw(pkg, changingPkg); 5009 } catch (PackageManagerException e) { 5010 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5011 } 5012 } 5013 } 5014 return res; 5015 } 5016 5017 /** 5018 * Derive the value of the {@code cpuAbiOverride} based on the provided 5019 * value and an optional stored value from the package settings. 5020 */ 5021 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5022 String cpuAbiOverride = null; 5023 5024 if (CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5025 cpuAbiOverride = null; 5026 } else if (abiOverride != null) { 5027 cpuAbiOverride = abiOverride; 5028 } else if (settings != null) { 5029 cpuAbiOverride = settings.cpuAbiOverrideString; 5030 } 5031 5032 return cpuAbiOverride; 5033 } 5034 5035 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5036 int scanMode, long currentTime, UserHandle user) 5037 throws PackageManagerException { 5038 final File scanFile = new File(pkg.codePath); 5039 if (pkg.applicationInfo.getCodePath() == null || 5040 pkg.applicationInfo.getResourcePath() == null) { 5041 // Bail out. The resource and code paths haven't been set. 5042 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5043 "Code and resource paths haven't been set correctly"); 5044 } 5045 5046 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5047 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5048 } 5049 5050 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5051 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED; 5052 } 5053 5054 if (mCustomResolverComponentName != null && 5055 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5056 setUpCustomResolverActivity(pkg); 5057 } 5058 5059 if (pkg.packageName.equals("android")) { 5060 synchronized (mPackages) { 5061 if (mAndroidApplication != null) { 5062 Slog.w(TAG, "*************************************************"); 5063 Slog.w(TAG, "Core android package being redefined. Skipping."); 5064 Slog.w(TAG, " file=" + scanFile); 5065 Slog.w(TAG, "*************************************************"); 5066 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5067 "Core android package being redefined. Skipping."); 5068 } 5069 5070 // Set up information for our fall-back user intent resolution activity. 5071 mPlatformPackage = pkg; 5072 pkg.mVersionCode = mSdkVersion; 5073 mAndroidApplication = pkg.applicationInfo; 5074 5075 if (!mResolverReplaced) { 5076 mResolveActivity.applicationInfo = mAndroidApplication; 5077 mResolveActivity.name = ResolverActivity.class.getName(); 5078 mResolveActivity.packageName = mAndroidApplication.packageName; 5079 mResolveActivity.processName = "system:ui"; 5080 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5081 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5082 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5083 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5084 mResolveActivity.exported = true; 5085 mResolveActivity.enabled = true; 5086 mResolveInfo.activityInfo = mResolveActivity; 5087 mResolveInfo.priority = 0; 5088 mResolveInfo.preferredOrder = 0; 5089 mResolveInfo.match = 0; 5090 mResolveComponentName = new ComponentName( 5091 mAndroidApplication.packageName, mResolveActivity.name); 5092 } 5093 } 5094 } 5095 5096 if (DEBUG_PACKAGE_SCANNING) { 5097 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5098 Log.d(TAG, "Scanning package " + pkg.packageName); 5099 } 5100 5101 if (mPackages.containsKey(pkg.packageName) 5102 || mSharedLibraries.containsKey(pkg.packageName)) { 5103 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5104 "Application package " + pkg.packageName 5105 + " already installed. Skipping duplicate."); 5106 } 5107 5108 // Initialize package source and resource directories 5109 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5110 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5111 5112 SharedUserSetting suid = null; 5113 PackageSetting pkgSetting = null; 5114 5115 if (!isSystemApp(pkg)) { 5116 // Only system apps can use these features. 5117 pkg.mOriginalPackages = null; 5118 pkg.mRealPackage = null; 5119 pkg.mAdoptPermissions = null; 5120 } 5121 5122 // writer 5123 synchronized (mPackages) { 5124 if (pkg.mSharedUserId != null) { 5125 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true); 5126 if (suid == null) { 5127 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5128 "Creating application package " + pkg.packageName 5129 + " for shared user failed"); 5130 } 5131 if (DEBUG_PACKAGE_SCANNING) { 5132 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5133 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5134 + "): packages=" + suid.packages); 5135 } 5136 } 5137 5138 // Check if we are renaming from an original package name. 5139 PackageSetting origPackage = null; 5140 String realName = null; 5141 if (pkg.mOriginalPackages != null) { 5142 // This package may need to be renamed to a previously 5143 // installed name. Let's check on that... 5144 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5145 if (pkg.mOriginalPackages.contains(renamed)) { 5146 // This package had originally been installed as the 5147 // original name, and we have already taken care of 5148 // transitioning to the new one. Just update the new 5149 // one to continue using the old name. 5150 realName = pkg.mRealPackage; 5151 if (!pkg.packageName.equals(renamed)) { 5152 // Callers into this function may have already taken 5153 // care of renaming the package; only do it here if 5154 // it is not already done. 5155 pkg.setPackageName(renamed); 5156 } 5157 5158 } else { 5159 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5160 if ((origPackage = mSettings.peekPackageLPr( 5161 pkg.mOriginalPackages.get(i))) != null) { 5162 // We do have the package already installed under its 5163 // original name... should we use it? 5164 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5165 // New package is not compatible with original. 5166 origPackage = null; 5167 continue; 5168 } else if (origPackage.sharedUser != null) { 5169 // Make sure uid is compatible between packages. 5170 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5171 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5172 + " to " + pkg.packageName + ": old uid " 5173 + origPackage.sharedUser.name 5174 + " differs from " + pkg.mSharedUserId); 5175 origPackage = null; 5176 continue; 5177 } 5178 } else { 5179 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5180 + pkg.packageName + " to old name " + origPackage.name); 5181 } 5182 break; 5183 } 5184 } 5185 } 5186 } 5187 5188 if (mTransferedPackages.contains(pkg.packageName)) { 5189 Slog.w(TAG, "Package " + pkg.packageName 5190 + " was transferred to another, but its .apk remains"); 5191 } 5192 5193 // Just create the setting, don't add it yet. For already existing packages 5194 // the PkgSetting exists already and doesn't have to be created. 5195 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5196 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 5197 pkg.applicationInfo.primaryCpuAbi, 5198 pkg.applicationInfo.secondaryCpuAbi, 5199 pkg.applicationInfo.flags, user, false); 5200 if (pkgSetting == null) { 5201 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5202 "Creating application package " + pkg.packageName + " failed"); 5203 } 5204 5205 if (pkgSetting.origPackage != null) { 5206 // If we are first transitioning from an original package, 5207 // fix up the new package's name now. We need to do this after 5208 // looking up the package under its new name, so getPackageLP 5209 // can take care of fiddling things correctly. 5210 pkg.setPackageName(origPackage.name); 5211 5212 // File a report about this. 5213 String msg = "New package " + pkgSetting.realName 5214 + " renamed to replace old package " + pkgSetting.name; 5215 reportSettingsProblem(Log.WARN, msg); 5216 5217 // Make a note of it. 5218 mTransferedPackages.add(origPackage.name); 5219 5220 // No longer need to retain this. 5221 pkgSetting.origPackage = null; 5222 } 5223 5224 if (realName != null) { 5225 // Make a note of it. 5226 mTransferedPackages.add(pkg.packageName); 5227 } 5228 5229 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5230 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5231 } 5232 5233 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5234 // Check all shared libraries and map to their actual file path. 5235 // We only do this here for apps not on a system dir, because those 5236 // are the only ones that can fail an install due to this. We 5237 // will take care of the system apps by updating all of their 5238 // library paths after the scan is done. 5239 updateSharedLibrariesLPw(pkg, null); 5240 } 5241 5242 if (mFoundPolicyFile) { 5243 SELinuxMMAC.assignSeinfoValue(pkg); 5244 } 5245 5246 pkg.applicationInfo.uid = pkgSetting.appId; 5247 pkg.mExtras = pkgSetting; 5248 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5249 try { 5250 verifySignaturesLP(pkgSetting, pkg); 5251 } catch (PackageManagerException e) { 5252 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5253 throw e; 5254 } 5255 // The signature has changed, but this package is in the system 5256 // image... let's recover! 5257 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5258 // However... if this package is part of a shared user, but it 5259 // doesn't match the signature of the shared user, let's fail. 5260 // What this means is that you can't change the signatures 5261 // associated with an overall shared user, which doesn't seem all 5262 // that unreasonable. 5263 if (pkgSetting.sharedUser != null) { 5264 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5265 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5266 throw new PackageManagerException( 5267 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 5268 "Signature mismatch for shared user : " 5269 + pkgSetting.sharedUser); 5270 } 5271 } 5272 // File a report about this. 5273 String msg = "System package " + pkg.packageName 5274 + " signature changed; retaining data."; 5275 reportSettingsProblem(Log.WARN, msg); 5276 } 5277 } else { 5278 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 5279 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5280 + pkg.packageName + " upgrade keys do not match the " 5281 + "previously installed version"); 5282 } else { 5283 // signatures may have changed as result of upgrade 5284 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5285 } 5286 } 5287 // Verify that this new package doesn't have any content providers 5288 // that conflict with existing packages. Only do this if the 5289 // package isn't already installed, since we don't want to break 5290 // things that are installed. 5291 if ((scanMode&SCAN_NEW_INSTALL) != 0) { 5292 final int N = pkg.providers.size(); 5293 int i; 5294 for (i=0; i<N; i++) { 5295 PackageParser.Provider p = pkg.providers.get(i); 5296 if (p.info.authority != null) { 5297 String names[] = p.info.authority.split(";"); 5298 for (int j = 0; j < names.length; j++) { 5299 if (mProvidersByAuthority.containsKey(names[j])) { 5300 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5301 final String otherPackageName = 5302 ((other != null && other.getComponentName() != null) ? 5303 other.getComponentName().getPackageName() : "?"); 5304 throw new PackageManagerException( 5305 INSTALL_FAILED_CONFLICTING_PROVIDER, 5306 "Can't install because provider name " + names[j] 5307 + " (in package " + pkg.applicationInfo.packageName 5308 + ") is already used by " + otherPackageName); 5309 } 5310 } 5311 } 5312 } 5313 } 5314 5315 if (pkg.mAdoptPermissions != null) { 5316 // This package wants to adopt ownership of permissions from 5317 // another package. 5318 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 5319 final String origName = pkg.mAdoptPermissions.get(i); 5320 final PackageSetting orig = mSettings.peekPackageLPr(origName); 5321 if (orig != null) { 5322 if (verifyPackageUpdateLPr(orig, pkg)) { 5323 Slog.i(TAG, "Adopting permissions from " + origName + " to " 5324 + pkg.packageName); 5325 mSettings.transferPermissionsLPw(origName, pkg.packageName); 5326 } 5327 } 5328 } 5329 } 5330 } 5331 5332 final String pkgName = pkg.packageName; 5333 5334 final long scanFileTime = scanFile.lastModified(); 5335 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0; 5336 pkg.applicationInfo.processName = fixProcessName( 5337 pkg.applicationInfo.packageName, 5338 pkg.applicationInfo.processName, 5339 pkg.applicationInfo.uid); 5340 5341 File dataPath; 5342 if (mPlatformPackage == pkg) { 5343 // The system package is special. 5344 dataPath = new File (Environment.getDataDirectory(), "system"); 5345 pkg.applicationInfo.dataDir = dataPath.getPath(); 5346 5347 } else { 5348 // This is a normal package, need to make its data directory. 5349 dataPath = getDataPathForPackage(pkg.packageName, 0); 5350 5351 boolean uidError = false; 5352 5353 if (dataPath.exists()) { 5354 int currentUid = 0; 5355 try { 5356 StructStat stat = Os.stat(dataPath.getPath()); 5357 currentUid = stat.st_uid; 5358 } catch (ErrnoException e) { 5359 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 5360 } 5361 5362 // If we have mismatched owners for the data path, we have a problem. 5363 if (currentUid != pkg.applicationInfo.uid) { 5364 boolean recovered = false; 5365 if (currentUid == 0) { 5366 // The directory somehow became owned by root. Wow. 5367 // This is probably because the system was stopped while 5368 // installd was in the middle of messing with its libs 5369 // directory. Ask installd to fix that. 5370 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 5371 pkg.applicationInfo.uid); 5372 if (ret >= 0) { 5373 recovered = true; 5374 String msg = "Package " + pkg.packageName 5375 + " unexpectedly changed to uid 0; recovered to " + 5376 + pkg.applicationInfo.uid; 5377 reportSettingsProblem(Log.WARN, msg); 5378 } 5379 } 5380 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5381 || (scanMode&SCAN_BOOTING) != 0)) { 5382 // If this is a system app, we can at least delete its 5383 // current data so the application will still work. 5384 int ret = removeDataDirsLI(pkgName); 5385 if (ret >= 0) { 5386 // TODO: Kill the processes first 5387 // Old data gone! 5388 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5389 ? "System package " : "Third party package "; 5390 String msg = prefix + pkg.packageName 5391 + " has changed from uid: " 5392 + currentUid + " to " 5393 + pkg.applicationInfo.uid + "; old data erased"; 5394 reportSettingsProblem(Log.WARN, msg); 5395 recovered = true; 5396 5397 // And now re-install the app. 5398 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5399 pkg.applicationInfo.seinfo); 5400 if (ret == -1) { 5401 // Ack should not happen! 5402 msg = prefix + pkg.packageName 5403 + " could not have data directory re-created after delete."; 5404 reportSettingsProblem(Log.WARN, msg); 5405 throw new PackageManagerException( 5406 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 5407 } 5408 } 5409 if (!recovered) { 5410 mHasSystemUidErrors = true; 5411 } 5412 } else if (!recovered) { 5413 // If we allow this install to proceed, we will be broken. 5414 // Abort, abort! 5415 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 5416 "scanPackageLI"); 5417 } 5418 if (!recovered) { 5419 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 5420 + pkg.applicationInfo.uid + "/fs_" 5421 + currentUid; 5422 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 5423 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 5424 String msg = "Package " + pkg.packageName 5425 + " has mismatched uid: " 5426 + currentUid + " on disk, " 5427 + pkg.applicationInfo.uid + " in settings"; 5428 // writer 5429 synchronized (mPackages) { 5430 mSettings.mReadMessages.append(msg); 5431 mSettings.mReadMessages.append('\n'); 5432 uidError = true; 5433 if (!pkgSetting.uidError) { 5434 reportSettingsProblem(Log.ERROR, msg); 5435 } 5436 } 5437 } 5438 } 5439 pkg.applicationInfo.dataDir = dataPath.getPath(); 5440 if (mShouldRestoreconData) { 5441 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 5442 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 5443 pkg.applicationInfo.uid); 5444 } 5445 } else { 5446 if (DEBUG_PACKAGE_SCANNING) { 5447 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5448 Log.v(TAG, "Want this data dir: " + dataPath); 5449 } 5450 //invoke installer to do the actual installation 5451 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5452 pkg.applicationInfo.seinfo); 5453 if (ret < 0) { 5454 // Error from installer 5455 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5456 "Unable to create data dirs [errorCode=" + ret + "]"); 5457 } 5458 5459 if (dataPath.exists()) { 5460 pkg.applicationInfo.dataDir = dataPath.getPath(); 5461 } else { 5462 Slog.w(TAG, "Unable to create data directory: " + dataPath); 5463 pkg.applicationInfo.dataDir = null; 5464 } 5465 } 5466 5467 pkgSetting.uidError = uidError; 5468 } 5469 5470 final String path = scanFile.getPath(); 5471 final String codePath = pkg.applicationInfo.getCodePath(); 5472 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 5473 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 5474 setBundledAppAbisAndRoots(pkg, pkgSetting); 5475 5476 // If we haven't found any native libraries for the app, check if it has 5477 // renderscript code. We'll need to force the app to 32 bit if it has 5478 // renderscript bitcode. 5479 if (pkg.applicationInfo.primaryCpuAbi == null 5480 && pkg.applicationInfo.secondaryCpuAbi == null 5481 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5482 NativeLibraryHelper.Handle handle = null; 5483 try { 5484 handle = NativeLibraryHelper.Handle.create(scanFile); 5485 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5486 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 5487 } 5488 } catch (IOException ioe) { 5489 Slog.w(TAG, "Error scanning system app : " + ioe); 5490 } finally { 5491 IoUtils.closeQuietly(handle); 5492 } 5493 } 5494 5495 setNativeLibraryPaths(pkg); 5496 } else { 5497 // TODO: We can probably be smarter about this stuff. For installed apps, 5498 // we can calculate this information at install time once and for all. For 5499 // system apps, we can probably assume that this information doesn't change 5500 // after the first boot scan. As things stand, we do lots of unnecessary work. 5501 5502 // Give ourselves some initial paths; we'll come back for another 5503 // pass once we've determined ABI below. 5504 setNativeLibraryPaths(pkg); 5505 5506 final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg); 5507 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 5508 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 5509 5510 NativeLibraryHelper.Handle handle = null; 5511 try { 5512 handle = NativeLibraryHelper.Handle.create(scanFile); 5513 // TODO(multiArch): This can be null for apps that didn't go through the 5514 // usual installation process. We can calculate it again, like we 5515 // do during install time. 5516 // 5517 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 5518 // unnecessary. 5519 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 5520 5521 // Null out the abis so that they can be recalculated. 5522 pkg.applicationInfo.primaryCpuAbi = null; 5523 pkg.applicationInfo.secondaryCpuAbi = null; 5524 if (isMultiArch(pkg.applicationInfo)) { 5525 // Warn if we've set an abiOverride for multi-lib packages.. 5526 // By definition, we need to copy both 32 and 64 bit libraries for 5527 // such packages. 5528 if (pkg.cpuAbiOverride != null && !CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 5529 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 5530 } 5531 5532 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 5533 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 5534 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 5535 if (isAsec) { 5536 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 5537 } else { 5538 abi32 = copyNativeLibrariesForInternalApp(handle, 5539 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, useIsaSpecificSubdirs); 5540 } 5541 } 5542 5543 maybeThrowExceptionForMultiArchCopy( 5544 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 5545 5546 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5547 if (isAsec) { 5548 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 5549 } else { 5550 abi64 = copyNativeLibrariesForInternalApp(handle, 5551 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, useIsaSpecificSubdirs); 5552 } 5553 } 5554 5555 maybeThrowExceptionForMultiArchCopy( 5556 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 5557 5558 if (abi64 >= 0) { 5559 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 5560 } 5561 5562 if (abi32 >= 0) { 5563 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 5564 if (abi64 >= 0) { 5565 pkg.applicationInfo.secondaryCpuAbi = abi; 5566 } else { 5567 pkg.applicationInfo.primaryCpuAbi = abi; 5568 } 5569 } 5570 } else { 5571 String[] abiList = (cpuAbiOverride != null) ? 5572 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 5573 5574 // Enable gross and lame hacks for apps that are built with old 5575 // SDK tools. We must scan their APKs for renderscript bitcode and 5576 // not launch them if it's present. Don't bother checking on devices 5577 // that don't have 64 bit support. 5578 boolean needsRenderScriptOverride = false; 5579 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 5580 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5581 abiList = Build.SUPPORTED_32_BIT_ABIS; 5582 needsRenderScriptOverride = true; 5583 } 5584 5585 final int copyRet; 5586 if (isAsec) { 5587 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 5588 } else { 5589 copyRet = copyNativeLibrariesForInternalApp(handle, nativeLibraryRoot, abiList, 5590 useIsaSpecificSubdirs); 5591 } 5592 5593 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5594 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5595 "Error unpackaging native libs for app, errorCode=" + copyRet); 5596 } 5597 5598 if (copyRet >= 0) { 5599 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 5600 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 5601 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 5602 } else if (needsRenderScriptOverride) { 5603 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 5604 } 5605 } 5606 } catch (IOException ioe) { 5607 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 5608 } finally { 5609 IoUtils.closeQuietly(handle); 5610 } 5611 5612 // Now that we've calculated the ABIs and determined if it's an internal app, 5613 // we will go ahead and populate the nativeLibraryPath. 5614 setNativeLibraryPaths(pkg); 5615 5616 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 5617 final int[] userIds = sUserManager.getUserIds(); 5618 synchronized (mInstallLock) { 5619 // Create a native library symlink only if we have native libraries 5620 // and if the native libraries are 32 bit libraries. We do not provide 5621 // this symlink for 64 bit libraries. 5622 if (pkg.applicationInfo.primaryCpuAbi != null && 5623 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 5624 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 5625 for (int userId : userIds) { 5626 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 5627 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5628 "Failed linking native library dir (user=" + userId + ")"); 5629 } 5630 } 5631 } 5632 } 5633 } 5634 5635 // This is a special case for the "system" package, where the ABI is 5636 // dictated by the zygote configuration (and init.rc). We should keep track 5637 // of this ABI so that we can deal with "normal" applications that run under 5638 // the same UID correctly. 5639 if (mPlatformPackage == pkg) { 5640 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 5641 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 5642 } 5643 5644 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 5645 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 5646 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 5647 // Copy the derived override back to the parsed package, so that we can 5648 // update the package settings accordingly. 5649 pkg.cpuAbiOverride = cpuAbiOverride; 5650 5651 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 5652 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 5653 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 5654 5655 // Push the derived path down into PackageSettings so we know what to 5656 // clean up at uninstall time. 5657 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 5658 5659 if (DEBUG_ABI_SELECTION) { 5660 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 5661 " primary=" + pkg.applicationInfo.primaryCpuAbi + 5662 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 5663 } 5664 5665 if ((scanMode&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 5666 // We don't do this here during boot because we can do it all 5667 // at once after scanning all existing packages. 5668 // 5669 // We also do this *before* we perform dexopt on this package, so that 5670 // we can avoid redundant dexopts, and also to make sure we've got the 5671 // code and package path correct. 5672 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 5673 pkg, forceDex, (scanMode & SCAN_DEFER_DEX) != 0); 5674 } 5675 5676 if ((scanMode&SCAN_NO_DEX) == 0) { 5677 if (performDexOptLI(pkg, null /* instruction sets */, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5678 == DEX_OPT_FAILED) { 5679 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5680 removeDataDirsLI(pkg.packageName); 5681 } 5682 5683 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 5684 } 5685 } 5686 5687 if (mFactoryTest && pkg.requestedPermissions.contains( 5688 android.Manifest.permission.FACTORY_TEST)) { 5689 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 5690 } 5691 5692 ArrayList<PackageParser.Package> clientLibPkgs = null; 5693 5694 // writer 5695 synchronized (mPackages) { 5696 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5697 // Only system apps can add new shared libraries. 5698 if (pkg.libraryNames != null) { 5699 for (int i=0; i<pkg.libraryNames.size(); i++) { 5700 String name = pkg.libraryNames.get(i); 5701 boolean allowed = false; 5702 if (isUpdatedSystemApp(pkg)) { 5703 // New library entries can only be added through the 5704 // system image. This is important to get rid of a lot 5705 // of nasty edge cases: for example if we allowed a non- 5706 // system update of the app to add a library, then uninstalling 5707 // the update would make the library go away, and assumptions 5708 // we made such as through app install filtering would now 5709 // have allowed apps on the device which aren't compatible 5710 // with it. Better to just have the restriction here, be 5711 // conservative, and create many fewer cases that can negatively 5712 // impact the user experience. 5713 final PackageSetting sysPs = mSettings 5714 .getDisabledSystemPkgLPr(pkg.packageName); 5715 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 5716 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 5717 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 5718 allowed = true; 5719 allowed = true; 5720 break; 5721 } 5722 } 5723 } 5724 } else { 5725 allowed = true; 5726 } 5727 if (allowed) { 5728 if (!mSharedLibraries.containsKey(name)) { 5729 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 5730 } else if (!name.equals(pkg.packageName)) { 5731 Slog.w(TAG, "Package " + pkg.packageName + " library " 5732 + name + " already exists; skipping"); 5733 } 5734 } else { 5735 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 5736 + name + " that is not declared on system image; skipping"); 5737 } 5738 } 5739 if ((scanMode&SCAN_BOOTING) == 0) { 5740 // If we are not booting, we need to update any applications 5741 // that are clients of our shared library. If we are booting, 5742 // this will all be done once the scan is complete. 5743 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 5744 } 5745 } 5746 } 5747 } 5748 5749 // We also need to dexopt any apps that are dependent on this library. Note that 5750 // if these fail, we should abort the install since installing the library will 5751 // result in some apps being broken. 5752 if (clientLibPkgs != null) { 5753 if ((scanMode&SCAN_NO_DEX) == 0) { 5754 for (int i=0; i<clientLibPkgs.size(); i++) { 5755 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5756 if (performDexOptLI(clientPkg, null /* instruction sets */, 5757 forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5758 == DEX_OPT_FAILED) { 5759 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5760 removeDataDirsLI(pkg.packageName); 5761 } 5762 5763 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 5764 "scanPackageLI failed to dexopt clientLibPkgs"); 5765 } 5766 } 5767 } 5768 } 5769 5770 // Request the ActivityManager to kill the process(only for existing packages) 5771 // so that we do not end up in a confused state while the user is still using the older 5772 // version of the application while the new one gets installed. 5773 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 5774 // If the package lives in an asec, tell everyone that the container is going 5775 // away so they can clean up any references to its resources (which would prevent 5776 // vold from being able to unmount the asec) 5777 if (isForwardLocked(pkg) || isExternal(pkg)) { 5778 if (DEBUG_INSTALL) { 5779 Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE"); 5780 } 5781 final int[] uidArray = new int[] { pkg.applicationInfo.uid }; 5782 final ArrayList<String> pkgList = new ArrayList<String>(1); 5783 pkgList.add(pkg.applicationInfo.packageName); 5784 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 5785 } 5786 5787 // Post the request that it be killed now that the going-away broadcast is en route 5788 killApplication(pkg.applicationInfo.packageName, 5789 pkg.applicationInfo.uid, "update pkg"); 5790 } 5791 5792 // Also need to kill any apps that are dependent on the library. 5793 if (clientLibPkgs != null) { 5794 for (int i=0; i<clientLibPkgs.size(); i++) { 5795 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5796 killApplication(clientPkg.applicationInfo.packageName, 5797 clientPkg.applicationInfo.uid, "update lib"); 5798 } 5799 } 5800 5801 // writer 5802 synchronized (mPackages) { 5803 // We don't expect installation to fail beyond this point, 5804 if ((scanMode&SCAN_MONITOR) != 0) { 5805 mAppDirs.put(pkg.codePath, pkg); 5806 } 5807 // Add the new setting to mSettings 5808 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 5809 // Add the new setting to mPackages 5810 mPackages.put(pkg.applicationInfo.packageName, pkg); 5811 // Make sure we don't accidentally delete its data. 5812 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 5813 while (iter.hasNext()) { 5814 PackageCleanItem item = iter.next(); 5815 if (pkgName.equals(item.packageName)) { 5816 iter.remove(); 5817 } 5818 } 5819 5820 // Take care of first install / last update times. 5821 if (currentTime != 0) { 5822 if (pkgSetting.firstInstallTime == 0) { 5823 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 5824 } else if ((scanMode&SCAN_UPDATE_TIME) != 0) { 5825 pkgSetting.lastUpdateTime = currentTime; 5826 } 5827 } else if (pkgSetting.firstInstallTime == 0) { 5828 // We need *something*. Take time time stamp of the file. 5829 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 5830 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 5831 if (scanFileTime != pkgSetting.timeStamp) { 5832 // A package on the system image has changed; consider this 5833 // to be an update. 5834 pkgSetting.lastUpdateTime = scanFileTime; 5835 } 5836 } 5837 5838 // Add the package's KeySets to the global KeySetManagerService 5839 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5840 try { 5841 // Old KeySetData no longer valid. 5842 ksms.removeAppKeySetDataLPw(pkg.packageName); 5843 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 5844 if (pkg.mKeySetMapping != null) { 5845 for (Map.Entry<String, ArraySet<PublicKey>> entry : 5846 pkg.mKeySetMapping.entrySet()) { 5847 if (entry.getValue() != null) { 5848 ksms.addDefinedKeySetToPackageLPw(pkg.packageName, 5849 entry.getValue(), entry.getKey()); 5850 } 5851 } 5852 if (pkg.mUpgradeKeySets != null) { 5853 for (String upgradeAlias : pkg.mUpgradeKeySets) { 5854 ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias); 5855 } 5856 } 5857 } 5858 } catch (NullPointerException e) { 5859 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 5860 } catch (IllegalArgumentException e) { 5861 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 5862 } 5863 5864 int N = pkg.providers.size(); 5865 StringBuilder r = null; 5866 int i; 5867 for (i=0; i<N; i++) { 5868 PackageParser.Provider p = pkg.providers.get(i); 5869 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 5870 p.info.processName, pkg.applicationInfo.uid); 5871 mProviders.addProvider(p); 5872 p.syncable = p.info.isSyncable; 5873 if (p.info.authority != null) { 5874 String names[] = p.info.authority.split(";"); 5875 p.info.authority = null; 5876 for (int j = 0; j < names.length; j++) { 5877 if (j == 1 && p.syncable) { 5878 // We only want the first authority for a provider to possibly be 5879 // syncable, so if we already added this provider using a different 5880 // authority clear the syncable flag. We copy the provider before 5881 // changing it because the mProviders object contains a reference 5882 // to a provider that we don't want to change. 5883 // Only do this for the second authority since the resulting provider 5884 // object can be the same for all future authorities for this provider. 5885 p = new PackageParser.Provider(p); 5886 p.syncable = false; 5887 } 5888 if (!mProvidersByAuthority.containsKey(names[j])) { 5889 mProvidersByAuthority.put(names[j], p); 5890 if (p.info.authority == null) { 5891 p.info.authority = names[j]; 5892 } else { 5893 p.info.authority = p.info.authority + ";" + names[j]; 5894 } 5895 if (DEBUG_PACKAGE_SCANNING) { 5896 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5897 Log.d(TAG, "Registered content provider: " + names[j] 5898 + ", className = " + p.info.name + ", isSyncable = " 5899 + p.info.isSyncable); 5900 } 5901 } else { 5902 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5903 Slog.w(TAG, "Skipping provider name " + names[j] + 5904 " (in package " + pkg.applicationInfo.packageName + 5905 "): name already used by " 5906 + ((other != null && other.getComponentName() != null) 5907 ? other.getComponentName().getPackageName() : "?")); 5908 } 5909 } 5910 } 5911 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5912 if (r == null) { 5913 r = new StringBuilder(256); 5914 } else { 5915 r.append(' '); 5916 } 5917 r.append(p.info.name); 5918 } 5919 } 5920 if (r != null) { 5921 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 5922 } 5923 5924 N = pkg.services.size(); 5925 r = null; 5926 for (i=0; i<N; i++) { 5927 PackageParser.Service s = pkg.services.get(i); 5928 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 5929 s.info.processName, pkg.applicationInfo.uid); 5930 mServices.addService(s); 5931 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5932 if (r == null) { 5933 r = new StringBuilder(256); 5934 } else { 5935 r.append(' '); 5936 } 5937 r.append(s.info.name); 5938 } 5939 } 5940 if (r != null) { 5941 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 5942 } 5943 5944 N = pkg.receivers.size(); 5945 r = null; 5946 for (i=0; i<N; i++) { 5947 PackageParser.Activity a = pkg.receivers.get(i); 5948 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5949 a.info.processName, pkg.applicationInfo.uid); 5950 mReceivers.addActivity(a, "receiver"); 5951 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5952 if (r == null) { 5953 r = new StringBuilder(256); 5954 } else { 5955 r.append(' '); 5956 } 5957 r.append(a.info.name); 5958 } 5959 } 5960 if (r != null) { 5961 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 5962 } 5963 5964 N = pkg.activities.size(); 5965 r = null; 5966 for (i=0; i<N; i++) { 5967 PackageParser.Activity a = pkg.activities.get(i); 5968 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5969 a.info.processName, pkg.applicationInfo.uid); 5970 mActivities.addActivity(a, "activity"); 5971 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5972 if (r == null) { 5973 r = new StringBuilder(256); 5974 } else { 5975 r.append(' '); 5976 } 5977 r.append(a.info.name); 5978 } 5979 } 5980 if (r != null) { 5981 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 5982 } 5983 5984 N = pkg.permissionGroups.size(); 5985 r = null; 5986 for (i=0; i<N; i++) { 5987 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 5988 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 5989 if (cur == null) { 5990 mPermissionGroups.put(pg.info.name, pg); 5991 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5992 if (r == null) { 5993 r = new StringBuilder(256); 5994 } else { 5995 r.append(' '); 5996 } 5997 r.append(pg.info.name); 5998 } 5999 } else { 6000 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 6001 + pg.info.packageName + " ignored: original from " 6002 + cur.info.packageName); 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("DUP:"); 6010 r.append(pg.info.name); 6011 } 6012 } 6013 } 6014 if (r != null) { 6015 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6016 } 6017 6018 N = pkg.permissions.size(); 6019 r = null; 6020 for (i=0; i<N; i++) { 6021 PackageParser.Permission p = pkg.permissions.get(i); 6022 HashMap<String, BasePermission> permissionMap = 6023 p.tree ? mSettings.mPermissionTrees 6024 : mSettings.mPermissions; 6025 p.group = mPermissionGroups.get(p.info.group); 6026 if (p.info.group == null || p.group != null) { 6027 BasePermission bp = permissionMap.get(p.info.name); 6028 if (bp == null) { 6029 bp = new BasePermission(p.info.name, p.info.packageName, 6030 BasePermission.TYPE_NORMAL); 6031 permissionMap.put(p.info.name, bp); 6032 } 6033 if (bp.perm == null) { 6034 if (bp.sourcePackage != null 6035 && !bp.sourcePackage.equals(p.info.packageName)) { 6036 // If this is a permission that was formerly defined by a non-system 6037 // app, but is now defined by a system app (following an upgrade), 6038 // discard the previous declaration and consider the system's to be 6039 // canonical. 6040 if (isSystemApp(p.owner)) { 6041 String msg = "New decl " + p.owner + " of permission " 6042 + p.info.name + " is system"; 6043 reportSettingsProblem(Log.WARN, msg); 6044 bp.sourcePackage = null; 6045 } 6046 } 6047 if (bp.sourcePackage == null 6048 || bp.sourcePackage.equals(p.info.packageName)) { 6049 BasePermission tree = findPermissionTreeLP(p.info.name); 6050 if (tree == null 6051 || tree.sourcePackage.equals(p.info.packageName)) { 6052 bp.packageSetting = pkgSetting; 6053 bp.perm = p; 6054 bp.uid = pkg.applicationInfo.uid; 6055 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6056 if (r == null) { 6057 r = new StringBuilder(256); 6058 } else { 6059 r.append(' '); 6060 } 6061 r.append(p.info.name); 6062 } 6063 } else { 6064 Slog.w(TAG, "Permission " + p.info.name + " from package " 6065 + p.info.packageName + " ignored: base tree " 6066 + tree.name + " is from package " 6067 + tree.sourcePackage); 6068 } 6069 } else { 6070 Slog.w(TAG, "Permission " + p.info.name + " from package " 6071 + p.info.packageName + " ignored: original from " 6072 + bp.sourcePackage); 6073 } 6074 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6075 if (r == null) { 6076 r = new StringBuilder(256); 6077 } else { 6078 r.append(' '); 6079 } 6080 r.append("DUP:"); 6081 r.append(p.info.name); 6082 } 6083 if (bp.perm == p) { 6084 bp.protectionLevel = p.info.protectionLevel; 6085 } 6086 } else { 6087 Slog.w(TAG, "Permission " + p.info.name + " from package " 6088 + p.info.packageName + " ignored: no group " 6089 + p.group); 6090 } 6091 } 6092 if (r != null) { 6093 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6094 } 6095 6096 N = pkg.instrumentation.size(); 6097 r = null; 6098 for (i=0; i<N; i++) { 6099 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6100 a.info.packageName = pkg.applicationInfo.packageName; 6101 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6102 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6103 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6104 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6105 a.info.dataDir = pkg.applicationInfo.dataDir; 6106 6107 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6108 // need other information about the application, like the ABI and what not ? 6109 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6110 mInstrumentation.put(a.getComponentName(), a); 6111 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6112 if (r == null) { 6113 r = new StringBuilder(256); 6114 } else { 6115 r.append(' '); 6116 } 6117 r.append(a.info.name); 6118 } 6119 } 6120 if (r != null) { 6121 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6122 } 6123 6124 if (pkg.protectedBroadcasts != null) { 6125 N = pkg.protectedBroadcasts.size(); 6126 for (i=0; i<N; i++) { 6127 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6128 } 6129 } 6130 6131 pkgSetting.setTimeStamp(scanFileTime); 6132 6133 // Create idmap files for pairs of (packages, overlay packages). 6134 // Note: "android", ie framework-res.apk, is handled by native layers. 6135 if (pkg.mOverlayTarget != null) { 6136 // This is an overlay package. 6137 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6138 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6139 mOverlays.put(pkg.mOverlayTarget, 6140 new HashMap<String, PackageParser.Package>()); 6141 } 6142 HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6143 map.put(pkg.packageName, pkg); 6144 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6145 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6146 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6147 "scanPackageLI failed to createIdmap"); 6148 } 6149 } 6150 } else if (mOverlays.containsKey(pkg.packageName) && 6151 !pkg.packageName.equals("android")) { 6152 // This is a regular package, with one or more known overlay packages. 6153 createIdmapsForPackageLI(pkg); 6154 } 6155 } 6156 6157 return pkg; 6158 } 6159 6160 /** 6161 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6162 * i.e, so that all packages can be run inside a single process if required. 6163 * 6164 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6165 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6166 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6167 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6168 * updating a package that belongs to a shared user. 6169 * 6170 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6171 * adds unnecessary complexity. 6172 */ 6173 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6174 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6175 String requiredInstructionSet = null; 6176 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6177 requiredInstructionSet = VMRuntime.getInstructionSet( 6178 scannedPackage.applicationInfo.primaryCpuAbi); 6179 } 6180 6181 PackageSetting requirer = null; 6182 for (PackageSetting ps : packagesForUser) { 6183 // If packagesForUser contains scannedPackage, we skip it. This will happen 6184 // when scannedPackage is an update of an existing package. Without this check, 6185 // we will never be able to change the ABI of any package belonging to a shared 6186 // user, even if it's compatible with other packages. 6187 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6188 if (ps.primaryCpuAbiString == null) { 6189 continue; 6190 } 6191 6192 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6193 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6194 // We have a mismatch between instruction sets (say arm vs arm64) warn about 6195 // this but there's not much we can do. 6196 String errorMessage = "Instruction set mismatch, " 6197 + ((requirer == null) ? "[caller]" : requirer) 6198 + " requires " + requiredInstructionSet + " whereas " + ps 6199 + " requires " + instructionSet; 6200 Slog.w(TAG, errorMessage); 6201 } 6202 6203 if (requiredInstructionSet == null) { 6204 requiredInstructionSet = instructionSet; 6205 requirer = ps; 6206 } 6207 } 6208 } 6209 6210 if (requiredInstructionSet != null) { 6211 String adjustedAbi; 6212 if (requirer != null) { 6213 // requirer != null implies that either scannedPackage was null or that scannedPackage 6214 // did not require an ABI, in which case we have to adjust scannedPackage to match 6215 // the ABI of the set (which is the same as requirer's ABI) 6216 adjustedAbi = requirer.primaryCpuAbiString; 6217 if (scannedPackage != null) { 6218 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6219 } 6220 } else { 6221 // requirer == null implies that we're updating all ABIs in the set to 6222 // match scannedPackage. 6223 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6224 } 6225 6226 for (PackageSetting ps : packagesForUser) { 6227 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6228 if (ps.primaryCpuAbiString != null) { 6229 continue; 6230 } 6231 6232 ps.primaryCpuAbiString = adjustedAbi; 6233 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6234 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6235 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6236 6237 if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt, 6238 deferDexOpt, true) == DEX_OPT_FAILED) { 6239 ps.primaryCpuAbiString = null; 6240 ps.pkg.applicationInfo.primaryCpuAbi = null; 6241 return; 6242 } else { 6243 mInstaller.rmdex(ps.codePathString, 6244 getDexCodeInstructionSet(getPreferredInstructionSet())); 6245 } 6246 } 6247 } 6248 } 6249 } 6250 } 6251 6252 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6253 synchronized (mPackages) { 6254 mResolverReplaced = true; 6255 // Set up information for custom user intent resolution activity. 6256 mResolveActivity.applicationInfo = pkg.applicationInfo; 6257 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6258 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6259 mResolveActivity.processName = null; 6260 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6261 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6262 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6263 mResolveActivity.theme = 0; 6264 mResolveActivity.exported = true; 6265 mResolveActivity.enabled = true; 6266 mResolveInfo.activityInfo = mResolveActivity; 6267 mResolveInfo.priority = 0; 6268 mResolveInfo.preferredOrder = 0; 6269 mResolveInfo.match = 0; 6270 mResolveComponentName = mCustomResolverComponentName; 6271 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6272 mResolveComponentName); 6273 } 6274 } 6275 6276 private static String calculateBundledApkRoot(final String codePathString) { 6277 final File codePath = new File(codePathString); 6278 final File codeRoot; 6279 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6280 codeRoot = Environment.getRootDirectory(); 6281 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6282 codeRoot = Environment.getOemDirectory(); 6283 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6284 codeRoot = Environment.getVendorDirectory(); 6285 } else { 6286 // Unrecognized code path; take its top real segment as the apk root: 6287 // e.g. /something/app/blah.apk => /something 6288 try { 6289 File f = codePath.getCanonicalFile(); 6290 File parent = f.getParentFile(); // non-null because codePath is a file 6291 File tmp; 6292 while ((tmp = parent.getParentFile()) != null) { 6293 f = parent; 6294 parent = tmp; 6295 } 6296 codeRoot = f; 6297 Slog.w(TAG, "Unrecognized code path " 6298 + codePath + " - using " + codeRoot); 6299 } catch (IOException e) { 6300 // Can't canonicalize the code path -- shenanigans? 6301 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6302 return Environment.getRootDirectory().getPath(); 6303 } 6304 } 6305 return codeRoot.getPath(); 6306 } 6307 6308 /** 6309 * Derive and set the location of native libraries for the given package, 6310 * which varies depending on where and how the package was installed. 6311 */ 6312 private void setNativeLibraryPaths(PackageParser.Package pkg) { 6313 final ApplicationInfo info = pkg.applicationInfo; 6314 final String codePath = pkg.codePath; 6315 final File codeFile = new File(codePath); 6316 final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info); 6317 final boolean asecApp = isForwardLocked(info) || isExternal(info); 6318 6319 info.nativeLibraryRootDir = null; 6320 info.nativeLibraryRootRequiresIsa = false; 6321 info.nativeLibraryDir = null; 6322 info.secondaryNativeLibraryDir = null; 6323 6324 if (isApkFile(codeFile)) { 6325 // Monolithic install 6326 if (bundledApp) { 6327 // If "/system/lib64/apkname" exists, assume that is the per-package 6328 // native library directory to use; otherwise use "/system/lib/apkname". 6329 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 6330 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 6331 getPrimaryInstructionSet(info)); 6332 6333 // This is a bundled system app so choose the path based on the ABI. 6334 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 6335 // is just the default path. 6336 final String apkName = deriveCodePathName(codePath); 6337 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 6338 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 6339 apkName).getAbsolutePath(); 6340 6341 if (info.secondaryCpuAbi != null) { 6342 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 6343 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 6344 secondaryLibDir, apkName).getAbsolutePath(); 6345 } 6346 } else if (asecApp) { 6347 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 6348 .getAbsolutePath(); 6349 } else { 6350 final String apkName = deriveCodePathName(codePath); 6351 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 6352 .getAbsolutePath(); 6353 } 6354 6355 info.nativeLibraryRootRequiresIsa = false; 6356 info.nativeLibraryDir = info.nativeLibraryRootDir; 6357 } else { 6358 // Cluster install 6359 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 6360 info.nativeLibraryRootRequiresIsa = true; 6361 6362 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 6363 getPrimaryInstructionSet(info)).getAbsolutePath(); 6364 6365 if (info.secondaryCpuAbi != null) { 6366 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 6367 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 6368 } 6369 } 6370 } 6371 6372 /** 6373 * Calculate the abis and roots for a bundled app. These can uniquely 6374 * be determined from the contents of the system partition, i.e whether 6375 * it contains 64 or 32 bit shared libraries etc. We do not validate any 6376 * of this information, and instead assume that the system was built 6377 * sensibly. 6378 */ 6379 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 6380 PackageSetting pkgSetting) { 6381 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 6382 6383 // If "/system/lib64/apkname" exists, assume that is the per-package 6384 // native library directory to use; otherwise use "/system/lib/apkname". 6385 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 6386 setBundledAppAbi(pkg, apkRoot, apkName); 6387 // pkgSetting might be null during rescan following uninstall of updates 6388 // to a bundled app, so accommodate that possibility. The settings in 6389 // that case will be established later from the parsed package. 6390 // 6391 // If the settings aren't null, sync them up with what we've just derived. 6392 // note that apkRoot isn't stored in the package settings. 6393 if (pkgSetting != null) { 6394 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6395 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6396 } 6397 } 6398 6399 /** 6400 * Deduces the ABI of a bundled app and sets the relevant fields on the 6401 * parsed pkg object. 6402 * 6403 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 6404 * under which system libraries are installed. 6405 * @param apkName the name of the installed package. 6406 */ 6407 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 6408 final File codeFile = new File(pkg.codePath); 6409 6410 final boolean has64BitLibs; 6411 final boolean has32BitLibs; 6412 if (isApkFile(codeFile)) { 6413 // Monolithic install 6414 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 6415 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 6416 } else { 6417 // Cluster install 6418 final File rootDir = new File(codeFile, LIB_DIR_NAME); 6419 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 6420 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 6421 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 6422 has64BitLibs = (new File(rootDir, isa)).exists(); 6423 } else { 6424 has64BitLibs = false; 6425 } 6426 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 6427 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 6428 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 6429 has32BitLibs = (new File(rootDir, isa)).exists(); 6430 } else { 6431 has32BitLibs = false; 6432 } 6433 } 6434 6435 if (has64BitLibs && !has32BitLibs) { 6436 // The package has 64 bit libs, but not 32 bit libs. Its primary 6437 // ABI should be 64 bit. We can safely assume here that the bundled 6438 // native libraries correspond to the most preferred ABI in the list. 6439 6440 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6441 pkg.applicationInfo.secondaryCpuAbi = null; 6442 } else if (has32BitLibs && !has64BitLibs) { 6443 // The package has 32 bit libs but not 64 bit libs. Its primary 6444 // ABI should be 32 bit. 6445 6446 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6447 pkg.applicationInfo.secondaryCpuAbi = null; 6448 } else if (has32BitLibs && has64BitLibs) { 6449 // The application has both 64 and 32 bit bundled libraries. We check 6450 // here that the app declares multiArch support, and warn if it doesn't. 6451 // 6452 // We will be lenient here and record both ABIs. The primary will be the 6453 // ABI that's higher on the list, i.e, a device that's configured to prefer 6454 // 64 bit apps will see a 64 bit primary ABI, 6455 6456 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 6457 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 6458 } 6459 6460 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 6461 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6462 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6463 } else { 6464 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6465 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6466 } 6467 } else { 6468 pkg.applicationInfo.primaryCpuAbi = null; 6469 pkg.applicationInfo.secondaryCpuAbi = null; 6470 } 6471 } 6472 6473 private static void createNativeLibrarySubdir(File path) throws IOException { 6474 if (!path.isDirectory()) { 6475 path.delete(); 6476 6477 if (!path.mkdir()) { 6478 throw new IOException("Cannot create " + path.getPath()); 6479 } 6480 6481 try { 6482 Os.chmod(path.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); 6483 } catch (ErrnoException e) { 6484 throw new IOException("Cannot chmod native library directory " 6485 + path.getPath(), e); 6486 } 6487 } else if (!SELinux.restorecon(path)) { 6488 throw new IOException("Cannot set SELinux context for " + path.getPath()); 6489 } 6490 } 6491 6492 private static int copyNativeLibrariesForInternalApp(NativeLibraryHelper.Handle handle, 6493 final File nativeLibraryRoot, String[] abiList, boolean useIsaSubdir) throws IOException { 6494 createNativeLibrarySubdir(nativeLibraryRoot); 6495 6496 /* 6497 * If this is an internal application or our nativeLibraryPath points to 6498 * the app-lib directory, unpack the libraries if necessary. 6499 */ 6500 int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList); 6501 if (abi >= 0) { 6502 /* 6503 * If we have a matching instruction set, construct a subdir under the native 6504 * library root that corresponds to this instruction set. 6505 */ 6506 final String instructionSet = VMRuntime.getInstructionSet(abiList[abi]); 6507 final File subDir; 6508 if (useIsaSubdir) { 6509 final File isaSubdir = new File(nativeLibraryRoot, instructionSet); 6510 createNativeLibrarySubdir(isaSubdir); 6511 subDir = isaSubdir; 6512 } else { 6513 subDir = nativeLibraryRoot; 6514 } 6515 6516 int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle, subDir, abiList[abi]); 6517 if (copyRet != PackageManager.INSTALL_SUCCEEDED) { 6518 return copyRet; 6519 } 6520 } 6521 6522 return abi; 6523 } 6524 6525 private void killApplication(String pkgName, int appId, String reason) { 6526 // Request the ActivityManager to kill the process(only for existing packages) 6527 // so that we do not end up in a confused state while the user is still using the older 6528 // version of the application while the new one gets installed. 6529 IActivityManager am = ActivityManagerNative.getDefault(); 6530 if (am != null) { 6531 try { 6532 am.killApplicationWithAppId(pkgName, appId, reason); 6533 } catch (RemoteException e) { 6534 } 6535 } 6536 } 6537 6538 void removePackageLI(PackageSetting ps, boolean chatty) { 6539 if (DEBUG_INSTALL) { 6540 if (chatty) 6541 Log.d(TAG, "Removing package " + ps.name); 6542 } 6543 6544 // writer 6545 synchronized (mPackages) { 6546 mPackages.remove(ps.name); 6547 if (ps.codePathString != null) { 6548 mAppDirs.remove(ps.codePathString); 6549 } 6550 6551 final PackageParser.Package pkg = ps.pkg; 6552 if (pkg != null) { 6553 cleanPackageDataStructuresLILPw(pkg, chatty); 6554 } 6555 } 6556 } 6557 6558 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 6559 if (DEBUG_INSTALL) { 6560 if (chatty) 6561 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 6562 } 6563 6564 // writer 6565 synchronized (mPackages) { 6566 mPackages.remove(pkg.applicationInfo.packageName); 6567 if (pkg.codePath != null) { 6568 mAppDirs.remove(pkg.codePath); 6569 } 6570 cleanPackageDataStructuresLILPw(pkg, chatty); 6571 } 6572 } 6573 6574 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 6575 int N = pkg.providers.size(); 6576 StringBuilder r = null; 6577 int i; 6578 for (i=0; i<N; i++) { 6579 PackageParser.Provider p = pkg.providers.get(i); 6580 mProviders.removeProvider(p); 6581 if (p.info.authority == null) { 6582 6583 /* There was another ContentProvider with this authority when 6584 * this app was installed so this authority is null, 6585 * Ignore it as we don't have to unregister the provider. 6586 */ 6587 continue; 6588 } 6589 String names[] = p.info.authority.split(";"); 6590 for (int j = 0; j < names.length; j++) { 6591 if (mProvidersByAuthority.get(names[j]) == p) { 6592 mProvidersByAuthority.remove(names[j]); 6593 if (DEBUG_REMOVE) { 6594 if (chatty) 6595 Log.d(TAG, "Unregistered content provider: " + names[j] 6596 + ", className = " + p.info.name + ", isSyncable = " 6597 + p.info.isSyncable); 6598 } 6599 } 6600 } 6601 if (DEBUG_REMOVE && chatty) { 6602 if (r == null) { 6603 r = new StringBuilder(256); 6604 } else { 6605 r.append(' '); 6606 } 6607 r.append(p.info.name); 6608 } 6609 } 6610 if (r != null) { 6611 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 6612 } 6613 6614 N = pkg.services.size(); 6615 r = null; 6616 for (i=0; i<N; i++) { 6617 PackageParser.Service s = pkg.services.get(i); 6618 mServices.removeService(s); 6619 if (chatty) { 6620 if (r == null) { 6621 r = new StringBuilder(256); 6622 } else { 6623 r.append(' '); 6624 } 6625 r.append(s.info.name); 6626 } 6627 } 6628 if (r != null) { 6629 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 6630 } 6631 6632 N = pkg.receivers.size(); 6633 r = null; 6634 for (i=0; i<N; i++) { 6635 PackageParser.Activity a = pkg.receivers.get(i); 6636 mReceivers.removeActivity(a, "receiver"); 6637 if (DEBUG_REMOVE && chatty) { 6638 if (r == null) { 6639 r = new StringBuilder(256); 6640 } else { 6641 r.append(' '); 6642 } 6643 r.append(a.info.name); 6644 } 6645 } 6646 if (r != null) { 6647 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 6648 } 6649 6650 N = pkg.activities.size(); 6651 r = null; 6652 for (i=0; i<N; i++) { 6653 PackageParser.Activity a = pkg.activities.get(i); 6654 mActivities.removeActivity(a, "activity"); 6655 if (DEBUG_REMOVE && chatty) { 6656 if (r == null) { 6657 r = new StringBuilder(256); 6658 } else { 6659 r.append(' '); 6660 } 6661 r.append(a.info.name); 6662 } 6663 } 6664 if (r != null) { 6665 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 6666 } 6667 6668 N = pkg.permissions.size(); 6669 r = null; 6670 for (i=0; i<N; i++) { 6671 PackageParser.Permission p = pkg.permissions.get(i); 6672 BasePermission bp = mSettings.mPermissions.get(p.info.name); 6673 if (bp == null) { 6674 bp = mSettings.mPermissionTrees.get(p.info.name); 6675 } 6676 if (bp != null && bp.perm == p) { 6677 bp.perm = null; 6678 if (DEBUG_REMOVE && chatty) { 6679 if (r == null) { 6680 r = new StringBuilder(256); 6681 } else { 6682 r.append(' '); 6683 } 6684 r.append(p.info.name); 6685 } 6686 } 6687 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6688 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 6689 if (appOpPerms != null) { 6690 appOpPerms.remove(pkg.packageName); 6691 } 6692 } 6693 } 6694 if (r != null) { 6695 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6696 } 6697 6698 N = pkg.requestedPermissions.size(); 6699 r = null; 6700 for (i=0; i<N; i++) { 6701 String perm = pkg.requestedPermissions.get(i); 6702 BasePermission bp = mSettings.mPermissions.get(perm); 6703 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6704 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 6705 if (appOpPerms != null) { 6706 appOpPerms.remove(pkg.packageName); 6707 if (appOpPerms.isEmpty()) { 6708 mAppOpPermissionPackages.remove(perm); 6709 } 6710 } 6711 } 6712 } 6713 if (r != null) { 6714 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6715 } 6716 6717 N = pkg.instrumentation.size(); 6718 r = null; 6719 for (i=0; i<N; i++) { 6720 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6721 mInstrumentation.remove(a.getComponentName()); 6722 if (DEBUG_REMOVE && chatty) { 6723 if (r == null) { 6724 r = new StringBuilder(256); 6725 } else { 6726 r.append(' '); 6727 } 6728 r.append(a.info.name); 6729 } 6730 } 6731 if (r != null) { 6732 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 6733 } 6734 6735 r = null; 6736 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6737 // Only system apps can hold shared libraries. 6738 if (pkg.libraryNames != null) { 6739 for (i=0; i<pkg.libraryNames.size(); i++) { 6740 String name = pkg.libraryNames.get(i); 6741 SharedLibraryEntry cur = mSharedLibraries.get(name); 6742 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 6743 mSharedLibraries.remove(name); 6744 if (DEBUG_REMOVE && chatty) { 6745 if (r == null) { 6746 r = new StringBuilder(256); 6747 } else { 6748 r.append(' '); 6749 } 6750 r.append(name); 6751 } 6752 } 6753 } 6754 } 6755 } 6756 if (r != null) { 6757 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 6758 } 6759 } 6760 6761 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 6762 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 6763 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 6764 return true; 6765 } 6766 } 6767 return false; 6768 } 6769 6770 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 6771 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 6772 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 6773 6774 private void updatePermissionsLPw(String changingPkg, 6775 PackageParser.Package pkgInfo, int flags) { 6776 // Make sure there are no dangling permission trees. 6777 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 6778 while (it.hasNext()) { 6779 final BasePermission bp = it.next(); 6780 if (bp.packageSetting == null) { 6781 // We may not yet have parsed the package, so just see if 6782 // we still know about its settings. 6783 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6784 } 6785 if (bp.packageSetting == null) { 6786 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 6787 + " from package " + bp.sourcePackage); 6788 it.remove(); 6789 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6790 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6791 Slog.i(TAG, "Removing old permission tree: " + bp.name 6792 + " from package " + bp.sourcePackage); 6793 flags |= UPDATE_PERMISSIONS_ALL; 6794 it.remove(); 6795 } 6796 } 6797 } 6798 6799 // Make sure all dynamic permissions have been assigned to a package, 6800 // and make sure there are no dangling permissions. 6801 it = mSettings.mPermissions.values().iterator(); 6802 while (it.hasNext()) { 6803 final BasePermission bp = it.next(); 6804 if (bp.type == BasePermission.TYPE_DYNAMIC) { 6805 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 6806 + bp.name + " pkg=" + bp.sourcePackage 6807 + " info=" + bp.pendingInfo); 6808 if (bp.packageSetting == null && bp.pendingInfo != null) { 6809 final BasePermission tree = findPermissionTreeLP(bp.name); 6810 if (tree != null && tree.perm != null) { 6811 bp.packageSetting = tree.packageSetting; 6812 bp.perm = new PackageParser.Permission(tree.perm.owner, 6813 new PermissionInfo(bp.pendingInfo)); 6814 bp.perm.info.packageName = tree.perm.info.packageName; 6815 bp.perm.info.name = bp.name; 6816 bp.uid = tree.uid; 6817 } 6818 } 6819 } 6820 if (bp.packageSetting == null) { 6821 // We may not yet have parsed the package, so just see if 6822 // we still know about its settings. 6823 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6824 } 6825 if (bp.packageSetting == null) { 6826 Slog.w(TAG, "Removing dangling permission: " + bp.name 6827 + " from package " + bp.sourcePackage); 6828 it.remove(); 6829 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6830 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6831 Slog.i(TAG, "Removing old permission: " + bp.name 6832 + " from package " + bp.sourcePackage); 6833 flags |= UPDATE_PERMISSIONS_ALL; 6834 it.remove(); 6835 } 6836 } 6837 } 6838 6839 // Now update the permissions for all packages, in particular 6840 // replace the granted permissions of the system packages. 6841 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 6842 for (PackageParser.Package pkg : mPackages.values()) { 6843 if (pkg != pkgInfo) { 6844 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0); 6845 } 6846 } 6847 } 6848 6849 if (pkgInfo != null) { 6850 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0); 6851 } 6852 } 6853 6854 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) { 6855 final PackageSetting ps = (PackageSetting) pkg.mExtras; 6856 if (ps == null) { 6857 return; 6858 } 6859 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 6860 HashSet<String> origPermissions = gp.grantedPermissions; 6861 boolean changedPermission = false; 6862 6863 if (replace) { 6864 ps.permissionsFixed = false; 6865 if (gp == ps) { 6866 origPermissions = new HashSet<String>(gp.grantedPermissions); 6867 gp.grantedPermissions.clear(); 6868 gp.gids = mGlobalGids; 6869 } 6870 } 6871 6872 if (gp.gids == null) { 6873 gp.gids = mGlobalGids; 6874 } 6875 6876 final int N = pkg.requestedPermissions.size(); 6877 for (int i=0; i<N; i++) { 6878 final String name = pkg.requestedPermissions.get(i); 6879 final boolean required = pkg.requestedPermissionsRequired.get(i); 6880 final BasePermission bp = mSettings.mPermissions.get(name); 6881 if (DEBUG_INSTALL) { 6882 if (gp != ps) { 6883 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 6884 } 6885 } 6886 6887 if (bp == null || bp.packageSetting == null) { 6888 Slog.w(TAG, "Unknown permission " + name 6889 + " in package " + pkg.packageName); 6890 continue; 6891 } 6892 6893 final String perm = bp.name; 6894 boolean allowed; 6895 boolean allowedSig = false; 6896 if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6897 // Keep track of app op permissions. 6898 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 6899 if (pkgs == null) { 6900 pkgs = new ArraySet<>(); 6901 mAppOpPermissionPackages.put(bp.name, pkgs); 6902 } 6903 pkgs.add(pkg.packageName); 6904 } 6905 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 6906 if (level == PermissionInfo.PROTECTION_NORMAL 6907 || level == PermissionInfo.PROTECTION_DANGEROUS) { 6908 // We grant a normal or dangerous permission if any of the following 6909 // are true: 6910 // 1) The permission is required 6911 // 2) The permission is optional, but was granted in the past 6912 // 3) The permission is optional, but was requested by an 6913 // app in /system (not /data) 6914 // 6915 // Otherwise, reject the permission. 6916 allowed = (required || origPermissions.contains(perm) 6917 || (isSystemApp(ps) && !isUpdatedSystemApp(ps))); 6918 } else if (bp.packageSetting == null) { 6919 // This permission is invalid; skip it. 6920 allowed = false; 6921 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 6922 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions); 6923 if (allowed) { 6924 allowedSig = true; 6925 } 6926 } else { 6927 allowed = false; 6928 } 6929 if (DEBUG_INSTALL) { 6930 if (gp != ps) { 6931 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 6932 } 6933 } 6934 if (allowed) { 6935 if (!isSystemApp(ps) && ps.permissionsFixed) { 6936 // If this is an existing, non-system package, then 6937 // we can't add any new permissions to it. 6938 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 6939 // Except... if this is a permission that was added 6940 // to the platform (note: need to only do this when 6941 // updating the platform). 6942 allowed = isNewPlatformPermissionForPackage(perm, pkg); 6943 } 6944 } 6945 if (allowed) { 6946 if (!gp.grantedPermissions.contains(perm)) { 6947 changedPermission = true; 6948 gp.grantedPermissions.add(perm); 6949 gp.gids = appendInts(gp.gids, bp.gids); 6950 } else if (!ps.haveGids) { 6951 gp.gids = appendInts(gp.gids, bp.gids); 6952 } 6953 } else { 6954 Slog.w(TAG, "Not granting permission " + perm 6955 + " to package " + pkg.packageName 6956 + " because it was previously installed without"); 6957 } 6958 } else { 6959 if (gp.grantedPermissions.remove(perm)) { 6960 changedPermission = true; 6961 gp.gids = removeInts(gp.gids, bp.gids); 6962 Slog.i(TAG, "Un-granting permission " + perm 6963 + " from package " + pkg.packageName 6964 + " (protectionLevel=" + bp.protectionLevel 6965 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6966 + ")"); 6967 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 6968 // Don't print warning for app op permissions, since it is fine for them 6969 // not to be granted, there is a UI for the user to decide. 6970 Slog.w(TAG, "Not granting permission " + perm 6971 + " to package " + pkg.packageName 6972 + " (protectionLevel=" + bp.protectionLevel 6973 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6974 + ")"); 6975 } 6976 } 6977 } 6978 6979 if ((changedPermission || replace) && !ps.permissionsFixed && 6980 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 6981 // This is the first that we have heard about this package, so the 6982 // permissions we have now selected are fixed until explicitly 6983 // changed. 6984 ps.permissionsFixed = true; 6985 } 6986 ps.haveGids = true; 6987 } 6988 6989 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 6990 boolean allowed = false; 6991 final int NP = PackageParser.NEW_PERMISSIONS.length; 6992 for (int ip=0; ip<NP; ip++) { 6993 final PackageParser.NewPermissionInfo npi 6994 = PackageParser.NEW_PERMISSIONS[ip]; 6995 if (npi.name.equals(perm) 6996 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 6997 allowed = true; 6998 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 6999 + pkg.packageName); 7000 break; 7001 } 7002 } 7003 return allowed; 7004 } 7005 7006 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 7007 BasePermission bp, HashSet<String> origPermissions) { 7008 boolean allowed; 7009 allowed = (compareSignatures( 7010 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 7011 == PackageManager.SIGNATURE_MATCH) 7012 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 7013 == PackageManager.SIGNATURE_MATCH); 7014 if (!allowed && (bp.protectionLevel 7015 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 7016 if (isSystemApp(pkg)) { 7017 // For updated system applications, a system permission 7018 // is granted only if it had been defined by the original application. 7019 if (isUpdatedSystemApp(pkg)) { 7020 final PackageSetting sysPs = mSettings 7021 .getDisabledSystemPkgLPr(pkg.packageName); 7022 final GrantedPermissions origGp = sysPs.sharedUser != null 7023 ? sysPs.sharedUser : sysPs; 7024 7025 if (origGp.grantedPermissions.contains(perm)) { 7026 // If the original was granted this permission, we take 7027 // that grant decision as read and propagate it to the 7028 // update. 7029 allowed = true; 7030 } else { 7031 // The system apk may have been updated with an older 7032 // version of the one on the data partition, but which 7033 // granted a new system permission that it didn't have 7034 // before. In this case we do want to allow the app to 7035 // now get the new permission if the ancestral apk is 7036 // privileged to get it. 7037 if (sysPs.pkg != null && sysPs.isPrivileged()) { 7038 for (int j=0; 7039 j<sysPs.pkg.requestedPermissions.size(); j++) { 7040 if (perm.equals( 7041 sysPs.pkg.requestedPermissions.get(j))) { 7042 allowed = true; 7043 break; 7044 } 7045 } 7046 } 7047 } 7048 } else { 7049 allowed = isPrivilegedApp(pkg); 7050 } 7051 } 7052 } 7053 if (!allowed && (bp.protectionLevel 7054 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 7055 // For development permissions, a development permission 7056 // is granted only if it was already granted. 7057 allowed = origPermissions.contains(perm); 7058 } 7059 return allowed; 7060 } 7061 7062 final class ActivityIntentResolver 7063 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 7064 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7065 boolean defaultOnly, int userId) { 7066 if (!sUserManager.exists(userId)) return null; 7067 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7068 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7069 } 7070 7071 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7072 int userId) { 7073 if (!sUserManager.exists(userId)) return null; 7074 mFlags = flags; 7075 return super.queryIntent(intent, resolvedType, 7076 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7077 } 7078 7079 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7080 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 7081 if (!sUserManager.exists(userId)) return null; 7082 if (packageActivities == null) { 7083 return null; 7084 } 7085 mFlags = flags; 7086 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7087 final int N = packageActivities.size(); 7088 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 7089 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 7090 7091 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 7092 for (int i = 0; i < N; ++i) { 7093 intentFilters = packageActivities.get(i).intents; 7094 if (intentFilters != null && intentFilters.size() > 0) { 7095 PackageParser.ActivityIntentInfo[] array = 7096 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 7097 intentFilters.toArray(array); 7098 listCut.add(array); 7099 } 7100 } 7101 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7102 } 7103 7104 public final void addActivity(PackageParser.Activity a, String type) { 7105 final boolean systemApp = isSystemApp(a.info.applicationInfo); 7106 mActivities.put(a.getComponentName(), a); 7107 if (DEBUG_SHOW_INFO) 7108 Log.v( 7109 TAG, " " + type + " " + 7110 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 7111 if (DEBUG_SHOW_INFO) 7112 Log.v(TAG, " Class=" + a.info.name); 7113 final int NI = a.intents.size(); 7114 for (int j=0; j<NI; j++) { 7115 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7116 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 7117 intent.setPriority(0); 7118 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 7119 + a.className + " with priority > 0, forcing to 0"); 7120 } 7121 if (DEBUG_SHOW_INFO) { 7122 Log.v(TAG, " IntentFilter:"); 7123 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7124 } 7125 if (!intent.debugCheck()) { 7126 Log.w(TAG, "==> For Activity " + a.info.name); 7127 } 7128 addFilter(intent); 7129 } 7130 } 7131 7132 public final void removeActivity(PackageParser.Activity a, String type) { 7133 mActivities.remove(a.getComponentName()); 7134 if (DEBUG_SHOW_INFO) { 7135 Log.v(TAG, " " + type + " " 7136 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 7137 : a.info.name) + ":"); 7138 Log.v(TAG, " Class=" + a.info.name); 7139 } 7140 final int NI = a.intents.size(); 7141 for (int j=0; j<NI; j++) { 7142 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7143 if (DEBUG_SHOW_INFO) { 7144 Log.v(TAG, " IntentFilter:"); 7145 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7146 } 7147 removeFilter(intent); 7148 } 7149 } 7150 7151 @Override 7152 protected boolean allowFilterResult( 7153 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 7154 ActivityInfo filterAi = filter.activity.info; 7155 for (int i=dest.size()-1; i>=0; i--) { 7156 ActivityInfo destAi = dest.get(i).activityInfo; 7157 if (destAi.name == filterAi.name 7158 && destAi.packageName == filterAi.packageName) { 7159 return false; 7160 } 7161 } 7162 return true; 7163 } 7164 7165 @Override 7166 protected ActivityIntentInfo[] newArray(int size) { 7167 return new ActivityIntentInfo[size]; 7168 } 7169 7170 @Override 7171 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 7172 if (!sUserManager.exists(userId)) return true; 7173 PackageParser.Package p = filter.activity.owner; 7174 if (p != null) { 7175 PackageSetting ps = (PackageSetting)p.mExtras; 7176 if (ps != null) { 7177 // System apps are never considered stopped for purposes of 7178 // filtering, because there may be no way for the user to 7179 // actually re-launch them. 7180 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 7181 && ps.getStopped(userId); 7182 } 7183 } 7184 return false; 7185 } 7186 7187 @Override 7188 protected boolean isPackageForFilter(String packageName, 7189 PackageParser.ActivityIntentInfo info) { 7190 return packageName.equals(info.activity.owner.packageName); 7191 } 7192 7193 @Override 7194 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7195 int match, int userId) { 7196 if (!sUserManager.exists(userId)) return null; 7197 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7198 return null; 7199 } 7200 final PackageParser.Activity activity = info.activity; 7201 if (mSafeMode && (activity.info.applicationInfo.flags 7202 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7203 return null; 7204 } 7205 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7206 if (ps == null) { 7207 return null; 7208 } 7209 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7210 ps.readUserState(userId), userId); 7211 if (ai == null) { 7212 return null; 7213 } 7214 final ResolveInfo res = new ResolveInfo(); 7215 res.activityInfo = ai; 7216 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7217 res.filter = info; 7218 } 7219 res.priority = info.getPriority(); 7220 res.preferredOrder = activity.owner.mPreferredOrder; 7221 //System.out.println("Result: " + res.activityInfo.className + 7222 // " = " + res.priority); 7223 res.match = match; 7224 res.isDefault = info.hasDefault; 7225 res.labelRes = info.labelRes; 7226 res.nonLocalizedLabel = info.nonLocalizedLabel; 7227 if (userNeedsBadging(userId)) { 7228 res.noResourceId = true; 7229 } else { 7230 res.icon = info.icon; 7231 } 7232 res.system = isSystemApp(res.activityInfo.applicationInfo); 7233 return res; 7234 } 7235 7236 @Override 7237 protected void sortResults(List<ResolveInfo> results) { 7238 Collections.sort(results, mResolvePrioritySorter); 7239 } 7240 7241 @Override 7242 protected void dumpFilter(PrintWriter out, String prefix, 7243 PackageParser.ActivityIntentInfo filter) { 7244 out.print(prefix); out.print( 7245 Integer.toHexString(System.identityHashCode(filter.activity))); 7246 out.print(' '); 7247 filter.activity.printComponentShortName(out); 7248 out.print(" filter "); 7249 out.println(Integer.toHexString(System.identityHashCode(filter))); 7250 } 7251 7252// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7253// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7254// final List<ResolveInfo> retList = Lists.newArrayList(); 7255// while (i.hasNext()) { 7256// final ResolveInfo resolveInfo = i.next(); 7257// if (isEnabledLP(resolveInfo.activityInfo)) { 7258// retList.add(resolveInfo); 7259// } 7260// } 7261// return retList; 7262// } 7263 7264 // Keys are String (activity class name), values are Activity. 7265 private final HashMap<ComponentName, PackageParser.Activity> mActivities 7266 = new HashMap<ComponentName, PackageParser.Activity>(); 7267 private int mFlags; 7268 } 7269 7270 private final class ServiceIntentResolver 7271 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 7272 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7273 boolean defaultOnly, int userId) { 7274 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7275 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7276 } 7277 7278 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7279 int userId) { 7280 if (!sUserManager.exists(userId)) return null; 7281 mFlags = flags; 7282 return super.queryIntent(intent, resolvedType, 7283 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7284 } 7285 7286 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7287 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 7288 if (!sUserManager.exists(userId)) return null; 7289 if (packageServices == null) { 7290 return null; 7291 } 7292 mFlags = flags; 7293 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7294 final int N = packageServices.size(); 7295 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 7296 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 7297 7298 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 7299 for (int i = 0; i < N; ++i) { 7300 intentFilters = packageServices.get(i).intents; 7301 if (intentFilters != null && intentFilters.size() > 0) { 7302 PackageParser.ServiceIntentInfo[] array = 7303 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 7304 intentFilters.toArray(array); 7305 listCut.add(array); 7306 } 7307 } 7308 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7309 } 7310 7311 public final void addService(PackageParser.Service s) { 7312 mServices.put(s.getComponentName(), s); 7313 if (DEBUG_SHOW_INFO) { 7314 Log.v(TAG, " " 7315 + (s.info.nonLocalizedLabel != null 7316 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7317 Log.v(TAG, " Class=" + s.info.name); 7318 } 7319 final int NI = s.intents.size(); 7320 int j; 7321 for (j=0; j<NI; j++) { 7322 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7323 if (DEBUG_SHOW_INFO) { 7324 Log.v(TAG, " IntentFilter:"); 7325 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7326 } 7327 if (!intent.debugCheck()) { 7328 Log.w(TAG, "==> For Service " + s.info.name); 7329 } 7330 addFilter(intent); 7331 } 7332 } 7333 7334 public final void removeService(PackageParser.Service s) { 7335 mServices.remove(s.getComponentName()); 7336 if (DEBUG_SHOW_INFO) { 7337 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 7338 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7339 Log.v(TAG, " Class=" + s.info.name); 7340 } 7341 final int NI = s.intents.size(); 7342 int j; 7343 for (j=0; j<NI; j++) { 7344 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7345 if (DEBUG_SHOW_INFO) { 7346 Log.v(TAG, " IntentFilter:"); 7347 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7348 } 7349 removeFilter(intent); 7350 } 7351 } 7352 7353 @Override 7354 protected boolean allowFilterResult( 7355 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 7356 ServiceInfo filterSi = filter.service.info; 7357 for (int i=dest.size()-1; i>=0; i--) { 7358 ServiceInfo destAi = dest.get(i).serviceInfo; 7359 if (destAi.name == filterSi.name 7360 && destAi.packageName == filterSi.packageName) { 7361 return false; 7362 } 7363 } 7364 return true; 7365 } 7366 7367 @Override 7368 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 7369 return new PackageParser.ServiceIntentInfo[size]; 7370 } 7371 7372 @Override 7373 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 7374 if (!sUserManager.exists(userId)) return true; 7375 PackageParser.Package p = filter.service.owner; 7376 if (p != null) { 7377 PackageSetting ps = (PackageSetting)p.mExtras; 7378 if (ps != null) { 7379 // System apps are never considered stopped for purposes of 7380 // filtering, because there may be no way for the user to 7381 // actually re-launch them. 7382 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7383 && ps.getStopped(userId); 7384 } 7385 } 7386 return false; 7387 } 7388 7389 @Override 7390 protected boolean isPackageForFilter(String packageName, 7391 PackageParser.ServiceIntentInfo info) { 7392 return packageName.equals(info.service.owner.packageName); 7393 } 7394 7395 @Override 7396 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 7397 int match, int userId) { 7398 if (!sUserManager.exists(userId)) return null; 7399 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 7400 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 7401 return null; 7402 } 7403 final PackageParser.Service service = info.service; 7404 if (mSafeMode && (service.info.applicationInfo.flags 7405 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7406 return null; 7407 } 7408 PackageSetting ps = (PackageSetting) service.owner.mExtras; 7409 if (ps == null) { 7410 return null; 7411 } 7412 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 7413 ps.readUserState(userId), userId); 7414 if (si == null) { 7415 return null; 7416 } 7417 final ResolveInfo res = new ResolveInfo(); 7418 res.serviceInfo = si; 7419 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7420 res.filter = filter; 7421 } 7422 res.priority = info.getPriority(); 7423 res.preferredOrder = service.owner.mPreferredOrder; 7424 //System.out.println("Result: " + res.activityInfo.className + 7425 // " = " + res.priority); 7426 res.match = match; 7427 res.isDefault = info.hasDefault; 7428 res.labelRes = info.labelRes; 7429 res.nonLocalizedLabel = info.nonLocalizedLabel; 7430 res.icon = info.icon; 7431 res.system = isSystemApp(res.serviceInfo.applicationInfo); 7432 return res; 7433 } 7434 7435 @Override 7436 protected void sortResults(List<ResolveInfo> results) { 7437 Collections.sort(results, mResolvePrioritySorter); 7438 } 7439 7440 @Override 7441 protected void dumpFilter(PrintWriter out, String prefix, 7442 PackageParser.ServiceIntentInfo filter) { 7443 out.print(prefix); out.print( 7444 Integer.toHexString(System.identityHashCode(filter.service))); 7445 out.print(' '); 7446 filter.service.printComponentShortName(out); 7447 out.print(" filter "); 7448 out.println(Integer.toHexString(System.identityHashCode(filter))); 7449 } 7450 7451// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7452// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7453// final List<ResolveInfo> retList = Lists.newArrayList(); 7454// while (i.hasNext()) { 7455// final ResolveInfo resolveInfo = (ResolveInfo) i; 7456// if (isEnabledLP(resolveInfo.serviceInfo)) { 7457// retList.add(resolveInfo); 7458// } 7459// } 7460// return retList; 7461// } 7462 7463 // Keys are String (activity class name), values are Activity. 7464 private final HashMap<ComponentName, PackageParser.Service> mServices 7465 = new HashMap<ComponentName, PackageParser.Service>(); 7466 private int mFlags; 7467 }; 7468 7469 private final class ProviderIntentResolver 7470 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 7471 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7472 boolean defaultOnly, int userId) { 7473 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7474 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7475 } 7476 7477 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7478 int userId) { 7479 if (!sUserManager.exists(userId)) 7480 return null; 7481 mFlags = flags; 7482 return super.queryIntent(intent, resolvedType, 7483 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7484 } 7485 7486 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7487 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 7488 if (!sUserManager.exists(userId)) 7489 return null; 7490 if (packageProviders == null) { 7491 return null; 7492 } 7493 mFlags = flags; 7494 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 7495 final int N = packageProviders.size(); 7496 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 7497 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 7498 7499 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 7500 for (int i = 0; i < N; ++i) { 7501 intentFilters = packageProviders.get(i).intents; 7502 if (intentFilters != null && intentFilters.size() > 0) { 7503 PackageParser.ProviderIntentInfo[] array = 7504 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 7505 intentFilters.toArray(array); 7506 listCut.add(array); 7507 } 7508 } 7509 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7510 } 7511 7512 public final void addProvider(PackageParser.Provider p) { 7513 if (mProviders.containsKey(p.getComponentName())) { 7514 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 7515 return; 7516 } 7517 7518 mProviders.put(p.getComponentName(), p); 7519 if (DEBUG_SHOW_INFO) { 7520 Log.v(TAG, " " 7521 + (p.info.nonLocalizedLabel != null 7522 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7523 Log.v(TAG, " Class=" + p.info.name); 7524 } 7525 final int NI = p.intents.size(); 7526 int j; 7527 for (j = 0; j < NI; j++) { 7528 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7529 if (DEBUG_SHOW_INFO) { 7530 Log.v(TAG, " IntentFilter:"); 7531 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7532 } 7533 if (!intent.debugCheck()) { 7534 Log.w(TAG, "==> For Provider " + p.info.name); 7535 } 7536 addFilter(intent); 7537 } 7538 } 7539 7540 public final void removeProvider(PackageParser.Provider p) { 7541 mProviders.remove(p.getComponentName()); 7542 if (DEBUG_SHOW_INFO) { 7543 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 7544 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7545 Log.v(TAG, " Class=" + p.info.name); 7546 } 7547 final int NI = p.intents.size(); 7548 int j; 7549 for (j = 0; j < NI; j++) { 7550 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7551 if (DEBUG_SHOW_INFO) { 7552 Log.v(TAG, " IntentFilter:"); 7553 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7554 } 7555 removeFilter(intent); 7556 } 7557 } 7558 7559 @Override 7560 protected boolean allowFilterResult( 7561 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 7562 ProviderInfo filterPi = filter.provider.info; 7563 for (int i = dest.size() - 1; i >= 0; i--) { 7564 ProviderInfo destPi = dest.get(i).providerInfo; 7565 if (destPi.name == filterPi.name 7566 && destPi.packageName == filterPi.packageName) { 7567 return false; 7568 } 7569 } 7570 return true; 7571 } 7572 7573 @Override 7574 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 7575 return new PackageParser.ProviderIntentInfo[size]; 7576 } 7577 7578 @Override 7579 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 7580 if (!sUserManager.exists(userId)) 7581 return true; 7582 PackageParser.Package p = filter.provider.owner; 7583 if (p != null) { 7584 PackageSetting ps = (PackageSetting) p.mExtras; 7585 if (ps != null) { 7586 // System apps are never considered stopped for purposes of 7587 // filtering, because there may be no way for the user to 7588 // actually re-launch them. 7589 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7590 && ps.getStopped(userId); 7591 } 7592 } 7593 return false; 7594 } 7595 7596 @Override 7597 protected boolean isPackageForFilter(String packageName, 7598 PackageParser.ProviderIntentInfo info) { 7599 return packageName.equals(info.provider.owner.packageName); 7600 } 7601 7602 @Override 7603 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 7604 int match, int userId) { 7605 if (!sUserManager.exists(userId)) 7606 return null; 7607 final PackageParser.ProviderIntentInfo info = filter; 7608 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 7609 return null; 7610 } 7611 final PackageParser.Provider provider = info.provider; 7612 if (mSafeMode && (provider.info.applicationInfo.flags 7613 & ApplicationInfo.FLAG_SYSTEM) == 0) { 7614 return null; 7615 } 7616 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 7617 if (ps == null) { 7618 return null; 7619 } 7620 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 7621 ps.readUserState(userId), userId); 7622 if (pi == null) { 7623 return null; 7624 } 7625 final ResolveInfo res = new ResolveInfo(); 7626 res.providerInfo = pi; 7627 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 7628 res.filter = filter; 7629 } 7630 res.priority = info.getPriority(); 7631 res.preferredOrder = provider.owner.mPreferredOrder; 7632 res.match = match; 7633 res.isDefault = info.hasDefault; 7634 res.labelRes = info.labelRes; 7635 res.nonLocalizedLabel = info.nonLocalizedLabel; 7636 res.icon = info.icon; 7637 res.system = isSystemApp(res.providerInfo.applicationInfo); 7638 return res; 7639 } 7640 7641 @Override 7642 protected void sortResults(List<ResolveInfo> results) { 7643 Collections.sort(results, mResolvePrioritySorter); 7644 } 7645 7646 @Override 7647 protected void dumpFilter(PrintWriter out, String prefix, 7648 PackageParser.ProviderIntentInfo filter) { 7649 out.print(prefix); 7650 out.print( 7651 Integer.toHexString(System.identityHashCode(filter.provider))); 7652 out.print(' '); 7653 filter.provider.printComponentShortName(out); 7654 out.print(" filter "); 7655 out.println(Integer.toHexString(System.identityHashCode(filter))); 7656 } 7657 7658 private final HashMap<ComponentName, PackageParser.Provider> mProviders 7659 = new HashMap<ComponentName, PackageParser.Provider>(); 7660 private int mFlags; 7661 }; 7662 7663 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 7664 new Comparator<ResolveInfo>() { 7665 public int compare(ResolveInfo r1, ResolveInfo r2) { 7666 int v1 = r1.priority; 7667 int v2 = r2.priority; 7668 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 7669 if (v1 != v2) { 7670 return (v1 > v2) ? -1 : 1; 7671 } 7672 v1 = r1.preferredOrder; 7673 v2 = r2.preferredOrder; 7674 if (v1 != v2) { 7675 return (v1 > v2) ? -1 : 1; 7676 } 7677 if (r1.isDefault != r2.isDefault) { 7678 return r1.isDefault ? -1 : 1; 7679 } 7680 v1 = r1.match; 7681 v2 = r2.match; 7682 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 7683 if (v1 != v2) { 7684 return (v1 > v2) ? -1 : 1; 7685 } 7686 if (r1.system != r2.system) { 7687 return r1.system ? -1 : 1; 7688 } 7689 return 0; 7690 } 7691 }; 7692 7693 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 7694 new Comparator<ProviderInfo>() { 7695 public int compare(ProviderInfo p1, ProviderInfo p2) { 7696 final int v1 = p1.initOrder; 7697 final int v2 = p2.initOrder; 7698 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 7699 } 7700 }; 7701 7702 static final void sendPackageBroadcast(String action, String pkg, 7703 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 7704 int[] userIds) { 7705 IActivityManager am = ActivityManagerNative.getDefault(); 7706 if (am != null) { 7707 try { 7708 if (userIds == null) { 7709 userIds = am.getRunningUserIds(); 7710 } 7711 for (int id : userIds) { 7712 final Intent intent = new Intent(action, 7713 pkg != null ? Uri.fromParts("package", pkg, null) : null); 7714 if (extras != null) { 7715 intent.putExtras(extras); 7716 } 7717 if (targetPkg != null) { 7718 intent.setPackage(targetPkg); 7719 } 7720 // Modify the UID when posting to other users 7721 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 7722 if (uid > 0 && UserHandle.getUserId(uid) != id) { 7723 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 7724 intent.putExtra(Intent.EXTRA_UID, uid); 7725 } 7726 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 7727 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 7728 if (DEBUG_BROADCASTS) { 7729 RuntimeException here = new RuntimeException("here"); 7730 here.fillInStackTrace(); 7731 Slog.d(TAG, "Sending to user " + id + ": " 7732 + intent.toShortString(false, true, false, false) 7733 + " " + intent.getExtras(), here); 7734 } 7735 am.broadcastIntent(null, intent, null, finishedReceiver, 7736 0, null, null, null, android.app.AppOpsManager.OP_NONE, 7737 finishedReceiver != null, false, id); 7738 } 7739 } catch (RemoteException ex) { 7740 } 7741 } 7742 } 7743 7744 /** 7745 * Check if the external storage media is available. This is true if there 7746 * is a mounted external storage medium or if the external storage is 7747 * emulated. 7748 */ 7749 private boolean isExternalMediaAvailable() { 7750 return mMediaMounted || Environment.isExternalStorageEmulated(); 7751 } 7752 7753 @Override 7754 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 7755 // writer 7756 synchronized (mPackages) { 7757 if (!isExternalMediaAvailable()) { 7758 // If the external storage is no longer mounted at this point, 7759 // the caller may not have been able to delete all of this 7760 // packages files and can not delete any more. Bail. 7761 return null; 7762 } 7763 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 7764 if (lastPackage != null) { 7765 pkgs.remove(lastPackage); 7766 } 7767 if (pkgs.size() > 0) { 7768 return pkgs.get(0); 7769 } 7770 } 7771 return null; 7772 } 7773 7774 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 7775 if (false) { 7776 RuntimeException here = new RuntimeException("here"); 7777 here.fillInStackTrace(); 7778 Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId 7779 + " andCode=" + andCode, here); 7780 } 7781 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, 7782 userId, andCode ? 1 : 0, packageName)); 7783 } 7784 7785 void startCleaningPackages() { 7786 // reader 7787 synchronized (mPackages) { 7788 if (!isExternalMediaAvailable()) { 7789 return; 7790 } 7791 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 7792 return; 7793 } 7794 } 7795 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 7796 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 7797 IActivityManager am = ActivityManagerNative.getDefault(); 7798 if (am != null) { 7799 try { 7800 am.startService(null, intent, null, UserHandle.USER_OWNER); 7801 } catch (RemoteException e) { 7802 } 7803 } 7804 } 7805 7806 @Override 7807 public void installPackage(String originPath, IPackageInstallObserver2 observer, int flags, 7808 String installerPackageName, VerificationParams verificationParams, 7809 String packageAbiOverride) { 7810 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7811 null); 7812 7813 final File originFile = new File(originPath); 7814 final int uid = Binder.getCallingUid(); 7815 if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) { 7816 try { 7817 if (observer != null) { 7818 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 7819 } 7820 } catch (RemoteException re) { 7821 } 7822 return; 7823 } 7824 7825 UserHandle user; 7826 if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) { 7827 user = UserHandle.ALL; 7828 } else { 7829 user = new UserHandle(UserHandle.getUserId(uid)); 7830 } 7831 7832 final int filteredFlags; 7833 if (uid == Process.SHELL_UID || uid == 0) { 7834 if (DEBUG_INSTALL) { 7835 Slog.v(TAG, "Install from ADB"); 7836 } 7837 filteredFlags = flags | PackageManager.INSTALL_FROM_ADB; 7838 } else { 7839 filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB; 7840 } 7841 7842 verificationParams.setInstallerUid(uid); 7843 7844 final Message msg = mHandler.obtainMessage(INIT_COPY); 7845 msg.obj = new InstallParams(originFile, null, false, observer, filteredFlags, 7846 installerPackageName, verificationParams, user, packageAbiOverride); 7847 mHandler.sendMessage(msg); 7848 } 7849 7850 void installStage(String packageName, File stagedDir, String stagedCid, 7851 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 7852 String installerPackageName, int installerUid, UserHandle user) { 7853 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 7854 params.referrerUri, installerUid, null); 7855 7856 final Message msg = mHandler.obtainMessage(INIT_COPY); 7857 msg.obj = new InstallParams(stagedDir, stagedCid, true, observer, params.installFlags, 7858 installerPackageName, verifParams, user, params.abiOverride); 7859 mHandler.sendMessage(msg); 7860 } 7861 7862 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 7863 Bundle extras = new Bundle(1); 7864 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 7865 7866 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 7867 packageName, extras, null, null, new int[] {userId}); 7868 try { 7869 IActivityManager am = ActivityManagerNative.getDefault(); 7870 final boolean isSystem = 7871 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 7872 if (isSystem && am.isUserRunning(userId, false)) { 7873 // The just-installed/enabled app is bundled on the system, so presumed 7874 // to be able to run automatically without needing an explicit launch. 7875 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 7876 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 7877 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 7878 .setPackage(packageName); 7879 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 7880 android.app.AppOpsManager.OP_NONE, false, false, userId); 7881 } 7882 } catch (RemoteException e) { 7883 // shouldn't happen 7884 Slog.w(TAG, "Unable to bootstrap installed package", e); 7885 } 7886 } 7887 7888 @Override 7889 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 7890 int userId) { 7891 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7892 PackageSetting pkgSetting; 7893 final int uid = Binder.getCallingUid(); 7894 if (UserHandle.getUserId(uid) != userId) { 7895 mContext.enforceCallingOrSelfPermission( 7896 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 7897 "setApplicationHiddenSetting for user " + userId); 7898 } 7899 7900 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 7901 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 7902 return false; 7903 } 7904 7905 long callingId = Binder.clearCallingIdentity(); 7906 try { 7907 boolean sendAdded = false; 7908 boolean sendRemoved = false; 7909 // writer 7910 synchronized (mPackages) { 7911 pkgSetting = mSettings.mPackages.get(packageName); 7912 if (pkgSetting == null) { 7913 return false; 7914 } 7915 if (pkgSetting.getHidden(userId) != hidden) { 7916 pkgSetting.setHidden(hidden, userId); 7917 mSettings.writePackageRestrictionsLPr(userId); 7918 if (hidden) { 7919 sendRemoved = true; 7920 } else { 7921 sendAdded = true; 7922 } 7923 } 7924 } 7925 if (sendAdded) { 7926 sendPackageAddedForUser(packageName, pkgSetting, userId); 7927 return true; 7928 } 7929 if (sendRemoved) { 7930 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 7931 "hiding pkg"); 7932 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 7933 } 7934 } finally { 7935 Binder.restoreCallingIdentity(callingId); 7936 } 7937 return false; 7938 } 7939 7940 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 7941 int userId) { 7942 final PackageRemovedInfo info = new PackageRemovedInfo(); 7943 info.removedPackage = packageName; 7944 info.removedUsers = new int[] {userId}; 7945 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 7946 info.sendBroadcast(false, false, false); 7947 } 7948 7949 /** 7950 * Returns true if application is not found or there was an error. Otherwise it returns 7951 * the hidden state of the package for the given user. 7952 */ 7953 @Override 7954 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 7955 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7956 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 7957 "getApplicationHidden for user " + userId); 7958 PackageSetting pkgSetting; 7959 long callingId = Binder.clearCallingIdentity(); 7960 try { 7961 // writer 7962 synchronized (mPackages) { 7963 pkgSetting = mSettings.mPackages.get(packageName); 7964 if (pkgSetting == null) { 7965 return true; 7966 } 7967 return pkgSetting.getHidden(userId); 7968 } 7969 } finally { 7970 Binder.restoreCallingIdentity(callingId); 7971 } 7972 } 7973 7974 /** 7975 * @hide 7976 */ 7977 @Override 7978 public int installExistingPackageAsUser(String packageName, int userId) { 7979 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7980 null); 7981 PackageSetting pkgSetting; 7982 final int uid = Binder.getCallingUid(); 7983 enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId); 7984 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 7985 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 7986 } 7987 7988 long callingId = Binder.clearCallingIdentity(); 7989 try { 7990 boolean sendAdded = false; 7991 Bundle extras = new Bundle(1); 7992 7993 // writer 7994 synchronized (mPackages) { 7995 pkgSetting = mSettings.mPackages.get(packageName); 7996 if (pkgSetting == null) { 7997 return PackageManager.INSTALL_FAILED_INVALID_URI; 7998 } 7999 if (!pkgSetting.getInstalled(userId)) { 8000 pkgSetting.setInstalled(true, userId); 8001 pkgSetting.setHidden(false, userId); 8002 mSettings.writePackageRestrictionsLPr(userId); 8003 sendAdded = true; 8004 } 8005 } 8006 8007 if (sendAdded) { 8008 sendPackageAddedForUser(packageName, pkgSetting, userId); 8009 } 8010 } finally { 8011 Binder.restoreCallingIdentity(callingId); 8012 } 8013 8014 return PackageManager.INSTALL_SUCCEEDED; 8015 } 8016 8017 boolean isUserRestricted(int userId, String restrictionKey) { 8018 Bundle restrictions = sUserManager.getUserRestrictions(userId); 8019 if (restrictions.getBoolean(restrictionKey, false)) { 8020 Log.w(TAG, "User is restricted: " + restrictionKey); 8021 return true; 8022 } 8023 return false; 8024 } 8025 8026 @Override 8027 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 8028 mContext.enforceCallingOrSelfPermission( 8029 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8030 "Only package verification agents can verify applications"); 8031 8032 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8033 final PackageVerificationResponse response = new PackageVerificationResponse( 8034 verificationCode, Binder.getCallingUid()); 8035 msg.arg1 = id; 8036 msg.obj = response; 8037 mHandler.sendMessage(msg); 8038 } 8039 8040 @Override 8041 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 8042 long millisecondsToDelay) { 8043 mContext.enforceCallingOrSelfPermission( 8044 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8045 "Only package verification agents can extend verification timeouts"); 8046 8047 final PackageVerificationState state = mPendingVerification.get(id); 8048 final PackageVerificationResponse response = new PackageVerificationResponse( 8049 verificationCodeAtTimeout, Binder.getCallingUid()); 8050 8051 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 8052 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 8053 } 8054 if (millisecondsToDelay < 0) { 8055 millisecondsToDelay = 0; 8056 } 8057 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 8058 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 8059 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 8060 } 8061 8062 if ((state != null) && !state.timeoutExtended()) { 8063 state.extendTimeout(); 8064 8065 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8066 msg.arg1 = id; 8067 msg.obj = response; 8068 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 8069 } 8070 } 8071 8072 private void broadcastPackageVerified(int verificationId, Uri packageUri, 8073 int verificationCode, UserHandle user) { 8074 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 8075 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 8076 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8077 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8078 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 8079 8080 mContext.sendBroadcastAsUser(intent, user, 8081 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 8082 } 8083 8084 private ComponentName matchComponentForVerifier(String packageName, 8085 List<ResolveInfo> receivers) { 8086 ActivityInfo targetReceiver = null; 8087 8088 final int NR = receivers.size(); 8089 for (int i = 0; i < NR; i++) { 8090 final ResolveInfo info = receivers.get(i); 8091 if (info.activityInfo == null) { 8092 continue; 8093 } 8094 8095 if (packageName.equals(info.activityInfo.packageName)) { 8096 targetReceiver = info.activityInfo; 8097 break; 8098 } 8099 } 8100 8101 if (targetReceiver == null) { 8102 return null; 8103 } 8104 8105 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8106 } 8107 8108 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8109 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8110 if (pkgInfo.verifiers.length == 0) { 8111 return null; 8112 } 8113 8114 final int N = pkgInfo.verifiers.length; 8115 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8116 for (int i = 0; i < N; i++) { 8117 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8118 8119 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8120 receivers); 8121 if (comp == null) { 8122 continue; 8123 } 8124 8125 final int verifierUid = getUidForVerifier(verifierInfo); 8126 if (verifierUid == -1) { 8127 continue; 8128 } 8129 8130 if (DEBUG_VERIFY) { 8131 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8132 + " with the correct signature"); 8133 } 8134 sufficientVerifiers.add(comp); 8135 verificationState.addSufficientVerifier(verifierUid); 8136 } 8137 8138 return sufficientVerifiers; 8139 } 8140 8141 private int getUidForVerifier(VerifierInfo verifierInfo) { 8142 synchronized (mPackages) { 8143 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8144 if (pkg == null) { 8145 return -1; 8146 } else if (pkg.mSignatures.length != 1) { 8147 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8148 + " has more than one signature; ignoring"); 8149 return -1; 8150 } 8151 8152 /* 8153 * If the public key of the package's signature does not match 8154 * our expected public key, then this is a different package and 8155 * we should skip. 8156 */ 8157 8158 final byte[] expectedPublicKey; 8159 try { 8160 final Signature verifierSig = pkg.mSignatures[0]; 8161 final PublicKey publicKey = verifierSig.getPublicKey(); 8162 expectedPublicKey = publicKey.getEncoded(); 8163 } catch (CertificateException e) { 8164 return -1; 8165 } 8166 8167 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8168 8169 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8170 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8171 + " does not have the expected public key; ignoring"); 8172 return -1; 8173 } 8174 8175 return pkg.applicationInfo.uid; 8176 } 8177 } 8178 8179 @Override 8180 public void finishPackageInstall(int token) { 8181 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8182 8183 if (DEBUG_INSTALL) { 8184 Slog.v(TAG, "BM finishing package install for " + token); 8185 } 8186 8187 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8188 mHandler.sendMessage(msg); 8189 } 8190 8191 /** 8192 * Get the verification agent timeout. 8193 * 8194 * @return verification timeout in milliseconds 8195 */ 8196 private long getVerificationTimeout() { 8197 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8198 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8199 DEFAULT_VERIFICATION_TIMEOUT); 8200 } 8201 8202 /** 8203 * Get the default verification agent response code. 8204 * 8205 * @return default verification response code 8206 */ 8207 private int getDefaultVerificationResponse() { 8208 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8209 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8210 DEFAULT_VERIFICATION_RESPONSE); 8211 } 8212 8213 /** 8214 * Check whether or not package verification has been enabled. 8215 * 8216 * @return true if verification should be performed 8217 */ 8218 private boolean isVerificationEnabled(int userId, int flags) { 8219 if (!DEFAULT_VERIFY_ENABLE) { 8220 return false; 8221 } 8222 8223 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 8224 8225 // Check if installing from ADB 8226 if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) { 8227 // Do not run verification in a test harness environment 8228 if (ActivityManager.isRunningInTestHarness()) { 8229 return false; 8230 } 8231 if (ensureVerifyAppsEnabled) { 8232 return true; 8233 } 8234 // Check if the developer does not want package verification for ADB installs 8235 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8236 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8237 return false; 8238 } 8239 } 8240 8241 if (ensureVerifyAppsEnabled) { 8242 return true; 8243 } 8244 8245 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8246 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8247 } 8248 8249 /** 8250 * Get the "allow unknown sources" setting. 8251 * 8252 * @return the current "allow unknown sources" setting 8253 */ 8254 private int getUnknownSourcesSettings() { 8255 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8256 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 8257 -1); 8258 } 8259 8260 @Override 8261 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 8262 final int uid = Binder.getCallingUid(); 8263 // writer 8264 synchronized (mPackages) { 8265 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 8266 if (targetPackageSetting == null) { 8267 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 8268 } 8269 8270 PackageSetting installerPackageSetting; 8271 if (installerPackageName != null) { 8272 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 8273 if (installerPackageSetting == null) { 8274 throw new IllegalArgumentException("Unknown installer package: " 8275 + installerPackageName); 8276 } 8277 } else { 8278 installerPackageSetting = null; 8279 } 8280 8281 Signature[] callerSignature; 8282 Object obj = mSettings.getUserIdLPr(uid); 8283 if (obj != null) { 8284 if (obj instanceof SharedUserSetting) { 8285 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 8286 } else if (obj instanceof PackageSetting) { 8287 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 8288 } else { 8289 throw new SecurityException("Bad object " + obj + " for uid " + uid); 8290 } 8291 } else { 8292 throw new SecurityException("Unknown calling uid " + uid); 8293 } 8294 8295 // Verify: can't set installerPackageName to a package that is 8296 // not signed with the same cert as the caller. 8297 if (installerPackageSetting != null) { 8298 if (compareSignatures(callerSignature, 8299 installerPackageSetting.signatures.mSignatures) 8300 != PackageManager.SIGNATURE_MATCH) { 8301 throw new SecurityException( 8302 "Caller does not have same cert as new installer package " 8303 + installerPackageName); 8304 } 8305 } 8306 8307 // Verify: if target already has an installer package, it must 8308 // be signed with the same cert as the caller. 8309 if (targetPackageSetting.installerPackageName != null) { 8310 PackageSetting setting = mSettings.mPackages.get( 8311 targetPackageSetting.installerPackageName); 8312 // If the currently set package isn't valid, then it's always 8313 // okay to change it. 8314 if (setting != null) { 8315 if (compareSignatures(callerSignature, 8316 setting.signatures.mSignatures) 8317 != PackageManager.SIGNATURE_MATCH) { 8318 throw new SecurityException( 8319 "Caller does not have same cert as old installer package " 8320 + targetPackageSetting.installerPackageName); 8321 } 8322 } 8323 } 8324 8325 // Okay! 8326 targetPackageSetting.installerPackageName = installerPackageName; 8327 scheduleWriteSettingsLocked(); 8328 } 8329 } 8330 8331 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 8332 // Queue up an async operation since the package installation may take a little while. 8333 mHandler.post(new Runnable() { 8334 public void run() { 8335 mHandler.removeCallbacks(this); 8336 // Result object to be returned 8337 PackageInstalledInfo res = new PackageInstalledInfo(); 8338 res.returnCode = currentStatus; 8339 res.uid = -1; 8340 res.pkg = null; 8341 res.removedInfo = new PackageRemovedInfo(); 8342 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 8343 args.doPreInstall(res.returnCode); 8344 synchronized (mInstallLock) { 8345 installPackageLI(args, true, res); 8346 } 8347 args.doPostInstall(res.returnCode, res.uid); 8348 } 8349 8350 // A restore should be performed at this point if (a) the install 8351 // succeeded, (b) the operation is not an update, and (c) the new 8352 // package has not opted out of backup participation. 8353 final boolean update = res.removedInfo.removedPackage != null; 8354 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 8355 boolean doRestore = !update 8356 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 8357 8358 // Set up the post-install work request bookkeeping. This will be used 8359 // and cleaned up by the post-install event handling regardless of whether 8360 // there's a restore pass performed. Token values are >= 1. 8361 int token; 8362 if (mNextInstallToken < 0) mNextInstallToken = 1; 8363 token = mNextInstallToken++; 8364 8365 PostInstallData data = new PostInstallData(args, res); 8366 mRunningInstalls.put(token, data); 8367 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 8368 8369 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 8370 // Pass responsibility to the Backup Manager. It will perform a 8371 // restore if appropriate, then pass responsibility back to the 8372 // Package Manager to run the post-install observer callbacks 8373 // and broadcasts. 8374 IBackupManager bm = IBackupManager.Stub.asInterface( 8375 ServiceManager.getService(Context.BACKUP_SERVICE)); 8376 if (bm != null) { 8377 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 8378 + " to BM for possible restore"); 8379 try { 8380 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 8381 } catch (RemoteException e) { 8382 // can't happen; the backup manager is local 8383 } catch (Exception e) { 8384 Slog.e(TAG, "Exception trying to enqueue restore", e); 8385 doRestore = false; 8386 } 8387 } else { 8388 Slog.e(TAG, "Backup Manager not found!"); 8389 doRestore = false; 8390 } 8391 } 8392 8393 if (!doRestore) { 8394 // No restore possible, or the Backup Manager was mysteriously not 8395 // available -- just fire the post-install work request directly. 8396 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 8397 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8398 mHandler.sendMessage(msg); 8399 } 8400 } 8401 }); 8402 } 8403 8404 private abstract class HandlerParams { 8405 private static final int MAX_RETRIES = 4; 8406 8407 /** 8408 * Number of times startCopy() has been attempted and had a non-fatal 8409 * error. 8410 */ 8411 private int mRetries = 0; 8412 8413 /** User handle for the user requesting the information or installation. */ 8414 private final UserHandle mUser; 8415 8416 HandlerParams(UserHandle user) { 8417 mUser = user; 8418 } 8419 8420 UserHandle getUser() { 8421 return mUser; 8422 } 8423 8424 final boolean startCopy() { 8425 boolean res; 8426 try { 8427 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 8428 8429 if (++mRetries > MAX_RETRIES) { 8430 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 8431 mHandler.sendEmptyMessage(MCS_GIVE_UP); 8432 handleServiceError(); 8433 return false; 8434 } else { 8435 handleStartCopy(); 8436 res = true; 8437 } 8438 } catch (RemoteException e) { 8439 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 8440 mHandler.sendEmptyMessage(MCS_RECONNECT); 8441 res = false; 8442 } 8443 handleReturnCode(); 8444 return res; 8445 } 8446 8447 final void serviceError() { 8448 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 8449 handleServiceError(); 8450 handleReturnCode(); 8451 } 8452 8453 abstract void handleStartCopy() throws RemoteException; 8454 abstract void handleServiceError(); 8455 abstract void handleReturnCode(); 8456 } 8457 8458 class MeasureParams extends HandlerParams { 8459 private final PackageStats mStats; 8460 private boolean mSuccess; 8461 8462 private final IPackageStatsObserver mObserver; 8463 8464 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 8465 super(new UserHandle(stats.userHandle)); 8466 mObserver = observer; 8467 mStats = stats; 8468 } 8469 8470 @Override 8471 public String toString() { 8472 return "MeasureParams{" 8473 + Integer.toHexString(System.identityHashCode(this)) 8474 + " " + mStats.packageName + "}"; 8475 } 8476 8477 @Override 8478 void handleStartCopy() throws RemoteException { 8479 synchronized (mInstallLock) { 8480 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 8481 } 8482 8483 if (mSuccess) { 8484 final boolean mounted; 8485 if (Environment.isExternalStorageEmulated()) { 8486 mounted = true; 8487 } else { 8488 final String status = Environment.getExternalStorageState(); 8489 mounted = (Environment.MEDIA_MOUNTED.equals(status) 8490 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 8491 } 8492 8493 if (mounted) { 8494 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 8495 8496 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 8497 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 8498 8499 mStats.externalDataSize = calculateDirectorySize(mContainerService, 8500 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 8501 8502 // Always subtract cache size, since it's a subdirectory 8503 mStats.externalDataSize -= mStats.externalCacheSize; 8504 8505 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 8506 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 8507 8508 mStats.externalObbSize = calculateDirectorySize(mContainerService, 8509 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 8510 } 8511 } 8512 } 8513 8514 @Override 8515 void handleReturnCode() { 8516 if (mObserver != null) { 8517 try { 8518 mObserver.onGetStatsCompleted(mStats, mSuccess); 8519 } catch (RemoteException e) { 8520 Slog.i(TAG, "Observer no longer exists."); 8521 } 8522 } 8523 } 8524 8525 @Override 8526 void handleServiceError() { 8527 Slog.e(TAG, "Could not measure application " + mStats.packageName 8528 + " external storage"); 8529 } 8530 } 8531 8532 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 8533 throws RemoteException { 8534 long result = 0; 8535 for (File path : paths) { 8536 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 8537 } 8538 return result; 8539 } 8540 8541 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 8542 for (File path : paths) { 8543 try { 8544 mcs.clearDirectory(path.getAbsolutePath()); 8545 } catch (RemoteException e) { 8546 } 8547 } 8548 } 8549 8550 class InstallParams extends HandlerParams { 8551 /** 8552 * Location where install is coming from, before it has been 8553 * copied/renamed into place. This could be a single monolithic APK 8554 * file, or a cluster directory. This location may be untrusted. 8555 */ 8556 final File originFile; 8557 final String originCid; 8558 8559 /** 8560 * Flag indicating that {@link #originFile} or {@link #originCid} has 8561 * already been staged, meaning downstream users don't need to 8562 * defensively copy the contents. 8563 */ 8564 boolean originStaged; 8565 8566 final IPackageInstallObserver2 observer; 8567 int flags; 8568 final String installerPackageName; 8569 final VerificationParams verificationParams; 8570 private InstallArgs mArgs; 8571 private int mRet; 8572 final String packageAbiOverride; 8573 boolean multiArch; 8574 8575 InstallParams(File originFile, String originCid, boolean originStaged, 8576 IPackageInstallObserver2 observer, int flags, String installerPackageName, 8577 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 8578 super(user); 8579 this.originFile = originFile; 8580 this.originCid = originCid; 8581 this.originStaged = originStaged; 8582 this.observer = observer; 8583 this.flags = flags; 8584 this.installerPackageName = installerPackageName; 8585 this.verificationParams = verificationParams; 8586 this.packageAbiOverride = packageAbiOverride; 8587 } 8588 8589 @Override 8590 public String toString() { 8591 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 8592 + " file=" + originFile + " cid=" + originCid + "}"; 8593 } 8594 8595 public ManifestDigest getManifestDigest() { 8596 if (verificationParams == null) { 8597 return null; 8598 } 8599 return verificationParams.getManifestDigest(); 8600 } 8601 8602 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) { 8603 String packageName = pkgLite.packageName; 8604 int installLocation = pkgLite.installLocation; 8605 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8606 // reader 8607 synchronized (mPackages) { 8608 PackageParser.Package pkg = mPackages.get(packageName); 8609 if (pkg != null) { 8610 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 8611 // Check for downgrading. 8612 if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 8613 if (pkgLite.versionCode < pkg.mVersionCode) { 8614 Slog.w(TAG, "Can't install update of " + packageName 8615 + " update version " + pkgLite.versionCode 8616 + " is older than installed version " 8617 + pkg.mVersionCode); 8618 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 8619 } 8620 } 8621 // Check for updated system application. 8622 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8623 if (onSd) { 8624 Slog.w(TAG, "Cannot install update to system app on sdcard"); 8625 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 8626 } 8627 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8628 } else { 8629 if (onSd) { 8630 // Install flag overrides everything. 8631 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8632 } 8633 // If current upgrade specifies particular preference 8634 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 8635 // Application explicitly specified internal. 8636 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8637 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 8638 // App explictly prefers external. Let policy decide 8639 } else { 8640 // Prefer previous location 8641 if (isExternal(pkg)) { 8642 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8643 } 8644 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8645 } 8646 } 8647 } else { 8648 // Invalid install. Return error code 8649 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 8650 } 8651 } 8652 } 8653 // All the special cases have been taken care of. 8654 // Return result based on recommended install location. 8655 if (onSd) { 8656 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8657 } 8658 return pkgLite.recommendedInstallLocation; 8659 } 8660 8661 /* 8662 * Invoke remote method to get package information and install 8663 * location values. Override install location based on default 8664 * policy if needed and then create install arguments based 8665 * on the install location. 8666 */ 8667 public void handleStartCopy() throws RemoteException { 8668 int ret = PackageManager.INSTALL_SUCCEEDED; 8669 final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8670 final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0; 8671 PackageInfoLite pkgLite = null; 8672 8673 if (onInt && onSd) { 8674 // Check if both bits are set. 8675 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 8676 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8677 } else { 8678 // Remote call to find out default install location 8679 final String originPath = originFile.getAbsolutePath(); 8680 pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags, 8681 packageAbiOverride); 8682 // Keep track of whether this package is a multiArch package until 8683 // we perform a full scan of it. We need to do this because we might 8684 // end up extracting the package shared libraries before we perform 8685 // a full scan. 8686 multiArch = pkgLite.multiArch; 8687 8688 /* 8689 * If we have too little free space, try to free cache 8690 * before giving up. 8691 */ 8692 if (pkgLite.recommendedInstallLocation 8693 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8694 // TODO: focus freeing disk space on the target device 8695 final StorageManager storage = StorageManager.from(mContext); 8696 final long lowThreshold = storage.getStorageLowBytes( 8697 Environment.getDataDirectory()); 8698 8699 final long sizeBytes = mContainerService.calculateInstalledSize( 8700 originPath, isForwardLocked(), packageAbiOverride); 8701 8702 if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) { 8703 pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags, 8704 packageAbiOverride); 8705 } 8706 8707 /* 8708 * The cache free must have deleted the file we 8709 * downloaded to install. 8710 * 8711 * TODO: fix the "freeCache" call to not delete 8712 * the file we care about. 8713 */ 8714 if (pkgLite.recommendedInstallLocation 8715 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8716 pkgLite.recommendedInstallLocation 8717 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 8718 } 8719 } 8720 } 8721 8722 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8723 int loc = pkgLite.recommendedInstallLocation; 8724 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 8725 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8726 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 8727 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 8728 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8729 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8730 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 8731 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 8732 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8733 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 8734 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 8735 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 8736 } else { 8737 // Override with defaults if needed. 8738 loc = installLocationPolicy(pkgLite, flags); 8739 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 8740 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 8741 } else if (!onSd && !onInt) { 8742 // Override install location with flags 8743 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 8744 // Set the flag to install on external media. 8745 flags |= PackageManager.INSTALL_EXTERNAL; 8746 flags &= ~PackageManager.INSTALL_INTERNAL; 8747 } else { 8748 // Make sure the flag for installing on external 8749 // media is unset 8750 flags |= PackageManager.INSTALL_INTERNAL; 8751 flags &= ~PackageManager.INSTALL_EXTERNAL; 8752 } 8753 } 8754 } 8755 } 8756 8757 final InstallArgs args = createInstallArgs(this); 8758 mArgs = args; 8759 8760 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8761 /* 8762 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 8763 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 8764 */ 8765 int userIdentifier = getUser().getIdentifier(); 8766 if (userIdentifier == UserHandle.USER_ALL 8767 && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) { 8768 userIdentifier = UserHandle.USER_OWNER; 8769 } 8770 8771 /* 8772 * Determine if we have any installed package verifiers. If we 8773 * do, then we'll defer to them to verify the packages. 8774 */ 8775 final int requiredUid = mRequiredVerifierPackage == null ? -1 8776 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 8777 if (requiredUid != -1 && isVerificationEnabled(userIdentifier, flags)) { 8778 // TODO: send verifier the install session instead of uri 8779 final Intent verification = new Intent( 8780 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 8781 verification.setDataAndType(Uri.fromFile(originFile), PACKAGE_MIME_TYPE); 8782 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8783 8784 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 8785 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 8786 0 /* TODO: Which userId? */); 8787 8788 if (DEBUG_VERIFY) { 8789 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 8790 + verification.toString() + " with " + pkgLite.verifiers.length 8791 + " optional verifiers"); 8792 } 8793 8794 final int verificationId = mPendingVerificationToken++; 8795 8796 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8797 8798 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 8799 installerPackageName); 8800 8801 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags); 8802 8803 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 8804 pkgLite.packageName); 8805 8806 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 8807 pkgLite.versionCode); 8808 8809 if (verificationParams != null) { 8810 if (verificationParams.getVerificationURI() != null) { 8811 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 8812 verificationParams.getVerificationURI()); 8813 } 8814 if (verificationParams.getOriginatingURI() != null) { 8815 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 8816 verificationParams.getOriginatingURI()); 8817 } 8818 if (verificationParams.getReferrer() != null) { 8819 verification.putExtra(Intent.EXTRA_REFERRER, 8820 verificationParams.getReferrer()); 8821 } 8822 if (verificationParams.getOriginatingUid() >= 0) { 8823 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 8824 verificationParams.getOriginatingUid()); 8825 } 8826 if (verificationParams.getInstallerUid() >= 0) { 8827 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 8828 verificationParams.getInstallerUid()); 8829 } 8830 } 8831 8832 final PackageVerificationState verificationState = new PackageVerificationState( 8833 requiredUid, args); 8834 8835 mPendingVerification.append(verificationId, verificationState); 8836 8837 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 8838 receivers, verificationState); 8839 8840 /* 8841 * If any sufficient verifiers were listed in the package 8842 * manifest, attempt to ask them. 8843 */ 8844 if (sufficientVerifiers != null) { 8845 final int N = sufficientVerifiers.size(); 8846 if (N == 0) { 8847 Slog.i(TAG, "Additional verifiers required, but none installed."); 8848 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 8849 } else { 8850 for (int i = 0; i < N; i++) { 8851 final ComponentName verifierComponent = sufficientVerifiers.get(i); 8852 8853 final Intent sufficientIntent = new Intent(verification); 8854 sufficientIntent.setComponent(verifierComponent); 8855 8856 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 8857 } 8858 } 8859 } 8860 8861 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 8862 mRequiredVerifierPackage, receivers); 8863 if (ret == PackageManager.INSTALL_SUCCEEDED 8864 && mRequiredVerifierPackage != null) { 8865 /* 8866 * Send the intent to the required verification agent, 8867 * but only start the verification timeout after the 8868 * target BroadcastReceivers have run. 8869 */ 8870 verification.setComponent(requiredVerifierComponent); 8871 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 8872 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8873 new BroadcastReceiver() { 8874 @Override 8875 public void onReceive(Context context, Intent intent) { 8876 final Message msg = mHandler 8877 .obtainMessage(CHECK_PENDING_VERIFICATION); 8878 msg.arg1 = verificationId; 8879 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 8880 } 8881 }, null, 0, null, null); 8882 8883 /* 8884 * We don't want the copy to proceed until verification 8885 * succeeds, so null out this field. 8886 */ 8887 mArgs = null; 8888 } 8889 } else { 8890 /* 8891 * No package verification is enabled, so immediately start 8892 * the remote call to initiate copy using temporary file. 8893 */ 8894 ret = args.copyApk(mContainerService, true); 8895 } 8896 } 8897 8898 mRet = ret; 8899 } 8900 8901 @Override 8902 void handleReturnCode() { 8903 // If mArgs is null, then MCS couldn't be reached. When it 8904 // reconnects, it will try again to install. At that point, this 8905 // will succeed. 8906 if (mArgs != null) { 8907 processPendingInstall(mArgs, mRet); 8908 } 8909 } 8910 8911 @Override 8912 void handleServiceError() { 8913 mArgs = createInstallArgs(this); 8914 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8915 } 8916 8917 public boolean isForwardLocked() { 8918 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8919 } 8920 } 8921 8922 /* 8923 * Utility class used in movePackage api. 8924 * srcArgs and targetArgs are not set for invalid flags and make 8925 * sure to do null checks when invoking methods on them. 8926 * We probably want to return ErrorPrams for both failed installs 8927 * and moves. 8928 */ 8929 class MoveParams extends HandlerParams { 8930 final IPackageMoveObserver observer; 8931 final int flags; 8932 final String packageName; 8933 final InstallArgs srcArgs; 8934 final InstallArgs targetArgs; 8935 int uid; 8936 int mRet; 8937 8938 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags, 8939 String packageName, String[] instructionSets, int uid, UserHandle user, 8940 boolean isMultiArch) { 8941 super(user); 8942 this.srcArgs = srcArgs; 8943 this.observer = observer; 8944 this.flags = flags; 8945 this.packageName = packageName; 8946 this.uid = uid; 8947 if (srcArgs != null) { 8948 final String codePath = srcArgs.getCodePath(); 8949 targetArgs = createInstallArgsForMoveTarget(codePath, flags, packageName, 8950 instructionSets, isMultiArch); 8951 } else { 8952 targetArgs = null; 8953 } 8954 } 8955 8956 @Override 8957 public String toString() { 8958 return "MoveParams{" 8959 + Integer.toHexString(System.identityHashCode(this)) 8960 + " " + packageName + "}"; 8961 } 8962 8963 public void handleStartCopy() throws RemoteException { 8964 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8965 // Check for storage space on target medium 8966 if (!targetArgs.checkFreeStorage(mContainerService)) { 8967 Log.w(TAG, "Insufficient storage to install"); 8968 return; 8969 } 8970 8971 mRet = srcArgs.doPreCopy(); 8972 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8973 return; 8974 } 8975 8976 mRet = targetArgs.copyApk(mContainerService, false); 8977 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8978 srcArgs.doPostCopy(uid); 8979 return; 8980 } 8981 8982 mRet = srcArgs.doPostCopy(uid); 8983 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8984 return; 8985 } 8986 8987 mRet = targetArgs.doPreInstall(mRet); 8988 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8989 return; 8990 } 8991 8992 if (DEBUG_SD_INSTALL) { 8993 StringBuilder builder = new StringBuilder(); 8994 if (srcArgs != null) { 8995 builder.append("src: "); 8996 builder.append(srcArgs.getCodePath()); 8997 } 8998 if (targetArgs != null) { 8999 builder.append(" target : "); 9000 builder.append(targetArgs.getCodePath()); 9001 } 9002 Log.i(TAG, builder.toString()); 9003 } 9004 } 9005 9006 @Override 9007 void handleReturnCode() { 9008 targetArgs.doPostInstall(mRet, uid); 9009 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 9010 if (mRet == PackageManager.INSTALL_SUCCEEDED) { 9011 currentStatus = PackageManager.MOVE_SUCCEEDED; 9012 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){ 9013 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 9014 } 9015 processPendingMove(this, currentStatus); 9016 } 9017 9018 @Override 9019 void handleServiceError() { 9020 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9021 } 9022 } 9023 9024 /** 9025 * Used during creation of InstallArgs 9026 * 9027 * @param flags package installation flags 9028 * @return true if should be installed on external storage 9029 */ 9030 private static boolean installOnSd(int flags) { 9031 if ((flags & PackageManager.INSTALL_INTERNAL) != 0) { 9032 return false; 9033 } 9034 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) { 9035 return true; 9036 } 9037 return false; 9038 } 9039 9040 /** 9041 * Used during creation of InstallArgs 9042 * 9043 * @param flags package installation flags 9044 * @return true if should be installed as forward locked 9045 */ 9046 private static boolean installForwardLocked(int flags) { 9047 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9048 } 9049 9050 private InstallArgs createInstallArgs(InstallParams params) { 9051 // TODO: extend to support incoming zero-copy locations 9052 9053 if (installOnSd(params.flags) || params.isForwardLocked()) { 9054 return new AsecInstallArgs(params); 9055 } else { 9056 return new FileInstallArgs(params); 9057 } 9058 } 9059 9060 /** 9061 * Create args that describe an existing installed package. Typically used 9062 * when cleaning up old installs, or used as a move source. 9063 */ 9064 private InstallArgs createInstallArgsForExisting(int flags, String codePath, 9065 String resourcePath, String nativeLibraryRoot, String[] instructionSets, 9066 boolean isMultiArch) { 9067 final boolean isInAsec; 9068 if (installOnSd(flags)) { 9069 /* Apps on SD card are always in ASEC containers. */ 9070 isInAsec = true; 9071 } else if (installForwardLocked(flags) 9072 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 9073 /* 9074 * Forward-locked apps are only in ASEC containers if they're the 9075 * new style 9076 */ 9077 isInAsec = true; 9078 } else { 9079 isInAsec = false; 9080 } 9081 9082 if (isInAsec) { 9083 return new AsecInstallArgs(codePath, instructionSets, 9084 installOnSd(flags), installForwardLocked(flags), isMultiArch); 9085 } else { 9086 return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot, 9087 instructionSets, isMultiArch); 9088 } 9089 } 9090 9091 private InstallArgs createInstallArgsForMoveTarget(String codePath, int flags, String pkgName, 9092 String[] instructionSets, boolean isMultiArch) { 9093 final File codeFile = new File(codePath); 9094 if (installOnSd(flags) || installForwardLocked(flags)) { 9095 String cid = getNextCodePath(codePath, pkgName, "/" 9096 + AsecInstallArgs.RES_FILE_NAME); 9097 return new AsecInstallArgs(codeFile, cid, instructionSets, installOnSd(flags), 9098 installForwardLocked(flags), isMultiArch); 9099 } else { 9100 return new FileInstallArgs(codeFile, instructionSets, isMultiArch); 9101 } 9102 } 9103 9104 static abstract class InstallArgs { 9105 /** @see InstallParams#originFile */ 9106 final File originFile; 9107 /** @see InstallParams#originStaged */ 9108 final boolean originStaged; 9109 9110 // TODO: define inherit location 9111 9112 final IPackageInstallObserver2 observer; 9113 // Always refers to PackageManager flags only 9114 final int flags; 9115 final String installerPackageName; 9116 final ManifestDigest manifestDigest; 9117 final UserHandle user; 9118 final String abiOverride; 9119 final boolean multiArch; 9120 9121 // The list of instruction sets supported by this app. This is currently 9122 // only used during the rmdex() phase to clean up resources. We can get rid of this 9123 // if we move dex files under the common app path. 9124 /* nullable */ String[] instructionSets; 9125 9126 InstallArgs(File originFile, boolean originStaged, IPackageInstallObserver2 observer, 9127 int flags, String installerPackageName, ManifestDigest manifestDigest, 9128 UserHandle user, String[] instructionSets, 9129 String abiOverride, boolean multiArch) { 9130 this.originFile = originFile; 9131 this.originStaged = originStaged; 9132 this.flags = flags; 9133 this.observer = observer; 9134 this.installerPackageName = installerPackageName; 9135 this.manifestDigest = manifestDigest; 9136 this.user = user; 9137 this.instructionSets = instructionSets; 9138 this.abiOverride = abiOverride; 9139 this.multiArch = multiArch; 9140 } 9141 9142 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 9143 abstract int doPreInstall(int status); 9144 9145 /** 9146 * Rename package into final resting place. All paths on the given 9147 * scanned package should be updated to reflect the rename. 9148 */ 9149 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 9150 abstract int doPostInstall(int status, int uid); 9151 9152 /** @see PackageSettingBase#codePathString */ 9153 abstract String getCodePath(); 9154 /** @see PackageSettingBase#resourcePathString */ 9155 abstract String getResourcePath(); 9156 abstract String getLegacyNativeLibraryPath(); 9157 9158 // Need installer lock especially for dex file removal. 9159 abstract void cleanUpResourcesLI(); 9160 abstract boolean doPostDeleteLI(boolean delete); 9161 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9162 9163 /** 9164 * Called before the source arguments are copied. This is used mostly 9165 * for MoveParams when it needs to read the source file to put it in the 9166 * destination. 9167 */ 9168 int doPreCopy() { 9169 return PackageManager.INSTALL_SUCCEEDED; 9170 } 9171 9172 /** 9173 * Called after the source arguments are copied. This is used mostly for 9174 * MoveParams when it needs to read the source file to put it in the 9175 * destination. 9176 * 9177 * @return 9178 */ 9179 int doPostCopy(int uid) { 9180 return PackageManager.INSTALL_SUCCEEDED; 9181 } 9182 9183 protected boolean isFwdLocked() { 9184 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9185 } 9186 9187 UserHandle getUser() { 9188 return user; 9189 } 9190 } 9191 9192 /** 9193 * Logic to handle installation of non-ASEC applications, including copying 9194 * and renaming logic. 9195 */ 9196 class FileInstallArgs extends InstallArgs { 9197 private File codeFile; 9198 private File resourceFile; 9199 private File legacyNativeLibraryPath; 9200 9201 // Example topology: 9202 // /data/app/com.example/base.apk 9203 // /data/app/com.example/split_foo.apk 9204 // /data/app/com.example/lib/arm/libfoo.so 9205 // /data/app/com.example/lib/arm64/libfoo.so 9206 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 9207 9208 /** New install */ 9209 FileInstallArgs(InstallParams params) { 9210 super(params.originFile, params.originStaged, params.observer, params.flags, 9211 params.installerPackageName, params.getManifestDigest(), params.getUser(), 9212 null /* instruction sets */, params.packageAbiOverride, 9213 params.multiArch); 9214 if (isFwdLocked()) { 9215 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 9216 } 9217 } 9218 9219 /** Existing install */ 9220 FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath, 9221 String[] instructionSets, boolean isMultiArch) { 9222 super(null, false, null, 0, null, null, null, instructionSets, null, isMultiArch); 9223 this.codeFile = (codePath != null) ? new File(codePath) : null; 9224 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 9225 this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ? 9226 new File(legacyNativeLibraryPath) : null; 9227 } 9228 9229 /** New install from existing */ 9230 FileInstallArgs(File originFile, String[] instructionSets, boolean isMultiArch) { 9231 super(originFile, false, null, 0, null, null, null, instructionSets, null, 9232 isMultiArch); 9233 } 9234 9235 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9236 final long sizeBytes = imcs.calculateInstalledSize(originFile.getAbsolutePath(), 9237 isFwdLocked(), abiOverride); 9238 9239 final StorageManager storage = StorageManager.from(mContext); 9240 return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory())); 9241 } 9242 9243 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9244 int ret = PackageManager.INSTALL_SUCCEEDED; 9245 9246 if (originStaged) { 9247 Slog.d(TAG, originFile + " already staged; skipping copy"); 9248 codeFile = originFile; 9249 resourceFile = originFile; 9250 } else { 9251 try { 9252 final File tempDir = mInstallerService.allocateInternalStageDirLegacy(); 9253 codeFile = tempDir; 9254 resourceFile = tempDir; 9255 } catch (IOException e) { 9256 Slog.w(TAG, "Failed to create copy file: " + e); 9257 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9258 } 9259 9260 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 9261 @Override 9262 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 9263 if (!FileUtils.isValidExtFilename(name)) { 9264 throw new IllegalArgumentException("Invalid filename: " + name); 9265 } 9266 try { 9267 final File file = new File(codeFile, name); 9268 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 9269 O_RDWR | O_CREAT, 0644); 9270 Os.chmod(file.getAbsolutePath(), 0644); 9271 return new ParcelFileDescriptor(fd); 9272 } catch (ErrnoException e) { 9273 throw new RemoteException("Failed to open: " + e.getMessage()); 9274 } 9275 } 9276 }; 9277 9278 ret = imcs.copyPackage(originFile.getAbsolutePath(), target); 9279 if (ret != PackageManager.INSTALL_SUCCEEDED) { 9280 Slog.e(TAG, "Failed to copy package"); 9281 return ret; 9282 } 9283 } 9284 9285 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 9286 NativeLibraryHelper.Handle handle = null; 9287 try { 9288 handle = NativeLibraryHelper.Handle.create(codeFile); 9289 if (multiArch) { 9290 // Warn if we've set an abiOverride for multi-lib packages.. 9291 // By definition, we need to copy both 32 and 64 bit libraries for 9292 // such packages. 9293 if (abiOverride != null && !CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 9294 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 9295 } 9296 9297 int copyRet = PackageManager.NO_NATIVE_LIBRARIES; 9298 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 9299 copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot, 9300 Build.SUPPORTED_32_BIT_ABIS, true /* use isa specific subdirs */); 9301 maybeThrowExceptionForMultiArchCopy("Failure copying 32 bit native libraries", copyRet); 9302 } 9303 9304 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 9305 copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot, 9306 Build.SUPPORTED_64_BIT_ABIS, true /* use isa specific subdirs */); 9307 maybeThrowExceptionForMultiArchCopy("Failure copying 64 bit native libraries", copyRet); 9308 } 9309 } else { 9310 final String cpuAbiOverride = deriveAbiOverride(this.abiOverride, null /* package setting */); 9311 String[] abiList = (cpuAbiOverride != null) ? 9312 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 9313 9314 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 9315 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9316 abiList = Build.SUPPORTED_32_BIT_ABIS; 9317 } 9318 9319 int copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot, abiList, 9320 true /* use isa specific subdirs */); 9321 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9322 Slog.w(TAG, "Failure copying native libraries [errorCode=" + copyRet + "]"); 9323 return copyRet; 9324 } 9325 } 9326 } catch (IOException e) { 9327 Slog.e(TAG, "Copying native libraries failed", e); 9328 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9329 } catch (PackageManagerException pme) { 9330 Slog.e(TAG, "Copying native libraries failed", pme); 9331 ret = pme.error; 9332 } finally { 9333 IoUtils.closeQuietly(handle); 9334 } 9335 9336 return ret; 9337 } 9338 9339 int doPreInstall(int status) { 9340 if (status != PackageManager.INSTALL_SUCCEEDED) { 9341 cleanUp(); 9342 } 9343 return status; 9344 } 9345 9346 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9347 if (status != PackageManager.INSTALL_SUCCEEDED) { 9348 cleanUp(); 9349 return false; 9350 } else { 9351 final File beforeCodeFile = codeFile; 9352 final File afterCodeFile = getNextCodePath(pkg.packageName); 9353 9354 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 9355 try { 9356 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 9357 } catch (ErrnoException e) { 9358 Slog.d(TAG, "Failed to rename", e); 9359 return false; 9360 } 9361 9362 if (!SELinux.restoreconRecursive(afterCodeFile)) { 9363 Slog.d(TAG, "Failed to restorecon"); 9364 return false; 9365 } 9366 9367 // Reflect the rename internally 9368 codeFile = afterCodeFile; 9369 resourceFile = afterCodeFile; 9370 9371 // Reflect the rename in scanned details 9372 pkg.codePath = afterCodeFile.getAbsolutePath(); 9373 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9374 pkg.baseCodePath); 9375 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9376 pkg.splitCodePaths); 9377 9378 // Reflect the rename in app info 9379 pkg.applicationInfo.setCodePath(pkg.codePath); 9380 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9381 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9382 pkg.applicationInfo.setResourcePath(pkg.codePath); 9383 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9384 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9385 9386 return true; 9387 } 9388 } 9389 9390 int doPostInstall(int status, int uid) { 9391 if (status != PackageManager.INSTALL_SUCCEEDED) { 9392 cleanUp(); 9393 } 9394 return status; 9395 } 9396 9397 @Override 9398 String getCodePath() { 9399 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 9400 } 9401 9402 @Override 9403 String getResourcePath() { 9404 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 9405 } 9406 9407 @Override 9408 String getLegacyNativeLibraryPath() { 9409 return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null; 9410 } 9411 9412 private boolean cleanUp() { 9413 if (codeFile == null || !codeFile.exists()) { 9414 return false; 9415 } 9416 9417 if (codeFile.isDirectory()) { 9418 FileUtils.deleteContents(codeFile); 9419 } 9420 codeFile.delete(); 9421 9422 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 9423 resourceFile.delete(); 9424 } 9425 9426 if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) { 9427 if (!FileUtils.deleteContents(legacyNativeLibraryPath)) { 9428 Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath); 9429 } 9430 legacyNativeLibraryPath.delete(); 9431 } 9432 9433 return true; 9434 } 9435 9436 void cleanUpResourcesLI() { 9437 // Try enumerating all code paths before deleting 9438 List<String> allCodePaths = Collections.EMPTY_LIST; 9439 if (codeFile != null && codeFile.exists()) { 9440 try { 9441 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9442 allCodePaths = pkg.getAllCodePaths(); 9443 } catch (PackageParserException e) { 9444 // Ignored; we tried our best 9445 } 9446 } 9447 9448 cleanUp(); 9449 9450 if (!allCodePaths.isEmpty()) { 9451 if (instructionSets == null) { 9452 throw new IllegalStateException("instructionSet == null"); 9453 } 9454 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9455 for (String codePath : allCodePaths) { 9456 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9457 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9458 if (retCode < 0) { 9459 Slog.w(TAG, "Couldn't remove dex file for package: " 9460 + " at location " + codePath + ", retcode=" + retCode); 9461 // we don't consider this to be a failure of the core package deletion 9462 } 9463 } 9464 } 9465 } 9466 } 9467 9468 boolean doPostDeleteLI(boolean delete) { 9469 // XXX err, shouldn't we respect the delete flag? 9470 cleanUpResourcesLI(); 9471 return true; 9472 } 9473 } 9474 9475 private boolean isAsecExternal(String cid) { 9476 final String asecPath = PackageHelper.getSdFilesystem(cid); 9477 return !asecPath.startsWith(mAsecInternalPath); 9478 } 9479 9480 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 9481 PackageManagerException { 9482 if (copyRet < 0) { 9483 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 9484 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 9485 throw new PackageManagerException(copyRet, message); 9486 } 9487 } 9488 } 9489 9490 /** 9491 * Extract the MountService "container ID" from the full code path of an 9492 * .apk. 9493 */ 9494 static String cidFromCodePath(String fullCodePath) { 9495 int eidx = fullCodePath.lastIndexOf("/"); 9496 String subStr1 = fullCodePath.substring(0, eidx); 9497 int sidx = subStr1.lastIndexOf("/"); 9498 return subStr1.substring(sidx+1, eidx); 9499 } 9500 9501 /** 9502 * Logic to handle installation of ASEC applications, including copying and 9503 * renaming logic. 9504 */ 9505 class AsecInstallArgs extends InstallArgs { 9506 // TODO: teach about handling cluster directories 9507 9508 static final String RES_FILE_NAME = "pkg.apk"; 9509 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 9510 9511 String cid; 9512 String packagePath; 9513 String resourcePath; 9514 String legacyNativeLibraryDir; 9515 9516 /** New install */ 9517 AsecInstallArgs(InstallParams params) { 9518 super(params.originFile, params.originStaged, params.observer, params.flags, 9519 params.installerPackageName, params.getManifestDigest(), 9520 params.getUser(), null /* instruction sets */, 9521 params.packageAbiOverride, params.multiArch); 9522 } 9523 9524 /** Existing install */ 9525 AsecInstallArgs(String fullCodePath, String[] instructionSets, 9526 boolean isExternal, boolean isForwardLocked, boolean isMultiArch) { 9527 super(null, false, null, (isExternal ? INSTALL_EXTERNAL : 0) 9528 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9529 instructionSets, null, isMultiArch); 9530 // Extract cid from fullCodePath 9531 int eidx = fullCodePath.lastIndexOf("/"); 9532 String subStr1 = fullCodePath.substring(0, eidx); 9533 int sidx = subStr1.lastIndexOf("/"); 9534 cid = subStr1.substring(sidx+1, eidx); 9535 setCachePath(subStr1); 9536 } 9537 9538 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked, 9539 boolean isMultiArch) { 9540 super(null, false, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 9541 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9542 instructionSets, null, isMultiArch); 9543 this.cid = cid; 9544 setCachePath(PackageHelper.getSdDir(cid)); 9545 } 9546 9547 /** New install from existing */ 9548 AsecInstallArgs(File originPackageFile, String cid, String[] instructionSets, 9549 boolean isExternal, boolean isForwardLocked, boolean isMultiArch) { 9550 super(originPackageFile, false, null, (isExternal ? INSTALL_EXTERNAL : 0) 9551 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9552 instructionSets, null, isMultiArch); 9553 this.cid = cid; 9554 } 9555 9556 void createCopyFile() { 9557 cid = mInstallerService.allocateExternalStageCidLegacy(); 9558 } 9559 9560 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9561 final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(), 9562 abiOverride); 9563 9564 final File target; 9565 if (isExternal()) { 9566 target = Environment.getExternalStorageDirectory(); 9567 } else { 9568 target = Environment.getDataDirectory(); 9569 } 9570 9571 final StorageManager storage = StorageManager.from(mContext); 9572 return (sizeBytes <= storage.getStorageBytesUntilLow(target)); 9573 } 9574 9575 private final boolean isExternal() { 9576 return (flags & PackageManager.INSTALL_EXTERNAL) != 0; 9577 } 9578 9579 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9580 if (temp) { 9581 createCopyFile(); 9582 } else { 9583 /* 9584 * Pre-emptively destroy the container since it's destroyed if 9585 * copying fails due to it existing anyway. 9586 */ 9587 PackageHelper.destroySdDir(cid); 9588 } 9589 9590 final String newCachePath = imcs.copyPackageToContainer( 9591 originFile.getAbsolutePath(), cid, getEncryptKey(), isExternal(), 9592 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 9593 9594 if (newCachePath != null) { 9595 setCachePath(newCachePath); 9596 return PackageManager.INSTALL_SUCCEEDED; 9597 } else { 9598 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9599 } 9600 } 9601 9602 @Override 9603 String getCodePath() { 9604 return packagePath; 9605 } 9606 9607 @Override 9608 String getResourcePath() { 9609 return resourcePath; 9610 } 9611 9612 @Override 9613 String getLegacyNativeLibraryPath() { 9614 return legacyNativeLibraryDir; 9615 } 9616 9617 int doPreInstall(int status) { 9618 if (status != PackageManager.INSTALL_SUCCEEDED) { 9619 // Destroy container 9620 PackageHelper.destroySdDir(cid); 9621 } else { 9622 boolean mounted = PackageHelper.isContainerMounted(cid); 9623 if (!mounted) { 9624 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), 9625 Process.SYSTEM_UID); 9626 if (newCachePath != null) { 9627 setCachePath(newCachePath); 9628 } else { 9629 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9630 } 9631 } 9632 } 9633 return status; 9634 } 9635 9636 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9637 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 9638 String newCachePath = null; 9639 if (PackageHelper.isContainerMounted(cid)) { 9640 // Unmount the container 9641 if (!PackageHelper.unMountSdDir(cid)) { 9642 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9643 return false; 9644 } 9645 } 9646 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9647 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9648 " which might be stale. Will try to clean up."); 9649 // Clean up the stale container and proceed to recreate. 9650 if (!PackageHelper.destroySdDir(newCacheId)) { 9651 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9652 return false; 9653 } 9654 // Successfully cleaned up stale container. Try to rename again. 9655 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9656 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9657 + " inspite of cleaning it up."); 9658 return false; 9659 } 9660 } 9661 if (!PackageHelper.isContainerMounted(newCacheId)) { 9662 Slog.w(TAG, "Mounting container " + newCacheId); 9663 newCachePath = PackageHelper.mountSdDir(newCacheId, 9664 getEncryptKey(), Process.SYSTEM_UID); 9665 } else { 9666 newCachePath = PackageHelper.getSdDir(newCacheId); 9667 } 9668 if (newCachePath == null) { 9669 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9670 return false; 9671 } 9672 Log.i(TAG, "Succesfully renamed " + cid + 9673 " to " + newCacheId + 9674 " at new path: " + newCachePath); 9675 cid = newCacheId; 9676 setCachePath(newCachePath); 9677 9678 // TODO: extend to support split APKs 9679 pkg.codePath = getCodePath(); 9680 pkg.baseCodePath = getCodePath(); 9681 pkg.splitCodePaths = null; 9682 9683 pkg.applicationInfo.setCodePath(getCodePath()); 9684 pkg.applicationInfo.setBaseCodePath(getCodePath()); 9685 pkg.applicationInfo.setSplitCodePaths(null); 9686 pkg.applicationInfo.setResourcePath(getResourcePath()); 9687 pkg.applicationInfo.setBaseResourcePath(getResourcePath()); 9688 pkg.applicationInfo.setSplitResourcePaths(null); 9689 9690 return true; 9691 } 9692 9693 private void setCachePath(String newCachePath) { 9694 File cachePath = new File(newCachePath); 9695 legacyNativeLibraryDir = new File(cachePath, LIB_DIR_NAME).getPath(); 9696 packagePath = new File(cachePath, RES_FILE_NAME).getPath(); 9697 9698 if (isFwdLocked()) { 9699 resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath(); 9700 } else { 9701 resourcePath = packagePath; 9702 } 9703 } 9704 9705 int doPostInstall(int status, int uid) { 9706 if (status != PackageManager.INSTALL_SUCCEEDED) { 9707 cleanUp(); 9708 } else { 9709 final int groupOwner; 9710 final String protectedFile; 9711 if (isFwdLocked()) { 9712 groupOwner = UserHandle.getSharedAppGid(uid); 9713 protectedFile = RES_FILE_NAME; 9714 } else { 9715 groupOwner = -1; 9716 protectedFile = null; 9717 } 9718 9719 if (uid < Process.FIRST_APPLICATION_UID 9720 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9721 Slog.e(TAG, "Failed to finalize " + cid); 9722 PackageHelper.destroySdDir(cid); 9723 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9724 } 9725 9726 boolean mounted = PackageHelper.isContainerMounted(cid); 9727 if (!mounted) { 9728 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9729 } 9730 } 9731 return status; 9732 } 9733 9734 private void cleanUp() { 9735 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9736 9737 // Destroy secure container 9738 PackageHelper.destroySdDir(cid); 9739 } 9740 9741 void cleanUpResourcesLI() { 9742 String sourceFile = getCodePath(); 9743 // Remove dex file 9744 if (instructionSets == null) { 9745 throw new IllegalStateException("instructionSet == null"); 9746 } 9747 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9748 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9749 int retCode = mInstaller.rmdex(sourceFile, dexCodeInstructionSet); 9750 if (retCode < 0) { 9751 Slog.w(TAG, "Couldn't remove dex file for package: " 9752 + " at location " 9753 + sourceFile.toString() + ", retcode=" + retCode); 9754 // we don't consider this to be a failure of the core package deletion 9755 } 9756 } 9757 cleanUp(); 9758 } 9759 9760 boolean matchContainer(String app) { 9761 if (cid.startsWith(app)) { 9762 return true; 9763 } 9764 return false; 9765 } 9766 9767 String getPackageName() { 9768 return getAsecPackageName(cid); 9769 } 9770 9771 boolean doPostDeleteLI(boolean delete) { 9772 boolean ret = false; 9773 boolean mounted = PackageHelper.isContainerMounted(cid); 9774 if (mounted) { 9775 // Unmount first 9776 ret = PackageHelper.unMountSdDir(cid); 9777 } 9778 if (ret && delete) { 9779 cleanUpResourcesLI(); 9780 } 9781 return ret; 9782 } 9783 9784 @Override 9785 int doPreCopy() { 9786 if (isFwdLocked()) { 9787 if (!PackageHelper.fixSdPermissions(cid, 9788 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 9789 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9790 } 9791 } 9792 9793 return PackageManager.INSTALL_SUCCEEDED; 9794 } 9795 9796 @Override 9797 int doPostCopy(int uid) { 9798 if (isFwdLocked()) { 9799 if (uid < Process.FIRST_APPLICATION_UID 9800 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 9801 RES_FILE_NAME)) { 9802 Slog.e(TAG, "Failed to finalize " + cid); 9803 PackageHelper.destroySdDir(cid); 9804 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9805 } 9806 } 9807 9808 return PackageManager.INSTALL_SUCCEEDED; 9809 } 9810 } 9811 9812 static String getAsecPackageName(String packageCid) { 9813 int idx = packageCid.lastIndexOf("-"); 9814 if (idx == -1) { 9815 return packageCid; 9816 } 9817 return packageCid.substring(0, idx); 9818 } 9819 9820 // Utility method used to create code paths based on package name and available index. 9821 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 9822 String idxStr = ""; 9823 int idx = 1; 9824 // Fall back to default value of idx=1 if prefix is not 9825 // part of oldCodePath 9826 if (oldCodePath != null) { 9827 String subStr = oldCodePath; 9828 // Drop the suffix right away 9829 if (suffix != null && subStr.endsWith(suffix)) { 9830 subStr = subStr.substring(0, subStr.length() - suffix.length()); 9831 } 9832 // If oldCodePath already contains prefix find out the 9833 // ending index to either increment or decrement. 9834 int sidx = subStr.lastIndexOf(prefix); 9835 if (sidx != -1) { 9836 subStr = subStr.substring(sidx + prefix.length()); 9837 if (subStr != null) { 9838 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 9839 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 9840 } 9841 try { 9842 idx = Integer.parseInt(subStr); 9843 if (idx <= 1) { 9844 idx++; 9845 } else { 9846 idx--; 9847 } 9848 } catch(NumberFormatException e) { 9849 } 9850 } 9851 } 9852 } 9853 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 9854 return prefix + idxStr; 9855 } 9856 9857 private File getNextCodePath(String packageName) { 9858 int suffix = 1; 9859 File result; 9860 do { 9861 result = new File(mAppInstallDir, packageName + "-" + suffix); 9862 suffix++; 9863 } while (result.exists()); 9864 return result; 9865 } 9866 9867 // Utility method used to ignore ADD/REMOVE events 9868 // by directory observer. 9869 private static boolean ignoreCodePath(String fullPathStr) { 9870 String apkName = deriveCodePathName(fullPathStr); 9871 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 9872 if (idx != -1 && ((idx+1) < apkName.length())) { 9873 // Make sure the package ends with a numeral 9874 String version = apkName.substring(idx+1); 9875 try { 9876 Integer.parseInt(version); 9877 return true; 9878 } catch (NumberFormatException e) {} 9879 } 9880 return false; 9881 } 9882 9883 // Utility method that returns the relative package path with respect 9884 // to the installation directory. Like say for /data/data/com.test-1.apk 9885 // string com.test-1 is returned. 9886 static String deriveCodePathName(String codePath) { 9887 if (codePath == null) { 9888 return null; 9889 } 9890 final File codeFile = new File(codePath); 9891 final String name = codeFile.getName(); 9892 if (codeFile.isDirectory()) { 9893 return name; 9894 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 9895 final int lastDot = name.lastIndexOf('.'); 9896 return name.substring(0, lastDot); 9897 } else { 9898 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 9899 return null; 9900 } 9901 } 9902 9903 class PackageInstalledInfo { 9904 String name; 9905 int uid; 9906 // The set of users that originally had this package installed. 9907 int[] origUsers; 9908 // The set of users that now have this package installed. 9909 int[] newUsers; 9910 PackageParser.Package pkg; 9911 int returnCode; 9912 String returnMsg; 9913 PackageRemovedInfo removedInfo; 9914 9915 public void setError(int code, String msg) { 9916 returnCode = code; 9917 returnMsg = msg; 9918 Slog.w(TAG, msg); 9919 } 9920 9921 public void setError(String msg, PackageParserException e) { 9922 returnCode = e.error; 9923 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9924 Slog.w(TAG, msg, e); 9925 } 9926 9927 public void setError(String msg, PackageManagerException e) { 9928 returnCode = e.error; 9929 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9930 Slog.w(TAG, msg, e); 9931 } 9932 9933 // In some error cases we want to convey more info back to the observer 9934 String origPackage; 9935 String origPermission; 9936 } 9937 9938 /* 9939 * Install a non-existing package. 9940 */ 9941 private void installNewPackageLI(PackageParser.Package pkg, 9942 int parseFlags, int scanMode, UserHandle user, 9943 String installerPackageName, PackageInstalledInfo res) { 9944 // Remember this for later, in case we need to rollback this install 9945 String pkgName = pkg.packageName; 9946 9947 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 9948 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 9949 synchronized(mPackages) { 9950 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 9951 // A package with the same name is already installed, though 9952 // it has been renamed to an older name. The package we 9953 // are trying to install should be installed as an update to 9954 // the existing one, but that has not been requested, so bail. 9955 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9956 + " without first uninstalling package running as " 9957 + mSettings.mRenamedPackages.get(pkgName)); 9958 return; 9959 } 9960 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.codePath)) { 9961 // Don't allow installation over an existing package with the same name. 9962 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9963 + " without first uninstalling."); 9964 return; 9965 } 9966 } 9967 9968 try { 9969 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode, 9970 System.currentTimeMillis(), user); 9971 9972 updateSettingsLI(newPackage, installerPackageName, null, null, res); 9973 // delete the partially installed application. the data directory will have to be 9974 // restored if it was already existing 9975 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9976 // remove package from internal structures. Note that we want deletePackageX to 9977 // delete the package data and cache directories that it created in 9978 // scanPackageLocked, unless those directories existed before we even tried to 9979 // install. 9980 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 9981 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 9982 res.removedInfo, true); 9983 } 9984 9985 } catch (PackageManagerException e) { 9986 res.setError("Package couldn't be installed in " + pkg.codePath, e); 9987 } 9988 } 9989 9990 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 9991 // Upgrade keysets are being used. Determine if new package has a superset of the 9992 // required keys. 9993 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 9994 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9995 for (int i = 0; i < upgradeKeySets.length; i++) { 9996 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 9997 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 9998 return true; 9999 } 10000 } 10001 return false; 10002 } 10003 10004 private void replacePackageLI(PackageParser.Package pkg, 10005 int parseFlags, int scanMode, UserHandle user, 10006 String installerPackageName, PackageInstalledInfo res) { 10007 PackageParser.Package oldPackage; 10008 String pkgName = pkg.packageName; 10009 int[] allUsers; 10010 boolean[] perUserInstalled; 10011 10012 // First find the old package info and check signatures 10013 synchronized(mPackages) { 10014 oldPackage = mPackages.get(pkgName); 10015 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 10016 PackageSetting ps = mSettings.mPackages.get(pkgName); 10017 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 10018 // default to original signature matching 10019 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 10020 != PackageManager.SIGNATURE_MATCH) { 10021 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 10022 "New package has a different signature: " + pkgName); 10023 return; 10024 } 10025 } else { 10026 if(!checkUpgradeKeySetLP(ps, pkg)) { 10027 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 10028 "New package not signed by keys specified by upgrade-keysets: " 10029 + pkgName); 10030 return; 10031 } 10032 } 10033 10034 // In case of rollback, remember per-user/profile install state 10035 allUsers = sUserManager.getUserIds(); 10036 perUserInstalled = new boolean[allUsers.length]; 10037 for (int i = 0; i < allUsers.length; i++) { 10038 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10039 } 10040 } 10041 10042 boolean sysPkg = (isSystemApp(oldPackage)); 10043 if (sysPkg) { 10044 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 10045 user, allUsers, perUserInstalled, installerPackageName, res); 10046 } else { 10047 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 10048 user, allUsers, perUserInstalled, installerPackageName, res); 10049 } 10050 } 10051 10052 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 10053 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 10054 int[] allUsers, boolean[] perUserInstalled, 10055 String installerPackageName, PackageInstalledInfo res) { 10056 String pkgName = deletedPackage.packageName; 10057 boolean deletedPkg = true; 10058 boolean updatedSettings = false; 10059 10060 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 10061 + deletedPackage); 10062 long origUpdateTime; 10063 if (pkg.mExtras != null) { 10064 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 10065 } else { 10066 origUpdateTime = 0; 10067 } 10068 10069 // First delete the existing package while retaining the data directory 10070 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 10071 res.removedInfo, true)) { 10072 // If the existing package wasn't successfully deleted 10073 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 10074 deletedPkg = false; 10075 } else { 10076 // Successfully deleted the old package. Now proceed with re-installation 10077 deleteCodeCacheDirsLI(pkgName); 10078 try { 10079 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 10080 scanMode | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 10081 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10082 updatedSettings = true; 10083 } catch (PackageManagerException e) { 10084 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10085 } 10086 } 10087 10088 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10089 // remove package from internal structures. Note that we want deletePackageX to 10090 // delete the package data and cache directories that it created in 10091 // scanPackageLocked, unless those directories existed before we even tried to 10092 // install. 10093 if(updatedSettings) { 10094 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 10095 deletePackageLI( 10096 pkgName, null, true, allUsers, perUserInstalled, 10097 PackageManager.DELETE_KEEP_DATA, 10098 res.removedInfo, true); 10099 } 10100 // Since we failed to install the new package we need to restore the old 10101 // package that we deleted. 10102 if (deletedPkg) { 10103 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 10104 File restoreFile = new File(deletedPackage.codePath); 10105 // Parse old package 10106 boolean oldOnSd = isExternal(deletedPackage); 10107 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 10108 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) | 10109 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 10110 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE 10111 | SCAN_UPDATE_TIME; 10112 try { 10113 scanPackageLI(restoreFile, oldParseFlags, oldScanMode, origUpdateTime, null); 10114 } catch (PackageManagerException e) { 10115 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 10116 + e.getMessage()); 10117 return; 10118 } 10119 // Restore of old package succeeded. Update permissions. 10120 // writer 10121 synchronized (mPackages) { 10122 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 10123 UPDATE_PERMISSIONS_ALL); 10124 // can downgrade to reader 10125 mSettings.writeLPr(); 10126 } 10127 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 10128 } 10129 } 10130 } 10131 10132 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 10133 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 10134 int[] allUsers, boolean[] perUserInstalled, 10135 String installerPackageName, PackageInstalledInfo res) { 10136 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 10137 + ", old=" + deletedPackage); 10138 boolean updatedSettings = false; 10139 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING | 10140 PackageParser.PARSE_IS_SYSTEM; 10141 if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) { 10142 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10143 } 10144 String packageName = deletedPackage.packageName; 10145 if (packageName == null) { 10146 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10147 "Attempt to delete null packageName."); 10148 return; 10149 } 10150 PackageParser.Package oldPkg; 10151 PackageSetting oldPkgSetting; 10152 // reader 10153 synchronized (mPackages) { 10154 oldPkg = mPackages.get(packageName); 10155 oldPkgSetting = mSettings.mPackages.get(packageName); 10156 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 10157 (oldPkgSetting == null)) { 10158 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10159 "Couldn't find package:" + packageName + " information"); 10160 return; 10161 } 10162 } 10163 10164 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 10165 10166 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10167 res.removedInfo.removedPackage = packageName; 10168 // Remove existing system package 10169 removePackageLI(oldPkgSetting, true); 10170 // writer 10171 synchronized (mPackages) { 10172 if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) { 10173 // We didn't need to disable the .apk as a current system package, 10174 // which means we are replacing another update that is already 10175 // installed. We need to make sure to delete the older one's .apk. 10176 res.removedInfo.args = createInstallArgsForExisting(0, 10177 deletedPackage.applicationInfo.getCodePath(), 10178 deletedPackage.applicationInfo.getResourcePath(), 10179 deletedPackage.applicationInfo.nativeLibraryRootDir, 10180 getAppDexInstructionSets(deletedPackage.applicationInfo), 10181 isMultiArch(deletedPackage.applicationInfo)); 10182 } else { 10183 res.removedInfo.args = null; 10184 } 10185 } 10186 10187 // Successfully disabled the old package. Now proceed with re-installation 10188 deleteCodeCacheDirsLI(packageName); 10189 10190 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10191 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10192 10193 PackageParser.Package newPackage = null; 10194 try { 10195 newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user); 10196 if (newPackage.mExtras != null) { 10197 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 10198 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10199 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10200 10201 // is the update attempting to change shared user? that isn't going to work... 10202 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10203 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 10204 "Forbidding shared user change from " + oldPkgSetting.sharedUser 10205 + " to " + newPkgSetting.sharedUser); 10206 updatedSettings = true; 10207 } 10208 } 10209 10210 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10211 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10212 updatedSettings = true; 10213 } 10214 10215 } catch (PackageManagerException e) { 10216 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10217 } 10218 10219 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10220 // Re installation failed. Restore old information 10221 // Remove new pkg information 10222 if (newPackage != null) { 10223 removeInstalledPackageLI(newPackage, true); 10224 } 10225 // Add back the old system package 10226 try { 10227 scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user); 10228 } catch (PackageManagerException e) { 10229 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 10230 } 10231 // Restore the old system information in Settings 10232 synchronized(mPackages) { 10233 if (updatedSettings) { 10234 mSettings.enableSystemPackageLPw(packageName); 10235 mSettings.setInstallerPackageName(packageName, 10236 oldPkgSetting.installerPackageName); 10237 } 10238 mSettings.writeLPr(); 10239 } 10240 } 10241 } 10242 10243 // Utility method used to move dex files during install. 10244 private int moveDexFilesLI(String oldCodePath, PackageParser.Package newPackage) { 10245 // TODO: extend to move split APK dex files 10246 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) { 10247 final String[] instructionSets = getAppDexInstructionSets(newPackage.applicationInfo); 10248 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10249 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10250 int retCode = mInstaller.movedex(oldCodePath, newPackage.baseCodePath, 10251 dexCodeInstructionSet); 10252 if (retCode != 0) { 10253 /* 10254 * Programs may be lazily run through dexopt, so the 10255 * source may not exist. However, something seems to 10256 * have gone wrong, so note that dexopt needs to be 10257 * run again and remove the source file. In addition, 10258 * remove the target to make sure there isn't a stale 10259 * file from a previous version of the package. 10260 */ 10261 newPackage.mDexOptPerformed.clear(); 10262 mInstaller.rmdex(oldCodePath, dexCodeInstructionSet); 10263 mInstaller.rmdex(newPackage.baseCodePath, dexCodeInstructionSet); 10264 } 10265 } 10266 } 10267 return PackageManager.INSTALL_SUCCEEDED; 10268 } 10269 10270 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10271 int[] allUsers, boolean[] perUserInstalled, 10272 PackageInstalledInfo res) { 10273 String pkgName = newPackage.packageName; 10274 synchronized (mPackages) { 10275 //write settings. the installStatus will be incomplete at this stage. 10276 //note that the new package setting would have already been 10277 //added to mPackages. It hasn't been persisted yet. 10278 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10279 mSettings.writeLPr(); 10280 } 10281 10282 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10283 10284 synchronized (mPackages) { 10285 updatePermissionsLPw(newPackage.packageName, newPackage, 10286 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10287 ? UPDATE_PERMISSIONS_ALL : 0)); 10288 // For system-bundled packages, we assume that installing an upgraded version 10289 // of the package implies that the user actually wants to run that new code, 10290 // so we enable the package. 10291 if (isSystemApp(newPackage)) { 10292 // NB: implicit assumption that system package upgrades apply to all users 10293 if (DEBUG_INSTALL) { 10294 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10295 } 10296 PackageSetting ps = mSettings.mPackages.get(pkgName); 10297 if (ps != null) { 10298 if (res.origUsers != null) { 10299 for (int userHandle : res.origUsers) { 10300 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10301 userHandle, installerPackageName); 10302 } 10303 } 10304 // Also convey the prior install/uninstall state 10305 if (allUsers != null && perUserInstalled != null) { 10306 for (int i = 0; i < allUsers.length; i++) { 10307 if (DEBUG_INSTALL) { 10308 Slog.d(TAG, " user " + allUsers[i] 10309 + " => " + perUserInstalled[i]); 10310 } 10311 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10312 } 10313 // these install state changes will be persisted in the 10314 // upcoming call to mSettings.writeLPr(). 10315 } 10316 } 10317 } 10318 res.name = pkgName; 10319 res.uid = newPackage.applicationInfo.uid; 10320 res.pkg = newPackage; 10321 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10322 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10323 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10324 //to update install status 10325 mSettings.writeLPr(); 10326 } 10327 } 10328 10329 private void installPackageLI(InstallArgs args, boolean newInstall, PackageInstalledInfo res) { 10330 int pFlags = args.flags; 10331 String installerPackageName = args.installerPackageName; 10332 File tmpPackageFile = new File(args.getCodePath()); 10333 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10334 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0); 10335 boolean replace = false; 10336 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE 10337 | (newInstall ? SCAN_NEW_INSTALL : 0); 10338 // Result object to be returned 10339 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10340 10341 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10342 // Retrieve PackageSettings and parse package 10343 int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10344 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10345 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 10346 PackageParser pp = new PackageParser(); 10347 pp.setSeparateProcesses(mSeparateProcesses); 10348 pp.setDisplayMetrics(mMetrics); 10349 10350 final PackageParser.Package pkg; 10351 try { 10352 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 10353 } catch (PackageParserException e) { 10354 res.setError("Failed parse during installPackageLI", e); 10355 return; 10356 } 10357 10358 // Mark that we have an install time CPU ABI override. 10359 pkg.cpuAbiOverride = args.abiOverride; 10360 10361 String pkgName = res.name = pkg.packageName; 10362 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 10363 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) { 10364 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 10365 return; 10366 } 10367 } 10368 10369 try { 10370 pp.collectCertificates(pkg, parseFlags); 10371 pp.collectManifestDigest(pkg); 10372 } catch (PackageParserException e) { 10373 res.setError("Failed collect during installPackageLI", e); 10374 return; 10375 } 10376 10377 /* If the installer passed in a manifest digest, compare it now. */ 10378 if (args.manifestDigest != null) { 10379 if (DEBUG_INSTALL) { 10380 final String parsedManifest = pkg.manifestDigest == null ? "null" 10381 : pkg.manifestDigest.toString(); 10382 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 10383 + parsedManifest); 10384 } 10385 10386 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 10387 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 10388 return; 10389 } 10390 } else if (DEBUG_INSTALL) { 10391 final String parsedManifest = pkg.manifestDigest == null 10392 ? "null" : pkg.manifestDigest.toString(); 10393 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 10394 } 10395 10396 // Get rid of all references to package scan path via parser. 10397 pp = null; 10398 String oldCodePath = null; 10399 boolean systemApp = false; 10400 synchronized (mPackages) { 10401 // Check whether the newly-scanned package wants to define an already-defined perm 10402 int N = pkg.permissions.size(); 10403 for (int i = N-1; i >= 0; i--) { 10404 PackageParser.Permission perm = pkg.permissions.get(i); 10405 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 10406 if (bp != null) { 10407 // If the defining package is signed with our cert, it's okay. This 10408 // also includes the "updating the same package" case, of course. 10409 if (compareSignatures(bp.packageSetting.signatures.mSignatures, 10410 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 10411 // If the owning package is the system itself, we log but allow 10412 // install to proceed; we fail the install on all other permission 10413 // redefinitions. 10414 if (!bp.sourcePackage.equals("android")) { 10415 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 10416 + pkg.packageName + " attempting to redeclare permission " 10417 + perm.info.name + " already owned by " + bp.sourcePackage); 10418 res.origPermission = perm.info.name; 10419 res.origPackage = bp.sourcePackage; 10420 return; 10421 } else { 10422 Slog.w(TAG, "Package " + pkg.packageName 10423 + " attempting to redeclare system permission " 10424 + perm.info.name + "; ignoring new declaration"); 10425 pkg.permissions.remove(i); 10426 } 10427 } 10428 } 10429 } 10430 10431 // Check if installing already existing package 10432 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10433 String oldName = mSettings.mRenamedPackages.get(pkgName); 10434 if (pkg.mOriginalPackages != null 10435 && pkg.mOriginalPackages.contains(oldName) 10436 && mPackages.containsKey(oldName)) { 10437 // This package is derived from an original package, 10438 // and this device has been updating from that original 10439 // name. We must continue using the original name, so 10440 // rename the new package here. 10441 pkg.setPackageName(oldName); 10442 pkgName = pkg.packageName; 10443 replace = true; 10444 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 10445 + oldName + " pkgName=" + pkgName); 10446 } else if (mPackages.containsKey(pkgName)) { 10447 // This package, under its official name, already exists 10448 // on the device; we should replace it. 10449 replace = true; 10450 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 10451 } 10452 } 10453 PackageSetting ps = mSettings.mPackages.get(pkgName); 10454 if (ps != null) { 10455 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 10456 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 10457 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 10458 systemApp = (ps.pkg.applicationInfo.flags & 10459 ApplicationInfo.FLAG_SYSTEM) != 0; 10460 } 10461 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10462 } 10463 } 10464 10465 if (systemApp && onSd) { 10466 // Disable updates to system apps on sdcard 10467 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 10468 "Cannot install updates to system apps on sdcard"); 10469 return; 10470 } 10471 10472 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 10473 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 10474 return; 10475 } 10476 10477 if (replace) { 10478 replacePackageLI(pkg, parseFlags, scanMode, args.user, 10479 installerPackageName, res); 10480 } else { 10481 installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user, 10482 installerPackageName, res); 10483 } 10484 synchronized (mPackages) { 10485 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10486 if (ps != null) { 10487 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10488 } 10489 } 10490 } 10491 10492 private static boolean isForwardLocked(PackageParser.Package pkg) { 10493 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10494 } 10495 10496 private static boolean isForwardLocked(ApplicationInfo info) { 10497 return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10498 } 10499 10500 private boolean isForwardLocked(PackageSetting ps) { 10501 return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10502 } 10503 10504 private static boolean isMultiArch(PackageSetting ps) { 10505 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10506 } 10507 10508 private static boolean isMultiArch(ApplicationInfo info) { 10509 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10510 } 10511 10512 private static boolean isExternal(PackageParser.Package pkg) { 10513 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10514 } 10515 10516 private static boolean isExternal(PackageSetting ps) { 10517 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10518 } 10519 10520 private static boolean isExternal(ApplicationInfo info) { 10521 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10522 } 10523 10524 private static boolean isSystemApp(PackageParser.Package pkg) { 10525 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10526 } 10527 10528 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 10529 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0; 10530 } 10531 10532 private static boolean isSystemApp(ApplicationInfo info) { 10533 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10534 } 10535 10536 private static boolean isSystemApp(PackageSetting ps) { 10537 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 10538 } 10539 10540 private static boolean isUpdatedSystemApp(PackageSetting ps) { 10541 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10542 } 10543 10544 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 10545 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10546 } 10547 10548 private static boolean isUpdatedSystemApp(ApplicationInfo info) { 10549 return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10550 } 10551 10552 private int packageFlagsToInstallFlags(PackageSetting ps) { 10553 int installFlags = 0; 10554 if (isExternal(ps)) { 10555 installFlags |= PackageManager.INSTALL_EXTERNAL; 10556 } 10557 if (isForwardLocked(ps)) { 10558 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 10559 } 10560 return installFlags; 10561 } 10562 10563 private void deleteTempPackageFiles() { 10564 final FilenameFilter filter = new FilenameFilter() { 10565 public boolean accept(File dir, String name) { 10566 return name.startsWith("vmdl") && name.endsWith(".tmp"); 10567 } 10568 }; 10569 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 10570 file.delete(); 10571 } 10572 } 10573 10574 @Override 10575 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 10576 int flags) { 10577 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 10578 flags); 10579 } 10580 10581 @Override 10582 public void deletePackage(final String packageName, 10583 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 10584 mContext.enforceCallingOrSelfPermission( 10585 android.Manifest.permission.DELETE_PACKAGES, null); 10586 final int uid = Binder.getCallingUid(); 10587 if (UserHandle.getUserId(uid) != userId) { 10588 mContext.enforceCallingPermission( 10589 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 10590 "deletePackage for user " + userId); 10591 } 10592 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 10593 try { 10594 observer.onPackageDeleted(packageName, 10595 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 10596 } catch (RemoteException re) { 10597 } 10598 return; 10599 } 10600 10601 boolean uninstallBlocked = false; 10602 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 10603 int[] users = sUserManager.getUserIds(); 10604 for (int i = 0; i < users.length; ++i) { 10605 if (getBlockUninstallForUser(packageName, users[i])) { 10606 uninstallBlocked = true; 10607 break; 10608 } 10609 } 10610 } else { 10611 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 10612 } 10613 if (uninstallBlocked) { 10614 try { 10615 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 10616 null); 10617 } catch (RemoteException re) { 10618 } 10619 return; 10620 } 10621 10622 if (DEBUG_REMOVE) { 10623 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 10624 } 10625 // Queue up an async operation since the package deletion may take a little while. 10626 mHandler.post(new Runnable() { 10627 public void run() { 10628 mHandler.removeCallbacks(this); 10629 final int returnCode = deletePackageX(packageName, userId, flags); 10630 if (observer != null) { 10631 try { 10632 observer.onPackageDeleted(packageName, returnCode, null); 10633 } catch (RemoteException e) { 10634 Log.i(TAG, "Observer no longer exists."); 10635 } //end catch 10636 } //end if 10637 } //end run 10638 }); 10639 } 10640 10641 private boolean isPackageDeviceAdmin(String packageName, int userId) { 10642 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 10643 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 10644 try { 10645 if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId) 10646 || dpm.isDeviceOwner(packageName))) { 10647 return true; 10648 } 10649 } catch (RemoteException e) { 10650 } 10651 return false; 10652 } 10653 10654 /** 10655 * This method is an internal method that could be get invoked either 10656 * to delete an installed package or to clean up a failed installation. 10657 * After deleting an installed package, a broadcast is sent to notify any 10658 * listeners that the package has been installed. For cleaning up a failed 10659 * installation, the broadcast is not necessary since the package's 10660 * installation wouldn't have sent the initial broadcast either 10661 * The key steps in deleting a package are 10662 * deleting the package information in internal structures like mPackages, 10663 * deleting the packages base directories through installd 10664 * updating mSettings to reflect current status 10665 * persisting settings for later use 10666 * sending a broadcast if necessary 10667 */ 10668 private int deletePackageX(String packageName, int userId, int flags) { 10669 final PackageRemovedInfo info = new PackageRemovedInfo(); 10670 final boolean res; 10671 10672 if (isPackageDeviceAdmin(packageName, userId)) { 10673 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 10674 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 10675 } 10676 10677 boolean removedForAllUsers = false; 10678 boolean systemUpdate = false; 10679 10680 // for the uninstall-updates case and restricted profiles, remember the per- 10681 // userhandle installed state 10682 int[] allUsers; 10683 boolean[] perUserInstalled; 10684 synchronized (mPackages) { 10685 PackageSetting ps = mSettings.mPackages.get(packageName); 10686 allUsers = sUserManager.getUserIds(); 10687 perUserInstalled = new boolean[allUsers.length]; 10688 for (int i = 0; i < allUsers.length; i++) { 10689 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10690 } 10691 } 10692 10693 synchronized (mInstallLock) { 10694 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 10695 res = deletePackageLI(packageName, 10696 (flags & PackageManager.DELETE_ALL_USERS) != 0 10697 ? UserHandle.ALL : new UserHandle(userId), 10698 true, allUsers, perUserInstalled, 10699 flags | REMOVE_CHATTY, info, true); 10700 systemUpdate = info.isRemovedPackageSystemUpdate; 10701 if (res && !systemUpdate && mPackages.get(packageName) == null) { 10702 removedForAllUsers = true; 10703 } 10704 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 10705 + " removedForAllUsers=" + removedForAllUsers); 10706 } 10707 10708 if (res) { 10709 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 10710 10711 // If the removed package was a system update, the old system package 10712 // was re-enabled; we need to broadcast this information 10713 if (systemUpdate) { 10714 Bundle extras = new Bundle(1); 10715 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 10716 ? info.removedAppId : info.uid); 10717 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10718 10719 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 10720 extras, null, null, null); 10721 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 10722 extras, null, null, null); 10723 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 10724 null, packageName, null, null); 10725 } 10726 } 10727 // Force a gc here. 10728 Runtime.getRuntime().gc(); 10729 // Delete the resources here after sending the broadcast to let 10730 // other processes clean up before deleting resources. 10731 if (info.args != null) { 10732 synchronized (mInstallLock) { 10733 info.args.doPostDeleteLI(true); 10734 } 10735 } 10736 10737 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10738 } 10739 10740 static class PackageRemovedInfo { 10741 String removedPackage; 10742 int uid = -1; 10743 int removedAppId = -1; 10744 int[] removedUsers = null; 10745 boolean isRemovedPackageSystemUpdate = false; 10746 // Clean up resources deleted packages. 10747 InstallArgs args = null; 10748 10749 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 10750 Bundle extras = new Bundle(1); 10751 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 10752 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 10753 if (replacing) { 10754 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10755 } 10756 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 10757 if (removedPackage != null) { 10758 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 10759 extras, null, null, removedUsers); 10760 if (fullRemove && !replacing) { 10761 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 10762 extras, null, null, removedUsers); 10763 } 10764 } 10765 if (removedAppId >= 0) { 10766 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 10767 removedUsers); 10768 } 10769 } 10770 } 10771 10772 /* 10773 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 10774 * flag is not set, the data directory is removed as well. 10775 * make sure this flag is set for partially installed apps. If not its meaningless to 10776 * delete a partially installed application. 10777 */ 10778 private void removePackageDataLI(PackageSetting ps, 10779 int[] allUserHandles, boolean[] perUserInstalled, 10780 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 10781 String packageName = ps.name; 10782 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 10783 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 10784 // Retrieve object to delete permissions for shared user later on 10785 final PackageSetting deletedPs; 10786 // reader 10787 synchronized (mPackages) { 10788 deletedPs = mSettings.mPackages.get(packageName); 10789 if (outInfo != null) { 10790 outInfo.removedPackage = packageName; 10791 outInfo.removedUsers = deletedPs != null 10792 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 10793 : null; 10794 } 10795 } 10796 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10797 removeDataDirsLI(packageName); 10798 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 10799 } 10800 // writer 10801 synchronized (mPackages) { 10802 if (deletedPs != null) { 10803 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10804 if (outInfo != null) { 10805 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 10806 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 10807 } 10808 if (deletedPs != null) { 10809 updatePermissionsLPw(deletedPs.name, null, 0); 10810 if (deletedPs.sharedUser != null) { 10811 // remove permissions associated with package 10812 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 10813 } 10814 } 10815 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 10816 } 10817 // make sure to preserve per-user disabled state if this removal was just 10818 // a downgrade of a system app to the factory package 10819 if (allUserHandles != null && perUserInstalled != null) { 10820 if (DEBUG_REMOVE) { 10821 Slog.d(TAG, "Propagating install state across downgrade"); 10822 } 10823 for (int i = 0; i < allUserHandles.length; i++) { 10824 if (DEBUG_REMOVE) { 10825 Slog.d(TAG, " user " + allUserHandles[i] 10826 + " => " + perUserInstalled[i]); 10827 } 10828 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10829 } 10830 } 10831 } 10832 // can downgrade to reader 10833 if (writeSettings) { 10834 // Save settings now 10835 mSettings.writeLPr(); 10836 } 10837 } 10838 if (outInfo != null) { 10839 // A user ID was deleted here. Go through all users and remove it 10840 // from KeyStore. 10841 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 10842 } 10843 } 10844 10845 static boolean locationIsPrivileged(File path) { 10846 try { 10847 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 10848 .getCanonicalPath(); 10849 return path.getCanonicalPath().startsWith(privilegedAppDir); 10850 } catch (IOException e) { 10851 Slog.e(TAG, "Unable to access code path " + path); 10852 } 10853 return false; 10854 } 10855 10856 /* 10857 * Tries to delete system package. 10858 */ 10859 private boolean deleteSystemPackageLI(PackageSetting newPs, 10860 int[] allUserHandles, boolean[] perUserInstalled, 10861 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 10862 final boolean applyUserRestrictions 10863 = (allUserHandles != null) && (perUserInstalled != null); 10864 PackageSetting disabledPs = null; 10865 // Confirm if the system package has been updated 10866 // An updated system app can be deleted. This will also have to restore 10867 // the system pkg from system partition 10868 // reader 10869 synchronized (mPackages) { 10870 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 10871 } 10872 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 10873 + " disabledPs=" + disabledPs); 10874 if (disabledPs == null) { 10875 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 10876 return false; 10877 } else if (DEBUG_REMOVE) { 10878 Slog.d(TAG, "Deleting system pkg from data partition"); 10879 } 10880 if (DEBUG_REMOVE) { 10881 if (applyUserRestrictions) { 10882 Slog.d(TAG, "Remembering install states:"); 10883 for (int i = 0; i < allUserHandles.length; i++) { 10884 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 10885 } 10886 } 10887 } 10888 // Delete the updated package 10889 outInfo.isRemovedPackageSystemUpdate = true; 10890 if (disabledPs.versionCode < newPs.versionCode) { 10891 // Delete data for downgrades 10892 flags &= ~PackageManager.DELETE_KEEP_DATA; 10893 } else { 10894 // Preserve data by setting flag 10895 flags |= PackageManager.DELETE_KEEP_DATA; 10896 } 10897 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 10898 allUserHandles, perUserInstalled, outInfo, writeSettings); 10899 if (!ret) { 10900 return false; 10901 } 10902 // writer 10903 synchronized (mPackages) { 10904 // Reinstate the old system package 10905 mSettings.enableSystemPackageLPw(newPs.name); 10906 // Remove any native libraries from the upgraded package. 10907 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 10908 } 10909 // Install the system package 10910 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 10911 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 10912 if (locationIsPrivileged(disabledPs.codePath)) { 10913 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10914 } 10915 10916 final PackageParser.Package newPkg; 10917 try { 10918 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, null); 10919 } catch (PackageManagerException e) { 10920 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 10921 return false; 10922 } 10923 10924 // writer 10925 synchronized (mPackages) { 10926 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 10927 updatePermissionsLPw(newPkg.packageName, newPkg, 10928 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 10929 if (applyUserRestrictions) { 10930 if (DEBUG_REMOVE) { 10931 Slog.d(TAG, "Propagating install state across reinstall"); 10932 } 10933 for (int i = 0; i < allUserHandles.length; i++) { 10934 if (DEBUG_REMOVE) { 10935 Slog.d(TAG, " user " + allUserHandles[i] 10936 + " => " + perUserInstalled[i]); 10937 } 10938 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10939 } 10940 // Regardless of writeSettings we need to ensure that this restriction 10941 // state propagation is persisted 10942 mSettings.writeAllUsersPackageRestrictionsLPr(); 10943 } 10944 // can downgrade to reader here 10945 if (writeSettings) { 10946 mSettings.writeLPr(); 10947 } 10948 } 10949 return true; 10950 } 10951 10952 private boolean deleteInstalledPackageLI(PackageSetting ps, 10953 boolean deleteCodeAndResources, int flags, 10954 int[] allUserHandles, boolean[] perUserInstalled, 10955 PackageRemovedInfo outInfo, boolean writeSettings) { 10956 if (outInfo != null) { 10957 outInfo.uid = ps.appId; 10958 } 10959 10960 // Delete package data from internal structures and also remove data if flag is set 10961 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 10962 10963 // Delete application code and resources 10964 if (deleteCodeAndResources && (outInfo != null)) { 10965 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 10966 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 10967 getAppDexInstructionSets(ps), isMultiArch(ps)); 10968 } 10969 return true; 10970 } 10971 10972 @Override 10973 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 10974 int userId) { 10975 mContext.enforceCallingOrSelfPermission( 10976 android.Manifest.permission.DELETE_PACKAGES, null); 10977 synchronized (mPackages) { 10978 PackageSetting ps = mSettings.mPackages.get(packageName); 10979 if (ps == null) { 10980 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 10981 return false; 10982 } 10983 if (!ps.getInstalled(userId)) { 10984 // Can't block uninstall for an app that is not installed or enabled. 10985 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 10986 return false; 10987 } 10988 ps.setBlockUninstall(blockUninstall, userId); 10989 mSettings.writePackageRestrictionsLPr(userId); 10990 } 10991 return true; 10992 } 10993 10994 @Override 10995 public boolean getBlockUninstallForUser(String packageName, int userId) { 10996 synchronized (mPackages) { 10997 PackageSetting ps = mSettings.mPackages.get(packageName); 10998 if (ps == null) { 10999 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 11000 return false; 11001 } 11002 return ps.getBlockUninstall(userId); 11003 } 11004 } 11005 11006 /* 11007 * This method handles package deletion in general 11008 */ 11009 private boolean deletePackageLI(String packageName, UserHandle user, 11010 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 11011 int flags, PackageRemovedInfo outInfo, 11012 boolean writeSettings) { 11013 if (packageName == null) { 11014 Slog.w(TAG, "Attempt to delete null packageName."); 11015 return false; 11016 } 11017 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 11018 PackageSetting ps; 11019 boolean dataOnly = false; 11020 int removeUser = -1; 11021 int appId = -1; 11022 synchronized (mPackages) { 11023 ps = mSettings.mPackages.get(packageName); 11024 if (ps == null) { 11025 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11026 return false; 11027 } 11028 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 11029 && user.getIdentifier() != UserHandle.USER_ALL) { 11030 // The caller is asking that the package only be deleted for a single 11031 // user. To do this, we just mark its uninstalled state and delete 11032 // its data. If this is a system app, we only allow this to happen if 11033 // they have set the special DELETE_SYSTEM_APP which requests different 11034 // semantics than normal for uninstalling system apps. 11035 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 11036 ps.setUserState(user.getIdentifier(), 11037 COMPONENT_ENABLED_STATE_DEFAULT, 11038 false, //installed 11039 true, //stopped 11040 true, //notLaunched 11041 false, //hidden 11042 null, null, null, 11043 false // blockUninstall 11044 ); 11045 if (!isSystemApp(ps)) { 11046 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 11047 // Other user still have this package installed, so all 11048 // we need to do is clear this user's data and save that 11049 // it is uninstalled. 11050 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 11051 removeUser = user.getIdentifier(); 11052 appId = ps.appId; 11053 mSettings.writePackageRestrictionsLPr(removeUser); 11054 } else { 11055 // We need to set it back to 'installed' so the uninstall 11056 // broadcasts will be sent correctly. 11057 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 11058 ps.setInstalled(true, user.getIdentifier()); 11059 } 11060 } else { 11061 // This is a system app, so we assume that the 11062 // other users still have this package installed, so all 11063 // we need to do is clear this user's data and save that 11064 // it is uninstalled. 11065 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 11066 removeUser = user.getIdentifier(); 11067 appId = ps.appId; 11068 mSettings.writePackageRestrictionsLPr(removeUser); 11069 } 11070 } 11071 } 11072 11073 if (removeUser >= 0) { 11074 // From above, we determined that we are deleting this only 11075 // for a single user. Continue the work here. 11076 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 11077 if (outInfo != null) { 11078 outInfo.removedPackage = packageName; 11079 outInfo.removedAppId = appId; 11080 outInfo.removedUsers = new int[] {removeUser}; 11081 } 11082 mInstaller.clearUserData(packageName, removeUser); 11083 removeKeystoreDataIfNeeded(removeUser, appId); 11084 schedulePackageCleaning(packageName, removeUser, false); 11085 return true; 11086 } 11087 11088 if (dataOnly) { 11089 // Delete application data first 11090 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 11091 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 11092 return true; 11093 } 11094 11095 boolean ret = false; 11096 if (isSystemApp(ps)) { 11097 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 11098 // When an updated system application is deleted we delete the existing resources as well and 11099 // fall back to existing code in system partition 11100 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 11101 flags, outInfo, writeSettings); 11102 } else { 11103 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 11104 // Kill application pre-emptively especially for apps on sd. 11105 killApplication(packageName, ps.appId, "uninstall pkg"); 11106 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 11107 allUserHandles, perUserInstalled, 11108 outInfo, writeSettings); 11109 } 11110 11111 return ret; 11112 } 11113 11114 private final class ClearStorageConnection implements ServiceConnection { 11115 IMediaContainerService mContainerService; 11116 11117 @Override 11118 public void onServiceConnected(ComponentName name, IBinder service) { 11119 synchronized (this) { 11120 mContainerService = IMediaContainerService.Stub.asInterface(service); 11121 notifyAll(); 11122 } 11123 } 11124 11125 @Override 11126 public void onServiceDisconnected(ComponentName name) { 11127 } 11128 } 11129 11130 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 11131 final boolean mounted; 11132 if (Environment.isExternalStorageEmulated()) { 11133 mounted = true; 11134 } else { 11135 final String status = Environment.getExternalStorageState(); 11136 11137 mounted = status.equals(Environment.MEDIA_MOUNTED) 11138 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 11139 } 11140 11141 if (!mounted) { 11142 return; 11143 } 11144 11145 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 11146 int[] users; 11147 if (userId == UserHandle.USER_ALL) { 11148 users = sUserManager.getUserIds(); 11149 } else { 11150 users = new int[] { userId }; 11151 } 11152 final ClearStorageConnection conn = new ClearStorageConnection(); 11153 if (mContext.bindServiceAsUser( 11154 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 11155 try { 11156 for (int curUser : users) { 11157 long timeout = SystemClock.uptimeMillis() + 5000; 11158 synchronized (conn) { 11159 long now = SystemClock.uptimeMillis(); 11160 while (conn.mContainerService == null && now < timeout) { 11161 try { 11162 conn.wait(timeout - now); 11163 } catch (InterruptedException e) { 11164 } 11165 } 11166 } 11167 if (conn.mContainerService == null) { 11168 return; 11169 } 11170 11171 final UserEnvironment userEnv = new UserEnvironment(curUser); 11172 clearDirectory(conn.mContainerService, 11173 userEnv.buildExternalStorageAppCacheDirs(packageName)); 11174 if (allData) { 11175 clearDirectory(conn.mContainerService, 11176 userEnv.buildExternalStorageAppDataDirs(packageName)); 11177 clearDirectory(conn.mContainerService, 11178 userEnv.buildExternalStorageAppMediaDirs(packageName)); 11179 } 11180 } 11181 } finally { 11182 mContext.unbindService(conn); 11183 } 11184 } 11185 } 11186 11187 @Override 11188 public void clearApplicationUserData(final String packageName, 11189 final IPackageDataObserver observer, final int userId) { 11190 mContext.enforceCallingOrSelfPermission( 11191 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 11192 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data"); 11193 // Queue up an async operation since the package deletion may take a little while. 11194 mHandler.post(new Runnable() { 11195 public void run() { 11196 mHandler.removeCallbacks(this); 11197 final boolean succeeded; 11198 synchronized (mInstallLock) { 11199 succeeded = clearApplicationUserDataLI(packageName, userId); 11200 } 11201 clearExternalStorageDataSync(packageName, userId, true); 11202 if (succeeded) { 11203 // invoke DeviceStorageMonitor's update method to clear any notifications 11204 DeviceStorageMonitorInternal 11205 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 11206 if (dsm != null) { 11207 dsm.checkMemory(); 11208 } 11209 } 11210 if(observer != null) { 11211 try { 11212 observer.onRemoveCompleted(packageName, succeeded); 11213 } catch (RemoteException e) { 11214 Log.i(TAG, "Observer no longer exists."); 11215 } 11216 } //end if observer 11217 } //end run 11218 }); 11219 } 11220 11221 private boolean clearApplicationUserDataLI(String packageName, int userId) { 11222 if (packageName == null) { 11223 Slog.w(TAG, "Attempt to delete null packageName."); 11224 return false; 11225 } 11226 PackageParser.Package p; 11227 boolean dataOnly = false; 11228 final int appId; 11229 synchronized (mPackages) { 11230 p = mPackages.get(packageName); 11231 if (p == null) { 11232 dataOnly = true; 11233 PackageSetting ps = mSettings.mPackages.get(packageName); 11234 if ((ps == null) || (ps.pkg == null)) { 11235 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11236 return false; 11237 } 11238 p = ps.pkg; 11239 } 11240 if (!dataOnly) { 11241 // need to check this only for fully installed applications 11242 if (p == null) { 11243 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11244 return false; 11245 } 11246 final ApplicationInfo applicationInfo = p.applicationInfo; 11247 if (applicationInfo == null) { 11248 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11249 return false; 11250 } 11251 } 11252 if (p != null && p.applicationInfo != null) { 11253 appId = p.applicationInfo.uid; 11254 } else { 11255 appId = -1; 11256 } 11257 } 11258 int retCode = mInstaller.clearUserData(packageName, userId); 11259 if (retCode < 0) { 11260 Slog.w(TAG, "Couldn't remove cache files for package: " 11261 + packageName); 11262 return false; 11263 } 11264 removeKeystoreDataIfNeeded(userId, appId); 11265 return true; 11266 } 11267 11268 /** 11269 * Remove entries from the keystore daemon. Will only remove it if the 11270 * {@code appId} is valid. 11271 */ 11272 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 11273 if (appId < 0) { 11274 return; 11275 } 11276 11277 final KeyStore keyStore = KeyStore.getInstance(); 11278 if (keyStore != null) { 11279 if (userId == UserHandle.USER_ALL) { 11280 for (final int individual : sUserManager.getUserIds()) { 11281 keyStore.clearUid(UserHandle.getUid(individual, appId)); 11282 } 11283 } else { 11284 keyStore.clearUid(UserHandle.getUid(userId, appId)); 11285 } 11286 } else { 11287 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 11288 } 11289 } 11290 11291 @Override 11292 public void deleteApplicationCacheFiles(final String packageName, 11293 final IPackageDataObserver observer) { 11294 mContext.enforceCallingOrSelfPermission( 11295 android.Manifest.permission.DELETE_CACHE_FILES, null); 11296 // Queue up an async operation since the package deletion may take a little while. 11297 final int userId = UserHandle.getCallingUserId(); 11298 mHandler.post(new Runnable() { 11299 public void run() { 11300 mHandler.removeCallbacks(this); 11301 final boolean succeded; 11302 synchronized (mInstallLock) { 11303 succeded = deleteApplicationCacheFilesLI(packageName, userId); 11304 } 11305 clearExternalStorageDataSync(packageName, userId, false); 11306 if(observer != null) { 11307 try { 11308 observer.onRemoveCompleted(packageName, succeded); 11309 } catch (RemoteException e) { 11310 Log.i(TAG, "Observer no longer exists."); 11311 } 11312 } //end if observer 11313 } //end run 11314 }); 11315 } 11316 11317 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 11318 if (packageName == null) { 11319 Slog.w(TAG, "Attempt to delete null packageName."); 11320 return false; 11321 } 11322 PackageParser.Package p; 11323 synchronized (mPackages) { 11324 p = mPackages.get(packageName); 11325 } 11326 if (p == null) { 11327 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11328 return false; 11329 } 11330 final ApplicationInfo applicationInfo = p.applicationInfo; 11331 if (applicationInfo == null) { 11332 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11333 return false; 11334 } 11335 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 11336 if (retCode < 0) { 11337 Slog.w(TAG, "Couldn't remove cache files for package: " 11338 + packageName + " u" + userId); 11339 return false; 11340 } 11341 return true; 11342 } 11343 11344 @Override 11345 public void getPackageSizeInfo(final String packageName, int userHandle, 11346 final IPackageStatsObserver observer) { 11347 mContext.enforceCallingOrSelfPermission( 11348 android.Manifest.permission.GET_PACKAGE_SIZE, null); 11349 if (packageName == null) { 11350 throw new IllegalArgumentException("Attempt to get size of null packageName"); 11351 } 11352 11353 PackageStats stats = new PackageStats(packageName, userHandle); 11354 11355 /* 11356 * Queue up an async operation since the package measurement may take a 11357 * little while. 11358 */ 11359 Message msg = mHandler.obtainMessage(INIT_COPY); 11360 msg.obj = new MeasureParams(stats, observer); 11361 mHandler.sendMessage(msg); 11362 } 11363 11364 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 11365 PackageStats pStats) { 11366 if (packageName == null) { 11367 Slog.w(TAG, "Attempt to get size of null packageName."); 11368 return false; 11369 } 11370 PackageParser.Package p; 11371 boolean dataOnly = false; 11372 String libDirRoot = null; 11373 String asecPath = null; 11374 PackageSetting ps = null; 11375 synchronized (mPackages) { 11376 p = mPackages.get(packageName); 11377 ps = mSettings.mPackages.get(packageName); 11378 if(p == null) { 11379 dataOnly = true; 11380 if((ps == null) || (ps.pkg == null)) { 11381 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11382 return false; 11383 } 11384 p = ps.pkg; 11385 } 11386 if (ps != null) { 11387 libDirRoot = ps.legacyNativeLibraryPathString; 11388 } 11389 if (p != null && (isExternal(p) || isForwardLocked(p))) { 11390 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 11391 if (secureContainerId != null) { 11392 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 11393 } 11394 } 11395 } 11396 String publicSrcDir = null; 11397 if(!dataOnly) { 11398 final ApplicationInfo applicationInfo = p.applicationInfo; 11399 if (applicationInfo == null) { 11400 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11401 return false; 11402 } 11403 if (isForwardLocked(p)) { 11404 publicSrcDir = applicationInfo.getBaseResourcePath(); 11405 } 11406 } 11407 // TODO: extend to measure size of split APKs 11408 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 11409 // not just the first level. 11410 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 11411 // just the primary. 11412 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 11413 int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot, 11414 publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 11415 if (res < 0) { 11416 return false; 11417 } 11418 11419 // Fix-up for forward-locked applications in ASEC containers. 11420 if (!isExternal(p)) { 11421 pStats.codeSize += pStats.externalCodeSize; 11422 pStats.externalCodeSize = 0L; 11423 } 11424 11425 return true; 11426 } 11427 11428 11429 @Override 11430 public void addPackageToPreferred(String packageName) { 11431 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 11432 } 11433 11434 @Override 11435 public void removePackageFromPreferred(String packageName) { 11436 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 11437 } 11438 11439 @Override 11440 public List<PackageInfo> getPreferredPackages(int flags) { 11441 return new ArrayList<PackageInfo>(); 11442 } 11443 11444 private int getUidTargetSdkVersionLockedLPr(int uid) { 11445 Object obj = mSettings.getUserIdLPr(uid); 11446 if (obj instanceof SharedUserSetting) { 11447 final SharedUserSetting sus = (SharedUserSetting) obj; 11448 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 11449 final Iterator<PackageSetting> it = sus.packages.iterator(); 11450 while (it.hasNext()) { 11451 final PackageSetting ps = it.next(); 11452 if (ps.pkg != null) { 11453 int v = ps.pkg.applicationInfo.targetSdkVersion; 11454 if (v < vers) vers = v; 11455 } 11456 } 11457 return vers; 11458 } else if (obj instanceof PackageSetting) { 11459 final PackageSetting ps = (PackageSetting) obj; 11460 if (ps.pkg != null) { 11461 return ps.pkg.applicationInfo.targetSdkVersion; 11462 } 11463 } 11464 return Build.VERSION_CODES.CUR_DEVELOPMENT; 11465 } 11466 11467 @Override 11468 public void addPreferredActivity(IntentFilter filter, int match, 11469 ComponentName[] set, ComponentName activity, int userId) { 11470 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11471 "Adding preferred"); 11472 } 11473 11474 private void addPreferredActivityInternal(IntentFilter filter, int match, 11475 ComponentName[] set, ComponentName activity, boolean always, int userId, 11476 String opname) { 11477 // writer 11478 int callingUid = Binder.getCallingUid(); 11479 enforceCrossUserPermission(callingUid, userId, true, "add preferred activity"); 11480 if (filter.countActions() == 0) { 11481 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11482 return; 11483 } 11484 synchronized (mPackages) { 11485 if (mContext.checkCallingOrSelfPermission( 11486 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11487 != PackageManager.PERMISSION_GRANTED) { 11488 if (getUidTargetSdkVersionLockedLPr(callingUid) 11489 < Build.VERSION_CODES.FROYO) { 11490 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 11491 + callingUid); 11492 return; 11493 } 11494 mContext.enforceCallingOrSelfPermission( 11495 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11496 } 11497 11498 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 11499 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 11500 + userId + ":"); 11501 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11502 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 11503 mSettings.writePackageRestrictionsLPr(userId); 11504 } 11505 } 11506 11507 @Override 11508 public void replacePreferredActivity(IntentFilter filter, int match, 11509 ComponentName[] set, ComponentName activity, int userId) { 11510 if (filter.countActions() != 1) { 11511 throw new IllegalArgumentException( 11512 "replacePreferredActivity expects filter to have only 1 action."); 11513 } 11514 if (filter.countDataAuthorities() != 0 11515 || filter.countDataPaths() != 0 11516 || filter.countDataSchemes() > 1 11517 || filter.countDataTypes() != 0) { 11518 throw new IllegalArgumentException( 11519 "replacePreferredActivity expects filter to have no data authorities, " + 11520 "paths, or types; and at most one scheme."); 11521 } 11522 11523 final int callingUid = Binder.getCallingUid(); 11524 enforceCrossUserPermission(callingUid, userId, true, "replace preferred activity"); 11525 synchronized (mPackages) { 11526 if (mContext.checkCallingOrSelfPermission( 11527 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11528 != PackageManager.PERMISSION_GRANTED) { 11529 if (getUidTargetSdkVersionLockedLPr(callingUid) 11530 < Build.VERSION_CODES.FROYO) { 11531 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 11532 + Binder.getCallingUid()); 11533 return; 11534 } 11535 mContext.enforceCallingOrSelfPermission( 11536 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11537 } 11538 11539 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11540 if (pir != null) { 11541 // Get all of the existing entries that exactly match this filter. 11542 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 11543 if (existing != null && existing.size() == 1) { 11544 PreferredActivity cur = existing.get(0); 11545 if (DEBUG_PREFERRED) { 11546 Slog.i(TAG, "Checking replace of preferred:"); 11547 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11548 if (!cur.mPref.mAlways) { 11549 Slog.i(TAG, " -- CUR; not mAlways!"); 11550 } else { 11551 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 11552 Slog.i(TAG, " -- CUR: mSet=" 11553 + Arrays.toString(cur.mPref.mSetComponents)); 11554 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 11555 Slog.i(TAG, " -- NEW: mMatch=" 11556 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 11557 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 11558 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 11559 } 11560 } 11561 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 11562 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 11563 && cur.mPref.sameSet(set)) { 11564 if (DEBUG_PREFERRED) { 11565 Slog.i(TAG, "Replacing with same preferred activity " 11566 + cur.mPref.mShortComponent + " for user " 11567 + userId + ":"); 11568 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11569 } else { 11570 Slog.i(TAG, "Replacing with same preferred activity " 11571 + cur.mPref.mShortComponent + " for user " 11572 + userId); 11573 } 11574 return; 11575 } 11576 } 11577 11578 if (DEBUG_PREFERRED) { 11579 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 11580 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11581 } 11582 for (int i = 0; i < existing.size(); i++) { 11583 PreferredActivity pa = existing.get(i); 11584 if (DEBUG_PREFERRED) { 11585 Slog.i(TAG, "Removing existing preferred activity " 11586 + pa.mPref.mComponent + ":"); 11587 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 11588 } 11589 pir.removeFilter(pa); 11590 } 11591 } 11592 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11593 "Replacing preferred"); 11594 } 11595 } 11596 11597 @Override 11598 public void clearPackagePreferredActivities(String packageName) { 11599 final int uid = Binder.getCallingUid(); 11600 // writer 11601 synchronized (mPackages) { 11602 PackageParser.Package pkg = mPackages.get(packageName); 11603 if (pkg == null || pkg.applicationInfo.uid != uid) { 11604 if (mContext.checkCallingOrSelfPermission( 11605 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11606 != PackageManager.PERMISSION_GRANTED) { 11607 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11608 < Build.VERSION_CODES.FROYO) { 11609 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 11610 + Binder.getCallingUid()); 11611 return; 11612 } 11613 mContext.enforceCallingOrSelfPermission( 11614 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11615 } 11616 } 11617 11618 int user = UserHandle.getCallingUserId(); 11619 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 11620 mSettings.writePackageRestrictionsLPr(user); 11621 scheduleWriteSettingsLocked(); 11622 } 11623 } 11624 } 11625 11626 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 11627 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 11628 ArrayList<PreferredActivity> removed = null; 11629 boolean changed = false; 11630 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11631 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 11632 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11633 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 11634 continue; 11635 } 11636 Iterator<PreferredActivity> it = pir.filterIterator(); 11637 while (it.hasNext()) { 11638 PreferredActivity pa = it.next(); 11639 // Mark entry for removal only if it matches the package name 11640 // and the entry is of type "always". 11641 if (packageName == null || 11642 (pa.mPref.mComponent.getPackageName().equals(packageName) 11643 && pa.mPref.mAlways)) { 11644 if (removed == null) { 11645 removed = new ArrayList<PreferredActivity>(); 11646 } 11647 removed.add(pa); 11648 } 11649 } 11650 if (removed != null) { 11651 for (int j=0; j<removed.size(); j++) { 11652 PreferredActivity pa = removed.get(j); 11653 pir.removeFilter(pa); 11654 } 11655 changed = true; 11656 } 11657 } 11658 return changed; 11659 } 11660 11661 @Override 11662 public void resetPreferredActivities(int userId) { 11663 mContext.enforceCallingOrSelfPermission( 11664 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11665 // writer 11666 synchronized (mPackages) { 11667 int user = UserHandle.getCallingUserId(); 11668 clearPackagePreferredActivitiesLPw(null, user); 11669 mSettings.readDefaultPreferredAppsLPw(this, user); 11670 mSettings.writePackageRestrictionsLPr(user); 11671 scheduleWriteSettingsLocked(); 11672 } 11673 } 11674 11675 @Override 11676 public int getPreferredActivities(List<IntentFilter> outFilters, 11677 List<ComponentName> outActivities, String packageName) { 11678 11679 int num = 0; 11680 final int userId = UserHandle.getCallingUserId(); 11681 // reader 11682 synchronized (mPackages) { 11683 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11684 if (pir != null) { 11685 final Iterator<PreferredActivity> it = pir.filterIterator(); 11686 while (it.hasNext()) { 11687 final PreferredActivity pa = it.next(); 11688 if (packageName == null 11689 || (pa.mPref.mComponent.getPackageName().equals(packageName) 11690 && pa.mPref.mAlways)) { 11691 if (outFilters != null) { 11692 outFilters.add(new IntentFilter(pa)); 11693 } 11694 if (outActivities != null) { 11695 outActivities.add(pa.mPref.mComponent); 11696 } 11697 } 11698 } 11699 } 11700 } 11701 11702 return num; 11703 } 11704 11705 @Override 11706 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 11707 int userId) { 11708 int callingUid = Binder.getCallingUid(); 11709 if (callingUid != Process.SYSTEM_UID) { 11710 throw new SecurityException( 11711 "addPersistentPreferredActivity can only be run by the system"); 11712 } 11713 if (filter.countActions() == 0) { 11714 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11715 return; 11716 } 11717 synchronized (mPackages) { 11718 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 11719 " :"); 11720 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11721 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 11722 new PersistentPreferredActivity(filter, activity)); 11723 mSettings.writePackageRestrictionsLPr(userId); 11724 } 11725 } 11726 11727 @Override 11728 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 11729 int callingUid = Binder.getCallingUid(); 11730 if (callingUid != Process.SYSTEM_UID) { 11731 throw new SecurityException( 11732 "clearPackagePersistentPreferredActivities can only be run by the system"); 11733 } 11734 ArrayList<PersistentPreferredActivity> removed = null; 11735 boolean changed = false; 11736 synchronized (mPackages) { 11737 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 11738 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 11739 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 11740 .valueAt(i); 11741 if (userId != thisUserId) { 11742 continue; 11743 } 11744 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 11745 while (it.hasNext()) { 11746 PersistentPreferredActivity ppa = it.next(); 11747 // Mark entry for removal only if it matches the package name. 11748 if (ppa.mComponent.getPackageName().equals(packageName)) { 11749 if (removed == null) { 11750 removed = new ArrayList<PersistentPreferredActivity>(); 11751 } 11752 removed.add(ppa); 11753 } 11754 } 11755 if (removed != null) { 11756 for (int j=0; j<removed.size(); j++) { 11757 PersistentPreferredActivity ppa = removed.get(j); 11758 ppir.removeFilter(ppa); 11759 } 11760 changed = true; 11761 } 11762 } 11763 11764 if (changed) { 11765 mSettings.writePackageRestrictionsLPr(userId); 11766 } 11767 } 11768 } 11769 11770 @Override 11771 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 11772 int ownerUserId, int sourceUserId, int targetUserId, int flags) { 11773 mContext.enforceCallingOrSelfPermission( 11774 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11775 int callingUid = Binder.getCallingUid(); 11776 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11777 if (intentFilter.countActions() == 0) { 11778 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 11779 return; 11780 } 11781 synchronized (mPackages) { 11782 CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter, 11783 ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags); 11784 mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter); 11785 mSettings.writePackageRestrictionsLPr(sourceUserId); 11786 } 11787 } 11788 11789 @Override 11790 public void addCrossProfileIntentsForPackage(String packageName, 11791 int sourceUserId, int targetUserId) { 11792 mContext.enforceCallingOrSelfPermission( 11793 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11794 mSettings.addCrossProfilePackage(packageName, sourceUserId, targetUserId); 11795 mSettings.writePackageRestrictionsLPr(sourceUserId); 11796 } 11797 11798 @Override 11799 public void removeCrossProfileIntentsForPackage(String packageName, 11800 int sourceUserId, int targetUserId) { 11801 mContext.enforceCallingOrSelfPermission( 11802 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11803 mSettings.removeCrossProfilePackage(packageName, sourceUserId, targetUserId); 11804 mSettings.writePackageRestrictionsLPr(sourceUserId); 11805 } 11806 11807 @Override 11808 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage, 11809 int ownerUserId) { 11810 mContext.enforceCallingOrSelfPermission( 11811 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11812 int callingUid = Binder.getCallingUid(); 11813 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11814 int callingUserId = UserHandle.getUserId(callingUid); 11815 synchronized (mPackages) { 11816 CrossProfileIntentResolver resolver = 11817 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11818 HashSet<CrossProfileIntentFilter> set = 11819 new HashSet<CrossProfileIntentFilter>(resolver.filterSet()); 11820 for (CrossProfileIntentFilter filter : set) { 11821 if (filter.getOwnerPackage().equals(ownerPackage) 11822 && filter.getOwnerUserId() == callingUserId) { 11823 resolver.removeFilter(filter); 11824 } 11825 } 11826 mSettings.writePackageRestrictionsLPr(sourceUserId); 11827 } 11828 } 11829 11830 // Enforcing that callingUid is owning pkg on userId 11831 private void enforceOwnerRights(String pkg, int userId, int callingUid) { 11832 // The system owns everything. 11833 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 11834 return; 11835 } 11836 int callingUserId = UserHandle.getUserId(callingUid); 11837 if (callingUserId != userId) { 11838 throw new SecurityException("calling uid " + callingUid 11839 + " pretends to own " + pkg + " on user " + userId + " but belongs to user " 11840 + callingUserId); 11841 } 11842 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 11843 if (pi == null) { 11844 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 11845 + callingUserId); 11846 } 11847 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 11848 throw new SecurityException("Calling uid " + callingUid 11849 + " does not own package " + pkg); 11850 } 11851 } 11852 11853 @Override 11854 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 11855 Intent intent = new Intent(Intent.ACTION_MAIN); 11856 intent.addCategory(Intent.CATEGORY_HOME); 11857 11858 final int callingUserId = UserHandle.getCallingUserId(); 11859 List<ResolveInfo> list = queryIntentActivities(intent, null, 11860 PackageManager.GET_META_DATA, callingUserId); 11861 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 11862 true, false, false, callingUserId); 11863 11864 allHomeCandidates.clear(); 11865 if (list != null) { 11866 for (ResolveInfo ri : list) { 11867 allHomeCandidates.add(ri); 11868 } 11869 } 11870 return (preferred == null || preferred.activityInfo == null) 11871 ? null 11872 : new ComponentName(preferred.activityInfo.packageName, 11873 preferred.activityInfo.name); 11874 } 11875 11876 /** 11877 * Check if calling UID is the current home app. This handles both the case 11878 * where the user has selected a specific home app, and where there is only 11879 * one home app. 11880 */ 11881 public boolean checkCallerIsHomeApp() { 11882 final Intent intent = new Intent(Intent.ACTION_MAIN); 11883 intent.addCategory(Intent.CATEGORY_HOME); 11884 11885 final int callingUid = Binder.getCallingUid(); 11886 final int callingUserId = UserHandle.getCallingUserId(); 11887 final List<ResolveInfo> allHomes = queryIntentActivities(intent, null, 0, callingUserId); 11888 final ResolveInfo preferredHome = findPreferredActivity(intent, null, 0, allHomes, 0, true, 11889 false, false, callingUserId); 11890 11891 if (preferredHome != null) { 11892 if (callingUid == preferredHome.activityInfo.applicationInfo.uid) { 11893 return true; 11894 } 11895 } else { 11896 for (ResolveInfo info : allHomes) { 11897 if (callingUid == info.activityInfo.applicationInfo.uid) { 11898 return true; 11899 } 11900 } 11901 } 11902 11903 return false; 11904 } 11905 11906 /** 11907 * Enforce that calling UID is the current home app. This handles both the 11908 * case where the user has selected a specific home app, and where there is 11909 * only one home app. 11910 */ 11911 public void enforceCallerIsHomeApp() { 11912 if (!checkCallerIsHomeApp()) { 11913 throw new SecurityException("Caller is not currently selected home app"); 11914 } 11915 } 11916 11917 @Override 11918 public void setApplicationEnabledSetting(String appPackageName, 11919 int newState, int flags, int userId, String callingPackage) { 11920 if (!sUserManager.exists(userId)) return; 11921 if (callingPackage == null) { 11922 callingPackage = Integer.toString(Binder.getCallingUid()); 11923 } 11924 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 11925 } 11926 11927 @Override 11928 public void setComponentEnabledSetting(ComponentName componentName, 11929 int newState, int flags, int userId) { 11930 if (!sUserManager.exists(userId)) return; 11931 setEnabledSetting(componentName.getPackageName(), 11932 componentName.getClassName(), newState, flags, userId, null); 11933 } 11934 11935 private void setEnabledSetting(final String packageName, String className, int newState, 11936 final int flags, int userId, String callingPackage) { 11937 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 11938 || newState == COMPONENT_ENABLED_STATE_ENABLED 11939 || newState == COMPONENT_ENABLED_STATE_DISABLED 11940 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 11941 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 11942 throw new IllegalArgumentException("Invalid new component state: " 11943 + newState); 11944 } 11945 PackageSetting pkgSetting; 11946 final int uid = Binder.getCallingUid(); 11947 final int permission = mContext.checkCallingOrSelfPermission( 11948 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11949 enforceCrossUserPermission(uid, userId, false, "set enabled"); 11950 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11951 boolean sendNow = false; 11952 boolean isApp = (className == null); 11953 String componentName = isApp ? packageName : className; 11954 int packageUid = -1; 11955 ArrayList<String> components; 11956 11957 // writer 11958 synchronized (mPackages) { 11959 pkgSetting = mSettings.mPackages.get(packageName); 11960 if (pkgSetting == null) { 11961 if (className == null) { 11962 throw new IllegalArgumentException( 11963 "Unknown package: " + packageName); 11964 } 11965 throw new IllegalArgumentException( 11966 "Unknown component: " + packageName 11967 + "/" + className); 11968 } 11969 // Allow root and verify that userId is not being specified by a different user 11970 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 11971 throw new SecurityException( 11972 "Permission Denial: attempt to change component state from pid=" 11973 + Binder.getCallingPid() 11974 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 11975 } 11976 if (className == null) { 11977 // We're dealing with an application/package level state change 11978 if (pkgSetting.getEnabled(userId) == newState) { 11979 // Nothing to do 11980 return; 11981 } 11982 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 11983 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 11984 // Don't care about who enables an app. 11985 callingPackage = null; 11986 } 11987 pkgSetting.setEnabled(newState, userId, callingPackage); 11988 // pkgSetting.pkg.mSetEnabled = newState; 11989 } else { 11990 // We're dealing with a component level state change 11991 // First, verify that this is a valid class name. 11992 PackageParser.Package pkg = pkgSetting.pkg; 11993 if (pkg == null || !pkg.hasComponentClassName(className)) { 11994 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 11995 throw new IllegalArgumentException("Component class " + className 11996 + " does not exist in " + packageName); 11997 } else { 11998 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 11999 + className + " does not exist in " + packageName); 12000 } 12001 } 12002 switch (newState) { 12003 case COMPONENT_ENABLED_STATE_ENABLED: 12004 if (!pkgSetting.enableComponentLPw(className, userId)) { 12005 return; 12006 } 12007 break; 12008 case COMPONENT_ENABLED_STATE_DISABLED: 12009 if (!pkgSetting.disableComponentLPw(className, userId)) { 12010 return; 12011 } 12012 break; 12013 case COMPONENT_ENABLED_STATE_DEFAULT: 12014 if (!pkgSetting.restoreComponentLPw(className, userId)) { 12015 return; 12016 } 12017 break; 12018 default: 12019 Slog.e(TAG, "Invalid new component state: " + newState); 12020 return; 12021 } 12022 } 12023 mSettings.writePackageRestrictionsLPr(userId); 12024 components = mPendingBroadcasts.get(userId, packageName); 12025 final boolean newPackage = components == null; 12026 if (newPackage) { 12027 components = new ArrayList<String>(); 12028 } 12029 if (!components.contains(componentName)) { 12030 components.add(componentName); 12031 } 12032 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 12033 sendNow = true; 12034 // Purge entry from pending broadcast list if another one exists already 12035 // since we are sending one right away. 12036 mPendingBroadcasts.remove(userId, packageName); 12037 } else { 12038 if (newPackage) { 12039 mPendingBroadcasts.put(userId, packageName, components); 12040 } 12041 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 12042 // Schedule a message 12043 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 12044 } 12045 } 12046 } 12047 12048 long callingId = Binder.clearCallingIdentity(); 12049 try { 12050 if (sendNow) { 12051 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 12052 sendPackageChangedBroadcast(packageName, 12053 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 12054 } 12055 } finally { 12056 Binder.restoreCallingIdentity(callingId); 12057 } 12058 } 12059 12060 private void sendPackageChangedBroadcast(String packageName, 12061 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 12062 if (DEBUG_INSTALL) 12063 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 12064 + componentNames); 12065 Bundle extras = new Bundle(4); 12066 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 12067 String nameList[] = new String[componentNames.size()]; 12068 componentNames.toArray(nameList); 12069 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 12070 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 12071 extras.putInt(Intent.EXTRA_UID, packageUid); 12072 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 12073 new int[] {UserHandle.getUserId(packageUid)}); 12074 } 12075 12076 @Override 12077 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 12078 if (!sUserManager.exists(userId)) return; 12079 final int uid = Binder.getCallingUid(); 12080 final int permission = mContext.checkCallingOrSelfPermission( 12081 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 12082 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 12083 enforceCrossUserPermission(uid, userId, true, "stop package"); 12084 // writer 12085 synchronized (mPackages) { 12086 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 12087 uid, userId)) { 12088 scheduleWritePackageRestrictionsLocked(userId); 12089 } 12090 } 12091 } 12092 12093 @Override 12094 public String getInstallerPackageName(String packageName) { 12095 // reader 12096 synchronized (mPackages) { 12097 return mSettings.getInstallerPackageNameLPr(packageName); 12098 } 12099 } 12100 12101 @Override 12102 public int getApplicationEnabledSetting(String packageName, int userId) { 12103 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12104 int uid = Binder.getCallingUid(); 12105 enforceCrossUserPermission(uid, userId, false, "get enabled"); 12106 // reader 12107 synchronized (mPackages) { 12108 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 12109 } 12110 } 12111 12112 @Override 12113 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 12114 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12115 int uid = Binder.getCallingUid(); 12116 enforceCrossUserPermission(uid, userId, false, "get component enabled"); 12117 // reader 12118 synchronized (mPackages) { 12119 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 12120 } 12121 } 12122 12123 @Override 12124 public void enterSafeMode() { 12125 enforceSystemOrRoot("Only the system can request entering safe mode"); 12126 12127 if (!mSystemReady) { 12128 mSafeMode = true; 12129 } 12130 } 12131 12132 @Override 12133 public void systemReady() { 12134 mSystemReady = true; 12135 12136 // Read the compatibilty setting when the system is ready. 12137 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 12138 mContext.getContentResolver(), 12139 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 12140 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 12141 if (DEBUG_SETTINGS) { 12142 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 12143 } 12144 12145 synchronized (mPackages) { 12146 // Verify that all of the preferred activity components actually 12147 // exist. It is possible for applications to be updated and at 12148 // that point remove a previously declared activity component that 12149 // had been set as a preferred activity. We try to clean this up 12150 // the next time we encounter that preferred activity, but it is 12151 // possible for the user flow to never be able to return to that 12152 // situation so here we do a sanity check to make sure we haven't 12153 // left any junk around. 12154 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 12155 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12156 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12157 removed.clear(); 12158 for (PreferredActivity pa : pir.filterSet()) { 12159 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 12160 removed.add(pa); 12161 } 12162 } 12163 if (removed.size() > 0) { 12164 for (int r=0; r<removed.size(); r++) { 12165 PreferredActivity pa = removed.get(r); 12166 Slog.w(TAG, "Removing dangling preferred activity: " 12167 + pa.mPref.mComponent); 12168 pir.removeFilter(pa); 12169 } 12170 mSettings.writePackageRestrictionsLPr( 12171 mSettings.mPreferredActivities.keyAt(i)); 12172 } 12173 } 12174 } 12175 sUserManager.systemReady(); 12176 } 12177 12178 @Override 12179 public boolean isSafeMode() { 12180 return mSafeMode; 12181 } 12182 12183 @Override 12184 public boolean hasSystemUidErrors() { 12185 return mHasSystemUidErrors; 12186 } 12187 12188 static String arrayToString(int[] array) { 12189 StringBuffer buf = new StringBuffer(128); 12190 buf.append('['); 12191 if (array != null) { 12192 for (int i=0; i<array.length; i++) { 12193 if (i > 0) buf.append(", "); 12194 buf.append(array[i]); 12195 } 12196 } 12197 buf.append(']'); 12198 return buf.toString(); 12199 } 12200 12201 static class DumpState { 12202 public static final int DUMP_LIBS = 1 << 0; 12203 public static final int DUMP_FEATURES = 1 << 1; 12204 public static final int DUMP_RESOLVERS = 1 << 2; 12205 public static final int DUMP_PERMISSIONS = 1 << 3; 12206 public static final int DUMP_PACKAGES = 1 << 4; 12207 public static final int DUMP_SHARED_USERS = 1 << 5; 12208 public static final int DUMP_MESSAGES = 1 << 6; 12209 public static final int DUMP_PROVIDERS = 1 << 7; 12210 public static final int DUMP_VERIFIERS = 1 << 8; 12211 public static final int DUMP_PREFERRED = 1 << 9; 12212 public static final int DUMP_PREFERRED_XML = 1 << 10; 12213 public static final int DUMP_KEYSETS = 1 << 11; 12214 public static final int DUMP_VERSION = 1 << 12; 12215 public static final int DUMP_INSTALLS = 1 << 13; 12216 12217 public static final int OPTION_SHOW_FILTERS = 1 << 0; 12218 12219 private int mTypes; 12220 12221 private int mOptions; 12222 12223 private boolean mTitlePrinted; 12224 12225 private SharedUserSetting mSharedUser; 12226 12227 public boolean isDumping(int type) { 12228 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 12229 return true; 12230 } 12231 12232 return (mTypes & type) != 0; 12233 } 12234 12235 public void setDump(int type) { 12236 mTypes |= type; 12237 } 12238 12239 public boolean isOptionEnabled(int option) { 12240 return (mOptions & option) != 0; 12241 } 12242 12243 public void setOptionEnabled(int option) { 12244 mOptions |= option; 12245 } 12246 12247 public boolean onTitlePrinted() { 12248 final boolean printed = mTitlePrinted; 12249 mTitlePrinted = true; 12250 return printed; 12251 } 12252 12253 public boolean getTitlePrinted() { 12254 return mTitlePrinted; 12255 } 12256 12257 public void setTitlePrinted(boolean enabled) { 12258 mTitlePrinted = enabled; 12259 } 12260 12261 public SharedUserSetting getSharedUser() { 12262 return mSharedUser; 12263 } 12264 12265 public void setSharedUser(SharedUserSetting user) { 12266 mSharedUser = user; 12267 } 12268 } 12269 12270 @Override 12271 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 12272 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 12273 != PackageManager.PERMISSION_GRANTED) { 12274 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 12275 + Binder.getCallingPid() 12276 + ", uid=" + Binder.getCallingUid() 12277 + " without permission " 12278 + android.Manifest.permission.DUMP); 12279 return; 12280 } 12281 12282 DumpState dumpState = new DumpState(); 12283 boolean fullPreferred = false; 12284 boolean checkin = false; 12285 12286 String packageName = null; 12287 12288 int opti = 0; 12289 while (opti < args.length) { 12290 String opt = args[opti]; 12291 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 12292 break; 12293 } 12294 opti++; 12295 if ("-a".equals(opt)) { 12296 // Right now we only know how to print all. 12297 } else if ("-h".equals(opt)) { 12298 pw.println("Package manager dump options:"); 12299 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 12300 pw.println(" --checkin: dump for a checkin"); 12301 pw.println(" -f: print details of intent filters"); 12302 pw.println(" -h: print this help"); 12303 pw.println(" cmd may be one of:"); 12304 pw.println(" l[ibraries]: list known shared libraries"); 12305 pw.println(" f[ibraries]: list device features"); 12306 pw.println(" k[eysets]: print known keysets"); 12307 pw.println(" r[esolvers]: dump intent resolvers"); 12308 pw.println(" perm[issions]: dump permissions"); 12309 pw.println(" pref[erred]: print preferred package settings"); 12310 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 12311 pw.println(" prov[iders]: dump content providers"); 12312 pw.println(" p[ackages]: dump installed packages"); 12313 pw.println(" s[hared-users]: dump shared user IDs"); 12314 pw.println(" m[essages]: print collected runtime messages"); 12315 pw.println(" v[erifiers]: print package verifier info"); 12316 pw.println(" version: print database version info"); 12317 pw.println(" write: write current settings now"); 12318 pw.println(" <package.name>: info about given package"); 12319 pw.println(" installs: details about install sessions"); 12320 return; 12321 } else if ("--checkin".equals(opt)) { 12322 checkin = true; 12323 } else if ("-f".equals(opt)) { 12324 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12325 } else { 12326 pw.println("Unknown argument: " + opt + "; use -h for help"); 12327 } 12328 } 12329 12330 // Is the caller requesting to dump a particular piece of data? 12331 if (opti < args.length) { 12332 String cmd = args[opti]; 12333 opti++; 12334 // Is this a package name? 12335 if ("android".equals(cmd) || cmd.contains(".")) { 12336 packageName = cmd; 12337 // When dumping a single package, we always dump all of its 12338 // filter information since the amount of data will be reasonable. 12339 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12340 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 12341 dumpState.setDump(DumpState.DUMP_LIBS); 12342 } else if ("f".equals(cmd) || "features".equals(cmd)) { 12343 dumpState.setDump(DumpState.DUMP_FEATURES); 12344 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 12345 dumpState.setDump(DumpState.DUMP_RESOLVERS); 12346 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 12347 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 12348 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 12349 dumpState.setDump(DumpState.DUMP_PREFERRED); 12350 } else if ("preferred-xml".equals(cmd)) { 12351 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 12352 if (opti < args.length && "--full".equals(args[opti])) { 12353 fullPreferred = true; 12354 opti++; 12355 } 12356 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 12357 dumpState.setDump(DumpState.DUMP_PACKAGES); 12358 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 12359 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 12360 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 12361 dumpState.setDump(DumpState.DUMP_PROVIDERS); 12362 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 12363 dumpState.setDump(DumpState.DUMP_MESSAGES); 12364 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 12365 dumpState.setDump(DumpState.DUMP_VERIFIERS); 12366 } else if ("version".equals(cmd)) { 12367 dumpState.setDump(DumpState.DUMP_VERSION); 12368 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 12369 dumpState.setDump(DumpState.DUMP_KEYSETS); 12370 } else if ("write".equals(cmd)) { 12371 synchronized (mPackages) { 12372 mSettings.writeLPr(); 12373 pw.println("Settings written."); 12374 return; 12375 } 12376 } else if ("installs".equals(cmd)) { 12377 dumpState.setDump(DumpState.DUMP_INSTALLS); 12378 } 12379 } 12380 12381 if (checkin) { 12382 pw.println("vers,1"); 12383 } 12384 12385 // reader 12386 synchronized (mPackages) { 12387 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 12388 if (!checkin) { 12389 if (dumpState.onTitlePrinted()) 12390 pw.println(); 12391 pw.println("Database versions:"); 12392 pw.print(" SDK Version:"); 12393 pw.print(" internal="); 12394 pw.print(mSettings.mInternalSdkPlatform); 12395 pw.print(" external="); 12396 pw.println(mSettings.mExternalSdkPlatform); 12397 pw.print(" DB Version:"); 12398 pw.print(" internal="); 12399 pw.print(mSettings.mInternalDatabaseVersion); 12400 pw.print(" external="); 12401 pw.println(mSettings.mExternalDatabaseVersion); 12402 } 12403 } 12404 12405 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 12406 if (!checkin) { 12407 if (dumpState.onTitlePrinted()) 12408 pw.println(); 12409 pw.println("Verifiers:"); 12410 pw.print(" Required: "); 12411 pw.print(mRequiredVerifierPackage); 12412 pw.print(" (uid="); 12413 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 12414 pw.println(")"); 12415 } else if (mRequiredVerifierPackage != null) { 12416 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 12417 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 12418 } 12419 } 12420 12421 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 12422 boolean printedHeader = false; 12423 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 12424 while (it.hasNext()) { 12425 String name = it.next(); 12426 SharedLibraryEntry ent = mSharedLibraries.get(name); 12427 if (!checkin) { 12428 if (!printedHeader) { 12429 if (dumpState.onTitlePrinted()) 12430 pw.println(); 12431 pw.println("Libraries:"); 12432 printedHeader = true; 12433 } 12434 pw.print(" "); 12435 } else { 12436 pw.print("lib,"); 12437 } 12438 pw.print(name); 12439 if (!checkin) { 12440 pw.print(" -> "); 12441 } 12442 if (ent.path != null) { 12443 if (!checkin) { 12444 pw.print("(jar) "); 12445 pw.print(ent.path); 12446 } else { 12447 pw.print(",jar,"); 12448 pw.print(ent.path); 12449 } 12450 } else { 12451 if (!checkin) { 12452 pw.print("(apk) "); 12453 pw.print(ent.apk); 12454 } else { 12455 pw.print(",apk,"); 12456 pw.print(ent.apk); 12457 } 12458 } 12459 pw.println(); 12460 } 12461 } 12462 12463 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 12464 if (dumpState.onTitlePrinted()) 12465 pw.println(); 12466 if (!checkin) { 12467 pw.println("Features:"); 12468 } 12469 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 12470 while (it.hasNext()) { 12471 String name = it.next(); 12472 if (!checkin) { 12473 pw.print(" "); 12474 } else { 12475 pw.print("feat,"); 12476 } 12477 pw.println(name); 12478 } 12479 } 12480 12481 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 12482 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 12483 : "Activity Resolver Table:", " ", packageName, 12484 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12485 dumpState.setTitlePrinted(true); 12486 } 12487 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 12488 : "Receiver Resolver Table:", " ", packageName, 12489 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12490 dumpState.setTitlePrinted(true); 12491 } 12492 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 12493 : "Service Resolver Table:", " ", packageName, 12494 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12495 dumpState.setTitlePrinted(true); 12496 } 12497 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 12498 : "Provider Resolver Table:", " ", packageName, 12499 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12500 dumpState.setTitlePrinted(true); 12501 } 12502 } 12503 12504 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 12505 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12506 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12507 int user = mSettings.mPreferredActivities.keyAt(i); 12508 if (pir.dump(pw, 12509 dumpState.getTitlePrinted() 12510 ? "\nPreferred Activities User " + user + ":" 12511 : "Preferred Activities User " + user + ":", " ", 12512 packageName, true)) { 12513 dumpState.setTitlePrinted(true); 12514 } 12515 } 12516 } 12517 12518 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 12519 pw.flush(); 12520 FileOutputStream fout = new FileOutputStream(fd); 12521 BufferedOutputStream str = new BufferedOutputStream(fout); 12522 XmlSerializer serializer = new FastXmlSerializer(); 12523 try { 12524 serializer.setOutput(str, "utf-8"); 12525 serializer.startDocument(null, true); 12526 serializer.setFeature( 12527 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 12528 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 12529 serializer.endDocument(); 12530 serializer.flush(); 12531 } catch (IllegalArgumentException e) { 12532 pw.println("Failed writing: " + e); 12533 } catch (IllegalStateException e) { 12534 pw.println("Failed writing: " + e); 12535 } catch (IOException e) { 12536 pw.println("Failed writing: " + e); 12537 } 12538 } 12539 12540 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 12541 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 12542 if (packageName == null) { 12543 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 12544 if (iperm == 0) { 12545 if (dumpState.onTitlePrinted()) 12546 pw.println(); 12547 pw.println("AppOp Permissions:"); 12548 } 12549 pw.print(" AppOp Permission "); 12550 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 12551 pw.println(":"); 12552 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 12553 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 12554 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 12555 } 12556 } 12557 } 12558 } 12559 12560 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 12561 boolean printedSomething = false; 12562 for (PackageParser.Provider p : mProviders.mProviders.values()) { 12563 if (packageName != null && !packageName.equals(p.info.packageName)) { 12564 continue; 12565 } 12566 if (!printedSomething) { 12567 if (dumpState.onTitlePrinted()) 12568 pw.println(); 12569 pw.println("Registered ContentProviders:"); 12570 printedSomething = true; 12571 } 12572 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 12573 pw.print(" "); pw.println(p.toString()); 12574 } 12575 printedSomething = false; 12576 for (Map.Entry<String, PackageParser.Provider> entry : 12577 mProvidersByAuthority.entrySet()) { 12578 PackageParser.Provider p = entry.getValue(); 12579 if (packageName != null && !packageName.equals(p.info.packageName)) { 12580 continue; 12581 } 12582 if (!printedSomething) { 12583 if (dumpState.onTitlePrinted()) 12584 pw.println(); 12585 pw.println("ContentProvider Authorities:"); 12586 printedSomething = true; 12587 } 12588 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 12589 pw.print(" "); pw.println(p.toString()); 12590 if (p.info != null && p.info.applicationInfo != null) { 12591 final String appInfo = p.info.applicationInfo.toString(); 12592 pw.print(" applicationInfo="); pw.println(appInfo); 12593 } 12594 } 12595 } 12596 12597 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 12598 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 12599 } 12600 12601 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 12602 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 12603 } 12604 12605 if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 12606 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState); 12607 } 12608 12609 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS)) { 12610 if (dumpState.onTitlePrinted()) pw.println(); 12611 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 12612 } 12613 12614 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 12615 if (dumpState.onTitlePrinted()) pw.println(); 12616 mSettings.dumpReadMessagesLPr(pw, dumpState); 12617 12618 pw.println(); 12619 pw.println("Package warning messages:"); 12620 final File fname = getSettingsProblemFile(); 12621 FileInputStream in = null; 12622 try { 12623 in = new FileInputStream(fname); 12624 final int avail = in.available(); 12625 final byte[] data = new byte[avail]; 12626 in.read(data); 12627 pw.print(new String(data)); 12628 } catch (FileNotFoundException e) { 12629 } catch (IOException e) { 12630 } finally { 12631 if (in != null) { 12632 try { 12633 in.close(); 12634 } catch (IOException e) { 12635 } 12636 } 12637 } 12638 } 12639 } 12640 } 12641 12642 // ------- apps on sdcard specific code ------- 12643 static final boolean DEBUG_SD_INSTALL = false; 12644 12645 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 12646 12647 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 12648 12649 private boolean mMediaMounted = false; 12650 12651 static String getEncryptKey() { 12652 try { 12653 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 12654 SD_ENCRYPTION_KEYSTORE_NAME); 12655 if (sdEncKey == null) { 12656 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 12657 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 12658 if (sdEncKey == null) { 12659 Slog.e(TAG, "Failed to create encryption keys"); 12660 return null; 12661 } 12662 } 12663 return sdEncKey; 12664 } catch (NoSuchAlgorithmException nsae) { 12665 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 12666 return null; 12667 } catch (IOException ioe) { 12668 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 12669 return null; 12670 } 12671 } 12672 12673 /* 12674 * Update media status on PackageManager. 12675 */ 12676 @Override 12677 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 12678 int callingUid = Binder.getCallingUid(); 12679 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 12680 throw new SecurityException("Media status can only be updated by the system"); 12681 } 12682 // reader; this apparently protects mMediaMounted, but should probably 12683 // be a different lock in that case. 12684 synchronized (mPackages) { 12685 Log.i(TAG, "Updating external media status from " 12686 + (mMediaMounted ? "mounted" : "unmounted") + " to " 12687 + (mediaStatus ? "mounted" : "unmounted")); 12688 if (DEBUG_SD_INSTALL) 12689 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 12690 + ", mMediaMounted=" + mMediaMounted); 12691 if (mediaStatus == mMediaMounted) { 12692 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 12693 : 0, -1); 12694 mHandler.sendMessage(msg); 12695 return; 12696 } 12697 mMediaMounted = mediaStatus; 12698 } 12699 // Queue up an async operation since the package installation may take a 12700 // little while. 12701 mHandler.post(new Runnable() { 12702 public void run() { 12703 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 12704 } 12705 }); 12706 } 12707 12708 /** 12709 * Called by MountService when the initial ASECs to scan are available. 12710 * Should block until all the ASEC containers are finished being scanned. 12711 */ 12712 public void scanAvailableAsecs() { 12713 updateExternalMediaStatusInner(true, false, false); 12714 if (mShouldRestoreconData) { 12715 SELinuxMMAC.setRestoreconDone(); 12716 mShouldRestoreconData = false; 12717 } 12718 } 12719 12720 /* 12721 * Collect information of applications on external media, map them against 12722 * existing containers and update information based on current mount status. 12723 * Please note that we always have to report status if reportStatus has been 12724 * set to true especially when unloading packages. 12725 */ 12726 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 12727 boolean externalStorage) { 12728 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 12729 int[] uidArr = EmptyArray.INT; 12730 12731 final String[] list = PackageHelper.getSecureContainerList(); 12732 if (ArrayUtils.isEmpty(list)) { 12733 Log.i(TAG, "No secure containers found"); 12734 } else { 12735 // Process list of secure containers and categorize them 12736 // as active or stale based on their package internal state. 12737 12738 // reader 12739 synchronized (mPackages) { 12740 for (String cid : list) { 12741 // Leave stages untouched for now; installer service owns them 12742 if (PackageInstallerService.isStageName(cid)) continue; 12743 12744 if (DEBUG_SD_INSTALL) 12745 Log.i(TAG, "Processing container " + cid); 12746 String pkgName = getAsecPackageName(cid); 12747 if (pkgName == null) { 12748 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 12749 continue; 12750 } 12751 if (DEBUG_SD_INSTALL) 12752 Log.i(TAG, "Looking for pkg : " + pkgName); 12753 12754 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12755 if (ps == null) { 12756 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 12757 continue; 12758 } 12759 12760 /* 12761 * Skip packages that are not external if we're unmounting 12762 * external storage. 12763 */ 12764 if (externalStorage && !isMounted && !isExternal(ps)) { 12765 continue; 12766 } 12767 12768 final AsecInstallArgs args = new AsecInstallArgs(cid, 12769 getAppDexInstructionSets(ps), isForwardLocked(ps), isMultiArch(ps)); 12770 // The package status is changed only if the code path 12771 // matches between settings and the container id. 12772 if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) { 12773 if (DEBUG_SD_INSTALL) { 12774 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 12775 + " at code path: " + ps.codePathString); 12776 } 12777 12778 // We do have a valid package installed on sdcard 12779 processCids.put(args, ps.codePathString); 12780 final int uid = ps.appId; 12781 if (uid != -1) { 12782 uidArr = ArrayUtils.appendInt(uidArr, uid); 12783 } 12784 } else { 12785 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 12786 + ps.codePathString); 12787 } 12788 } 12789 } 12790 12791 Arrays.sort(uidArr); 12792 } 12793 12794 // Process packages with valid entries. 12795 if (isMounted) { 12796 if (DEBUG_SD_INSTALL) 12797 Log.i(TAG, "Loading packages"); 12798 loadMediaPackages(processCids, uidArr); 12799 startCleaningPackages(); 12800 mInstallerService.onSecureContainersAvailable(); 12801 } else { 12802 if (DEBUG_SD_INSTALL) 12803 Log.i(TAG, "Unloading packages"); 12804 unloadMediaPackages(processCids, uidArr, reportStatus); 12805 } 12806 } 12807 12808 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 12809 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 12810 int size = pkgList.size(); 12811 if (size > 0) { 12812 // Send broadcasts here 12813 Bundle extras = new Bundle(); 12814 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 12815 .toArray(new String[size])); 12816 if (uidArr != null) { 12817 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 12818 } 12819 if (replacing) { 12820 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 12821 } 12822 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 12823 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 12824 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 12825 } 12826 } 12827 12828 /* 12829 * Look at potentially valid container ids from processCids If package 12830 * information doesn't match the one on record or package scanning fails, 12831 * the cid is added to list of removeCids. We currently don't delete stale 12832 * containers. 12833 */ 12834 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 12835 ArrayList<String> pkgList = new ArrayList<String>(); 12836 Set<AsecInstallArgs> keys = processCids.keySet(); 12837 12838 for (AsecInstallArgs args : keys) { 12839 String codePath = processCids.get(args); 12840 if (DEBUG_SD_INSTALL) 12841 Log.i(TAG, "Loading container : " + args.cid); 12842 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12843 try { 12844 // Make sure there are no container errors first. 12845 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 12846 Slog.e(TAG, "Failed to mount cid : " + args.cid 12847 + " when installing from sdcard"); 12848 continue; 12849 } 12850 // Check code path here. 12851 if (codePath == null || !codePath.equals(args.getCodePath())) { 12852 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 12853 + " does not match one in settings " + codePath); 12854 continue; 12855 } 12856 // Parse package 12857 int parseFlags = mDefParseFlags; 12858 if (args.isExternal()) { 12859 parseFlags |= PackageParser.PARSE_ON_SDCARD; 12860 } 12861 if (args.isFwdLocked()) { 12862 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 12863 } 12864 12865 synchronized (mInstallLock) { 12866 PackageParser.Package pkg = null; 12867 try { 12868 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 12869 } catch (PackageManagerException e) { 12870 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 12871 } 12872 // Scan the package 12873 if (pkg != null) { 12874 /* 12875 * TODO why is the lock being held? doPostInstall is 12876 * called in other places without the lock. This needs 12877 * to be straightened out. 12878 */ 12879 // writer 12880 synchronized (mPackages) { 12881 retCode = PackageManager.INSTALL_SUCCEEDED; 12882 pkgList.add(pkg.packageName); 12883 // Post process args 12884 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 12885 pkg.applicationInfo.uid); 12886 } 12887 } else { 12888 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 12889 } 12890 } 12891 12892 } finally { 12893 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 12894 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 12895 } 12896 } 12897 } 12898 // writer 12899 synchronized (mPackages) { 12900 // If the platform SDK has changed since the last time we booted, 12901 // we need to re-grant app permission to catch any new ones that 12902 // appear. This is really a hack, and means that apps can in some 12903 // cases get permissions that the user didn't initially explicitly 12904 // allow... it would be nice to have some better way to handle 12905 // this situation. 12906 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 12907 if (regrantPermissions) 12908 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 12909 + mSdkVersion + "; regranting permissions for external storage"); 12910 mSettings.mExternalSdkPlatform = mSdkVersion; 12911 12912 // Make sure group IDs have been assigned, and any permission 12913 // changes in other apps are accounted for 12914 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 12915 | (regrantPermissions 12916 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 12917 : 0)); 12918 12919 mSettings.updateExternalDatabaseVersion(); 12920 12921 // can downgrade to reader 12922 // Persist settings 12923 mSettings.writeLPr(); 12924 } 12925 // Send a broadcast to let everyone know we are done processing 12926 if (pkgList.size() > 0) { 12927 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12928 } 12929 } 12930 12931 /* 12932 * Utility method to unload a list of specified containers 12933 */ 12934 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 12935 // Just unmount all valid containers. 12936 for (AsecInstallArgs arg : cidArgs) { 12937 synchronized (mInstallLock) { 12938 arg.doPostDeleteLI(false); 12939 } 12940 } 12941 } 12942 12943 /* 12944 * Unload packages mounted on external media. This involves deleting package 12945 * data from internal structures, sending broadcasts about diabled packages, 12946 * gc'ing to free up references, unmounting all secure containers 12947 * corresponding to packages on external media, and posting a 12948 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 12949 * that we always have to post this message if status has been requested no 12950 * matter what. 12951 */ 12952 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 12953 final boolean reportStatus) { 12954 if (DEBUG_SD_INSTALL) 12955 Log.i(TAG, "unloading media packages"); 12956 ArrayList<String> pkgList = new ArrayList<String>(); 12957 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 12958 final Set<AsecInstallArgs> keys = processCids.keySet(); 12959 for (AsecInstallArgs args : keys) { 12960 String pkgName = args.getPackageName(); 12961 if (DEBUG_SD_INSTALL) 12962 Log.i(TAG, "Trying to unload pkg : " + pkgName); 12963 // Delete package internally 12964 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 12965 synchronized (mInstallLock) { 12966 boolean res = deletePackageLI(pkgName, null, false, null, null, 12967 PackageManager.DELETE_KEEP_DATA, outInfo, false); 12968 if (res) { 12969 pkgList.add(pkgName); 12970 } else { 12971 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 12972 failedList.add(args); 12973 } 12974 } 12975 } 12976 12977 // reader 12978 synchronized (mPackages) { 12979 // We didn't update the settings after removing each package; 12980 // write them now for all packages. 12981 mSettings.writeLPr(); 12982 } 12983 12984 // We have to absolutely send UPDATED_MEDIA_STATUS only 12985 // after confirming that all the receivers processed the ordered 12986 // broadcast when packages get disabled, force a gc to clean things up. 12987 // and unload all the containers. 12988 if (pkgList.size() > 0) { 12989 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 12990 new IIntentReceiver.Stub() { 12991 public void performReceive(Intent intent, int resultCode, String data, 12992 Bundle extras, boolean ordered, boolean sticky, 12993 int sendingUser) throws RemoteException { 12994 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 12995 reportStatus ? 1 : 0, 1, keys); 12996 mHandler.sendMessage(msg); 12997 } 12998 }); 12999 } else { 13000 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 13001 keys); 13002 mHandler.sendMessage(msg); 13003 } 13004 } 13005 13006 /** Binder call */ 13007 @Override 13008 public void movePackage(final String packageName, final IPackageMoveObserver observer, 13009 final int flags) { 13010 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 13011 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 13012 int returnCode = PackageManager.MOVE_SUCCEEDED; 13013 int currFlags = 0; 13014 int newFlags = 0; 13015 // reader 13016 synchronized (mPackages) { 13017 PackageParser.Package pkg = mPackages.get(packageName); 13018 if (pkg == null) { 13019 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 13020 } else { 13021 // Disable moving fwd locked apps and system packages 13022 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 13023 Slog.w(TAG, "Cannot move system application"); 13024 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 13025 } else if (pkg.mOperationPending) { 13026 Slog.w(TAG, "Attempt to move package which has pending operations"); 13027 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 13028 } else { 13029 // Find install location first 13030 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 13031 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 13032 Slog.w(TAG, "Ambigous flags specified for move location."); 13033 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 13034 } else { 13035 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL 13036 : PackageManager.INSTALL_INTERNAL; 13037 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL 13038 : PackageManager.INSTALL_INTERNAL; 13039 13040 if (newFlags == currFlags) { 13041 Slog.w(TAG, "No move required. Trying to move to same location"); 13042 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 13043 } else { 13044 if (isForwardLocked(pkg)) { 13045 currFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13046 newFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13047 } 13048 } 13049 } 13050 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13051 pkg.mOperationPending = true; 13052 } 13053 } 13054 } 13055 13056 /* 13057 * TODO this next block probably shouldn't be inside the lock. We 13058 * can't guarantee these won't change after this is fired off 13059 * anyway. 13060 */ 13061 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 13062 processPendingMove(new MoveParams(null, observer, 0, packageName, null, -1, user, false), 13063 returnCode); 13064 } else { 13065 Message msg = mHandler.obtainMessage(INIT_COPY); 13066 final String[] instructionSets = getAppDexInstructionSets(pkg.applicationInfo); 13067 final boolean multiArch = isMultiArch(pkg.applicationInfo); 13068 InstallArgs srcArgs = createInstallArgsForExisting(currFlags, 13069 pkg.applicationInfo.getCodePath(), pkg.applicationInfo.getResourcePath(), 13070 pkg.applicationInfo.nativeLibraryRootDir, instructionSets, multiArch); 13071 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName, 13072 instructionSets, pkg.applicationInfo.uid, user, multiArch); 13073 msg.obj = mp; 13074 mHandler.sendMessage(msg); 13075 } 13076 } 13077 } 13078 13079 private void processPendingMove(final MoveParams mp, final int currentStatus) { 13080 // Queue up an async operation since the package deletion may take a 13081 // little while. 13082 mHandler.post(new Runnable() { 13083 public void run() { 13084 // TODO fix this; this does nothing. 13085 mHandler.removeCallbacks(this); 13086 int returnCode = currentStatus; 13087 if (currentStatus == PackageManager.MOVE_SUCCEEDED) { 13088 int uidArr[] = null; 13089 ArrayList<String> pkgList = null; 13090 synchronized (mPackages) { 13091 PackageParser.Package pkg = mPackages.get(mp.packageName); 13092 if (pkg == null) { 13093 Slog.w(TAG, " Package " + mp.packageName 13094 + " doesn't exist. Aborting move"); 13095 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 13096 } else if (!mp.srcArgs.getCodePath().equals( 13097 pkg.applicationInfo.getCodePath())) { 13098 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " 13099 + mp.srcArgs.getCodePath() + " to " 13100 + pkg.applicationInfo.getCodePath() 13101 + " Aborting move and returning error"); 13102 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 13103 } else { 13104 uidArr = new int[] { 13105 pkg.applicationInfo.uid 13106 }; 13107 pkgList = new ArrayList<String>(); 13108 pkgList.add(mp.packageName); 13109 } 13110 } 13111 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13112 // Send resources unavailable broadcast 13113 sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null); 13114 // Update package code and resource paths 13115 synchronized (mInstallLock) { 13116 synchronized (mPackages) { 13117 PackageParser.Package pkg = mPackages.get(mp.packageName); 13118 // Recheck for package again. 13119 if (pkg == null) { 13120 Slog.w(TAG, " Package " + mp.packageName 13121 + " doesn't exist. Aborting move"); 13122 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 13123 } else if (!mp.srcArgs.getCodePath().equals( 13124 pkg.applicationInfo.getCodePath())) { 13125 Slog.w(TAG, "Package " + mp.packageName 13126 + " code path changed from " + mp.srcArgs.getCodePath() 13127 + " to " + pkg.applicationInfo.getCodePath() 13128 + " Aborting move and returning error"); 13129 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 13130 } else { 13131 final String oldCodePath = pkg.codePath; 13132 final String newCodePath = mp.targetArgs.getCodePath(); 13133 final String newResPath = mp.targetArgs.getResourcePath(); 13134 // TODO: This assumes the new style of installation. 13135 // should we look at legacyNativeLibraryPath ? 13136 final String newNativeRoot = new File(pkg.codePath, LIB_DIR_NAME).getAbsolutePath(); 13137 final File newNativeDir = new File(newNativeRoot); 13138 13139 if (!isForwardLocked(pkg) && !isExternal(pkg)) { 13140 // TODO(multiArch): Fix this so that it looks at the existing 13141 // recorded CPU abis from the package. There's no need for a separate 13142 // round of ABI scanning here. 13143 NativeLibraryHelper.Handle handle = null; 13144 try { 13145 handle = NativeLibraryHelper.Handle.create( 13146 new File(newCodePath)); 13147 final int abi = NativeLibraryHelper.findSupportedAbi( 13148 handle, Build.SUPPORTED_ABIS); 13149 if (abi >= 0) { 13150 NativeLibraryHelper.copyNativeBinariesIfNeededLI( 13151 handle, newNativeDir, Build.SUPPORTED_ABIS[abi]); 13152 } 13153 } catch (IOException ioe) { 13154 Slog.w(TAG, "Unable to extract native libs for package :" 13155 + mp.packageName, ioe); 13156 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 13157 } finally { 13158 IoUtils.closeQuietly(handle); 13159 } 13160 } 13161 13162 final int[] users = sUserManager.getUserIds(); 13163 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13164 for (int user : users) { 13165 // TODO(multiArch): Fix this so that it links to the 13166 // correct directory. We're currently pointing to root. but we 13167 // must point to the arch specific subdirectory (if applicable). 13168 // 13169 // TODO(multiArch): Bogus reference to nativeLibraryDir. 13170 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, 13171 newNativeRoot, user) < 0) { 13172 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 13173 } 13174 } 13175 } 13176 13177 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13178 pkg.codePath = newCodePath; 13179 pkg.baseCodePath = newCodePath; 13180 // Move dex files around 13181 if (moveDexFilesLI(oldCodePath, pkg) != PackageManager.INSTALL_SUCCEEDED) { 13182 // Moving of dex files failed. Set 13183 // error code and abort move. 13184 pkg.codePath = oldCodePath; 13185 pkg.baseCodePath = oldCodePath; 13186 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 13187 } 13188 } 13189 13190 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13191 pkg.applicationInfo.setCodePath(newCodePath); 13192 pkg.applicationInfo.setBaseCodePath(newCodePath); 13193 pkg.applicationInfo.setSplitCodePaths(null); 13194 pkg.applicationInfo.setResourcePath(newResPath); 13195 pkg.applicationInfo.setBaseResourcePath(newResPath); 13196 pkg.applicationInfo.setSplitResourcePaths(null); 13197 13198 PackageSetting ps = (PackageSetting) pkg.mExtras; 13199 ps.codePath = new File(pkg.applicationInfo.getCodePath()); 13200 ps.codePathString = ps.codePath.getPath(); 13201 ps.resourcePath = new File(pkg.applicationInfo.getResourcePath()); 13202 ps.resourcePathString = ps.resourcePath.getPath(); 13203 13204 // Note that we don't have to recalculate the primary and secondary 13205 // CPU ABIs because they must already have been calculated during the 13206 // initial install of the app. 13207 ps.legacyNativeLibraryPathString = null; 13208 13209 // Set the application info flag 13210 // correctly. 13211 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) { 13212 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE; 13213 } else { 13214 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE; 13215 } 13216 ps.setFlags(pkg.applicationInfo.flags); 13217 mAppDirs.remove(oldCodePath); 13218 mAppDirs.put(newCodePath, pkg); 13219 // Persist settings 13220 mSettings.writeLPr(); 13221 } 13222 } 13223 } 13224 } 13225 // Send resources available broadcast 13226 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 13227 } 13228 } 13229 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 13230 // Clean up failed installation 13231 if (mp.targetArgs != null) { 13232 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR, 13233 -1); 13234 } 13235 } else { 13236 // Force a gc to clear things up. 13237 Runtime.getRuntime().gc(); 13238 // Delete older code 13239 synchronized (mInstallLock) { 13240 mp.srcArgs.doPostDeleteLI(true); 13241 } 13242 } 13243 13244 // Allow more operations on this file if we didn't fail because 13245 // an operation was already pending for this package. 13246 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) { 13247 synchronized (mPackages) { 13248 PackageParser.Package pkg = mPackages.get(mp.packageName); 13249 if (pkg != null) { 13250 pkg.mOperationPending = false; 13251 } 13252 } 13253 } 13254 13255 IPackageMoveObserver observer = mp.observer; 13256 if (observer != null) { 13257 try { 13258 observer.packageMoved(mp.packageName, returnCode); 13259 } catch (RemoteException e) { 13260 Log.i(TAG, "Observer no longer exists."); 13261 } 13262 } 13263 } 13264 }); 13265 } 13266 13267 @Override 13268 public boolean setInstallLocation(int loc) { 13269 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 13270 null); 13271 if (getInstallLocation() == loc) { 13272 return true; 13273 } 13274 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 13275 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 13276 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 13277 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 13278 return true; 13279 } 13280 return false; 13281 } 13282 13283 @Override 13284 public int getInstallLocation() { 13285 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13286 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 13287 PackageHelper.APP_INSTALL_AUTO); 13288 } 13289 13290 /** Called by UserManagerService */ 13291 void cleanUpUserLILPw(int userHandle) { 13292 mDirtyUsers.remove(userHandle); 13293 mSettings.removeUserLPw(userHandle); 13294 mPendingBroadcasts.remove(userHandle); 13295 if (mInstaller != null) { 13296 // Technically, we shouldn't be doing this with the package lock 13297 // held. However, this is very rare, and there is already so much 13298 // other disk I/O going on, that we'll let it slide for now. 13299 mInstaller.removeUserDataDirs(userHandle); 13300 } 13301 mUserNeedsBadging.delete(userHandle); 13302 } 13303 13304 /** Called by UserManagerService */ 13305 void createNewUserLILPw(int userHandle, File path) { 13306 if (mInstaller != null) { 13307 mInstaller.createUserConfig(userHandle); 13308 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 13309 } 13310 } 13311 13312 @Override 13313 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 13314 mContext.enforceCallingOrSelfPermission( 13315 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13316 "Only package verification agents can read the verifier device identity"); 13317 13318 synchronized (mPackages) { 13319 return mSettings.getVerifierDeviceIdentityLPw(); 13320 } 13321 } 13322 13323 @Override 13324 public void setPermissionEnforced(String permission, boolean enforced) { 13325 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 13326 if (READ_EXTERNAL_STORAGE.equals(permission)) { 13327 synchronized (mPackages) { 13328 if (mSettings.mReadExternalStorageEnforced == null 13329 || mSettings.mReadExternalStorageEnforced != enforced) { 13330 mSettings.mReadExternalStorageEnforced = enforced; 13331 mSettings.writeLPr(); 13332 } 13333 } 13334 // kill any non-foreground processes so we restart them and 13335 // grant/revoke the GID. 13336 final IActivityManager am = ActivityManagerNative.getDefault(); 13337 if (am != null) { 13338 final long token = Binder.clearCallingIdentity(); 13339 try { 13340 am.killProcessesBelowForeground("setPermissionEnforcement"); 13341 } catch (RemoteException e) { 13342 } finally { 13343 Binder.restoreCallingIdentity(token); 13344 } 13345 } 13346 } else { 13347 throw new IllegalArgumentException("No selective enforcement for " + permission); 13348 } 13349 } 13350 13351 @Override 13352 @Deprecated 13353 public boolean isPermissionEnforced(String permission) { 13354 return true; 13355 } 13356 13357 @Override 13358 public boolean isStorageLow() { 13359 final long token = Binder.clearCallingIdentity(); 13360 try { 13361 final DeviceStorageMonitorInternal 13362 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13363 if (dsm != null) { 13364 return dsm.isMemoryLow(); 13365 } else { 13366 return false; 13367 } 13368 } finally { 13369 Binder.restoreCallingIdentity(token); 13370 } 13371 } 13372 13373 @Override 13374 public IPackageInstaller getPackageInstaller() { 13375 return mInstallerService; 13376 } 13377 13378 private boolean userNeedsBadging(int userId) { 13379 int index = mUserNeedsBadging.indexOfKey(userId); 13380 if (index < 0) { 13381 final UserInfo userInfo; 13382 final long token = Binder.clearCallingIdentity(); 13383 try { 13384 userInfo = sUserManager.getUserInfo(userId); 13385 } finally { 13386 Binder.restoreCallingIdentity(token); 13387 } 13388 final boolean b; 13389 if (userInfo != null && userInfo.isManagedProfile()) { 13390 b = true; 13391 } else { 13392 b = false; 13393 } 13394 mUserNeedsBadging.put(userId, b); 13395 return b; 13396 } 13397 return mUserNeedsBadging.valueAt(index); 13398 } 13399 13400 @Override 13401 public KeySetHandle getKeySetByAlias(String packageName, String alias) { 13402 if (packageName == null || alias == null) { 13403 return null; 13404 } 13405 synchronized(mPackages) { 13406 final PackageParser.Package pkg = mPackages.get(packageName); 13407 if (pkg == null) { 13408 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13409 throw new IllegalArgumentException("Unknown package: " + packageName); 13410 } 13411 if (pkg.applicationInfo.uid != Binder.getCallingUid() 13412 && Process.SYSTEM_UID != Binder.getCallingUid()) { 13413 throw new SecurityException("May not access KeySets defined by" 13414 + " aliases in other applications."); 13415 } 13416 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13417 return ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias); 13418 } 13419 } 13420 13421 @Override 13422 public KeySetHandle getSigningKeySet(String packageName) { 13423 if (packageName == null) { 13424 return null; 13425 } 13426 synchronized(mPackages) { 13427 final PackageParser.Package pkg = mPackages.get(packageName); 13428 if (pkg == null) { 13429 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13430 throw new IllegalArgumentException("Unknown package: " + packageName); 13431 } 13432 if (pkg.applicationInfo.uid != Binder.getCallingUid() 13433 && Process.SYSTEM_UID != Binder.getCallingUid()) { 13434 throw new SecurityException("May not access signing KeySet of other apps."); 13435 } 13436 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13437 return ksms.getSigningKeySetByPackageNameLPr(packageName); 13438 } 13439 } 13440 13441 @Override 13442 public boolean isPackageSignedByKeySet(String packageName, IBinder ks) { 13443 if (packageName == null || ks == null) { 13444 return false; 13445 } 13446 synchronized(mPackages) { 13447 final PackageParser.Package pkg = mPackages.get(packageName); 13448 if (pkg == null) { 13449 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13450 throw new IllegalArgumentException("Unknown package: " + packageName); 13451 } 13452 if (ks instanceof KeySetHandle) { 13453 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13454 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ks); 13455 } 13456 return false; 13457 } 13458 } 13459 13460 @Override 13461 public boolean isPackageSignedByKeySetExactly(String packageName, IBinder ks) { 13462 if (packageName == null || ks == null) { 13463 return false; 13464 } 13465 synchronized(mPackages) { 13466 final PackageParser.Package pkg = mPackages.get(packageName); 13467 if (pkg == null) { 13468 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13469 throw new IllegalArgumentException("Unknown package: " + packageName); 13470 } 13471 if (ks instanceof KeySetHandle) { 13472 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13473 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ks); 13474 } 13475 return false; 13476 } 13477 } 13478} 13479