PackageManagerService.java revision 376e4ba96222163be1f1cf409dc697550be4a285
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.InstallSessionParams; 111import android.content.pm.InstrumentationInfo; 112import android.content.pm.ManifestDigest; 113import android.content.pm.PackageCleanItem; 114import android.content.pm.PackageInfo; 115import android.content.pm.PackageInfoLite; 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.FileUtils; 144import android.os.Handler; 145import android.os.IBinder; 146import android.os.Looper; 147import android.os.Message; 148import android.os.Parcel; 149import android.os.ParcelFileDescriptor; 150import android.os.Process; 151import android.os.RemoteException; 152import android.os.SELinux; 153import android.os.ServiceManager; 154import android.os.SystemClock; 155import android.os.SystemProperties; 156import android.os.UserHandle; 157import android.os.UserManager; 158import android.security.KeyStore; 159import android.security.SystemKeyStore; 160import android.system.ErrnoException; 161import android.system.Os; 162import android.system.StructStat; 163import android.text.TextUtils; 164import android.util.ArraySet; 165import android.util.AtomicFile; 166import android.util.DisplayMetrics; 167import android.util.EventLog; 168import android.util.ExceptionUtils; 169import android.util.Log; 170import android.util.LogPrinter; 171import android.util.PrintStreamPrinter; 172import android.util.Slog; 173import android.util.SparseArray; 174import android.util.SparseBooleanArray; 175import android.view.Display; 176 177import java.io.BufferedInputStream; 178import java.io.BufferedOutputStream; 179import java.io.File; 180import java.io.FileDescriptor; 181import java.io.FileInputStream; 182import java.io.FileNotFoundException; 183import java.io.FileOutputStream; 184import java.io.FilenameFilter; 185import java.io.IOException; 186import java.io.InputStream; 187import java.io.PrintWriter; 188import java.nio.charset.StandardCharsets; 189import java.security.NoSuchAlgorithmException; 190import java.security.PublicKey; 191import java.security.cert.CertificateEncodingException; 192import java.security.cert.CertificateException; 193import java.text.SimpleDateFormat; 194import java.util.ArrayList; 195import java.util.Arrays; 196import java.util.Collection; 197import java.util.Collections; 198import java.util.Comparator; 199import java.util.Date; 200import java.util.HashMap; 201import java.util.HashSet; 202import java.util.Iterator; 203import java.util.List; 204import java.util.Map; 205import java.util.Set; 206import java.util.concurrent.atomic.AtomicBoolean; 207import java.util.concurrent.atomic.AtomicLong; 208 209import dalvik.system.DexFile; 210import dalvik.system.StaleDexCacheError; 211import dalvik.system.VMRuntime; 212 213import libcore.io.IoUtils; 214 215/** 216 * Keep track of all those .apks everywhere. 217 * 218 * This is very central to the platform's security; please run the unit 219 * tests whenever making modifications here: 220 * 221mmm frameworks/base/tests/AndroidTests 222adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 223adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 224 * 225 * {@hide} 226 */ 227public class PackageManagerService extends IPackageManager.Stub { 228 static final String TAG = "PackageManager"; 229 static final boolean DEBUG_SETTINGS = false; 230 static final boolean DEBUG_PREFERRED = false; 231 static final boolean DEBUG_UPGRADE = false; 232 private static final boolean DEBUG_INSTALL = false; 233 private static final boolean DEBUG_REMOVE = false; 234 private static final boolean DEBUG_BROADCASTS = false; 235 private static final boolean DEBUG_SHOW_INFO = false; 236 private static final boolean DEBUG_PACKAGE_INFO = false; 237 private static final boolean DEBUG_INTENT_MATCHING = false; 238 private static final boolean DEBUG_PACKAGE_SCANNING = false; 239 private static final boolean DEBUG_VERIFY = false; 240 private static final boolean DEBUG_DEXOPT = false; 241 private static final boolean DEBUG_ABI_SELECTION = false; 242 243 private static final int RADIO_UID = Process.PHONE_UID; 244 private static final int LOG_UID = Process.LOG_UID; 245 private static final int NFC_UID = Process.NFC_UID; 246 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 247 private static final int SHELL_UID = Process.SHELL_UID; 248 249 // Cap the size of permission trees that 3rd party apps can define 250 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 251 252 // Suffix used during package installation when copying/moving 253 // package apks to install directory. 254 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 255 256 // Special value for {@code PackageParser.Package#cpuAbiOverride} to indicate 257 // that the cpuAbiOverride must be clear. 258 private static final String CLEAR_ABI_OVERRIDE = "-"; 259 260 static final int SCAN_MONITOR = 1<<0; 261 static final int SCAN_NO_DEX = 1<<1; 262 static final int SCAN_FORCE_DEX = 1<<2; 263 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 264 static final int SCAN_NEW_INSTALL = 1<<4; 265 static final int SCAN_NO_PATHS = 1<<5; 266 static final int SCAN_UPDATE_TIME = 1<<6; 267 static final int SCAN_DEFER_DEX = 1<<7; 268 static final int SCAN_BOOTING = 1<<8; 269 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 270 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 271 272 static final int REMOVE_CHATTY = 1<<16; 273 274 /** 275 * Timeout (in milliseconds) after which the watchdog should declare that 276 * our handler thread is wedged. The usual default for such things is one 277 * minute but we sometimes do very lengthy I/O operations on this thread, 278 * such as installing multi-gigabyte applications, so ours needs to be longer. 279 */ 280 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 281 282 /** 283 * Whether verification is enabled by default. 284 */ 285 private static final boolean DEFAULT_VERIFY_ENABLE = true; 286 287 /** 288 * The default maximum time to wait for the verification agent to return in 289 * milliseconds. 290 */ 291 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 292 293 /** 294 * The default response for package verification timeout. 295 * 296 * This can be either PackageManager.VERIFICATION_ALLOW or 297 * PackageManager.VERIFICATION_REJECT. 298 */ 299 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 300 301 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 302 303 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 304 DEFAULT_CONTAINER_PACKAGE, 305 "com.android.defcontainer.DefaultContainerService"); 306 307 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 308 309 private static final String LIB_DIR_NAME = "lib"; 310 private static final String LIB64_DIR_NAME = "lib64"; 311 312 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 313 314 static final String mTempContainerPrefix = "smdl2tmp"; 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 String bootClassPath = System.getProperty("java.boot.class.path"); 1398 if (bootClassPath != null) { 1399 String[] paths = splitString(bootClassPath, ':'); 1400 for (int i=0; i<paths.length; i++) { 1401 alreadyDexOpted.add(paths[i]); 1402 } 1403 } else { 1404 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1405 } 1406 1407 boolean didDexOptLibraryOrTool = false; 1408 1409 final List<String> allInstructionSets = getAllInstructionSets(); 1410 final String[] dexCodeInstructionSets = 1411 getDexCodeInstructionSets(allInstructionSets.toArray(new String[allInstructionSets.size()])); 1412 1413 /** 1414 * Ensure all external libraries have had dexopt run on them. 1415 */ 1416 if (mSharedLibraries.size() > 0) { 1417 // NOTE: For now, we're compiling these system "shared libraries" 1418 // (and framework jars) into all available architectures. It's possible 1419 // to compile them only when we come across an app that uses them (there's 1420 // already logic for that in scanPackageLI) but that adds some complexity. 1421 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1422 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1423 final String lib = libEntry.path; 1424 if (lib == null) { 1425 continue; 1426 } 1427 1428 try { 1429 byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null, 1430 dexCodeInstructionSet, 1431 false); 1432 if (dexoptRequired != DexFile.UP_TO_DATE) { 1433 alreadyDexOpted.add(lib); 1434 1435 // The list of "shared libraries" we have at this point is 1436 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1437 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1438 } else { 1439 mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1440 } 1441 didDexOptLibraryOrTool = true; 1442 } 1443 } catch (FileNotFoundException e) { 1444 Slog.w(TAG, "Library not found: " + lib); 1445 } catch (IOException e) { 1446 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1447 + e.getMessage()); 1448 } 1449 } 1450 } 1451 } 1452 1453 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1454 1455 // Gross hack for now: we know this file doesn't contain any 1456 // code, so don't dexopt it to avoid the resulting log spew. 1457 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1458 1459 // Gross hack for now: we know this file is only part of 1460 // the boot class path for art, so don't dexopt it to 1461 // avoid the resulting log spew. 1462 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1463 1464 /** 1465 * And there are a number of commands implemented in Java, which 1466 * we currently need to do the dexopt on so that they can be 1467 * run from a non-root shell. 1468 */ 1469 String[] frameworkFiles = frameworkDir.list(); 1470 if (frameworkFiles != null) { 1471 // TODO: We could compile these only for the most preferred ABI. We should 1472 // first double check that the dex files for these commands are not referenced 1473 // by other system apps. 1474 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1475 for (int i=0; i<frameworkFiles.length; i++) { 1476 File libPath = new File(frameworkDir, frameworkFiles[i]); 1477 String path = libPath.getPath(); 1478 // Skip the file if we already did it. 1479 if (alreadyDexOpted.contains(path)) { 1480 continue; 1481 } 1482 // Skip the file if it is not a type we want to dexopt. 1483 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1484 continue; 1485 } 1486 try { 1487 byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null, 1488 dexCodeInstructionSet, 1489 false); 1490 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1491 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1492 didDexOptLibraryOrTool = true; 1493 } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) { 1494 mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1495 didDexOptLibraryOrTool = true; 1496 } 1497 } catch (FileNotFoundException e) { 1498 Slog.w(TAG, "Jar not found: " + path); 1499 } catch (IOException e) { 1500 Slog.w(TAG, "Exception reading jar: " + path, e); 1501 } 1502 } 1503 } 1504 } 1505 1506 if (didDexOptLibraryOrTool) { 1507 // If we dexopted a library or tool, then something on the system has 1508 // changed. Consider this significant, and wipe away all other 1509 // existing dexopt files to ensure we don't leave any dangling around. 1510 // 1511 // TODO: This should be revisited because it isn't as good an indicator 1512 // as it used to be. It used to include the boot classpath but at some point 1513 // DexFile.isDexOptNeeded started returning false for the boot 1514 // class path files in all cases. It is very possible in a 1515 // small maintenance release update that the library and tool 1516 // jars may be unchanged but APK could be removed resulting in 1517 // unused dalvik-cache files. 1518 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1519 mInstaller.pruneDexCache(dexCodeInstructionSet); 1520 } 1521 1522 // Additionally, delete all dex files from the root directory 1523 // since there shouldn't be any there anyway, unless we're upgrading 1524 // from an older OS version or a build that contained the "old" style 1525 // flat scheme. 1526 mInstaller.pruneDexCache("."); 1527 } 1528 1529 // Collect vendor overlay packages. 1530 // (Do this before scanning any apps.) 1531 // For security and version matching reason, only consider 1532 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1533 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1534 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1535 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode | SCAN_TRUSTED_OVERLAY, 0); 1536 1537 // Find base frameworks (resource packages without code). 1538 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1539 | PackageParser.PARSE_IS_SYSTEM_DIR 1540 | PackageParser.PARSE_IS_PRIVILEGED, 1541 scanMode | SCAN_NO_DEX, 0); 1542 1543 // Collected privileged system packages. 1544 File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1545 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1546 | PackageParser.PARSE_IS_SYSTEM_DIR 1547 | PackageParser.PARSE_IS_PRIVILEGED, scanMode, 0); 1548 1549 // Collect ordinary system packages. 1550 File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1551 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1552 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1553 1554 // Collect all vendor packages. 1555 File vendorAppDir = new File("/vendor/app"); 1556 try { 1557 vendorAppDir = vendorAppDir.getCanonicalFile(); 1558 } catch (IOException e) { 1559 // failed to look up canonical path, continue with original one 1560 } 1561 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1562 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1563 1564 // Collect all OEM packages. 1565 File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1566 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1567 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1568 1569 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1570 mInstaller.moveFiles(); 1571 1572 // Prune any system packages that no longer exist. 1573 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1574 if (!mOnlyCore) { 1575 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1576 while (psit.hasNext()) { 1577 PackageSetting ps = psit.next(); 1578 1579 /* 1580 * If this is not a system app, it can't be a 1581 * disable system app. 1582 */ 1583 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1584 continue; 1585 } 1586 1587 /* 1588 * If the package is scanned, it's not erased. 1589 */ 1590 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1591 if (scannedPkg != null) { 1592 /* 1593 * If the system app is both scanned and in the 1594 * disabled packages list, then it must have been 1595 * added via OTA. Remove it from the currently 1596 * scanned package so the previously user-installed 1597 * application can be scanned. 1598 */ 1599 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1600 Slog.i(TAG, "Expecting better updatd system app for " + ps.name 1601 + "; removing system app"); 1602 removePackageLI(ps, true); 1603 } 1604 1605 continue; 1606 } 1607 1608 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1609 psit.remove(); 1610 String msg = "System package " + ps.name 1611 + " no longer exists; wiping its data"; 1612 reportSettingsProblem(Log.WARN, msg); 1613 removeDataDirsLI(ps.name); 1614 } else { 1615 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1616 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1617 possiblyDeletedUpdatedSystemApps.add(ps.name); 1618 } 1619 } 1620 } 1621 } 1622 1623 //look for any incomplete package installations 1624 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1625 //clean up list 1626 for(int i = 0; i < deletePkgsList.size(); i++) { 1627 //clean up here 1628 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1629 } 1630 //delete tmp files 1631 deleteTempPackageFiles(); 1632 1633 // Remove any shared userIDs that have no associated packages 1634 mSettings.pruneSharedUsersLPw(); 1635 1636 if (!mOnlyCore) { 1637 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 1638 SystemClock.uptimeMillis()); 1639 scanDirLI(mAppInstallDir, 0, scanMode, 0); 1640 1641 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 1642 scanMode, 0); 1643 1644 /** 1645 * Remove disable package settings for any updated system 1646 * apps that were removed via an OTA. If they're not a 1647 * previously-updated app, remove them completely. 1648 * Otherwise, just revoke their system-level permissions. 1649 */ 1650 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 1651 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 1652 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 1653 1654 String msg; 1655 if (deletedPkg == null) { 1656 msg = "Updated system package " + deletedAppName 1657 + " no longer exists; wiping its data"; 1658 removeDataDirsLI(deletedAppName); 1659 } else { 1660 msg = "Updated system app + " + deletedAppName 1661 + " no longer present; removing system privileges for " 1662 + deletedAppName; 1663 1664 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 1665 1666 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 1667 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 1668 } 1669 reportSettingsProblem(Log.WARN, msg); 1670 } 1671 } 1672 1673 // Now that we know all of the shared libraries, update all clients to have 1674 // the correct library paths. 1675 updateAllSharedLibrariesLPw(); 1676 1677 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 1678 // NOTE: We ignore potential failures here during a system scan (like 1679 // the rest of the commands above) because there's precious little we 1680 // can do about it. A settings error is reported, though. 1681 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 1682 false /* force dexopt */, false /* defer dexopt */); 1683 } 1684 1685 // Now that we know all the packages we are keeping, 1686 // read and update their last usage times. 1687 mPackageUsage.readLP(); 1688 1689 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 1690 SystemClock.uptimeMillis()); 1691 Slog.i(TAG, "Time to scan packages: " 1692 + ((SystemClock.uptimeMillis()-startTime)/1000f) 1693 + " seconds"); 1694 1695 // If the platform SDK has changed since the last time we booted, 1696 // we need to re-grant app permission to catch any new ones that 1697 // appear. This is really a hack, and means that apps can in some 1698 // cases get permissions that the user didn't initially explicitly 1699 // allow... it would be nice to have some better way to handle 1700 // this situation. 1701 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 1702 != mSdkVersion; 1703 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 1704 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 1705 + "; regranting permissions for internal storage"); 1706 mSettings.mInternalSdkPlatform = mSdkVersion; 1707 1708 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 1709 | (regrantPermissions 1710 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 1711 : 0)); 1712 1713 // If this is the first boot, and it is a normal boot, then 1714 // we need to initialize the default preferred apps. 1715 if (!mRestoredSettings && !onlyCore) { 1716 mSettings.readDefaultPreferredAppsLPw(this, 0); 1717 } 1718 1719 // If this is first boot after an OTA, and a normal boot, then 1720 // we need to clear code cache directories. 1721 if (!Build.FINGERPRINT.equals(mSettings.mFingerprint) && !onlyCore) { 1722 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 1723 for (String pkgName : mSettings.mPackages.keySet()) { 1724 deleteCodeCacheDirsLI(pkgName); 1725 } 1726 mSettings.mFingerprint = Build.FINGERPRINT; 1727 } 1728 1729 // All the changes are done during package scanning. 1730 mSettings.updateInternalDatabaseVersion(); 1731 1732 // can downgrade to reader 1733 mSettings.writeLPr(); 1734 1735 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 1736 SystemClock.uptimeMillis()); 1737 1738 1739 mRequiredVerifierPackage = getRequiredVerifierLPr(); 1740 } // synchronized (mPackages) 1741 } // synchronized (mInstallLock) 1742 1743 mInstallerService = new PackageInstallerService(context, this, mAppInstallDir); 1744 1745 // Now after opening every single application zip, make sure they 1746 // are all flushed. Not really needed, but keeps things nice and 1747 // tidy. 1748 Runtime.getRuntime().gc(); 1749 } 1750 1751 @Override 1752 public boolean isFirstBoot() { 1753 return !mRestoredSettings; 1754 } 1755 1756 @Override 1757 public boolean isOnlyCoreApps() { 1758 return mOnlyCore; 1759 } 1760 1761 private String getRequiredVerifierLPr() { 1762 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 1763 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 1764 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 1765 1766 String requiredVerifier = null; 1767 1768 final int N = receivers.size(); 1769 for (int i = 0; i < N; i++) { 1770 final ResolveInfo info = receivers.get(i); 1771 1772 if (info.activityInfo == null) { 1773 continue; 1774 } 1775 1776 final String packageName = info.activityInfo.packageName; 1777 1778 final PackageSetting ps = mSettings.mPackages.get(packageName); 1779 if (ps == null) { 1780 continue; 1781 } 1782 1783 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1784 if (!gp.grantedPermissions 1785 .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) { 1786 continue; 1787 } 1788 1789 if (requiredVerifier != null) { 1790 throw new RuntimeException("There can be only one required verifier"); 1791 } 1792 1793 requiredVerifier = packageName; 1794 } 1795 1796 return requiredVerifier; 1797 } 1798 1799 @Override 1800 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 1801 throws RemoteException { 1802 try { 1803 return super.onTransact(code, data, reply, flags); 1804 } catch (RuntimeException e) { 1805 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 1806 Slog.wtf(TAG, "Package Manager Crash", e); 1807 } 1808 throw e; 1809 } 1810 } 1811 1812 void cleanupInstallFailedPackage(PackageSetting ps) { 1813 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name); 1814 removeDataDirsLI(ps.name); 1815 1816 // TODO: try cleaning up codePath directory contents first, since it 1817 // might be a cluster 1818 1819 if (ps.codePath != null) { 1820 if (!ps.codePath.delete()) { 1821 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath); 1822 } 1823 } 1824 if (ps.resourcePath != null) { 1825 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) { 1826 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath); 1827 } 1828 } 1829 mSettings.removePackageLPw(ps.name); 1830 } 1831 1832 static int[] appendInts(int[] cur, int[] add) { 1833 if (add == null) return cur; 1834 if (cur == null) return add; 1835 final int N = add.length; 1836 for (int i=0; i<N; i++) { 1837 cur = appendInt(cur, add[i]); 1838 } 1839 return cur; 1840 } 1841 1842 static int[] removeInts(int[] cur, int[] rem) { 1843 if (rem == null) return cur; 1844 if (cur == null) return cur; 1845 final int N = rem.length; 1846 for (int i=0; i<N; i++) { 1847 cur = removeInt(cur, rem[i]); 1848 } 1849 return cur; 1850 } 1851 1852 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 1853 if (!sUserManager.exists(userId)) return null; 1854 final PackageSetting ps = (PackageSetting) p.mExtras; 1855 if (ps == null) { 1856 return null; 1857 } 1858 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1859 final PackageUserState state = ps.readUserState(userId); 1860 return PackageParser.generatePackageInfo(p, gp.gids, flags, 1861 ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions, 1862 state, userId); 1863 } 1864 1865 @Override 1866 public boolean isPackageAvailable(String packageName, int userId) { 1867 if (!sUserManager.exists(userId)) return false; 1868 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available"); 1869 synchronized (mPackages) { 1870 PackageParser.Package p = mPackages.get(packageName); 1871 if (p != null) { 1872 final PackageSetting ps = (PackageSetting) p.mExtras; 1873 if (ps != null) { 1874 final PackageUserState state = ps.readUserState(userId); 1875 if (state != null) { 1876 return PackageParser.isAvailable(state); 1877 } 1878 } 1879 } 1880 } 1881 return false; 1882 } 1883 1884 @Override 1885 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 1886 if (!sUserManager.exists(userId)) return null; 1887 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info"); 1888 // reader 1889 synchronized (mPackages) { 1890 PackageParser.Package p = mPackages.get(packageName); 1891 if (DEBUG_PACKAGE_INFO) 1892 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 1893 if (p != null) { 1894 return generatePackageInfo(p, flags, userId); 1895 } 1896 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 1897 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 1898 } 1899 } 1900 return null; 1901 } 1902 1903 @Override 1904 public String[] currentToCanonicalPackageNames(String[] names) { 1905 String[] out = new String[names.length]; 1906 // reader 1907 synchronized (mPackages) { 1908 for (int i=names.length-1; i>=0; i--) { 1909 PackageSetting ps = mSettings.mPackages.get(names[i]); 1910 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 1911 } 1912 } 1913 return out; 1914 } 1915 1916 @Override 1917 public String[] canonicalToCurrentPackageNames(String[] names) { 1918 String[] out = new String[names.length]; 1919 // reader 1920 synchronized (mPackages) { 1921 for (int i=names.length-1; i>=0; i--) { 1922 String cur = mSettings.mRenamedPackages.get(names[i]); 1923 out[i] = cur != null ? cur : names[i]; 1924 } 1925 } 1926 return out; 1927 } 1928 1929 @Override 1930 public int getPackageUid(String packageName, int userId) { 1931 if (!sUserManager.exists(userId)) return -1; 1932 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid"); 1933 // reader 1934 synchronized (mPackages) { 1935 PackageParser.Package p = mPackages.get(packageName); 1936 if(p != null) { 1937 return UserHandle.getUid(userId, p.applicationInfo.uid); 1938 } 1939 PackageSetting ps = mSettings.mPackages.get(packageName); 1940 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 1941 return -1; 1942 } 1943 p = ps.pkg; 1944 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 1945 } 1946 } 1947 1948 @Override 1949 public int[] getPackageGids(String packageName) { 1950 // reader 1951 synchronized (mPackages) { 1952 PackageParser.Package p = mPackages.get(packageName); 1953 if (DEBUG_PACKAGE_INFO) 1954 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 1955 if (p != null) { 1956 final PackageSetting ps = (PackageSetting)p.mExtras; 1957 return ps.getGids(); 1958 } 1959 } 1960 // stupid thing to indicate an error. 1961 return new int[0]; 1962 } 1963 1964 static final PermissionInfo generatePermissionInfo( 1965 BasePermission bp, int flags) { 1966 if (bp.perm != null) { 1967 return PackageParser.generatePermissionInfo(bp.perm, flags); 1968 } 1969 PermissionInfo pi = new PermissionInfo(); 1970 pi.name = bp.name; 1971 pi.packageName = bp.sourcePackage; 1972 pi.nonLocalizedLabel = bp.name; 1973 pi.protectionLevel = bp.protectionLevel; 1974 return pi; 1975 } 1976 1977 @Override 1978 public PermissionInfo getPermissionInfo(String name, int flags) { 1979 // reader 1980 synchronized (mPackages) { 1981 final BasePermission p = mSettings.mPermissions.get(name); 1982 if (p != null) { 1983 return generatePermissionInfo(p, flags); 1984 } 1985 return null; 1986 } 1987 } 1988 1989 @Override 1990 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 1991 // reader 1992 synchronized (mPackages) { 1993 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 1994 for (BasePermission p : mSettings.mPermissions.values()) { 1995 if (group == null) { 1996 if (p.perm == null || p.perm.info.group == null) { 1997 out.add(generatePermissionInfo(p, flags)); 1998 } 1999 } else { 2000 if (p.perm != null && group.equals(p.perm.info.group)) { 2001 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2002 } 2003 } 2004 } 2005 2006 if (out.size() > 0) { 2007 return out; 2008 } 2009 return mPermissionGroups.containsKey(group) ? out : null; 2010 } 2011 } 2012 2013 @Override 2014 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2015 // reader 2016 synchronized (mPackages) { 2017 return PackageParser.generatePermissionGroupInfo( 2018 mPermissionGroups.get(name), flags); 2019 } 2020 } 2021 2022 @Override 2023 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2024 // reader 2025 synchronized (mPackages) { 2026 final int N = mPermissionGroups.size(); 2027 ArrayList<PermissionGroupInfo> out 2028 = new ArrayList<PermissionGroupInfo>(N); 2029 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2030 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2031 } 2032 return out; 2033 } 2034 } 2035 2036 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2037 int userId) { 2038 if (!sUserManager.exists(userId)) return null; 2039 PackageSetting ps = mSettings.mPackages.get(packageName); 2040 if (ps != null) { 2041 if (ps.pkg == null) { 2042 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2043 flags, userId); 2044 if (pInfo != null) { 2045 return pInfo.applicationInfo; 2046 } 2047 return null; 2048 } 2049 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2050 ps.readUserState(userId), userId); 2051 } 2052 return null; 2053 } 2054 2055 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2056 int userId) { 2057 if (!sUserManager.exists(userId)) return null; 2058 PackageSetting ps = mSettings.mPackages.get(packageName); 2059 if (ps != null) { 2060 PackageParser.Package pkg = ps.pkg; 2061 if (pkg == null) { 2062 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2063 return null; 2064 } 2065 // Only data remains, so we aren't worried about code paths 2066 pkg = new PackageParser.Package(packageName); 2067 pkg.applicationInfo.packageName = packageName; 2068 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2069 pkg.applicationInfo.dataDir = 2070 getDataPathForPackage(packageName, 0).getPath(); 2071 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2072 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2073 } 2074 return generatePackageInfo(pkg, flags, userId); 2075 } 2076 return null; 2077 } 2078 2079 @Override 2080 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2081 if (!sUserManager.exists(userId)) return null; 2082 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info"); 2083 // writer 2084 synchronized (mPackages) { 2085 PackageParser.Package p = mPackages.get(packageName); 2086 if (DEBUG_PACKAGE_INFO) Log.v( 2087 TAG, "getApplicationInfo " + packageName 2088 + ": " + p); 2089 if (p != null) { 2090 PackageSetting ps = mSettings.mPackages.get(packageName); 2091 if (ps == null) return null; 2092 // Note: isEnabledLP() does not apply here - always return info 2093 return PackageParser.generateApplicationInfo( 2094 p, flags, ps.readUserState(userId), userId); 2095 } 2096 if ("android".equals(packageName)||"system".equals(packageName)) { 2097 return mAndroidApplication; 2098 } 2099 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2100 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2101 } 2102 } 2103 return null; 2104 } 2105 2106 2107 @Override 2108 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2109 mContext.enforceCallingOrSelfPermission( 2110 android.Manifest.permission.CLEAR_APP_CACHE, null); 2111 // Queue up an async operation since clearing cache may take a little while. 2112 mHandler.post(new Runnable() { 2113 public void run() { 2114 mHandler.removeCallbacks(this); 2115 int retCode = -1; 2116 synchronized (mInstallLock) { 2117 retCode = mInstaller.freeCache(freeStorageSize); 2118 if (retCode < 0) { 2119 Slog.w(TAG, "Couldn't clear application caches"); 2120 } 2121 } 2122 if (observer != null) { 2123 try { 2124 observer.onRemoveCompleted(null, (retCode >= 0)); 2125 } catch (RemoteException e) { 2126 Slog.w(TAG, "RemoveException when invoking call back"); 2127 } 2128 } 2129 } 2130 }); 2131 } 2132 2133 @Override 2134 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2135 mContext.enforceCallingOrSelfPermission( 2136 android.Manifest.permission.CLEAR_APP_CACHE, null); 2137 // Queue up an async operation since clearing cache may take a little while. 2138 mHandler.post(new Runnable() { 2139 public void run() { 2140 mHandler.removeCallbacks(this); 2141 int retCode = -1; 2142 synchronized (mInstallLock) { 2143 retCode = mInstaller.freeCache(freeStorageSize); 2144 if (retCode < 0) { 2145 Slog.w(TAG, "Couldn't clear application caches"); 2146 } 2147 } 2148 if(pi != null) { 2149 try { 2150 // Callback via pending intent 2151 int code = (retCode >= 0) ? 1 : 0; 2152 pi.sendIntent(null, code, null, 2153 null, null); 2154 } catch (SendIntentException e1) { 2155 Slog.i(TAG, "Failed to send pending intent"); 2156 } 2157 } 2158 } 2159 }); 2160 } 2161 2162 void freeStorage(long freeStorageSize) throws IOException { 2163 synchronized (mInstallLock) { 2164 if (mInstaller.freeCache(freeStorageSize) < 0) { 2165 throw new IOException("Failed to free enough space"); 2166 } 2167 } 2168 } 2169 2170 @Override 2171 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2172 if (!sUserManager.exists(userId)) return null; 2173 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info"); 2174 synchronized (mPackages) { 2175 PackageParser.Activity a = mActivities.mActivities.get(component); 2176 2177 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2178 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2179 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2180 if (ps == null) return null; 2181 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2182 userId); 2183 } 2184 if (mResolveComponentName.equals(component)) { 2185 return mResolveActivity; 2186 } 2187 } 2188 return null; 2189 } 2190 2191 @Override 2192 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2193 String resolvedType) { 2194 synchronized (mPackages) { 2195 PackageParser.Activity a = mActivities.mActivities.get(component); 2196 if (a == null) { 2197 return false; 2198 } 2199 for (int i=0; i<a.intents.size(); i++) { 2200 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2201 intent.getData(), intent.getCategories(), TAG) >= 0) { 2202 return true; 2203 } 2204 } 2205 return false; 2206 } 2207 } 2208 2209 @Override 2210 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2211 if (!sUserManager.exists(userId)) return null; 2212 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info"); 2213 synchronized (mPackages) { 2214 PackageParser.Activity a = mReceivers.mActivities.get(component); 2215 if (DEBUG_PACKAGE_INFO) Log.v( 2216 TAG, "getReceiverInfo " + component + ": " + a); 2217 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2218 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2219 if (ps == null) return null; 2220 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2221 userId); 2222 } 2223 } 2224 return null; 2225 } 2226 2227 @Override 2228 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2229 if (!sUserManager.exists(userId)) return null; 2230 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info"); 2231 synchronized (mPackages) { 2232 PackageParser.Service s = mServices.mServices.get(component); 2233 if (DEBUG_PACKAGE_INFO) Log.v( 2234 TAG, "getServiceInfo " + component + ": " + s); 2235 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2236 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2237 if (ps == null) return null; 2238 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2239 userId); 2240 } 2241 } 2242 return null; 2243 } 2244 2245 @Override 2246 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2247 if (!sUserManager.exists(userId)) return null; 2248 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info"); 2249 synchronized (mPackages) { 2250 PackageParser.Provider p = mProviders.mProviders.get(component); 2251 if (DEBUG_PACKAGE_INFO) Log.v( 2252 TAG, "getProviderInfo " + component + ": " + p); 2253 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2254 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2255 if (ps == null) return null; 2256 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2257 userId); 2258 } 2259 } 2260 return null; 2261 } 2262 2263 @Override 2264 public String[] getSystemSharedLibraryNames() { 2265 Set<String> libSet; 2266 synchronized (mPackages) { 2267 libSet = mSharedLibraries.keySet(); 2268 int size = libSet.size(); 2269 if (size > 0) { 2270 String[] libs = new String[size]; 2271 libSet.toArray(libs); 2272 return libs; 2273 } 2274 } 2275 return null; 2276 } 2277 2278 @Override 2279 public FeatureInfo[] getSystemAvailableFeatures() { 2280 Collection<FeatureInfo> featSet; 2281 synchronized (mPackages) { 2282 featSet = mAvailableFeatures.values(); 2283 int size = featSet.size(); 2284 if (size > 0) { 2285 FeatureInfo[] features = new FeatureInfo[size+1]; 2286 featSet.toArray(features); 2287 FeatureInfo fi = new FeatureInfo(); 2288 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2289 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2290 features[size] = fi; 2291 return features; 2292 } 2293 } 2294 return null; 2295 } 2296 2297 @Override 2298 public boolean hasSystemFeature(String name) { 2299 synchronized (mPackages) { 2300 return mAvailableFeatures.containsKey(name); 2301 } 2302 } 2303 2304 private void checkValidCaller(int uid, int userId) { 2305 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2306 return; 2307 2308 throw new SecurityException("Caller uid=" + uid 2309 + " is not privileged to communicate with user=" + userId); 2310 } 2311 2312 @Override 2313 public int checkPermission(String permName, String pkgName) { 2314 synchronized (mPackages) { 2315 PackageParser.Package p = mPackages.get(pkgName); 2316 if (p != null && p.mExtras != null) { 2317 PackageSetting ps = (PackageSetting)p.mExtras; 2318 if (ps.sharedUser != null) { 2319 if (ps.sharedUser.grantedPermissions.contains(permName)) { 2320 return PackageManager.PERMISSION_GRANTED; 2321 } 2322 } else if (ps.grantedPermissions.contains(permName)) { 2323 return PackageManager.PERMISSION_GRANTED; 2324 } 2325 } 2326 } 2327 return PackageManager.PERMISSION_DENIED; 2328 } 2329 2330 @Override 2331 public int checkUidPermission(String permName, int uid) { 2332 synchronized (mPackages) { 2333 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2334 if (obj != null) { 2335 GrantedPermissions gp = (GrantedPermissions)obj; 2336 if (gp.grantedPermissions.contains(permName)) { 2337 return PackageManager.PERMISSION_GRANTED; 2338 } 2339 } else { 2340 HashSet<String> perms = mSystemPermissions.get(uid); 2341 if (perms != null && perms.contains(permName)) { 2342 return PackageManager.PERMISSION_GRANTED; 2343 } 2344 } 2345 } 2346 return PackageManager.PERMISSION_DENIED; 2347 } 2348 2349 /** 2350 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2351 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2352 * @param message the message to log on security exception 2353 */ 2354 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2355 String message) { 2356 if (userId < 0) { 2357 throw new IllegalArgumentException("Invalid userId " + userId); 2358 } 2359 if (userId == UserHandle.getUserId(callingUid)) return; 2360 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2361 if (requireFullPermission) { 2362 mContext.enforceCallingOrSelfPermission( 2363 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2364 } else { 2365 try { 2366 mContext.enforceCallingOrSelfPermission( 2367 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2368 } catch (SecurityException se) { 2369 mContext.enforceCallingOrSelfPermission( 2370 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2371 } 2372 } 2373 } 2374 } 2375 2376 private BasePermission findPermissionTreeLP(String permName) { 2377 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2378 if (permName.startsWith(bp.name) && 2379 permName.length() > bp.name.length() && 2380 permName.charAt(bp.name.length()) == '.') { 2381 return bp; 2382 } 2383 } 2384 return null; 2385 } 2386 2387 private BasePermission checkPermissionTreeLP(String permName) { 2388 if (permName != null) { 2389 BasePermission bp = findPermissionTreeLP(permName); 2390 if (bp != null) { 2391 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2392 return bp; 2393 } 2394 throw new SecurityException("Calling uid " 2395 + Binder.getCallingUid() 2396 + " is not allowed to add to permission tree " 2397 + bp.name + " owned by uid " + bp.uid); 2398 } 2399 } 2400 throw new SecurityException("No permission tree found for " + permName); 2401 } 2402 2403 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2404 if (s1 == null) { 2405 return s2 == null; 2406 } 2407 if (s2 == null) { 2408 return false; 2409 } 2410 if (s1.getClass() != s2.getClass()) { 2411 return false; 2412 } 2413 return s1.equals(s2); 2414 } 2415 2416 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2417 if (pi1.icon != pi2.icon) return false; 2418 if (pi1.logo != pi2.logo) return false; 2419 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2420 if (!compareStrings(pi1.name, pi2.name)) return false; 2421 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2422 // We'll take care of setting this one. 2423 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2424 // These are not currently stored in settings. 2425 //if (!compareStrings(pi1.group, pi2.group)) return false; 2426 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2427 //if (pi1.labelRes != pi2.labelRes) return false; 2428 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2429 return true; 2430 } 2431 2432 int permissionInfoFootprint(PermissionInfo info) { 2433 int size = info.name.length(); 2434 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2435 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2436 return size; 2437 } 2438 2439 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2440 int size = 0; 2441 for (BasePermission perm : mSettings.mPermissions.values()) { 2442 if (perm.uid == tree.uid) { 2443 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2444 } 2445 } 2446 return size; 2447 } 2448 2449 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2450 // We calculate the max size of permissions defined by this uid and throw 2451 // if that plus the size of 'info' would exceed our stated maximum. 2452 if (tree.uid != Process.SYSTEM_UID) { 2453 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2454 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2455 throw new SecurityException("Permission tree size cap exceeded"); 2456 } 2457 } 2458 } 2459 2460 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2461 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2462 throw new SecurityException("Label must be specified in permission"); 2463 } 2464 BasePermission tree = checkPermissionTreeLP(info.name); 2465 BasePermission bp = mSettings.mPermissions.get(info.name); 2466 boolean added = bp == null; 2467 boolean changed = true; 2468 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2469 if (added) { 2470 enforcePermissionCapLocked(info, tree); 2471 bp = new BasePermission(info.name, tree.sourcePackage, 2472 BasePermission.TYPE_DYNAMIC); 2473 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2474 throw new SecurityException( 2475 "Not allowed to modify non-dynamic permission " 2476 + info.name); 2477 } else { 2478 if (bp.protectionLevel == fixedLevel 2479 && bp.perm.owner.equals(tree.perm.owner) 2480 && bp.uid == tree.uid 2481 && comparePermissionInfos(bp.perm.info, info)) { 2482 changed = false; 2483 } 2484 } 2485 bp.protectionLevel = fixedLevel; 2486 info = new PermissionInfo(info); 2487 info.protectionLevel = fixedLevel; 2488 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 2489 bp.perm.info.packageName = tree.perm.info.packageName; 2490 bp.uid = tree.uid; 2491 if (added) { 2492 mSettings.mPermissions.put(info.name, bp); 2493 } 2494 if (changed) { 2495 if (!async) { 2496 mSettings.writeLPr(); 2497 } else { 2498 scheduleWriteSettingsLocked(); 2499 } 2500 } 2501 return added; 2502 } 2503 2504 @Override 2505 public boolean addPermission(PermissionInfo info) { 2506 synchronized (mPackages) { 2507 return addPermissionLocked(info, false); 2508 } 2509 } 2510 2511 @Override 2512 public boolean addPermissionAsync(PermissionInfo info) { 2513 synchronized (mPackages) { 2514 return addPermissionLocked(info, true); 2515 } 2516 } 2517 2518 @Override 2519 public void removePermission(String name) { 2520 synchronized (mPackages) { 2521 checkPermissionTreeLP(name); 2522 BasePermission bp = mSettings.mPermissions.get(name); 2523 if (bp != null) { 2524 if (bp.type != BasePermission.TYPE_DYNAMIC) { 2525 throw new SecurityException( 2526 "Not allowed to modify non-dynamic permission " 2527 + name); 2528 } 2529 mSettings.mPermissions.remove(name); 2530 mSettings.writeLPr(); 2531 } 2532 } 2533 } 2534 2535 private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) { 2536 int index = pkg.requestedPermissions.indexOf(bp.name); 2537 if (index == -1) { 2538 throw new SecurityException("Package " + pkg.packageName 2539 + " has not requested permission " + bp.name); 2540 } 2541 boolean isNormal = 2542 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2543 == PermissionInfo.PROTECTION_NORMAL); 2544 boolean isDangerous = 2545 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2546 == PermissionInfo.PROTECTION_DANGEROUS); 2547 boolean isDevelopment = 2548 ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0); 2549 2550 if (!isNormal && !isDangerous && !isDevelopment) { 2551 throw new SecurityException("Permission " + bp.name 2552 + " is not a changeable permission type"); 2553 } 2554 2555 if (isNormal || isDangerous) { 2556 if (pkg.requestedPermissionsRequired.get(index)) { 2557 throw new SecurityException("Can't change " + bp.name 2558 + ". It is required by the application"); 2559 } 2560 } 2561 } 2562 2563 @Override 2564 public void grantPermission(String packageName, String permissionName) { 2565 mContext.enforceCallingOrSelfPermission( 2566 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2567 synchronized (mPackages) { 2568 final PackageParser.Package pkg = mPackages.get(packageName); 2569 if (pkg == null) { 2570 throw new IllegalArgumentException("Unknown package: " + packageName); 2571 } 2572 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2573 if (bp == null) { 2574 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2575 } 2576 2577 checkGrantRevokePermissions(pkg, bp); 2578 2579 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2580 if (ps == null) { 2581 return; 2582 } 2583 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2584 if (gp.grantedPermissions.add(permissionName)) { 2585 if (ps.haveGids) { 2586 gp.gids = appendInts(gp.gids, bp.gids); 2587 } 2588 mSettings.writeLPr(); 2589 } 2590 } 2591 } 2592 2593 @Override 2594 public void revokePermission(String packageName, String permissionName) { 2595 int changedAppId = -1; 2596 2597 synchronized (mPackages) { 2598 final PackageParser.Package pkg = mPackages.get(packageName); 2599 if (pkg == null) { 2600 throw new IllegalArgumentException("Unknown package: " + packageName); 2601 } 2602 if (pkg.applicationInfo.uid != Binder.getCallingUid()) { 2603 mContext.enforceCallingOrSelfPermission( 2604 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2605 } 2606 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2607 if (bp == null) { 2608 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2609 } 2610 2611 checkGrantRevokePermissions(pkg, bp); 2612 2613 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2614 if (ps == null) { 2615 return; 2616 } 2617 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2618 if (gp.grantedPermissions.remove(permissionName)) { 2619 gp.grantedPermissions.remove(permissionName); 2620 if (ps.haveGids) { 2621 gp.gids = removeInts(gp.gids, bp.gids); 2622 } 2623 mSettings.writeLPr(); 2624 changedAppId = ps.appId; 2625 } 2626 } 2627 2628 if (changedAppId >= 0) { 2629 // We changed the perm on someone, kill its processes. 2630 IActivityManager am = ActivityManagerNative.getDefault(); 2631 if (am != null) { 2632 final int callingUserId = UserHandle.getCallingUserId(); 2633 final long ident = Binder.clearCallingIdentity(); 2634 try { 2635 //XXX we should only revoke for the calling user's app permissions, 2636 // but for now we impact all users. 2637 //am.killUid(UserHandle.getUid(callingUserId, changedAppId), 2638 // "revoke " + permissionName); 2639 int[] users = sUserManager.getUserIds(); 2640 for (int user : users) { 2641 am.killUid(UserHandle.getUid(user, changedAppId), 2642 "revoke " + permissionName); 2643 } 2644 } catch (RemoteException e) { 2645 } finally { 2646 Binder.restoreCallingIdentity(ident); 2647 } 2648 } 2649 } 2650 } 2651 2652 @Override 2653 public boolean isProtectedBroadcast(String actionName) { 2654 synchronized (mPackages) { 2655 return mProtectedBroadcasts.contains(actionName); 2656 } 2657 } 2658 2659 @Override 2660 public int checkSignatures(String pkg1, String pkg2) { 2661 synchronized (mPackages) { 2662 final PackageParser.Package p1 = mPackages.get(pkg1); 2663 final PackageParser.Package p2 = mPackages.get(pkg2); 2664 if (p1 == null || p1.mExtras == null 2665 || p2 == null || p2.mExtras == null) { 2666 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2667 } 2668 return compareSignatures(p1.mSignatures, p2.mSignatures); 2669 } 2670 } 2671 2672 @Override 2673 public int checkUidSignatures(int uid1, int uid2) { 2674 // Map to base uids. 2675 uid1 = UserHandle.getAppId(uid1); 2676 uid2 = UserHandle.getAppId(uid2); 2677 // reader 2678 synchronized (mPackages) { 2679 Signature[] s1; 2680 Signature[] s2; 2681 Object obj = mSettings.getUserIdLPr(uid1); 2682 if (obj != null) { 2683 if (obj instanceof SharedUserSetting) { 2684 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 2685 } else if (obj instanceof PackageSetting) { 2686 s1 = ((PackageSetting)obj).signatures.mSignatures; 2687 } else { 2688 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2689 } 2690 } else { 2691 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2692 } 2693 obj = mSettings.getUserIdLPr(uid2); 2694 if (obj != null) { 2695 if (obj instanceof SharedUserSetting) { 2696 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 2697 } else if (obj instanceof PackageSetting) { 2698 s2 = ((PackageSetting)obj).signatures.mSignatures; 2699 } else { 2700 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2701 } 2702 } else { 2703 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2704 } 2705 return compareSignatures(s1, s2); 2706 } 2707 } 2708 2709 /** 2710 * Compares two sets of signatures. Returns: 2711 * <br /> 2712 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 2713 * <br /> 2714 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 2715 * <br /> 2716 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 2717 * <br /> 2718 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 2719 * <br /> 2720 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 2721 */ 2722 static int compareSignatures(Signature[] s1, Signature[] s2) { 2723 if (s1 == null) { 2724 return s2 == null 2725 ? PackageManager.SIGNATURE_NEITHER_SIGNED 2726 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 2727 } 2728 2729 if (s2 == null) { 2730 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 2731 } 2732 2733 if (s1.length != s2.length) { 2734 return PackageManager.SIGNATURE_NO_MATCH; 2735 } 2736 2737 // Since both signature sets are of size 1, we can compare without HashSets. 2738 if (s1.length == 1) { 2739 return s1[0].equals(s2[0]) ? 2740 PackageManager.SIGNATURE_MATCH : 2741 PackageManager.SIGNATURE_NO_MATCH; 2742 } 2743 2744 HashSet<Signature> set1 = new HashSet<Signature>(); 2745 for (Signature sig : s1) { 2746 set1.add(sig); 2747 } 2748 HashSet<Signature> set2 = new HashSet<Signature>(); 2749 for (Signature sig : s2) { 2750 set2.add(sig); 2751 } 2752 // Make sure s2 contains all signatures in s1. 2753 if (set1.equals(set2)) { 2754 return PackageManager.SIGNATURE_MATCH; 2755 } 2756 return PackageManager.SIGNATURE_NO_MATCH; 2757 } 2758 2759 /** 2760 * If the database version for this type of package (internal storage or 2761 * external storage) is less than the version where package signatures 2762 * were updated, return true. 2763 */ 2764 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2765 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 2766 DatabaseVersion.SIGNATURE_END_ENTITY)) 2767 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 2768 DatabaseVersion.SIGNATURE_END_ENTITY)); 2769 } 2770 2771 /** 2772 * Used for backward compatibility to make sure any packages with 2773 * certificate chains get upgraded to the new style. {@code existingSigs} 2774 * will be in the old format (since they were stored on disk from before the 2775 * system upgrade) and {@code scannedSigs} will be in the newer format. 2776 */ 2777 private int compareSignaturesCompat(PackageSignatures existingSigs, 2778 PackageParser.Package scannedPkg) { 2779 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 2780 return PackageManager.SIGNATURE_NO_MATCH; 2781 } 2782 2783 HashSet<Signature> existingSet = new HashSet<Signature>(); 2784 for (Signature sig : existingSigs.mSignatures) { 2785 existingSet.add(sig); 2786 } 2787 HashSet<Signature> scannedCompatSet = new HashSet<Signature>(); 2788 for (Signature sig : scannedPkg.mSignatures) { 2789 try { 2790 Signature[] chainSignatures = sig.getChainSignatures(); 2791 for (Signature chainSig : chainSignatures) { 2792 scannedCompatSet.add(chainSig); 2793 } 2794 } catch (CertificateEncodingException e) { 2795 scannedCompatSet.add(sig); 2796 } 2797 } 2798 /* 2799 * Make sure the expanded scanned set contains all signatures in the 2800 * existing one. 2801 */ 2802 if (scannedCompatSet.equals(existingSet)) { 2803 // Migrate the old signatures to the new scheme. 2804 existingSigs.assignSignatures(scannedPkg.mSignatures); 2805 // The new KeySets will be re-added later in the scanning process. 2806 synchronized (mPackages) { 2807 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 2808 } 2809 return PackageManager.SIGNATURE_MATCH; 2810 } 2811 return PackageManager.SIGNATURE_NO_MATCH; 2812 } 2813 2814 @Override 2815 public String[] getPackagesForUid(int uid) { 2816 uid = UserHandle.getAppId(uid); 2817 // reader 2818 synchronized (mPackages) { 2819 Object obj = mSettings.getUserIdLPr(uid); 2820 if (obj instanceof SharedUserSetting) { 2821 final SharedUserSetting sus = (SharedUserSetting) obj; 2822 final int N = sus.packages.size(); 2823 final String[] res = new String[N]; 2824 final Iterator<PackageSetting> it = sus.packages.iterator(); 2825 int i = 0; 2826 while (it.hasNext()) { 2827 res[i++] = it.next().name; 2828 } 2829 return res; 2830 } else if (obj instanceof PackageSetting) { 2831 final PackageSetting ps = (PackageSetting) obj; 2832 return new String[] { ps.name }; 2833 } 2834 } 2835 return null; 2836 } 2837 2838 @Override 2839 public String getNameForUid(int uid) { 2840 // reader 2841 synchronized (mPackages) { 2842 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2843 if (obj instanceof SharedUserSetting) { 2844 final SharedUserSetting sus = (SharedUserSetting) obj; 2845 return sus.name + ":" + sus.userId; 2846 } else if (obj instanceof PackageSetting) { 2847 final PackageSetting ps = (PackageSetting) obj; 2848 return ps.name; 2849 } 2850 } 2851 return null; 2852 } 2853 2854 @Override 2855 public int getUidForSharedUser(String sharedUserName) { 2856 if(sharedUserName == null) { 2857 return -1; 2858 } 2859 // reader 2860 synchronized (mPackages) { 2861 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false); 2862 if (suid == null) { 2863 return -1; 2864 } 2865 return suid.userId; 2866 } 2867 } 2868 2869 @Override 2870 public int getFlagsForUid(int uid) { 2871 synchronized (mPackages) { 2872 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2873 if (obj instanceof SharedUserSetting) { 2874 final SharedUserSetting sus = (SharedUserSetting) obj; 2875 return sus.pkgFlags; 2876 } else if (obj instanceof PackageSetting) { 2877 final PackageSetting ps = (PackageSetting) obj; 2878 return ps.pkgFlags; 2879 } 2880 } 2881 return 0; 2882 } 2883 2884 @Override 2885 public String[] getAppOpPermissionPackages(String permissionName) { 2886 synchronized (mPackages) { 2887 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 2888 if (pkgs == null) { 2889 return null; 2890 } 2891 return pkgs.toArray(new String[pkgs.size()]); 2892 } 2893 } 2894 2895 @Override 2896 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 2897 int flags, int userId) { 2898 if (!sUserManager.exists(userId)) return null; 2899 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent"); 2900 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2901 return chooseBestActivity(intent, resolvedType, flags, query, userId); 2902 } 2903 2904 @Override 2905 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 2906 IntentFilter filter, int match, ComponentName activity) { 2907 final int userId = UserHandle.getCallingUserId(); 2908 if (DEBUG_PREFERRED) { 2909 Log.v(TAG, "setLastChosenActivity intent=" + intent 2910 + " resolvedType=" + resolvedType 2911 + " flags=" + flags 2912 + " filter=" + filter 2913 + " match=" + match 2914 + " activity=" + activity); 2915 filter.dump(new PrintStreamPrinter(System.out), " "); 2916 } 2917 intent.setComponent(null); 2918 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2919 // Find any earlier preferred or last chosen entries and nuke them 2920 findPreferredActivity(intent, resolvedType, 2921 flags, query, 0, false, true, false, userId); 2922 // Add the new activity as the last chosen for this filter 2923 addPreferredActivityInternal(filter, match, null, activity, false, userId); 2924 } 2925 2926 @Override 2927 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 2928 final int userId = UserHandle.getCallingUserId(); 2929 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 2930 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2931 return findPreferredActivity(intent, resolvedType, flags, query, 0, 2932 false, false, false, userId); 2933 } 2934 2935 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 2936 int flags, List<ResolveInfo> query, int userId) { 2937 if (query != null) { 2938 final int N = query.size(); 2939 if (N == 1) { 2940 return query.get(0); 2941 } else if (N > 1) { 2942 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 2943 // If there is more than one activity with the same priority, 2944 // then let the user decide between them. 2945 ResolveInfo r0 = query.get(0); 2946 ResolveInfo r1 = query.get(1); 2947 if (DEBUG_INTENT_MATCHING || debug) { 2948 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 2949 + r1.activityInfo.name + "=" + r1.priority); 2950 } 2951 // If the first activity has a higher priority, or a different 2952 // default, then it is always desireable to pick it. 2953 if (r0.priority != r1.priority 2954 || r0.preferredOrder != r1.preferredOrder 2955 || r0.isDefault != r1.isDefault) { 2956 return query.get(0); 2957 } 2958 // If we have saved a preference for a preferred activity for 2959 // this Intent, use that. 2960 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 2961 flags, query, r0.priority, true, false, debug, userId); 2962 if (ri != null) { 2963 return ri; 2964 } 2965 if (userId != 0) { 2966 ri = new ResolveInfo(mResolveInfo); 2967 ri.activityInfo = new ActivityInfo(ri.activityInfo); 2968 ri.activityInfo.applicationInfo = new ApplicationInfo( 2969 ri.activityInfo.applicationInfo); 2970 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 2971 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 2972 return ri; 2973 } 2974 return mResolveInfo; 2975 } 2976 } 2977 return null; 2978 } 2979 2980 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 2981 int flags, List<ResolveInfo> query, boolean debug, int userId) { 2982 final int N = query.size(); 2983 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 2984 .get(userId); 2985 // Get the list of persistent preferred activities that handle the intent 2986 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 2987 List<PersistentPreferredActivity> pprefs = ppir != null 2988 ? ppir.queryIntent(intent, resolvedType, 2989 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 2990 : null; 2991 if (pprefs != null && pprefs.size() > 0) { 2992 final int M = pprefs.size(); 2993 for (int i=0; i<M; i++) { 2994 final PersistentPreferredActivity ppa = pprefs.get(i); 2995 if (DEBUG_PREFERRED || debug) { 2996 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 2997 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 2998 + "\n component=" + ppa.mComponent); 2999 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3000 } 3001 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3002 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3003 if (DEBUG_PREFERRED || debug) { 3004 Slog.v(TAG, "Found persistent preferred activity:"); 3005 if (ai != null) { 3006 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3007 } else { 3008 Slog.v(TAG, " null"); 3009 } 3010 } 3011 if (ai == null) { 3012 // This previously registered persistent preferred activity 3013 // component is no longer known. Ignore it and do NOT remove it. 3014 continue; 3015 } 3016 for (int j=0; j<N; j++) { 3017 final ResolveInfo ri = query.get(j); 3018 if (!ri.activityInfo.applicationInfo.packageName 3019 .equals(ai.applicationInfo.packageName)) { 3020 continue; 3021 } 3022 if (!ri.activityInfo.name.equals(ai.name)) { 3023 continue; 3024 } 3025 // Found a persistent preference that can handle the intent. 3026 if (DEBUG_PREFERRED || debug) { 3027 Slog.v(TAG, "Returning persistent preferred activity: " + 3028 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3029 } 3030 return ri; 3031 } 3032 } 3033 } 3034 return null; 3035 } 3036 3037 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3038 List<ResolveInfo> query, int priority, boolean always, 3039 boolean removeMatches, boolean debug, int userId) { 3040 if (!sUserManager.exists(userId)) return null; 3041 // writer 3042 synchronized (mPackages) { 3043 if (intent.getSelector() != null) { 3044 intent = intent.getSelector(); 3045 } 3046 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3047 3048 // Try to find a matching persistent preferred activity. 3049 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3050 debug, userId); 3051 3052 // If a persistent preferred activity matched, use it. 3053 if (pri != null) { 3054 return pri; 3055 } 3056 3057 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3058 // Get the list of preferred activities that handle the intent 3059 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3060 List<PreferredActivity> prefs = pir != null 3061 ? pir.queryIntent(intent, resolvedType, 3062 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3063 : null; 3064 if (prefs != null && prefs.size() > 0) { 3065 // First figure out how good the original match set is. 3066 // We will only allow preferred activities that came 3067 // from the same match quality. 3068 int match = 0; 3069 3070 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3071 3072 final int N = query.size(); 3073 for (int j=0; j<N; j++) { 3074 final ResolveInfo ri = query.get(j); 3075 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3076 + ": 0x" + Integer.toHexString(match)); 3077 if (ri.match > match) { 3078 match = ri.match; 3079 } 3080 } 3081 3082 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3083 + Integer.toHexString(match)); 3084 3085 match &= IntentFilter.MATCH_CATEGORY_MASK; 3086 final int M = prefs.size(); 3087 for (int i=0; i<M; i++) { 3088 final PreferredActivity pa = prefs.get(i); 3089 if (DEBUG_PREFERRED || debug) { 3090 Slog.v(TAG, "Checking PreferredActivity ds=" 3091 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3092 + "\n component=" + pa.mPref.mComponent); 3093 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3094 } 3095 if (pa.mPref.mMatch != match) { 3096 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3097 + Integer.toHexString(pa.mPref.mMatch)); 3098 continue; 3099 } 3100 // If it's not an "always" type preferred activity and that's what we're 3101 // looking for, skip it. 3102 if (always && !pa.mPref.mAlways) { 3103 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3104 continue; 3105 } 3106 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3107 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3108 if (DEBUG_PREFERRED || debug) { 3109 Slog.v(TAG, "Found preferred activity:"); 3110 if (ai != null) { 3111 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3112 } else { 3113 Slog.v(TAG, " null"); 3114 } 3115 } 3116 if (ai == null) { 3117 // This previously registered preferred activity 3118 // component is no longer known. Most likely an update 3119 // to the app was installed and in the new version this 3120 // component no longer exists. Clean it up by removing 3121 // it from the preferred activities list, and skip it. 3122 Slog.w(TAG, "Removing dangling preferred activity: " 3123 + pa.mPref.mComponent); 3124 pir.removeFilter(pa); 3125 continue; 3126 } 3127 for (int j=0; j<N; j++) { 3128 final ResolveInfo ri = query.get(j); 3129 if (!ri.activityInfo.applicationInfo.packageName 3130 .equals(ai.applicationInfo.packageName)) { 3131 continue; 3132 } 3133 if (!ri.activityInfo.name.equals(ai.name)) { 3134 continue; 3135 } 3136 3137 if (removeMatches) { 3138 pir.removeFilter(pa); 3139 if (DEBUG_PREFERRED) { 3140 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3141 } 3142 break; 3143 } 3144 3145 // Okay we found a previously set preferred or last chosen app. 3146 // If the result set is different from when this 3147 // was created, we need to clear it and re-ask the 3148 // user their preference, if we're looking for an "always" type entry. 3149 if (always && !pa.mPref.sameSet(query, priority)) { 3150 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3151 + intent + " type " + resolvedType); 3152 if (DEBUG_PREFERRED) { 3153 Slog.v(TAG, "Removing preferred activity since set changed " 3154 + pa.mPref.mComponent); 3155 } 3156 pir.removeFilter(pa); 3157 // Re-add the filter as a "last chosen" entry (!always) 3158 PreferredActivity lastChosen = new PreferredActivity( 3159 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3160 pir.addFilter(lastChosen); 3161 mSettings.writePackageRestrictionsLPr(userId); 3162 return null; 3163 } 3164 3165 // Yay! Either the set matched or we're looking for the last chosen 3166 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3167 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3168 mSettings.writePackageRestrictionsLPr(userId); 3169 return ri; 3170 } 3171 } 3172 } 3173 mSettings.writePackageRestrictionsLPr(userId); 3174 } 3175 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3176 return null; 3177 } 3178 3179 /* 3180 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3181 */ 3182 @Override 3183 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3184 int targetUserId) { 3185 mContext.enforceCallingOrSelfPermission( 3186 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3187 List<CrossProfileIntentFilter> matches = 3188 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3189 if (matches != null) { 3190 int size = matches.size(); 3191 for (int i = 0; i < size; i++) { 3192 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3193 } 3194 } 3195 ArrayList<String> packageNames = null; 3196 SparseArray<ArrayList<String>> fromSource = 3197 mSettings.mCrossProfilePackageInfo.get(sourceUserId); 3198 if (fromSource != null) { 3199 packageNames = fromSource.get(targetUserId); 3200 if (packageNames != null) { 3201 // We need the package name, so we try to resolve with the loosest flags possible 3202 List<ResolveInfo> resolveInfos = mActivities.queryIntent(intent, resolvedType, 3203 PackageManager.GET_UNINSTALLED_PACKAGES, targetUserId); 3204 int count = resolveInfos.size(); 3205 for (int i = 0; i < count; i++) { 3206 ResolveInfo resolveInfo = resolveInfos.get(i); 3207 if (packageNames.contains(resolveInfo.activityInfo.packageName)) { 3208 return true; 3209 } 3210 } 3211 } 3212 } 3213 return false; 3214 } 3215 3216 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3217 String resolvedType, int userId) { 3218 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3219 if (resolver != null) { 3220 return resolver.queryIntent(intent, resolvedType, false, userId); 3221 } 3222 return null; 3223 } 3224 3225 @Override 3226 public List<ResolveInfo> queryIntentActivities(Intent intent, 3227 String resolvedType, int flags, int userId) { 3228 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3229 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities"); 3230 ComponentName comp = intent.getComponent(); 3231 if (comp == null) { 3232 if (intent.getSelector() != null) { 3233 intent = intent.getSelector(); 3234 comp = intent.getComponent(); 3235 } 3236 } 3237 3238 if (comp != null) { 3239 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3240 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3241 if (ai != null) { 3242 final ResolveInfo ri = new ResolveInfo(); 3243 ri.activityInfo = ai; 3244 list.add(ri); 3245 } 3246 return list; 3247 } 3248 3249 // reader 3250 synchronized (mPackages) { 3251 final String pkgName = intent.getPackage(); 3252 boolean queryCrossProfile = (flags & PackageManager.NO_CROSS_PROFILE) == 0; 3253 if (pkgName == null) { 3254 ResolveInfo resolveInfo = null; 3255 if (queryCrossProfile) { 3256 // Check if the intent needs to be forwarded to another user for this package 3257 ArrayList<ResolveInfo> crossProfileResult = 3258 queryIntentActivitiesCrossProfilePackage( 3259 intent, resolvedType, flags, userId); 3260 if (!crossProfileResult.isEmpty()) { 3261 // Skip the current profile 3262 return crossProfileResult; 3263 } 3264 List<CrossProfileIntentFilter> matchingFilters = 3265 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3266 // Check for results that need to skip the current profile. 3267 resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3268 resolvedType, flags, userId); 3269 if (resolveInfo != null) { 3270 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3271 result.add(resolveInfo); 3272 return result; 3273 } 3274 // Check for cross profile results. 3275 resolveInfo = queryCrossProfileIntents( 3276 matchingFilters, intent, resolvedType, flags, userId); 3277 } 3278 // Check for results in the current profile. 3279 List<ResolveInfo> result = mActivities.queryIntent( 3280 intent, resolvedType, flags, userId); 3281 if (resolveInfo != null) { 3282 result.add(resolveInfo); 3283 } 3284 return result; 3285 } 3286 final PackageParser.Package pkg = mPackages.get(pkgName); 3287 if (pkg != null) { 3288 if (queryCrossProfile) { 3289 ArrayList<ResolveInfo> crossProfileResult = 3290 queryIntentActivitiesCrossProfilePackage( 3291 intent, resolvedType, flags, userId, pkg, pkgName); 3292 if (!crossProfileResult.isEmpty()) { 3293 // Skip the current profile 3294 return crossProfileResult; 3295 } 3296 } 3297 return mActivities.queryIntentForPackage(intent, resolvedType, flags, 3298 pkg.activities, userId); 3299 } 3300 return new ArrayList<ResolveInfo>(); 3301 } 3302 } 3303 3304 private ResolveInfo querySkipCurrentProfileIntents( 3305 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3306 int flags, int sourceUserId) { 3307 if (matchingFilters != null) { 3308 int size = matchingFilters.size(); 3309 for (int i = 0; i < size; i ++) { 3310 CrossProfileIntentFilter filter = matchingFilters.get(i); 3311 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 3312 // Checking if there are activities in the target user that can handle the 3313 // intent. 3314 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3315 flags, sourceUserId); 3316 if (resolveInfo != null) { 3317 return resolveInfo; 3318 } 3319 } 3320 } 3321 } 3322 return null; 3323 } 3324 3325 private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage( 3326 Intent intent, String resolvedType, int flags, int userId) { 3327 ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>(); 3328 SparseArray<ArrayList<String>> sourceForwardingInfo = 3329 mSettings.mCrossProfilePackageInfo.get(userId); 3330 if (sourceForwardingInfo != null) { 3331 int NI = sourceForwardingInfo.size(); 3332 for (int i = 0; i < NI; i++) { 3333 int targetUserId = sourceForwardingInfo.keyAt(i); 3334 ArrayList<String> packageNames = sourceForwardingInfo.valueAt(i); 3335 List<ResolveInfo> resolveInfos = mActivities.queryIntent( 3336 intent, resolvedType, flags, targetUserId); 3337 int NJ = resolveInfos.size(); 3338 for (int j = 0; j < NJ; j++) { 3339 ResolveInfo resolveInfo = resolveInfos.get(j); 3340 if (packageNames.contains(resolveInfo.activityInfo.packageName)) { 3341 matchingResolveInfos.add(createForwardingResolveInfo( 3342 resolveInfo.filter, userId, targetUserId)); 3343 } 3344 } 3345 } 3346 } 3347 return matchingResolveInfos; 3348 } 3349 3350 private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage( 3351 Intent intent, String resolvedType, int flags, int userId, PackageParser.Package pkg, 3352 String packageName) { 3353 ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>(); 3354 SparseArray<ArrayList<String>> sourceForwardingInfo = 3355 mSettings.mCrossProfilePackageInfo.get(userId); 3356 if (sourceForwardingInfo != null) { 3357 int NI = sourceForwardingInfo.size(); 3358 for (int i = 0; i < NI; i++) { 3359 int targetUserId = sourceForwardingInfo.keyAt(i); 3360 if (sourceForwardingInfo.valueAt(i).contains(packageName)) { 3361 List<ResolveInfo> resolveInfos = mActivities.queryIntentForPackage( 3362 intent, resolvedType, flags, pkg.activities, targetUserId); 3363 int NJ = resolveInfos.size(); 3364 for (int j = 0; j < NJ; j++) { 3365 ResolveInfo resolveInfo = resolveInfos.get(j); 3366 matchingResolveInfos.add(createForwardingResolveInfo( 3367 resolveInfo.filter, userId, targetUserId)); 3368 } 3369 } 3370 } 3371 } 3372 return matchingResolveInfos; 3373 } 3374 3375 // Return matching ResolveInfo if any for skip current profile intent filters. 3376 private ResolveInfo queryCrossProfileIntents( 3377 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3378 int flags, int sourceUserId) { 3379 if (matchingFilters != null) { 3380 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 3381 // match the same intent. For performance reasons, it is better not to 3382 // run queryIntent twice for the same userId 3383 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 3384 int size = matchingFilters.size(); 3385 for (int i = 0; i < size; i++) { 3386 CrossProfileIntentFilter filter = matchingFilters.get(i); 3387 int targetUserId = filter.getTargetUserId(); 3388 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 3389 && !alreadyTriedUserIds.get(targetUserId)) { 3390 // Checking if there are activities in the target user that can handle the 3391 // intent. 3392 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3393 flags, sourceUserId); 3394 if (resolveInfo != null) return resolveInfo; 3395 alreadyTriedUserIds.put(targetUserId, true); 3396 } 3397 } 3398 } 3399 return null; 3400 } 3401 3402 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 3403 String resolvedType, int flags, int sourceUserId) { 3404 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 3405 resolvedType, flags, filter.getTargetUserId()); 3406 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 3407 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 3408 } 3409 return null; 3410 } 3411 3412 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 3413 int sourceUserId, int targetUserId) { 3414 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 3415 String className; 3416 if (targetUserId == UserHandle.USER_OWNER) { 3417 className = FORWARD_INTENT_TO_USER_OWNER; 3418 } else { 3419 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 3420 } 3421 ComponentName forwardingActivityComponentName = new ComponentName( 3422 mAndroidApplication.packageName, className); 3423 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 3424 sourceUserId); 3425 if (targetUserId == UserHandle.USER_OWNER) { 3426 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 3427 forwardingResolveInfo.noResourceId = true; 3428 } 3429 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 3430 forwardingResolveInfo.priority = 0; 3431 forwardingResolveInfo.preferredOrder = 0; 3432 forwardingResolveInfo.match = 0; 3433 forwardingResolveInfo.isDefault = true; 3434 forwardingResolveInfo.filter = filter; 3435 forwardingResolveInfo.targetUserId = targetUserId; 3436 return forwardingResolveInfo; 3437 } 3438 3439 @Override 3440 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 3441 Intent[] specifics, String[] specificTypes, Intent intent, 3442 String resolvedType, int flags, int userId) { 3443 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3444 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 3445 "query intent activity options"); 3446 final String resultsAction = intent.getAction(); 3447 3448 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 3449 | PackageManager.GET_RESOLVED_FILTER, userId); 3450 3451 if (DEBUG_INTENT_MATCHING) { 3452 Log.v(TAG, "Query " + intent + ": " + results); 3453 } 3454 3455 int specificsPos = 0; 3456 int N; 3457 3458 // todo: note that the algorithm used here is O(N^2). This 3459 // isn't a problem in our current environment, but if we start running 3460 // into situations where we have more than 5 or 10 matches then this 3461 // should probably be changed to something smarter... 3462 3463 // First we go through and resolve each of the specific items 3464 // that were supplied, taking care of removing any corresponding 3465 // duplicate items in the generic resolve list. 3466 if (specifics != null) { 3467 for (int i=0; i<specifics.length; i++) { 3468 final Intent sintent = specifics[i]; 3469 if (sintent == null) { 3470 continue; 3471 } 3472 3473 if (DEBUG_INTENT_MATCHING) { 3474 Log.v(TAG, "Specific #" + i + ": " + sintent); 3475 } 3476 3477 String action = sintent.getAction(); 3478 if (resultsAction != null && resultsAction.equals(action)) { 3479 // If this action was explicitly requested, then don't 3480 // remove things that have it. 3481 action = null; 3482 } 3483 3484 ResolveInfo ri = null; 3485 ActivityInfo ai = null; 3486 3487 ComponentName comp = sintent.getComponent(); 3488 if (comp == null) { 3489 ri = resolveIntent( 3490 sintent, 3491 specificTypes != null ? specificTypes[i] : null, 3492 flags, userId); 3493 if (ri == null) { 3494 continue; 3495 } 3496 if (ri == mResolveInfo) { 3497 // ACK! Must do something better with this. 3498 } 3499 ai = ri.activityInfo; 3500 comp = new ComponentName(ai.applicationInfo.packageName, 3501 ai.name); 3502 } else { 3503 ai = getActivityInfo(comp, flags, userId); 3504 if (ai == null) { 3505 continue; 3506 } 3507 } 3508 3509 // Look for any generic query activities that are duplicates 3510 // of this specific one, and remove them from the results. 3511 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 3512 N = results.size(); 3513 int j; 3514 for (j=specificsPos; j<N; j++) { 3515 ResolveInfo sri = results.get(j); 3516 if ((sri.activityInfo.name.equals(comp.getClassName()) 3517 && sri.activityInfo.applicationInfo.packageName.equals( 3518 comp.getPackageName())) 3519 || (action != null && sri.filter.matchAction(action))) { 3520 results.remove(j); 3521 if (DEBUG_INTENT_MATCHING) Log.v( 3522 TAG, "Removing duplicate item from " + j 3523 + " due to specific " + specificsPos); 3524 if (ri == null) { 3525 ri = sri; 3526 } 3527 j--; 3528 N--; 3529 } 3530 } 3531 3532 // Add this specific item to its proper place. 3533 if (ri == null) { 3534 ri = new ResolveInfo(); 3535 ri.activityInfo = ai; 3536 } 3537 results.add(specificsPos, ri); 3538 ri.specificIndex = i; 3539 specificsPos++; 3540 } 3541 } 3542 3543 // Now we go through the remaining generic results and remove any 3544 // duplicate actions that are found here. 3545 N = results.size(); 3546 for (int i=specificsPos; i<N-1; i++) { 3547 final ResolveInfo rii = results.get(i); 3548 if (rii.filter == null) { 3549 continue; 3550 } 3551 3552 // Iterate over all of the actions of this result's intent 3553 // filter... typically this should be just one. 3554 final Iterator<String> it = rii.filter.actionsIterator(); 3555 if (it == null) { 3556 continue; 3557 } 3558 while (it.hasNext()) { 3559 final String action = it.next(); 3560 if (resultsAction != null && resultsAction.equals(action)) { 3561 // If this action was explicitly requested, then don't 3562 // remove things that have it. 3563 continue; 3564 } 3565 for (int j=i+1; j<N; j++) { 3566 final ResolveInfo rij = results.get(j); 3567 if (rij.filter != null && rij.filter.hasAction(action)) { 3568 results.remove(j); 3569 if (DEBUG_INTENT_MATCHING) Log.v( 3570 TAG, "Removing duplicate item from " + j 3571 + " due to action " + action + " at " + i); 3572 j--; 3573 N--; 3574 } 3575 } 3576 } 3577 3578 // If the caller didn't request filter information, drop it now 3579 // so we don't have to marshall/unmarshall it. 3580 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3581 rii.filter = null; 3582 } 3583 } 3584 3585 // Filter out the caller activity if so requested. 3586 if (caller != null) { 3587 N = results.size(); 3588 for (int i=0; i<N; i++) { 3589 ActivityInfo ainfo = results.get(i).activityInfo; 3590 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 3591 && caller.getClassName().equals(ainfo.name)) { 3592 results.remove(i); 3593 break; 3594 } 3595 } 3596 } 3597 3598 // If the caller didn't request filter information, 3599 // drop them now so we don't have to 3600 // marshall/unmarshall it. 3601 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3602 N = results.size(); 3603 for (int i=0; i<N; i++) { 3604 results.get(i).filter = null; 3605 } 3606 } 3607 3608 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 3609 return results; 3610 } 3611 3612 @Override 3613 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 3614 int userId) { 3615 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3616 ComponentName comp = intent.getComponent(); 3617 if (comp == null) { 3618 if (intent.getSelector() != null) { 3619 intent = intent.getSelector(); 3620 comp = intent.getComponent(); 3621 } 3622 } 3623 if (comp != null) { 3624 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3625 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 3626 if (ai != null) { 3627 ResolveInfo ri = new ResolveInfo(); 3628 ri.activityInfo = ai; 3629 list.add(ri); 3630 } 3631 return list; 3632 } 3633 3634 // reader 3635 synchronized (mPackages) { 3636 String pkgName = intent.getPackage(); 3637 if (pkgName == null) { 3638 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 3639 } 3640 final PackageParser.Package pkg = mPackages.get(pkgName); 3641 if (pkg != null) { 3642 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 3643 userId); 3644 } 3645 return null; 3646 } 3647 } 3648 3649 @Override 3650 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 3651 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 3652 if (!sUserManager.exists(userId)) return null; 3653 if (query != null) { 3654 if (query.size() >= 1) { 3655 // If there is more than one service with the same priority, 3656 // just arbitrarily pick the first one. 3657 return query.get(0); 3658 } 3659 } 3660 return null; 3661 } 3662 3663 @Override 3664 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 3665 int userId) { 3666 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3667 ComponentName comp = intent.getComponent(); 3668 if (comp == null) { 3669 if (intent.getSelector() != null) { 3670 intent = intent.getSelector(); 3671 comp = intent.getComponent(); 3672 } 3673 } 3674 if (comp != null) { 3675 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3676 final ServiceInfo si = getServiceInfo(comp, flags, userId); 3677 if (si != null) { 3678 final ResolveInfo ri = new ResolveInfo(); 3679 ri.serviceInfo = si; 3680 list.add(ri); 3681 } 3682 return list; 3683 } 3684 3685 // reader 3686 synchronized (mPackages) { 3687 String pkgName = intent.getPackage(); 3688 if (pkgName == null) { 3689 return mServices.queryIntent(intent, resolvedType, flags, userId); 3690 } 3691 final PackageParser.Package pkg = mPackages.get(pkgName); 3692 if (pkg != null) { 3693 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 3694 userId); 3695 } 3696 return null; 3697 } 3698 } 3699 3700 @Override 3701 public List<ResolveInfo> queryIntentContentProviders( 3702 Intent intent, String resolvedType, int flags, int userId) { 3703 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3704 ComponentName comp = intent.getComponent(); 3705 if (comp == null) { 3706 if (intent.getSelector() != null) { 3707 intent = intent.getSelector(); 3708 comp = intent.getComponent(); 3709 } 3710 } 3711 if (comp != null) { 3712 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3713 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 3714 if (pi != null) { 3715 final ResolveInfo ri = new ResolveInfo(); 3716 ri.providerInfo = pi; 3717 list.add(ri); 3718 } 3719 return list; 3720 } 3721 3722 // reader 3723 synchronized (mPackages) { 3724 String pkgName = intent.getPackage(); 3725 if (pkgName == null) { 3726 return mProviders.queryIntent(intent, resolvedType, flags, userId); 3727 } 3728 final PackageParser.Package pkg = mPackages.get(pkgName); 3729 if (pkg != null) { 3730 return mProviders.queryIntentForPackage( 3731 intent, resolvedType, flags, pkg.providers, userId); 3732 } 3733 return null; 3734 } 3735 } 3736 3737 @Override 3738 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 3739 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3740 3741 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages"); 3742 3743 // writer 3744 synchronized (mPackages) { 3745 ArrayList<PackageInfo> list; 3746 if (listUninstalled) { 3747 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 3748 for (PackageSetting ps : mSettings.mPackages.values()) { 3749 PackageInfo pi; 3750 if (ps.pkg != null) { 3751 pi = generatePackageInfo(ps.pkg, flags, userId); 3752 } else { 3753 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3754 } 3755 if (pi != null) { 3756 list.add(pi); 3757 } 3758 } 3759 } else { 3760 list = new ArrayList<PackageInfo>(mPackages.size()); 3761 for (PackageParser.Package p : mPackages.values()) { 3762 PackageInfo pi = generatePackageInfo(p, flags, userId); 3763 if (pi != null) { 3764 list.add(pi); 3765 } 3766 } 3767 } 3768 3769 return new ParceledListSlice<PackageInfo>(list); 3770 } 3771 } 3772 3773 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 3774 String[] permissions, boolean[] tmp, int flags, int userId) { 3775 int numMatch = 0; 3776 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 3777 for (int i=0; i<permissions.length; i++) { 3778 if (gp.grantedPermissions.contains(permissions[i])) { 3779 tmp[i] = true; 3780 numMatch++; 3781 } else { 3782 tmp[i] = false; 3783 } 3784 } 3785 if (numMatch == 0) { 3786 return; 3787 } 3788 PackageInfo pi; 3789 if (ps.pkg != null) { 3790 pi = generatePackageInfo(ps.pkg, flags, userId); 3791 } else { 3792 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3793 } 3794 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 3795 if (numMatch == permissions.length) { 3796 pi.requestedPermissions = permissions; 3797 } else { 3798 pi.requestedPermissions = new String[numMatch]; 3799 numMatch = 0; 3800 for (int i=0; i<permissions.length; i++) { 3801 if (tmp[i]) { 3802 pi.requestedPermissions[numMatch] = permissions[i]; 3803 numMatch++; 3804 } 3805 } 3806 } 3807 } 3808 list.add(pi); 3809 } 3810 3811 @Override 3812 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 3813 String[] permissions, int flags, int userId) { 3814 if (!sUserManager.exists(userId)) return null; 3815 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3816 3817 // writer 3818 synchronized (mPackages) { 3819 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 3820 boolean[] tmpBools = new boolean[permissions.length]; 3821 if (listUninstalled) { 3822 for (PackageSetting ps : mSettings.mPackages.values()) { 3823 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 3824 } 3825 } else { 3826 for (PackageParser.Package pkg : mPackages.values()) { 3827 PackageSetting ps = (PackageSetting)pkg.mExtras; 3828 if (ps != null) { 3829 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 3830 userId); 3831 } 3832 } 3833 } 3834 3835 return new ParceledListSlice<PackageInfo>(list); 3836 } 3837 } 3838 3839 @Override 3840 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 3841 if (!sUserManager.exists(userId)) return null; 3842 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3843 3844 // writer 3845 synchronized (mPackages) { 3846 ArrayList<ApplicationInfo> list; 3847 if (listUninstalled) { 3848 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 3849 for (PackageSetting ps : mSettings.mPackages.values()) { 3850 ApplicationInfo ai; 3851 if (ps.pkg != null) { 3852 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3853 ps.readUserState(userId), userId); 3854 } else { 3855 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 3856 } 3857 if (ai != null) { 3858 list.add(ai); 3859 } 3860 } 3861 } else { 3862 list = new ArrayList<ApplicationInfo>(mPackages.size()); 3863 for (PackageParser.Package p : mPackages.values()) { 3864 if (p.mExtras != null) { 3865 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3866 ((PackageSetting)p.mExtras).readUserState(userId), userId); 3867 if (ai != null) { 3868 list.add(ai); 3869 } 3870 } 3871 } 3872 } 3873 3874 return new ParceledListSlice<ApplicationInfo>(list); 3875 } 3876 } 3877 3878 public List<ApplicationInfo> getPersistentApplications(int flags) { 3879 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 3880 3881 // reader 3882 synchronized (mPackages) { 3883 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 3884 final int userId = UserHandle.getCallingUserId(); 3885 while (i.hasNext()) { 3886 final PackageParser.Package p = i.next(); 3887 if (p.applicationInfo != null 3888 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 3889 && (!mSafeMode || isSystemApp(p))) { 3890 PackageSetting ps = mSettings.mPackages.get(p.packageName); 3891 if (ps != null) { 3892 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3893 ps.readUserState(userId), userId); 3894 if (ai != null) { 3895 finalList.add(ai); 3896 } 3897 } 3898 } 3899 } 3900 } 3901 3902 return finalList; 3903 } 3904 3905 @Override 3906 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 3907 if (!sUserManager.exists(userId)) return null; 3908 // reader 3909 synchronized (mPackages) { 3910 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 3911 PackageSetting ps = provider != null 3912 ? mSettings.mPackages.get(provider.owner.packageName) 3913 : null; 3914 return ps != null 3915 && mSettings.isEnabledLPr(provider.info, flags, userId) 3916 && (!mSafeMode || (provider.info.applicationInfo.flags 3917 &ApplicationInfo.FLAG_SYSTEM) != 0) 3918 ? PackageParser.generateProviderInfo(provider, flags, 3919 ps.readUserState(userId), userId) 3920 : null; 3921 } 3922 } 3923 3924 /** 3925 * @deprecated 3926 */ 3927 @Deprecated 3928 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 3929 // reader 3930 synchronized (mPackages) { 3931 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 3932 .entrySet().iterator(); 3933 final int userId = UserHandle.getCallingUserId(); 3934 while (i.hasNext()) { 3935 Map.Entry<String, PackageParser.Provider> entry = i.next(); 3936 PackageParser.Provider p = entry.getValue(); 3937 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3938 3939 if (ps != null && p.syncable 3940 && (!mSafeMode || (p.info.applicationInfo.flags 3941 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 3942 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 3943 ps.readUserState(userId), userId); 3944 if (info != null) { 3945 outNames.add(entry.getKey()); 3946 outInfo.add(info); 3947 } 3948 } 3949 } 3950 } 3951 } 3952 3953 @Override 3954 public List<ProviderInfo> queryContentProviders(String processName, 3955 int uid, int flags) { 3956 ArrayList<ProviderInfo> finalList = null; 3957 // reader 3958 synchronized (mPackages) { 3959 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 3960 final int userId = processName != null ? 3961 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 3962 while (i.hasNext()) { 3963 final PackageParser.Provider p = i.next(); 3964 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3965 if (ps != null && p.info.authority != null 3966 && (processName == null 3967 || (p.info.processName.equals(processName) 3968 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 3969 && mSettings.isEnabledLPr(p.info, flags, userId) 3970 && (!mSafeMode 3971 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 3972 if (finalList == null) { 3973 finalList = new ArrayList<ProviderInfo>(3); 3974 } 3975 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 3976 ps.readUserState(userId), userId); 3977 if (info != null) { 3978 finalList.add(info); 3979 } 3980 } 3981 } 3982 } 3983 3984 if (finalList != null) { 3985 Collections.sort(finalList, mProviderInitOrderSorter); 3986 } 3987 3988 return finalList; 3989 } 3990 3991 @Override 3992 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 3993 int flags) { 3994 // reader 3995 synchronized (mPackages) { 3996 final PackageParser.Instrumentation i = mInstrumentation.get(name); 3997 return PackageParser.generateInstrumentationInfo(i, flags); 3998 } 3999 } 4000 4001 @Override 4002 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4003 int flags) { 4004 ArrayList<InstrumentationInfo> finalList = 4005 new ArrayList<InstrumentationInfo>(); 4006 4007 // reader 4008 synchronized (mPackages) { 4009 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4010 while (i.hasNext()) { 4011 final PackageParser.Instrumentation p = i.next(); 4012 if (targetPackage == null 4013 || targetPackage.equals(p.info.targetPackage)) { 4014 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4015 flags); 4016 if (ii != null) { 4017 finalList.add(ii); 4018 } 4019 } 4020 } 4021 } 4022 4023 return finalList; 4024 } 4025 4026 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4027 HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4028 if (overlays == null) { 4029 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4030 return; 4031 } 4032 for (PackageParser.Package opkg : overlays.values()) { 4033 // Not much to do if idmap fails: we already logged the error 4034 // and we certainly don't want to abort installation of pkg simply 4035 // because an overlay didn't fit properly. For these reasons, 4036 // ignore the return value of createIdmapForPackagePairLI. 4037 createIdmapForPackagePairLI(pkg, opkg); 4038 } 4039 } 4040 4041 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4042 PackageParser.Package opkg) { 4043 if (!opkg.mTrustedOverlay) { 4044 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4045 opkg.baseCodePath + ": overlay not trusted"); 4046 return false; 4047 } 4048 HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4049 if (overlaySet == null) { 4050 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4051 opkg.baseCodePath + " but target package has no known overlays"); 4052 return false; 4053 } 4054 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4055 // TODO: generate idmap for split APKs 4056 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4057 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4058 + opkg.baseCodePath); 4059 return false; 4060 } 4061 PackageParser.Package[] overlayArray = 4062 overlaySet.values().toArray(new PackageParser.Package[0]); 4063 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4064 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4065 return p1.mOverlayPriority - p2.mOverlayPriority; 4066 } 4067 }; 4068 Arrays.sort(overlayArray, cmp); 4069 4070 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4071 int i = 0; 4072 for (PackageParser.Package p : overlayArray) { 4073 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4074 } 4075 return true; 4076 } 4077 4078 private void scanDirLI(File dir, int flags, int scanMode, long currentTime) { 4079 final File[] files = dir.listFiles(); 4080 if (ArrayUtils.isEmpty(files)) { 4081 Log.d(TAG, "No files in app dir " + dir); 4082 return; 4083 } 4084 4085 if (DEBUG_PACKAGE_SCANNING) { 4086 Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode 4087 + " flags=0x" + Integer.toHexString(flags)); 4088 } 4089 4090 for (File file : files) { 4091 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 4092 && !PackageInstallerService.isStageFile(file); 4093 if (!isPackage) { 4094 // Ignore entries which are not apk's 4095 continue; 4096 } 4097 try { 4098 scanPackageLI(file, flags | PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, null); 4099 } catch (PackageManagerException e) { 4100 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4101 4102 // Don't mess around with apps in system partition. 4103 if ((flags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4104 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4105 // Delete the apk 4106 Slog.w(TAG, "Cleaning up failed install of " + file); 4107 file.delete(); 4108 } 4109 } 4110 } 4111 } 4112 4113 private static File getSettingsProblemFile() { 4114 File dataDir = Environment.getDataDirectory(); 4115 File systemDir = new File(dataDir, "system"); 4116 File fname = new File(systemDir, "uiderrors.txt"); 4117 return fname; 4118 } 4119 4120 static void reportSettingsProblem(int priority, String msg) { 4121 try { 4122 File fname = getSettingsProblemFile(); 4123 FileOutputStream out = new FileOutputStream(fname, true); 4124 PrintWriter pw = new FastPrintWriter(out); 4125 SimpleDateFormat formatter = new SimpleDateFormat(); 4126 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4127 pw.println(dateString + ": " + msg); 4128 pw.close(); 4129 FileUtils.setPermissions( 4130 fname.toString(), 4131 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4132 -1, -1); 4133 } catch (java.io.IOException e) { 4134 } 4135 Slog.println(priority, TAG, msg); 4136 } 4137 4138 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 4139 PackageParser.Package pkg, File srcFile, int parseFlags) 4140 throws PackageManagerException { 4141 if (ps != null 4142 && ps.codePath.equals(srcFile) 4143 && ps.timeStamp == srcFile.lastModified() 4144 && !isCompatSignatureUpdateNeeded(pkg)) { 4145 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4146 if (ps.signatures.mSignatures != null 4147 && ps.signatures.mSignatures.length != 0 4148 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4149 // Optimization: reuse the existing cached certificates 4150 // if the package appears to be unchanged. 4151 pkg.mSignatures = ps.signatures.mSignatures; 4152 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4153 synchronized (mPackages) { 4154 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 4155 } 4156 return; 4157 } 4158 4159 Slog.w(TAG, "PackageSetting for " + ps.name 4160 + " is missing signatures. Collecting certs again to recover them."); 4161 } else { 4162 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4163 } 4164 4165 try { 4166 pp.collectCertificates(pkg, parseFlags); 4167 pp.collectManifestDigest(pkg); 4168 } catch (PackageParserException e) { 4169 throw new PackageManagerException(e.error, "Failed to collect certificates for " 4170 + pkg.packageName + ": " + e.getMessage()); 4171 } 4172 } 4173 4174 /* 4175 * Scan a package and return the newly parsed package. 4176 * Returns null in case of errors and the error code is stored in mLastScanError 4177 */ 4178 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanMode, 4179 long currentTime, UserHandle user) throws PackageManagerException { 4180 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4181 parseFlags |= mDefParseFlags; 4182 PackageParser pp = new PackageParser(); 4183 pp.setSeparateProcesses(mSeparateProcesses); 4184 pp.setOnlyCoreApps(mOnlyCore); 4185 pp.setDisplayMetrics(mMetrics); 4186 4187 if ((scanMode & SCAN_TRUSTED_OVERLAY) != 0) { 4188 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4189 } 4190 4191 final PackageParser.Package pkg; 4192 try { 4193 pkg = pp.parsePackage(scanFile, parseFlags); 4194 } catch (PackageParserException e) { 4195 throw new PackageManagerException(e.error, 4196 "Failed to scan " + scanFile + ": " + e.getMessage()); 4197 } 4198 4199 PackageSetting ps = null; 4200 PackageSetting updatedPkg; 4201 // reader 4202 synchronized (mPackages) { 4203 // Look to see if we already know about this package. 4204 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4205 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4206 // This package has been renamed to its original name. Let's 4207 // use that. 4208 ps = mSettings.peekPackageLPr(oldName); 4209 } 4210 // If there was no original package, see one for the real package name. 4211 if (ps == null) { 4212 ps = mSettings.peekPackageLPr(pkg.packageName); 4213 } 4214 // Check to see if this package could be hiding/updating a system 4215 // package. Must look for it either under the original or real 4216 // package name depending on our state. 4217 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4218 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4219 } 4220 boolean updatedPkgBetter = false; 4221 // First check if this is a system package that may involve an update 4222 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4223 if (ps != null && !ps.codePath.equals(scanFile)) { 4224 // The path has changed from what was last scanned... check the 4225 // version of the new path against what we have stored to determine 4226 // what to do. 4227 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4228 if (pkg.mVersionCode < ps.versionCode) { 4229 // The system package has been updated and the code path does not match 4230 // Ignore entry. Skip it. 4231 Log.i(TAG, "Package " + ps.name + " at " + scanFile 4232 + " ignored: updated version " + ps.versionCode 4233 + " better than this " + pkg.mVersionCode); 4234 if (!updatedPkg.codePath.equals(scanFile)) { 4235 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4236 + ps.name + " changing from " + updatedPkg.codePathString 4237 + " to " + scanFile); 4238 updatedPkg.codePath = scanFile; 4239 updatedPkg.codePathString = scanFile.toString(); 4240 // This is the point at which we know that the system-disk APK 4241 // for this package has moved during a reboot (e.g. due to an OTA), 4242 // so we need to reevaluate it for privilege policy. 4243 if (locationIsPrivileged(scanFile)) { 4244 updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED; 4245 } 4246 } 4247 updatedPkg.pkg = pkg; 4248 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 4249 } else { 4250 // The current app on the system partition is better than 4251 // what we have updated to on the data partition; switch 4252 // back to the system partition version. 4253 // At this point, its safely assumed that package installation for 4254 // apps in system partition will go through. If not there won't be a working 4255 // version of the app 4256 // writer 4257 synchronized (mPackages) { 4258 // Just remove the loaded entries from package lists. 4259 mPackages.remove(ps.name); 4260 } 4261 Slog.w(TAG, "Package " + ps.name + " at " + scanFile 4262 + "reverting from " + ps.codePathString 4263 + ": new version " + pkg.mVersionCode 4264 + " better than installed " + ps.versionCode); 4265 4266 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4267 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4268 getAppDexInstructionSets(ps), isMultiArch(ps)); 4269 synchronized (mInstallLock) { 4270 args.cleanUpResourcesLI(); 4271 } 4272 synchronized (mPackages) { 4273 mSettings.enableSystemPackageLPw(ps.name); 4274 } 4275 updatedPkgBetter = true; 4276 } 4277 } 4278 } 4279 4280 if (updatedPkg != null) { 4281 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4282 // initially 4283 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4284 4285 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4286 // flag set initially 4287 if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) { 4288 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4289 } 4290 } 4291 4292 // Verify certificates against what was last scanned 4293 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 4294 4295 /* 4296 * A new system app appeared, but we already had a non-system one of the 4297 * same name installed earlier. 4298 */ 4299 boolean shouldHideSystemApp = false; 4300 if (updatedPkg == null && ps != null 4301 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4302 /* 4303 * Check to make sure the signatures match first. If they don't, 4304 * wipe the installed application and its data. 4305 */ 4306 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4307 != PackageManager.SIGNATURE_MATCH) { 4308 if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!"); 4309 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4310 ps = null; 4311 } else { 4312 /* 4313 * If the newly-added system app is an older version than the 4314 * already installed version, hide it. It will be scanned later 4315 * and re-added like an update. 4316 */ 4317 if (pkg.mVersionCode < ps.versionCode) { 4318 shouldHideSystemApp = true; 4319 } else { 4320 /* 4321 * The newly found system app is a newer version that the 4322 * one previously installed. Simply remove the 4323 * already-installed application and replace it with our own 4324 * while keeping the application data. 4325 */ 4326 Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from " 4327 + ps.codePathString + ": new version " + pkg.mVersionCode 4328 + " better than installed " + ps.versionCode); 4329 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4330 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4331 getAppDexInstructionSets(ps), isMultiArch(ps)); 4332 synchronized (mInstallLock) { 4333 args.cleanUpResourcesLI(); 4334 } 4335 } 4336 } 4337 } 4338 4339 // The apk is forward locked (not public) if its code and resources 4340 // are kept in different files. (except for app in either system or 4341 // vendor path). 4342 // TODO grab this value from PackageSettings 4343 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4344 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4345 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 4346 } 4347 } 4348 4349 // TODO: extend to support forward-locked splits 4350 String resourcePath = null; 4351 String baseResourcePath = null; 4352 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 4353 if (ps != null && ps.resourcePathString != null) { 4354 resourcePath = ps.resourcePathString; 4355 baseResourcePath = ps.resourcePathString; 4356 } else { 4357 // Should not happen at all. Just log an error. 4358 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 4359 } 4360 } else { 4361 resourcePath = pkg.codePath; 4362 baseResourcePath = pkg.baseCodePath; 4363 } 4364 4365 // Set application objects path explicitly. 4366 pkg.applicationInfo.setCodePath(pkg.codePath); 4367 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 4368 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 4369 pkg.applicationInfo.setResourcePath(resourcePath); 4370 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 4371 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 4372 4373 // Note that we invoke the following method only if we are about to unpack an application 4374 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode 4375 | SCAN_UPDATE_SIGNATURE, currentTime, user); 4376 4377 /* 4378 * If the system app should be overridden by a previously installed 4379 * data, hide the system app now and let the /data/app scan pick it up 4380 * again. 4381 */ 4382 if (shouldHideSystemApp) { 4383 synchronized (mPackages) { 4384 /* 4385 * We have to grant systems permissions before we hide, because 4386 * grantPermissions will assume the package update is trying to 4387 * expand its permissions. 4388 */ 4389 grantPermissionsLPw(pkg, true); 4390 mSettings.disableSystemPackageLPw(pkg.packageName); 4391 } 4392 } 4393 4394 return scannedPkg; 4395 } 4396 4397 private static String fixProcessName(String defProcessName, 4398 String processName, int uid) { 4399 if (processName == null) { 4400 return defProcessName; 4401 } 4402 return processName; 4403 } 4404 4405 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 4406 throws PackageManagerException { 4407 if (pkgSetting.signatures.mSignatures != null) { 4408 // Already existing package. Make sure signatures match 4409 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 4410 == PackageManager.SIGNATURE_MATCH; 4411 if (!match) { 4412 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 4413 == PackageManager.SIGNATURE_MATCH; 4414 } 4415 if (!match) { 4416 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 4417 + pkg.packageName + " signatures do not match the " 4418 + "previously installed version; ignoring!"); 4419 } 4420 } 4421 4422 // Check for shared user signatures 4423 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 4424 // Already existing package. Make sure signatures match 4425 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4426 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 4427 if (!match) { 4428 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 4429 == PackageManager.SIGNATURE_MATCH; 4430 } 4431 if (!match) { 4432 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 4433 "Package " + pkg.packageName 4434 + " has no signatures that match those in shared user " 4435 + pkgSetting.sharedUser.name + "; ignoring!"); 4436 } 4437 } 4438 } 4439 4440 /** 4441 * Enforces that only the system UID or root's UID can call a method exposed 4442 * via Binder. 4443 * 4444 * @param message used as message if SecurityException is thrown 4445 * @throws SecurityException if the caller is not system or root 4446 */ 4447 private static final void enforceSystemOrRoot(String message) { 4448 final int uid = Binder.getCallingUid(); 4449 if (uid != Process.SYSTEM_UID && uid != 0) { 4450 throw new SecurityException(message); 4451 } 4452 } 4453 4454 @Override 4455 public void performBootDexOpt() { 4456 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4457 4458 final HashSet<PackageParser.Package> pkgs; 4459 synchronized (mPackages) { 4460 pkgs = mDeferredDexOpt; 4461 mDeferredDexOpt = null; 4462 } 4463 4464 if (pkgs != null) { 4465 // Filter out packages that aren't recently used. 4466 // 4467 // The exception is first boot of a non-eng device, which 4468 // should do a full dexopt. 4469 boolean eng = "eng".equals(SystemProperties.get("ro.build.type")); 4470 if (eng || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 4471 // TODO: add a property to control this? 4472 long dexOptLRUThresholdInMinutes; 4473 if (eng) { 4474 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 4475 } else { 4476 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 4477 } 4478 long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 4479 4480 int total = pkgs.size(); 4481 int skipped = 0; 4482 long now = System.currentTimeMillis(); 4483 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 4484 PackageParser.Package pkg = i.next(); 4485 long then = pkg.mLastPackageUsageTimeInMills; 4486 if (then + dexOptLRUThresholdInMills < now) { 4487 if (DEBUG_DEXOPT) { 4488 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 4489 ((then == 0) ? "never" : new Date(then))); 4490 } 4491 i.remove(); 4492 skipped++; 4493 } 4494 } 4495 if (DEBUG_DEXOPT) { 4496 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 4497 } 4498 } 4499 4500 int i = 0; 4501 for (PackageParser.Package pkg : pkgs) { 4502 i++; 4503 if (DEBUG_DEXOPT) { 4504 Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size() 4505 + ": " + pkg.packageName); 4506 } 4507 if (!isFirstBoot()) { 4508 try { 4509 ActivityManagerNative.getDefault().showBootMessage( 4510 mContext.getResources().getString( 4511 R.string.android_upgrading_apk, 4512 i, pkgs.size()), true); 4513 } catch (RemoteException e) { 4514 } 4515 } 4516 PackageParser.Package p = pkg; 4517 synchronized (mInstallLock) { 4518 performDexOptLI(p, null /* instruction sets */, false /* force dex */, false /* defer */, 4519 true /* include dependencies */); 4520 } 4521 } 4522 } 4523 } 4524 4525 @Override 4526 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 4527 return performDexOpt(packageName, instructionSet, true); 4528 } 4529 4530 private static String getPrimaryInstructionSet(ApplicationInfo info) { 4531 if (info.primaryCpuAbi == null) { 4532 return getPreferredInstructionSet(); 4533 } 4534 4535 return VMRuntime.getInstructionSet(info.primaryCpuAbi); 4536 } 4537 4538 public boolean performDexOpt(String packageName, String instructionSet, boolean updateUsage) { 4539 PackageParser.Package p; 4540 final String targetInstructionSet; 4541 synchronized (mPackages) { 4542 p = mPackages.get(packageName); 4543 if (p == null) { 4544 return false; 4545 } 4546 if (updateUsage) { 4547 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 4548 } 4549 mPackageUsage.write(false); 4550 4551 targetInstructionSet = instructionSet != null ? instructionSet : 4552 getPrimaryInstructionSet(p.applicationInfo); 4553 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 4554 return false; 4555 } 4556 } 4557 4558 synchronized (mInstallLock) { 4559 final String[] instructionSets = new String[] { targetInstructionSet }; 4560 return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */, 4561 true /* include dependencies */) == DEX_OPT_PERFORMED; 4562 } 4563 } 4564 4565 public HashSet<String> getPackagesThatNeedDexOpt() { 4566 HashSet<String> pkgs = null; 4567 synchronized (mPackages) { 4568 for (PackageParser.Package p : mPackages.values()) { 4569 if (DEBUG_DEXOPT) { 4570 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 4571 } 4572 if (!p.mDexOptPerformed.isEmpty()) { 4573 continue; 4574 } 4575 if (pkgs == null) { 4576 pkgs = new HashSet<String>(); 4577 } 4578 pkgs.add(p.packageName); 4579 } 4580 } 4581 return pkgs; 4582 } 4583 4584 public void shutdown() { 4585 mPackageUsage.write(true); 4586 } 4587 4588 private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets, 4589 boolean forceDex, boolean defer, HashSet<String> done) { 4590 for (int i=0; i<libs.size(); i++) { 4591 PackageParser.Package libPkg; 4592 String libName; 4593 synchronized (mPackages) { 4594 libName = libs.get(i); 4595 SharedLibraryEntry lib = mSharedLibraries.get(libName); 4596 if (lib != null && lib.apk != null) { 4597 libPkg = mPackages.get(lib.apk); 4598 } else { 4599 libPkg = null; 4600 } 4601 } 4602 if (libPkg != null && !done.contains(libName)) { 4603 performDexOptLI(libPkg, instructionSets, forceDex, defer, done); 4604 } 4605 } 4606 } 4607 4608 static final int DEX_OPT_SKIPPED = 0; 4609 static final int DEX_OPT_PERFORMED = 1; 4610 static final int DEX_OPT_DEFERRED = 2; 4611 static final int DEX_OPT_FAILED = -1; 4612 4613 private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets, 4614 boolean forceDex, boolean defer, HashSet<String> done) { 4615 final String[] instructionSets = targetInstructionSets != null ? 4616 targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo); 4617 4618 if (done != null) { 4619 done.add(pkg.packageName); 4620 if (pkg.usesLibraries != null) { 4621 performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done); 4622 } 4623 if (pkg.usesOptionalLibraries != null) { 4624 performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done); 4625 } 4626 } 4627 4628 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) { 4629 return DEX_OPT_SKIPPED; 4630 } 4631 4632 final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly(); 4633 boolean performedDexOpt = false; 4634 // There are three basic cases here: 4635 // 1.) we need to dexopt, either because we are forced or it is needed 4636 // 2.) we are defering a needed dexopt 4637 // 3.) we are skipping an unneeded dexopt 4638 final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 4639 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 4640 if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) { 4641 continue; 4642 } 4643 4644 for (String path : paths) { 4645 try { 4646 // This will return DEXOPT_NEEDED if we either cannot find any odex file for this 4647 // patckage or the one we find does not match the image checksum (i.e. it was 4648 // compiled against an old image). It will return PATCHOAT_NEEDED if we can find a 4649 // odex file and it matches the checksum of the image but not its base address, 4650 // meaning we need to move it. 4651 final byte isDexOptNeeded = DexFile.isDexOptNeededInternal(path, 4652 pkg.packageName, dexCodeInstructionSet, defer); 4653 if (forceDex || (!defer && isDexOptNeeded == DexFile.DEXOPT_NEEDED)) { 4654 Log.i(TAG, "Running dexopt on: " + path + " pkg=" 4655 + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet); 4656 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4657 final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg), 4658 pkg.packageName, dexCodeInstructionSet); 4659 4660 if (ret < 0) { 4661 // Don't bother running dexopt again if we failed, it will probably 4662 // just result in an error again. Also, don't bother dexopting for other 4663 // paths & ISAs. 4664 return DEX_OPT_FAILED; 4665 } 4666 4667 performedDexOpt = true; 4668 } else if (!defer && isDexOptNeeded == DexFile.PATCHOAT_NEEDED) { 4669 Log.i(TAG, "Running patchoat on: " + pkg.applicationInfo.packageName); 4670 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4671 final int ret = mInstaller.patchoat(path, sharedGid, !isForwardLocked(pkg), 4672 pkg.packageName, dexCodeInstructionSet); 4673 4674 if (ret < 0) { 4675 // Don't bother running patchoat again if we failed, it will probably 4676 // just result in an error again. Also, don't bother dexopting for other 4677 // paths & ISAs. 4678 return DEX_OPT_FAILED; 4679 } 4680 4681 performedDexOpt = true; 4682 } 4683 4684 // We're deciding to defer a needed dexopt. Don't bother dexopting for other 4685 // paths and instruction sets. We'll deal with them all together when we process 4686 // our list of deferred dexopts. 4687 if (defer && isDexOptNeeded != DexFile.UP_TO_DATE) { 4688 if (mDeferredDexOpt == null) { 4689 mDeferredDexOpt = new HashSet<PackageParser.Package>(); 4690 } 4691 mDeferredDexOpt.add(pkg); 4692 return DEX_OPT_DEFERRED; 4693 } 4694 } catch (FileNotFoundException e) { 4695 Slog.w(TAG, "Apk not found for dexopt: " + path); 4696 return DEX_OPT_FAILED; 4697 } catch (IOException e) { 4698 Slog.w(TAG, "IOException reading apk: " + path, e); 4699 return DEX_OPT_FAILED; 4700 } catch (StaleDexCacheError e) { 4701 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e); 4702 return DEX_OPT_FAILED; 4703 } catch (Exception e) { 4704 Slog.w(TAG, "Exception when doing dexopt : ", e); 4705 return DEX_OPT_FAILED; 4706 } 4707 } 4708 4709 // At this point we haven't failed dexopt and we haven't deferred dexopt. We must 4710 // either have either succeeded dexopt, or have had isDexOptNeededInternal tell us 4711 // it isn't required. We therefore mark that this package doesn't need dexopt unless 4712 // it's forced. performedDexOpt will tell us whether we performed dex-opt or skipped 4713 // it. 4714 pkg.mDexOptPerformed.add(dexCodeInstructionSet); 4715 } 4716 4717 // If we've gotten here, we're sure that no error occurred and that we haven't 4718 // deferred dex-opt. We've either dex-opted one more paths or instruction sets or 4719 // we've skipped all of them because they are up to date. In both cases this 4720 // package doesn't need dexopt any longer. 4721 return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED; 4722 } 4723 4724 private static String[] getAppDexInstructionSets(ApplicationInfo info) { 4725 if (info.primaryCpuAbi != null) { 4726 if (info.secondaryCpuAbi != null) { 4727 return new String[] { 4728 VMRuntime.getInstructionSet(info.primaryCpuAbi), 4729 VMRuntime.getInstructionSet(info.secondaryCpuAbi) }; 4730 } else { 4731 return new String[] { 4732 VMRuntime.getInstructionSet(info.primaryCpuAbi) }; 4733 } 4734 } 4735 4736 return new String[] { getPreferredInstructionSet() }; 4737 } 4738 4739 private static String[] getAppDexInstructionSets(PackageSetting ps) { 4740 if (ps.primaryCpuAbiString != null) { 4741 if (ps.secondaryCpuAbiString != null) { 4742 return new String[] { 4743 VMRuntime.getInstructionSet(ps.primaryCpuAbiString), 4744 VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) }; 4745 } else { 4746 return new String[] { 4747 VMRuntime.getInstructionSet(ps.primaryCpuAbiString) }; 4748 } 4749 } 4750 4751 return new String[] { getPreferredInstructionSet() }; 4752 } 4753 4754 private static String getPreferredInstructionSet() { 4755 if (sPreferredInstructionSet == null) { 4756 sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]); 4757 } 4758 4759 return sPreferredInstructionSet; 4760 } 4761 4762 private static List<String> getAllInstructionSets() { 4763 final String[] allAbis = Build.SUPPORTED_ABIS; 4764 final List<String> allInstructionSets = new ArrayList<String>(allAbis.length); 4765 4766 for (String abi : allAbis) { 4767 final String instructionSet = VMRuntime.getInstructionSet(abi); 4768 if (!allInstructionSets.contains(instructionSet)) { 4769 allInstructionSets.add(instructionSet); 4770 } 4771 } 4772 4773 return allInstructionSets; 4774 } 4775 4776 /** 4777 * Returns the instruction set that should be used to compile dex code. In the presence of 4778 * a native bridge this might be different than the one shared libraries use. 4779 */ 4780 private static String getDexCodeInstructionSet(String sharedLibraryIsa) { 4781 String dexCodeIsa = SystemProperties.get("ro.dalvik.vm.isa." + sharedLibraryIsa); 4782 return (dexCodeIsa.isEmpty() ? sharedLibraryIsa : dexCodeIsa); 4783 } 4784 4785 private static String[] getDexCodeInstructionSets(String[] instructionSets) { 4786 HashSet<String> dexCodeInstructionSets = new HashSet<String>(instructionSets.length); 4787 for (String instructionSet : instructionSets) { 4788 dexCodeInstructionSets.add(getDexCodeInstructionSet(instructionSet)); 4789 } 4790 return dexCodeInstructionSets.toArray(new String[dexCodeInstructionSets.size()]); 4791 } 4792 4793 @Override 4794 public void forceDexOpt(String packageName) { 4795 enforceSystemOrRoot("forceDexOpt"); 4796 4797 PackageParser.Package pkg; 4798 synchronized (mPackages) { 4799 pkg = mPackages.get(packageName); 4800 if (pkg == null) { 4801 throw new IllegalArgumentException("Missing package: " + packageName); 4802 } 4803 } 4804 4805 synchronized (mInstallLock) { 4806 final String[] instructionSets = new String[] { 4807 getPrimaryInstructionSet(pkg.applicationInfo) }; 4808 final int res = performDexOptLI(pkg, instructionSets, true, false, true); 4809 if (res != DEX_OPT_PERFORMED) { 4810 throw new IllegalStateException("Failed to dexopt: " + res); 4811 } 4812 } 4813 } 4814 4815 private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets, 4816 boolean forceDex, boolean defer, boolean inclDependencies) { 4817 HashSet<String> done; 4818 if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) { 4819 done = new HashSet<String>(); 4820 done.add(pkg.packageName); 4821 } else { 4822 done = null; 4823 } 4824 return performDexOptLI(pkg, instructionSets, forceDex, defer, done); 4825 } 4826 4827 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 4828 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 4829 Slog.w(TAG, "Unable to update from " + oldPkg.name 4830 + " to " + newPkg.packageName 4831 + ": old package not in system partition"); 4832 return false; 4833 } else if (mPackages.get(oldPkg.name) != null) { 4834 Slog.w(TAG, "Unable to update from " + oldPkg.name 4835 + " to " + newPkg.packageName 4836 + ": old package still exists"); 4837 return false; 4838 } 4839 return true; 4840 } 4841 4842 File getDataPathForUser(int userId) { 4843 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId); 4844 } 4845 4846 private File getDataPathForPackage(String packageName, int userId) { 4847 /* 4848 * Until we fully support multiple users, return the directory we 4849 * previously would have. The PackageManagerTests will need to be 4850 * revised when this is changed back.. 4851 */ 4852 if (userId == 0) { 4853 return new File(mAppDataDir, packageName); 4854 } else { 4855 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 4856 + File.separator + packageName); 4857 } 4858 } 4859 4860 private int createDataDirsLI(String packageName, int uid, String seinfo) { 4861 int[] users = sUserManager.getUserIds(); 4862 int res = mInstaller.install(packageName, uid, uid, seinfo); 4863 if (res < 0) { 4864 return res; 4865 } 4866 for (int user : users) { 4867 if (user != 0) { 4868 res = mInstaller.createUserData(packageName, 4869 UserHandle.getUid(user, uid), user, seinfo); 4870 if (res < 0) { 4871 return res; 4872 } 4873 } 4874 } 4875 return res; 4876 } 4877 4878 private int removeDataDirsLI(String packageName) { 4879 int[] users = sUserManager.getUserIds(); 4880 int res = 0; 4881 for (int user : users) { 4882 int resInner = mInstaller.remove(packageName, user); 4883 if (resInner < 0) { 4884 res = resInner; 4885 } 4886 } 4887 4888 return res; 4889 } 4890 4891 private int deleteCodeCacheDirsLI(String packageName) { 4892 int[] users = sUserManager.getUserIds(); 4893 int res = 0; 4894 for (int user : users) { 4895 int resInner = mInstaller.deleteCodeCacheFiles(packageName, user); 4896 if (resInner < 0) { 4897 res = resInner; 4898 } 4899 } 4900 return res; 4901 } 4902 4903 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 4904 PackageParser.Package changingLib) { 4905 if (file.path != null) { 4906 usesLibraryFiles.add(file.path); 4907 return; 4908 } 4909 PackageParser.Package p = mPackages.get(file.apk); 4910 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 4911 // If we are doing this while in the middle of updating a library apk, 4912 // then we need to make sure to use that new apk for determining the 4913 // dependencies here. (We haven't yet finished committing the new apk 4914 // to the package manager state.) 4915 if (p == null || p.packageName.equals(changingLib.packageName)) { 4916 p = changingLib; 4917 } 4918 } 4919 if (p != null) { 4920 usesLibraryFiles.addAll(p.getAllCodePaths()); 4921 } 4922 } 4923 4924 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 4925 PackageParser.Package changingLib) throws PackageManagerException { 4926 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 4927 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 4928 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 4929 for (int i=0; i<N; i++) { 4930 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 4931 if (file == null) { 4932 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 4933 "Package " + pkg.packageName + " requires unavailable shared library " 4934 + pkg.usesLibraries.get(i) + "; failing!"); 4935 } 4936 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4937 } 4938 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 4939 for (int i=0; i<N; i++) { 4940 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 4941 if (file == null) { 4942 Slog.w(TAG, "Package " + pkg.packageName 4943 + " desires unavailable shared library " 4944 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 4945 } else { 4946 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4947 } 4948 } 4949 N = usesLibraryFiles.size(); 4950 if (N > 0) { 4951 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 4952 } else { 4953 pkg.usesLibraryFiles = null; 4954 } 4955 } 4956 } 4957 4958 private static boolean hasString(List<String> list, List<String> which) { 4959 if (list == null) { 4960 return false; 4961 } 4962 for (int i=list.size()-1; i>=0; i--) { 4963 for (int j=which.size()-1; j>=0; j--) { 4964 if (which.get(j).equals(list.get(i))) { 4965 return true; 4966 } 4967 } 4968 } 4969 return false; 4970 } 4971 4972 private void updateAllSharedLibrariesLPw() { 4973 for (PackageParser.Package pkg : mPackages.values()) { 4974 try { 4975 updateSharedLibrariesLPw(pkg, null); 4976 } catch (PackageManagerException e) { 4977 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 4978 } 4979 } 4980 } 4981 4982 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 4983 PackageParser.Package changingPkg) { 4984 ArrayList<PackageParser.Package> res = null; 4985 for (PackageParser.Package pkg : mPackages.values()) { 4986 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 4987 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 4988 if (res == null) { 4989 res = new ArrayList<PackageParser.Package>(); 4990 } 4991 res.add(pkg); 4992 try { 4993 updateSharedLibrariesLPw(pkg, changingPkg); 4994 } catch (PackageManagerException e) { 4995 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 4996 } 4997 } 4998 } 4999 return res; 5000 } 5001 5002 /** 5003 * Derive the value of the {@code cpuAbiOverride} based on the provided 5004 * value and an optional stored value from the package settings. 5005 */ 5006 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5007 String cpuAbiOverride = null; 5008 5009 if (CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5010 cpuAbiOverride = null; 5011 } else if (abiOverride != null) { 5012 cpuAbiOverride = abiOverride; 5013 } else if (settings != null) { 5014 cpuAbiOverride = settings.cpuAbiOverrideString; 5015 } 5016 5017 return cpuAbiOverride; 5018 } 5019 5020 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5021 int scanMode, long currentTime, UserHandle user) 5022 throws PackageManagerException { 5023 final File scanFile = new File(pkg.codePath); 5024 if (pkg.applicationInfo.getCodePath() == null || 5025 pkg.applicationInfo.getResourcePath() == null) { 5026 // Bail out. The resource and code paths haven't been set. 5027 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5028 "Code and resource paths haven't been set correctly"); 5029 } 5030 5031 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5032 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5033 } 5034 5035 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5036 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED; 5037 } 5038 5039 if (mCustomResolverComponentName != null && 5040 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5041 setUpCustomResolverActivity(pkg); 5042 } 5043 5044 if (pkg.packageName.equals("android")) { 5045 synchronized (mPackages) { 5046 if (mAndroidApplication != null) { 5047 Slog.w(TAG, "*************************************************"); 5048 Slog.w(TAG, "Core android package being redefined. Skipping."); 5049 Slog.w(TAG, " file=" + scanFile); 5050 Slog.w(TAG, "*************************************************"); 5051 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5052 "Core android package being redefined. Skipping."); 5053 } 5054 5055 // Set up information for our fall-back user intent resolution activity. 5056 mPlatformPackage = pkg; 5057 pkg.mVersionCode = mSdkVersion; 5058 mAndroidApplication = pkg.applicationInfo; 5059 5060 if (!mResolverReplaced) { 5061 mResolveActivity.applicationInfo = mAndroidApplication; 5062 mResolveActivity.name = ResolverActivity.class.getName(); 5063 mResolveActivity.packageName = mAndroidApplication.packageName; 5064 mResolveActivity.processName = "system:ui"; 5065 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5066 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5067 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5068 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5069 mResolveActivity.exported = true; 5070 mResolveActivity.enabled = true; 5071 mResolveInfo.activityInfo = mResolveActivity; 5072 mResolveInfo.priority = 0; 5073 mResolveInfo.preferredOrder = 0; 5074 mResolveInfo.match = 0; 5075 mResolveComponentName = new ComponentName( 5076 mAndroidApplication.packageName, mResolveActivity.name); 5077 } 5078 } 5079 } 5080 5081 if (DEBUG_PACKAGE_SCANNING) { 5082 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5083 Log.d(TAG, "Scanning package " + pkg.packageName); 5084 } 5085 5086 if (mPackages.containsKey(pkg.packageName) 5087 || mSharedLibraries.containsKey(pkg.packageName)) { 5088 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5089 "Application package " + pkg.packageName 5090 + " already installed. Skipping duplicate."); 5091 } 5092 5093 // Initialize package source and resource directories 5094 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5095 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5096 5097 SharedUserSetting suid = null; 5098 PackageSetting pkgSetting = null; 5099 5100 if (!isSystemApp(pkg)) { 5101 // Only system apps can use these features. 5102 pkg.mOriginalPackages = null; 5103 pkg.mRealPackage = null; 5104 pkg.mAdoptPermissions = null; 5105 } 5106 5107 // writer 5108 synchronized (mPackages) { 5109 if (pkg.mSharedUserId != null) { 5110 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true); 5111 if (suid == null) { 5112 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5113 "Creating application package " + pkg.packageName 5114 + " for shared user failed"); 5115 } 5116 if (DEBUG_PACKAGE_SCANNING) { 5117 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5118 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5119 + "): packages=" + suid.packages); 5120 } 5121 } 5122 5123 // Check if we are renaming from an original package name. 5124 PackageSetting origPackage = null; 5125 String realName = null; 5126 if (pkg.mOriginalPackages != null) { 5127 // This package may need to be renamed to a previously 5128 // installed name. Let's check on that... 5129 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5130 if (pkg.mOriginalPackages.contains(renamed)) { 5131 // This package had originally been installed as the 5132 // original name, and we have already taken care of 5133 // transitioning to the new one. Just update the new 5134 // one to continue using the old name. 5135 realName = pkg.mRealPackage; 5136 if (!pkg.packageName.equals(renamed)) { 5137 // Callers into this function may have already taken 5138 // care of renaming the package; only do it here if 5139 // it is not already done. 5140 pkg.setPackageName(renamed); 5141 } 5142 5143 } else { 5144 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5145 if ((origPackage = mSettings.peekPackageLPr( 5146 pkg.mOriginalPackages.get(i))) != null) { 5147 // We do have the package already installed under its 5148 // original name... should we use it? 5149 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5150 // New package is not compatible with original. 5151 origPackage = null; 5152 continue; 5153 } else if (origPackage.sharedUser != null) { 5154 // Make sure uid is compatible between packages. 5155 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5156 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5157 + " to " + pkg.packageName + ": old uid " 5158 + origPackage.sharedUser.name 5159 + " differs from " + pkg.mSharedUserId); 5160 origPackage = null; 5161 continue; 5162 } 5163 } else { 5164 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5165 + pkg.packageName + " to old name " + origPackage.name); 5166 } 5167 break; 5168 } 5169 } 5170 } 5171 } 5172 5173 if (mTransferedPackages.contains(pkg.packageName)) { 5174 Slog.w(TAG, "Package " + pkg.packageName 5175 + " was transferred to another, but its .apk remains"); 5176 } 5177 5178 // Just create the setting, don't add it yet. For already existing packages 5179 // the PkgSetting exists already and doesn't have to be created. 5180 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5181 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 5182 pkg.applicationInfo.primaryCpuAbi, 5183 pkg.applicationInfo.secondaryCpuAbi, 5184 pkg.applicationInfo.flags, user, false); 5185 if (pkgSetting == null) { 5186 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5187 "Creating application package " + pkg.packageName + " failed"); 5188 } 5189 5190 if (pkgSetting.origPackage != null) { 5191 // If we are first transitioning from an original package, 5192 // fix up the new package's name now. We need to do this after 5193 // looking up the package under its new name, so getPackageLP 5194 // can take care of fiddling things correctly. 5195 pkg.setPackageName(origPackage.name); 5196 5197 // File a report about this. 5198 String msg = "New package " + pkgSetting.realName 5199 + " renamed to replace old package " + pkgSetting.name; 5200 reportSettingsProblem(Log.WARN, msg); 5201 5202 // Make a note of it. 5203 mTransferedPackages.add(origPackage.name); 5204 5205 // No longer need to retain this. 5206 pkgSetting.origPackage = null; 5207 } 5208 5209 if (realName != null) { 5210 // Make a note of it. 5211 mTransferedPackages.add(pkg.packageName); 5212 } 5213 5214 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5215 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5216 } 5217 5218 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5219 // Check all shared libraries and map to their actual file path. 5220 // We only do this here for apps not on a system dir, because those 5221 // are the only ones that can fail an install due to this. We 5222 // will take care of the system apps by updating all of their 5223 // library paths after the scan is done. 5224 updateSharedLibrariesLPw(pkg, null); 5225 } 5226 5227 if (mFoundPolicyFile) { 5228 SELinuxMMAC.assignSeinfoValue(pkg); 5229 } 5230 5231 pkg.applicationInfo.uid = pkgSetting.appId; 5232 pkg.mExtras = pkgSetting; 5233 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5234 try { 5235 verifySignaturesLP(pkgSetting, pkg); 5236 } catch (PackageManagerException e) { 5237 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5238 throw e; 5239 } 5240 // The signature has changed, but this package is in the system 5241 // image... let's recover! 5242 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5243 // However... if this package is part of a shared user, but it 5244 // doesn't match the signature of the shared user, let's fail. 5245 // What this means is that you can't change the signatures 5246 // associated with an overall shared user, which doesn't seem all 5247 // that unreasonable. 5248 if (pkgSetting.sharedUser != null) { 5249 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5250 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5251 throw new PackageManagerException( 5252 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 5253 "Signature mismatch for shared user : " 5254 + pkgSetting.sharedUser); 5255 } 5256 } 5257 // File a report about this. 5258 String msg = "System package " + pkg.packageName 5259 + " signature changed; retaining data."; 5260 reportSettingsProblem(Log.WARN, msg); 5261 } 5262 } else { 5263 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 5264 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5265 + pkg.packageName + " upgrade keys do not match the " 5266 + "previously installed version"); 5267 } else { 5268 // signatures may have changed as result of upgrade 5269 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5270 } 5271 } 5272 // Verify that this new package doesn't have any content providers 5273 // that conflict with existing packages. Only do this if the 5274 // package isn't already installed, since we don't want to break 5275 // things that are installed. 5276 if ((scanMode&SCAN_NEW_INSTALL) != 0) { 5277 final int N = pkg.providers.size(); 5278 int i; 5279 for (i=0; i<N; i++) { 5280 PackageParser.Provider p = pkg.providers.get(i); 5281 if (p.info.authority != null) { 5282 String names[] = p.info.authority.split(";"); 5283 for (int j = 0; j < names.length; j++) { 5284 if (mProvidersByAuthority.containsKey(names[j])) { 5285 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5286 final String otherPackageName = 5287 ((other != null && other.getComponentName() != null) ? 5288 other.getComponentName().getPackageName() : "?"); 5289 throw new PackageManagerException( 5290 INSTALL_FAILED_CONFLICTING_PROVIDER, 5291 "Can't install because provider name " + names[j] 5292 + " (in package " + pkg.applicationInfo.packageName 5293 + ") is already used by " + otherPackageName); 5294 } 5295 } 5296 } 5297 } 5298 } 5299 5300 if (pkg.mAdoptPermissions != null) { 5301 // This package wants to adopt ownership of permissions from 5302 // another package. 5303 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 5304 final String origName = pkg.mAdoptPermissions.get(i); 5305 final PackageSetting orig = mSettings.peekPackageLPr(origName); 5306 if (orig != null) { 5307 if (verifyPackageUpdateLPr(orig, pkg)) { 5308 Slog.i(TAG, "Adopting permissions from " + origName + " to " 5309 + pkg.packageName); 5310 mSettings.transferPermissionsLPw(origName, pkg.packageName); 5311 } 5312 } 5313 } 5314 } 5315 } 5316 5317 final String pkgName = pkg.packageName; 5318 5319 final long scanFileTime = scanFile.lastModified(); 5320 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0; 5321 pkg.applicationInfo.processName = fixProcessName( 5322 pkg.applicationInfo.packageName, 5323 pkg.applicationInfo.processName, 5324 pkg.applicationInfo.uid); 5325 5326 File dataPath; 5327 if (mPlatformPackage == pkg) { 5328 // The system package is special. 5329 dataPath = new File (Environment.getDataDirectory(), "system"); 5330 pkg.applicationInfo.dataDir = dataPath.getPath(); 5331 5332 } else { 5333 // This is a normal package, need to make its data directory. 5334 dataPath = getDataPathForPackage(pkg.packageName, 0); 5335 5336 boolean uidError = false; 5337 5338 if (dataPath.exists()) { 5339 int currentUid = 0; 5340 try { 5341 StructStat stat = Os.stat(dataPath.getPath()); 5342 currentUid = stat.st_uid; 5343 } catch (ErrnoException e) { 5344 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 5345 } 5346 5347 // If we have mismatched owners for the data path, we have a problem. 5348 if (currentUid != pkg.applicationInfo.uid) { 5349 boolean recovered = false; 5350 if (currentUid == 0) { 5351 // The directory somehow became owned by root. Wow. 5352 // This is probably because the system was stopped while 5353 // installd was in the middle of messing with its libs 5354 // directory. Ask installd to fix that. 5355 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 5356 pkg.applicationInfo.uid); 5357 if (ret >= 0) { 5358 recovered = true; 5359 String msg = "Package " + pkg.packageName 5360 + " unexpectedly changed to uid 0; recovered to " + 5361 + pkg.applicationInfo.uid; 5362 reportSettingsProblem(Log.WARN, msg); 5363 } 5364 } 5365 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5366 || (scanMode&SCAN_BOOTING) != 0)) { 5367 // If this is a system app, we can at least delete its 5368 // current data so the application will still work. 5369 int ret = removeDataDirsLI(pkgName); 5370 if (ret >= 0) { 5371 // TODO: Kill the processes first 5372 // Old data gone! 5373 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5374 ? "System package " : "Third party package "; 5375 String msg = prefix + pkg.packageName 5376 + " has changed from uid: " 5377 + currentUid + " to " 5378 + pkg.applicationInfo.uid + "; old data erased"; 5379 reportSettingsProblem(Log.WARN, msg); 5380 recovered = true; 5381 5382 // And now re-install the app. 5383 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5384 pkg.applicationInfo.seinfo); 5385 if (ret == -1) { 5386 // Ack should not happen! 5387 msg = prefix + pkg.packageName 5388 + " could not have data directory re-created after delete."; 5389 reportSettingsProblem(Log.WARN, msg); 5390 throw new PackageManagerException( 5391 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 5392 } 5393 } 5394 if (!recovered) { 5395 mHasSystemUidErrors = true; 5396 } 5397 } else if (!recovered) { 5398 // If we allow this install to proceed, we will be broken. 5399 // Abort, abort! 5400 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 5401 "scanPackageLI"); 5402 } 5403 if (!recovered) { 5404 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 5405 + pkg.applicationInfo.uid + "/fs_" 5406 + currentUid; 5407 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 5408 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 5409 String msg = "Package " + pkg.packageName 5410 + " has mismatched uid: " 5411 + currentUid + " on disk, " 5412 + pkg.applicationInfo.uid + " in settings"; 5413 // writer 5414 synchronized (mPackages) { 5415 mSettings.mReadMessages.append(msg); 5416 mSettings.mReadMessages.append('\n'); 5417 uidError = true; 5418 if (!pkgSetting.uidError) { 5419 reportSettingsProblem(Log.ERROR, msg); 5420 } 5421 } 5422 } 5423 } 5424 pkg.applicationInfo.dataDir = dataPath.getPath(); 5425 if (mShouldRestoreconData) { 5426 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 5427 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 5428 pkg.applicationInfo.uid); 5429 } 5430 } else { 5431 if (DEBUG_PACKAGE_SCANNING) { 5432 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5433 Log.v(TAG, "Want this data dir: " + dataPath); 5434 } 5435 //invoke installer to do the actual installation 5436 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5437 pkg.applicationInfo.seinfo); 5438 if (ret < 0) { 5439 // Error from installer 5440 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5441 "Unable to create data dirs [errorCode=" + ret + "]"); 5442 } 5443 5444 if (dataPath.exists()) { 5445 pkg.applicationInfo.dataDir = dataPath.getPath(); 5446 } else { 5447 Slog.w(TAG, "Unable to create data directory: " + dataPath); 5448 pkg.applicationInfo.dataDir = null; 5449 } 5450 } 5451 5452 pkgSetting.uidError = uidError; 5453 } 5454 5455 final String path = scanFile.getPath(); 5456 final String codePath = pkg.applicationInfo.getCodePath(); 5457 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 5458 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 5459 setBundledAppAbisAndRoots(pkg, pkgSetting); 5460 5461 // If we haven't found any native libraries for the app, check if it has 5462 // renderscript code. We'll need to force the app to 32 bit if it has 5463 // renderscript bitcode. 5464 if (pkg.applicationInfo.primaryCpuAbi == null 5465 && pkg.applicationInfo.secondaryCpuAbi == null 5466 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5467 NativeLibraryHelper.Handle handle = null; 5468 try { 5469 handle = NativeLibraryHelper.Handle.create(scanFile); 5470 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5471 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 5472 } 5473 } catch (IOException ioe) { 5474 Slog.w(TAG, "Error scanning system app : " + ioe); 5475 } finally { 5476 IoUtils.closeQuietly(handle); 5477 } 5478 } 5479 5480 setNativeLibraryPaths(pkg); 5481 } else { 5482 // TODO: We can probably be smarter about this stuff. For installed apps, 5483 // we can calculate this information at install time once and for all. For 5484 // system apps, we can probably assume that this information doesn't change 5485 // after the first boot scan. As things stand, we do lots of unnecessary work. 5486 5487 // Give ourselves some initial paths; we'll come back for another 5488 // pass once we've determined ABI below. 5489 setNativeLibraryPaths(pkg); 5490 5491 final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg); 5492 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 5493 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 5494 5495 NativeLibraryHelper.Handle handle = null; 5496 try { 5497 handle = NativeLibraryHelper.Handle.create(scanFile); 5498 // TODO(multiArch): This can be null for apps that didn't go through the 5499 // usual installation process. We can calculate it again, like we 5500 // do during install time. 5501 // 5502 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 5503 // unnecessary. 5504 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 5505 5506 // Null out the abis so that they can be recalculated. 5507 pkg.applicationInfo.primaryCpuAbi = null; 5508 pkg.applicationInfo.secondaryCpuAbi = null; 5509 if (isMultiArch(pkg.applicationInfo)) { 5510 // Warn if we've set an abiOverride for multi-lib packages.. 5511 // By definition, we need to copy both 32 and 64 bit libraries for 5512 // such packages. 5513 if (pkg.cpuAbiOverride != null && !CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 5514 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 5515 } 5516 5517 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 5518 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 5519 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 5520 if (isAsec) { 5521 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 5522 } else { 5523 abi32 = copyNativeLibrariesForInternalApp(handle, 5524 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, useIsaSpecificSubdirs); 5525 } 5526 } 5527 5528 maybeThrowExceptionForMultiArchCopy( 5529 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 5530 5531 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5532 if (isAsec) { 5533 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 5534 } else { 5535 abi64 = copyNativeLibrariesForInternalApp(handle, 5536 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, useIsaSpecificSubdirs); 5537 } 5538 } 5539 5540 maybeThrowExceptionForMultiArchCopy( 5541 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 5542 5543 if (abi64 >= 0) { 5544 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 5545 } 5546 5547 if (abi32 >= 0) { 5548 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 5549 if (abi64 >= 0) { 5550 pkg.applicationInfo.secondaryCpuAbi = abi; 5551 } else { 5552 pkg.applicationInfo.primaryCpuAbi = abi; 5553 } 5554 } 5555 } else { 5556 String[] abiList = (cpuAbiOverride != null) ? 5557 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 5558 5559 // Enable gross and lame hacks for apps that are built with old 5560 // SDK tools. We must scan their APKs for renderscript bitcode and 5561 // not launch them if it's present. Don't bother checking on devices 5562 // that don't have 64 bit support. 5563 boolean needsRenderScriptOverride = false; 5564 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 5565 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5566 abiList = Build.SUPPORTED_32_BIT_ABIS; 5567 needsRenderScriptOverride = true; 5568 } 5569 5570 final int copyRet; 5571 if (isAsec) { 5572 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 5573 } else { 5574 copyRet = copyNativeLibrariesForInternalApp(handle, nativeLibraryRoot, abiList, 5575 useIsaSpecificSubdirs); 5576 } 5577 5578 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5579 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5580 "Error unpackaging native libs for app, errorCode=" + copyRet); 5581 } 5582 5583 if (copyRet >= 0) { 5584 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 5585 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 5586 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 5587 } else if (needsRenderScriptOverride) { 5588 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 5589 } 5590 } 5591 } catch (IOException ioe) { 5592 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 5593 } finally { 5594 IoUtils.closeQuietly(handle); 5595 } 5596 5597 // Now that we've calculated the ABIs and determined if it's an internal app, 5598 // we will go ahead and populate the nativeLibraryPath. 5599 setNativeLibraryPaths(pkg); 5600 5601 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 5602 final int[] userIds = sUserManager.getUserIds(); 5603 synchronized (mInstallLock) { 5604 // Create a native library symlink only if we have native libraries 5605 // and if the native libraries are 32 bit libraries. We do not provide 5606 // this symlink for 64 bit libraries. 5607 if (pkg.applicationInfo.primaryCpuAbi != null && 5608 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 5609 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 5610 for (int userId : userIds) { 5611 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 5612 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5613 "Failed linking native library dir (user=" + userId + ")"); 5614 } 5615 } 5616 } 5617 } 5618 } 5619 5620 // This is a special case for the "system" package, where the ABI is 5621 // dictated by the zygote configuration (and init.rc). We should keep track 5622 // of this ABI so that we can deal with "normal" applications that run under 5623 // the same UID correctly. 5624 if (mPlatformPackage == pkg) { 5625 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 5626 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 5627 } 5628 5629 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 5630 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 5631 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 5632 // Copy the derived override back to the parsed package, so that we can 5633 // update the package settings accordingly. 5634 pkg.cpuAbiOverride = cpuAbiOverride; 5635 5636 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 5637 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 5638 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 5639 5640 // Push the derived path down into PackageSettings so we know what to 5641 // clean up at uninstall time. 5642 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 5643 5644 if (DEBUG_ABI_SELECTION) { 5645 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 5646 " primary=" + pkg.applicationInfo.primaryCpuAbi + 5647 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 5648 } 5649 5650 if ((scanMode&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 5651 // We don't do this here during boot because we can do it all 5652 // at once after scanning all existing packages. 5653 // 5654 // We also do this *before* we perform dexopt on this package, so that 5655 // we can avoid redundant dexopts, and also to make sure we've got the 5656 // code and package path correct. 5657 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 5658 pkg, forceDex, (scanMode & SCAN_DEFER_DEX) != 0); 5659 } 5660 5661 if ((scanMode&SCAN_NO_DEX) == 0) { 5662 if (performDexOptLI(pkg, null /* instruction sets */, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5663 == DEX_OPT_FAILED) { 5664 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5665 removeDataDirsLI(pkg.packageName); 5666 } 5667 5668 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 5669 } 5670 } 5671 5672 if (mFactoryTest && pkg.requestedPermissions.contains( 5673 android.Manifest.permission.FACTORY_TEST)) { 5674 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 5675 } 5676 5677 ArrayList<PackageParser.Package> clientLibPkgs = null; 5678 5679 // writer 5680 synchronized (mPackages) { 5681 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5682 // Only system apps can add new shared libraries. 5683 if (pkg.libraryNames != null) { 5684 for (int i=0; i<pkg.libraryNames.size(); i++) { 5685 String name = pkg.libraryNames.get(i); 5686 boolean allowed = false; 5687 if (isUpdatedSystemApp(pkg)) { 5688 // New library entries can only be added through the 5689 // system image. This is important to get rid of a lot 5690 // of nasty edge cases: for example if we allowed a non- 5691 // system update of the app to add a library, then uninstalling 5692 // the update would make the library go away, and assumptions 5693 // we made such as through app install filtering would now 5694 // have allowed apps on the device which aren't compatible 5695 // with it. Better to just have the restriction here, be 5696 // conservative, and create many fewer cases that can negatively 5697 // impact the user experience. 5698 final PackageSetting sysPs = mSettings 5699 .getDisabledSystemPkgLPr(pkg.packageName); 5700 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 5701 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 5702 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 5703 allowed = true; 5704 allowed = true; 5705 break; 5706 } 5707 } 5708 } 5709 } else { 5710 allowed = true; 5711 } 5712 if (allowed) { 5713 if (!mSharedLibraries.containsKey(name)) { 5714 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 5715 } else if (!name.equals(pkg.packageName)) { 5716 Slog.w(TAG, "Package " + pkg.packageName + " library " 5717 + name + " already exists; skipping"); 5718 } 5719 } else { 5720 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 5721 + name + " that is not declared on system image; skipping"); 5722 } 5723 } 5724 if ((scanMode&SCAN_BOOTING) == 0) { 5725 // If we are not booting, we need to update any applications 5726 // that are clients of our shared library. If we are booting, 5727 // this will all be done once the scan is complete. 5728 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 5729 } 5730 } 5731 } 5732 } 5733 5734 // We also need to dexopt any apps that are dependent on this library. Note that 5735 // if these fail, we should abort the install since installing the library will 5736 // result in some apps being broken. 5737 if (clientLibPkgs != null) { 5738 if ((scanMode&SCAN_NO_DEX) == 0) { 5739 for (int i=0; i<clientLibPkgs.size(); i++) { 5740 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5741 if (performDexOptLI(clientPkg, null /* instruction sets */, 5742 forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5743 == DEX_OPT_FAILED) { 5744 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5745 removeDataDirsLI(pkg.packageName); 5746 } 5747 5748 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 5749 "scanPackageLI failed to dexopt clientLibPkgs"); 5750 } 5751 } 5752 } 5753 } 5754 5755 // Request the ActivityManager to kill the process(only for existing packages) 5756 // so that we do not end up in a confused state while the user is still using the older 5757 // version of the application while the new one gets installed. 5758 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 5759 // If the package lives in an asec, tell everyone that the container is going 5760 // away so they can clean up any references to its resources (which would prevent 5761 // vold from being able to unmount the asec) 5762 if (isForwardLocked(pkg) || isExternal(pkg)) { 5763 if (DEBUG_INSTALL) { 5764 Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE"); 5765 } 5766 final int[] uidArray = new int[] { pkg.applicationInfo.uid }; 5767 final ArrayList<String> pkgList = new ArrayList<String>(1); 5768 pkgList.add(pkg.applicationInfo.packageName); 5769 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 5770 } 5771 5772 // Post the request that it be killed now that the going-away broadcast is en route 5773 killApplication(pkg.applicationInfo.packageName, 5774 pkg.applicationInfo.uid, "update pkg"); 5775 } 5776 5777 // Also need to kill any apps that are dependent on the library. 5778 if (clientLibPkgs != null) { 5779 for (int i=0; i<clientLibPkgs.size(); i++) { 5780 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5781 killApplication(clientPkg.applicationInfo.packageName, 5782 clientPkg.applicationInfo.uid, "update lib"); 5783 } 5784 } 5785 5786 // writer 5787 synchronized (mPackages) { 5788 // We don't expect installation to fail beyond this point, 5789 if ((scanMode&SCAN_MONITOR) != 0) { 5790 mAppDirs.put(pkg.codePath, pkg); 5791 } 5792 // Add the new setting to mSettings 5793 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 5794 // Add the new setting to mPackages 5795 mPackages.put(pkg.applicationInfo.packageName, pkg); 5796 // Make sure we don't accidentally delete its data. 5797 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 5798 while (iter.hasNext()) { 5799 PackageCleanItem item = iter.next(); 5800 if (pkgName.equals(item.packageName)) { 5801 iter.remove(); 5802 } 5803 } 5804 5805 // Take care of first install / last update times. 5806 if (currentTime != 0) { 5807 if (pkgSetting.firstInstallTime == 0) { 5808 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 5809 } else if ((scanMode&SCAN_UPDATE_TIME) != 0) { 5810 pkgSetting.lastUpdateTime = currentTime; 5811 } 5812 } else if (pkgSetting.firstInstallTime == 0) { 5813 // We need *something*. Take time time stamp of the file. 5814 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 5815 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 5816 if (scanFileTime != pkgSetting.timeStamp) { 5817 // A package on the system image has changed; consider this 5818 // to be an update. 5819 pkgSetting.lastUpdateTime = scanFileTime; 5820 } 5821 } 5822 5823 // Add the package's KeySets to the global KeySetManagerService 5824 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5825 try { 5826 // Old KeySetData no longer valid. 5827 ksms.removeAppKeySetDataLPw(pkg.packageName); 5828 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 5829 if (pkg.mKeySetMapping != null) { 5830 for (Map.Entry<String, ArraySet<PublicKey>> entry : 5831 pkg.mKeySetMapping.entrySet()) { 5832 if (entry.getValue() != null) { 5833 ksms.addDefinedKeySetToPackageLPw(pkg.packageName, 5834 entry.getValue(), entry.getKey()); 5835 } 5836 } 5837 if (pkg.mUpgradeKeySets != null) { 5838 for (String upgradeAlias : pkg.mUpgradeKeySets) { 5839 ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias); 5840 } 5841 } 5842 } 5843 } catch (NullPointerException e) { 5844 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 5845 } catch (IllegalArgumentException e) { 5846 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 5847 } 5848 5849 int N = pkg.providers.size(); 5850 StringBuilder r = null; 5851 int i; 5852 for (i=0; i<N; i++) { 5853 PackageParser.Provider p = pkg.providers.get(i); 5854 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 5855 p.info.processName, pkg.applicationInfo.uid); 5856 mProviders.addProvider(p); 5857 p.syncable = p.info.isSyncable; 5858 if (p.info.authority != null) { 5859 String names[] = p.info.authority.split(";"); 5860 p.info.authority = null; 5861 for (int j = 0; j < names.length; j++) { 5862 if (j == 1 && p.syncable) { 5863 // We only want the first authority for a provider to possibly be 5864 // syncable, so if we already added this provider using a different 5865 // authority clear the syncable flag. We copy the provider before 5866 // changing it because the mProviders object contains a reference 5867 // to a provider that we don't want to change. 5868 // Only do this for the second authority since the resulting provider 5869 // object can be the same for all future authorities for this provider. 5870 p = new PackageParser.Provider(p); 5871 p.syncable = false; 5872 } 5873 if (!mProvidersByAuthority.containsKey(names[j])) { 5874 mProvidersByAuthority.put(names[j], p); 5875 if (p.info.authority == null) { 5876 p.info.authority = names[j]; 5877 } else { 5878 p.info.authority = p.info.authority + ";" + names[j]; 5879 } 5880 if (DEBUG_PACKAGE_SCANNING) { 5881 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5882 Log.d(TAG, "Registered content provider: " + names[j] 5883 + ", className = " + p.info.name + ", isSyncable = " 5884 + p.info.isSyncable); 5885 } 5886 } else { 5887 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5888 Slog.w(TAG, "Skipping provider name " + names[j] + 5889 " (in package " + pkg.applicationInfo.packageName + 5890 "): name already used by " 5891 + ((other != null && other.getComponentName() != null) 5892 ? other.getComponentName().getPackageName() : "?")); 5893 } 5894 } 5895 } 5896 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5897 if (r == null) { 5898 r = new StringBuilder(256); 5899 } else { 5900 r.append(' '); 5901 } 5902 r.append(p.info.name); 5903 } 5904 } 5905 if (r != null) { 5906 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 5907 } 5908 5909 N = pkg.services.size(); 5910 r = null; 5911 for (i=0; i<N; i++) { 5912 PackageParser.Service s = pkg.services.get(i); 5913 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 5914 s.info.processName, pkg.applicationInfo.uid); 5915 mServices.addService(s); 5916 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5917 if (r == null) { 5918 r = new StringBuilder(256); 5919 } else { 5920 r.append(' '); 5921 } 5922 r.append(s.info.name); 5923 } 5924 } 5925 if (r != null) { 5926 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 5927 } 5928 5929 N = pkg.receivers.size(); 5930 r = null; 5931 for (i=0; i<N; i++) { 5932 PackageParser.Activity a = pkg.receivers.get(i); 5933 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5934 a.info.processName, pkg.applicationInfo.uid); 5935 mReceivers.addActivity(a, "receiver"); 5936 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5937 if (r == null) { 5938 r = new StringBuilder(256); 5939 } else { 5940 r.append(' '); 5941 } 5942 r.append(a.info.name); 5943 } 5944 } 5945 if (r != null) { 5946 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 5947 } 5948 5949 N = pkg.activities.size(); 5950 r = null; 5951 for (i=0; i<N; i++) { 5952 PackageParser.Activity a = pkg.activities.get(i); 5953 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5954 a.info.processName, pkg.applicationInfo.uid); 5955 mActivities.addActivity(a, "activity"); 5956 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5957 if (r == null) { 5958 r = new StringBuilder(256); 5959 } else { 5960 r.append(' '); 5961 } 5962 r.append(a.info.name); 5963 } 5964 } 5965 if (r != null) { 5966 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 5967 } 5968 5969 N = pkg.permissionGroups.size(); 5970 r = null; 5971 for (i=0; i<N; i++) { 5972 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 5973 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 5974 if (cur == null) { 5975 mPermissionGroups.put(pg.info.name, pg); 5976 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5977 if (r == null) { 5978 r = new StringBuilder(256); 5979 } else { 5980 r.append(' '); 5981 } 5982 r.append(pg.info.name); 5983 } 5984 } else { 5985 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 5986 + pg.info.packageName + " ignored: original from " 5987 + cur.info.packageName); 5988 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5989 if (r == null) { 5990 r = new StringBuilder(256); 5991 } else { 5992 r.append(' '); 5993 } 5994 r.append("DUP:"); 5995 r.append(pg.info.name); 5996 } 5997 } 5998 } 5999 if (r != null) { 6000 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6001 } 6002 6003 N = pkg.permissions.size(); 6004 r = null; 6005 for (i=0; i<N; i++) { 6006 PackageParser.Permission p = pkg.permissions.get(i); 6007 HashMap<String, BasePermission> permissionMap = 6008 p.tree ? mSettings.mPermissionTrees 6009 : mSettings.mPermissions; 6010 p.group = mPermissionGroups.get(p.info.group); 6011 if (p.info.group == null || p.group != null) { 6012 BasePermission bp = permissionMap.get(p.info.name); 6013 if (bp == null) { 6014 bp = new BasePermission(p.info.name, p.info.packageName, 6015 BasePermission.TYPE_NORMAL); 6016 permissionMap.put(p.info.name, bp); 6017 } 6018 if (bp.perm == null) { 6019 if (bp.sourcePackage != null 6020 && !bp.sourcePackage.equals(p.info.packageName)) { 6021 // If this is a permission that was formerly defined by a non-system 6022 // app, but is now defined by a system app (following an upgrade), 6023 // discard the previous declaration and consider the system's to be 6024 // canonical. 6025 if (isSystemApp(p.owner)) { 6026 String msg = "New decl " + p.owner + " of permission " 6027 + p.info.name + " is system"; 6028 reportSettingsProblem(Log.WARN, msg); 6029 bp.sourcePackage = null; 6030 } 6031 } 6032 if (bp.sourcePackage == null 6033 || bp.sourcePackage.equals(p.info.packageName)) { 6034 BasePermission tree = findPermissionTreeLP(p.info.name); 6035 if (tree == null 6036 || tree.sourcePackage.equals(p.info.packageName)) { 6037 bp.packageSetting = pkgSetting; 6038 bp.perm = p; 6039 bp.uid = pkg.applicationInfo.uid; 6040 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6041 if (r == null) { 6042 r = new StringBuilder(256); 6043 } else { 6044 r.append(' '); 6045 } 6046 r.append(p.info.name); 6047 } 6048 } else { 6049 Slog.w(TAG, "Permission " + p.info.name + " from package " 6050 + p.info.packageName + " ignored: base tree " 6051 + tree.name + " is from package " 6052 + tree.sourcePackage); 6053 } 6054 } else { 6055 Slog.w(TAG, "Permission " + p.info.name + " from package " 6056 + p.info.packageName + " ignored: original from " 6057 + bp.sourcePackage); 6058 } 6059 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6060 if (r == null) { 6061 r = new StringBuilder(256); 6062 } else { 6063 r.append(' '); 6064 } 6065 r.append("DUP:"); 6066 r.append(p.info.name); 6067 } 6068 if (bp.perm == p) { 6069 bp.protectionLevel = p.info.protectionLevel; 6070 } 6071 } else { 6072 Slog.w(TAG, "Permission " + p.info.name + " from package " 6073 + p.info.packageName + " ignored: no group " 6074 + p.group); 6075 } 6076 } 6077 if (r != null) { 6078 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6079 } 6080 6081 N = pkg.instrumentation.size(); 6082 r = null; 6083 for (i=0; i<N; i++) { 6084 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6085 a.info.packageName = pkg.applicationInfo.packageName; 6086 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6087 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6088 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6089 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6090 a.info.dataDir = pkg.applicationInfo.dataDir; 6091 6092 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6093 // need other information about the application, like the ABI and what not ? 6094 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6095 mInstrumentation.put(a.getComponentName(), a); 6096 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6097 if (r == null) { 6098 r = new StringBuilder(256); 6099 } else { 6100 r.append(' '); 6101 } 6102 r.append(a.info.name); 6103 } 6104 } 6105 if (r != null) { 6106 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6107 } 6108 6109 if (pkg.protectedBroadcasts != null) { 6110 N = pkg.protectedBroadcasts.size(); 6111 for (i=0; i<N; i++) { 6112 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6113 } 6114 } 6115 6116 pkgSetting.setTimeStamp(scanFileTime); 6117 6118 // Create idmap files for pairs of (packages, overlay packages). 6119 // Note: "android", ie framework-res.apk, is handled by native layers. 6120 if (pkg.mOverlayTarget != null) { 6121 // This is an overlay package. 6122 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6123 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6124 mOverlays.put(pkg.mOverlayTarget, 6125 new HashMap<String, PackageParser.Package>()); 6126 } 6127 HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6128 map.put(pkg.packageName, pkg); 6129 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6130 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6131 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6132 "scanPackageLI failed to createIdmap"); 6133 } 6134 } 6135 } else if (mOverlays.containsKey(pkg.packageName) && 6136 !pkg.packageName.equals("android")) { 6137 // This is a regular package, with one or more known overlay packages. 6138 createIdmapsForPackageLI(pkg); 6139 } 6140 } 6141 6142 return pkg; 6143 } 6144 6145 /** 6146 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6147 * i.e, so that all packages can be run inside a single process if required. 6148 * 6149 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6150 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6151 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6152 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6153 * updating a package that belongs to a shared user. 6154 * 6155 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6156 * adds unnecessary complexity. 6157 */ 6158 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6159 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6160 String requiredInstructionSet = null; 6161 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6162 requiredInstructionSet = VMRuntime.getInstructionSet( 6163 scannedPackage.applicationInfo.primaryCpuAbi); 6164 } 6165 6166 PackageSetting requirer = null; 6167 for (PackageSetting ps : packagesForUser) { 6168 // If packagesForUser contains scannedPackage, we skip it. This will happen 6169 // when scannedPackage is an update of an existing package. Without this check, 6170 // we will never be able to change the ABI of any package belonging to a shared 6171 // user, even if it's compatible with other packages. 6172 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6173 if (ps.primaryCpuAbiString == null) { 6174 continue; 6175 } 6176 6177 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6178 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6179 // We have a mismatch between instruction sets (say arm vs arm64) warn about 6180 // this but there's not much we can do. 6181 String errorMessage = "Instruction set mismatch, " 6182 + ((requirer == null) ? "[caller]" : requirer) 6183 + " requires " + requiredInstructionSet + " whereas " + ps 6184 + " requires " + instructionSet; 6185 Slog.w(TAG, errorMessage); 6186 } 6187 6188 if (requiredInstructionSet == null) { 6189 requiredInstructionSet = instructionSet; 6190 requirer = ps; 6191 } 6192 } 6193 } 6194 6195 if (requiredInstructionSet != null) { 6196 String adjustedAbi; 6197 if (requirer != null) { 6198 // requirer != null implies that either scannedPackage was null or that scannedPackage 6199 // did not require an ABI, in which case we have to adjust scannedPackage to match 6200 // the ABI of the set (which is the same as requirer's ABI) 6201 adjustedAbi = requirer.primaryCpuAbiString; 6202 if (scannedPackage != null) { 6203 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6204 } 6205 } else { 6206 // requirer == null implies that we're updating all ABIs in the set to 6207 // match scannedPackage. 6208 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6209 } 6210 6211 for (PackageSetting ps : packagesForUser) { 6212 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6213 if (ps.primaryCpuAbiString != null) { 6214 continue; 6215 } 6216 6217 ps.primaryCpuAbiString = adjustedAbi; 6218 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6219 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6220 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6221 6222 if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt, 6223 deferDexOpt, true) == DEX_OPT_FAILED) { 6224 ps.primaryCpuAbiString = null; 6225 ps.pkg.applicationInfo.primaryCpuAbi = null; 6226 return; 6227 } else { 6228 mInstaller.rmdex(ps.codePathString, 6229 getDexCodeInstructionSet(getPreferredInstructionSet())); 6230 } 6231 } 6232 } 6233 } 6234 } 6235 } 6236 6237 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6238 synchronized (mPackages) { 6239 mResolverReplaced = true; 6240 // Set up information for custom user intent resolution activity. 6241 mResolveActivity.applicationInfo = pkg.applicationInfo; 6242 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6243 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6244 mResolveActivity.processName = null; 6245 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6246 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6247 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6248 mResolveActivity.theme = 0; 6249 mResolveActivity.exported = true; 6250 mResolveActivity.enabled = true; 6251 mResolveInfo.activityInfo = mResolveActivity; 6252 mResolveInfo.priority = 0; 6253 mResolveInfo.preferredOrder = 0; 6254 mResolveInfo.match = 0; 6255 mResolveComponentName = mCustomResolverComponentName; 6256 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6257 mResolveComponentName); 6258 } 6259 } 6260 6261 private static String calculateBundledApkRoot(final String codePathString) { 6262 final File codePath = new File(codePathString); 6263 final File codeRoot; 6264 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6265 codeRoot = Environment.getRootDirectory(); 6266 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6267 codeRoot = Environment.getOemDirectory(); 6268 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6269 codeRoot = Environment.getVendorDirectory(); 6270 } else { 6271 // Unrecognized code path; take its top real segment as the apk root: 6272 // e.g. /something/app/blah.apk => /something 6273 try { 6274 File f = codePath.getCanonicalFile(); 6275 File parent = f.getParentFile(); // non-null because codePath is a file 6276 File tmp; 6277 while ((tmp = parent.getParentFile()) != null) { 6278 f = parent; 6279 parent = tmp; 6280 } 6281 codeRoot = f; 6282 Slog.w(TAG, "Unrecognized code path " 6283 + codePath + " - using " + codeRoot); 6284 } catch (IOException e) { 6285 // Can't canonicalize the code path -- shenanigans? 6286 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6287 return Environment.getRootDirectory().getPath(); 6288 } 6289 } 6290 return codeRoot.getPath(); 6291 } 6292 6293 /** 6294 * Derive and set the location of native libraries for the given package, 6295 * which varies depending on where and how the package was installed. 6296 */ 6297 private void setNativeLibraryPaths(PackageParser.Package pkg) { 6298 final ApplicationInfo info = pkg.applicationInfo; 6299 final String codePath = pkg.codePath; 6300 final File codeFile = new File(codePath); 6301 final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info); 6302 final boolean asecApp = isForwardLocked(info) || isExternal(info); 6303 6304 info.nativeLibraryRootDir = null; 6305 info.nativeLibraryRootRequiresIsa = false; 6306 info.nativeLibraryDir = null; 6307 info.secondaryNativeLibraryDir = null; 6308 6309 if (isApkFile(codeFile)) { 6310 // Monolithic install 6311 if (bundledApp) { 6312 // If "/system/lib64/apkname" exists, assume that is the per-package 6313 // native library directory to use; otherwise use "/system/lib/apkname". 6314 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 6315 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 6316 getPrimaryInstructionSet(info)); 6317 6318 // This is a bundled system app so choose the path based on the ABI. 6319 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 6320 // is just the default path. 6321 final String apkName = deriveCodePathName(codePath); 6322 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 6323 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 6324 apkName).getAbsolutePath(); 6325 6326 if (info.secondaryCpuAbi != null) { 6327 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 6328 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 6329 secondaryLibDir, apkName).getAbsolutePath(); 6330 } 6331 } else if (asecApp) { 6332 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 6333 .getAbsolutePath(); 6334 } else { 6335 final String apkName = deriveCodePathName(codePath); 6336 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 6337 .getAbsolutePath(); 6338 } 6339 6340 info.nativeLibraryRootRequiresIsa = false; 6341 info.nativeLibraryDir = info.nativeLibraryRootDir; 6342 } else { 6343 // Cluster install 6344 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 6345 info.nativeLibraryRootRequiresIsa = true; 6346 6347 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 6348 getPrimaryInstructionSet(info)).getAbsolutePath(); 6349 6350 if (info.secondaryCpuAbi != null) { 6351 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 6352 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 6353 } 6354 } 6355 } 6356 6357 /** 6358 * Calculate the abis and roots for a bundled app. These can uniquely 6359 * be determined from the contents of the system partition, i.e whether 6360 * it contains 64 or 32 bit shared libraries etc. We do not validate any 6361 * of this information, and instead assume that the system was built 6362 * sensibly. 6363 */ 6364 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 6365 PackageSetting pkgSetting) { 6366 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 6367 6368 // If "/system/lib64/apkname" exists, assume that is the per-package 6369 // native library directory to use; otherwise use "/system/lib/apkname". 6370 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 6371 setBundledAppAbi(pkg, apkRoot, apkName); 6372 // pkgSetting might be null during rescan following uninstall of updates 6373 // to a bundled app, so accommodate that possibility. The settings in 6374 // that case will be established later from the parsed package. 6375 // 6376 // If the settings aren't null, sync them up with what we've just derived. 6377 // note that apkRoot isn't stored in the package settings. 6378 if (pkgSetting != null) { 6379 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6380 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6381 } 6382 } 6383 6384 /** 6385 * Deduces the ABI of a bundled app and sets the relevant fields on the 6386 * parsed pkg object. 6387 * 6388 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 6389 * under which system libraries are installed. 6390 * @param apkName the name of the installed package. 6391 */ 6392 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 6393 final File codeFile = new File(pkg.codePath); 6394 6395 final boolean has64BitLibs; 6396 final boolean has32BitLibs; 6397 if (isApkFile(codeFile)) { 6398 // Monolithic install 6399 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 6400 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 6401 } else { 6402 // Cluster install 6403 final File rootDir = new File(codeFile, LIB_DIR_NAME); 6404 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 6405 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 6406 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 6407 has64BitLibs = (new File(rootDir, isa)).exists(); 6408 } else { 6409 has64BitLibs = false; 6410 } 6411 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 6412 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 6413 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 6414 has32BitLibs = (new File(rootDir, isa)).exists(); 6415 } else { 6416 has32BitLibs = false; 6417 } 6418 } 6419 6420 if (has64BitLibs && !has32BitLibs) { 6421 // The package has 64 bit libs, but not 32 bit libs. Its primary 6422 // ABI should be 64 bit. We can safely assume here that the bundled 6423 // native libraries correspond to the most preferred ABI in the list. 6424 6425 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6426 pkg.applicationInfo.secondaryCpuAbi = null; 6427 } else if (has32BitLibs && !has64BitLibs) { 6428 // The package has 32 bit libs but not 64 bit libs. Its primary 6429 // ABI should be 32 bit. 6430 6431 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6432 pkg.applicationInfo.secondaryCpuAbi = null; 6433 } else if (has32BitLibs && has64BitLibs) { 6434 // The application has both 64 and 32 bit bundled libraries. We check 6435 // here that the app declares multiArch support, and warn if it doesn't. 6436 // 6437 // We will be lenient here and record both ABIs. The primary will be the 6438 // ABI that's higher on the list, i.e, a device that's configured to prefer 6439 // 64 bit apps will see a 64 bit primary ABI, 6440 6441 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 6442 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 6443 } 6444 6445 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 6446 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6447 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6448 } else { 6449 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6450 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6451 } 6452 } else { 6453 pkg.applicationInfo.primaryCpuAbi = null; 6454 pkg.applicationInfo.secondaryCpuAbi = null; 6455 } 6456 } 6457 6458 private static void createNativeLibrarySubdir(File path) throws IOException { 6459 if (!path.isDirectory()) { 6460 path.delete(); 6461 6462 if (!path.mkdir()) { 6463 throw new IOException("Cannot create " + path.getPath()); 6464 } 6465 6466 try { 6467 Os.chmod(path.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); 6468 } catch (ErrnoException e) { 6469 throw new IOException("Cannot chmod native library directory " 6470 + path.getPath(), e); 6471 } 6472 } else if (!SELinux.restorecon(path)) { 6473 throw new IOException("Cannot set SELinux context for " + path.getPath()); 6474 } 6475 } 6476 6477 private static int copyNativeLibrariesForInternalApp(NativeLibraryHelper.Handle handle, 6478 final File nativeLibraryRoot, String[] abiList, boolean useIsaSubdir) throws IOException { 6479 createNativeLibrarySubdir(nativeLibraryRoot); 6480 6481 /* 6482 * If this is an internal application or our nativeLibraryPath points to 6483 * the app-lib directory, unpack the libraries if necessary. 6484 */ 6485 int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList); 6486 if (abi >= 0) { 6487 /* 6488 * If we have a matching instruction set, construct a subdir under the native 6489 * library root that corresponds to this instruction set. 6490 */ 6491 final String instructionSet = VMRuntime.getInstructionSet(abiList[abi]); 6492 final File subDir; 6493 if (useIsaSubdir) { 6494 final File isaSubdir = new File(nativeLibraryRoot, instructionSet); 6495 createNativeLibrarySubdir(isaSubdir); 6496 subDir = isaSubdir; 6497 } else { 6498 subDir = nativeLibraryRoot; 6499 } 6500 6501 int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle, subDir, abiList[abi]); 6502 if (copyRet != PackageManager.INSTALL_SUCCEEDED) { 6503 return copyRet; 6504 } 6505 } 6506 6507 return abi; 6508 } 6509 6510 private void killApplication(String pkgName, int appId, String reason) { 6511 // Request the ActivityManager to kill the process(only for existing packages) 6512 // so that we do not end up in a confused state while the user is still using the older 6513 // version of the application while the new one gets installed. 6514 IActivityManager am = ActivityManagerNative.getDefault(); 6515 if (am != null) { 6516 try { 6517 am.killApplicationWithAppId(pkgName, appId, reason); 6518 } catch (RemoteException e) { 6519 } 6520 } 6521 } 6522 6523 void removePackageLI(PackageSetting ps, boolean chatty) { 6524 if (DEBUG_INSTALL) { 6525 if (chatty) 6526 Log.d(TAG, "Removing package " + ps.name); 6527 } 6528 6529 // writer 6530 synchronized (mPackages) { 6531 mPackages.remove(ps.name); 6532 if (ps.codePathString != null) { 6533 mAppDirs.remove(ps.codePathString); 6534 } 6535 6536 final PackageParser.Package pkg = ps.pkg; 6537 if (pkg != null) { 6538 cleanPackageDataStructuresLILPw(pkg, chatty); 6539 } 6540 } 6541 } 6542 6543 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 6544 if (DEBUG_INSTALL) { 6545 if (chatty) 6546 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 6547 } 6548 6549 // writer 6550 synchronized (mPackages) { 6551 mPackages.remove(pkg.applicationInfo.packageName); 6552 if (pkg.codePath != null) { 6553 mAppDirs.remove(pkg.codePath); 6554 } 6555 cleanPackageDataStructuresLILPw(pkg, chatty); 6556 } 6557 } 6558 6559 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 6560 int N = pkg.providers.size(); 6561 StringBuilder r = null; 6562 int i; 6563 for (i=0; i<N; i++) { 6564 PackageParser.Provider p = pkg.providers.get(i); 6565 mProviders.removeProvider(p); 6566 if (p.info.authority == null) { 6567 6568 /* There was another ContentProvider with this authority when 6569 * this app was installed so this authority is null, 6570 * Ignore it as we don't have to unregister the provider. 6571 */ 6572 continue; 6573 } 6574 String names[] = p.info.authority.split(";"); 6575 for (int j = 0; j < names.length; j++) { 6576 if (mProvidersByAuthority.get(names[j]) == p) { 6577 mProvidersByAuthority.remove(names[j]); 6578 if (DEBUG_REMOVE) { 6579 if (chatty) 6580 Log.d(TAG, "Unregistered content provider: " + names[j] 6581 + ", className = " + p.info.name + ", isSyncable = " 6582 + p.info.isSyncable); 6583 } 6584 } 6585 } 6586 if (DEBUG_REMOVE && chatty) { 6587 if (r == null) { 6588 r = new StringBuilder(256); 6589 } else { 6590 r.append(' '); 6591 } 6592 r.append(p.info.name); 6593 } 6594 } 6595 if (r != null) { 6596 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 6597 } 6598 6599 N = pkg.services.size(); 6600 r = null; 6601 for (i=0; i<N; i++) { 6602 PackageParser.Service s = pkg.services.get(i); 6603 mServices.removeService(s); 6604 if (chatty) { 6605 if (r == null) { 6606 r = new StringBuilder(256); 6607 } else { 6608 r.append(' '); 6609 } 6610 r.append(s.info.name); 6611 } 6612 } 6613 if (r != null) { 6614 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 6615 } 6616 6617 N = pkg.receivers.size(); 6618 r = null; 6619 for (i=0; i<N; i++) { 6620 PackageParser.Activity a = pkg.receivers.get(i); 6621 mReceivers.removeActivity(a, "receiver"); 6622 if (DEBUG_REMOVE && chatty) { 6623 if (r == null) { 6624 r = new StringBuilder(256); 6625 } else { 6626 r.append(' '); 6627 } 6628 r.append(a.info.name); 6629 } 6630 } 6631 if (r != null) { 6632 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 6633 } 6634 6635 N = pkg.activities.size(); 6636 r = null; 6637 for (i=0; i<N; i++) { 6638 PackageParser.Activity a = pkg.activities.get(i); 6639 mActivities.removeActivity(a, "activity"); 6640 if (DEBUG_REMOVE && chatty) { 6641 if (r == null) { 6642 r = new StringBuilder(256); 6643 } else { 6644 r.append(' '); 6645 } 6646 r.append(a.info.name); 6647 } 6648 } 6649 if (r != null) { 6650 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 6651 } 6652 6653 N = pkg.permissions.size(); 6654 r = null; 6655 for (i=0; i<N; i++) { 6656 PackageParser.Permission p = pkg.permissions.get(i); 6657 BasePermission bp = mSettings.mPermissions.get(p.info.name); 6658 if (bp == null) { 6659 bp = mSettings.mPermissionTrees.get(p.info.name); 6660 } 6661 if (bp != null && bp.perm == p) { 6662 bp.perm = null; 6663 if (DEBUG_REMOVE && chatty) { 6664 if (r == null) { 6665 r = new StringBuilder(256); 6666 } else { 6667 r.append(' '); 6668 } 6669 r.append(p.info.name); 6670 } 6671 } 6672 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6673 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 6674 if (appOpPerms != null) { 6675 appOpPerms.remove(pkg.packageName); 6676 } 6677 } 6678 } 6679 if (r != null) { 6680 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6681 } 6682 6683 N = pkg.requestedPermissions.size(); 6684 r = null; 6685 for (i=0; i<N; i++) { 6686 String perm = pkg.requestedPermissions.get(i); 6687 BasePermission bp = mSettings.mPermissions.get(perm); 6688 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6689 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 6690 if (appOpPerms != null) { 6691 appOpPerms.remove(pkg.packageName); 6692 if (appOpPerms.isEmpty()) { 6693 mAppOpPermissionPackages.remove(perm); 6694 } 6695 } 6696 } 6697 } 6698 if (r != null) { 6699 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6700 } 6701 6702 N = pkg.instrumentation.size(); 6703 r = null; 6704 for (i=0; i<N; i++) { 6705 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6706 mInstrumentation.remove(a.getComponentName()); 6707 if (DEBUG_REMOVE && chatty) { 6708 if (r == null) { 6709 r = new StringBuilder(256); 6710 } else { 6711 r.append(' '); 6712 } 6713 r.append(a.info.name); 6714 } 6715 } 6716 if (r != null) { 6717 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 6718 } 6719 6720 r = null; 6721 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6722 // Only system apps can hold shared libraries. 6723 if (pkg.libraryNames != null) { 6724 for (i=0; i<pkg.libraryNames.size(); i++) { 6725 String name = pkg.libraryNames.get(i); 6726 SharedLibraryEntry cur = mSharedLibraries.get(name); 6727 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 6728 mSharedLibraries.remove(name); 6729 if (DEBUG_REMOVE && chatty) { 6730 if (r == null) { 6731 r = new StringBuilder(256); 6732 } else { 6733 r.append(' '); 6734 } 6735 r.append(name); 6736 } 6737 } 6738 } 6739 } 6740 } 6741 if (r != null) { 6742 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 6743 } 6744 } 6745 6746 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 6747 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 6748 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 6749 return true; 6750 } 6751 } 6752 return false; 6753 } 6754 6755 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 6756 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 6757 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 6758 6759 private void updatePermissionsLPw(String changingPkg, 6760 PackageParser.Package pkgInfo, int flags) { 6761 // Make sure there are no dangling permission trees. 6762 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 6763 while (it.hasNext()) { 6764 final BasePermission bp = it.next(); 6765 if (bp.packageSetting == null) { 6766 // We may not yet have parsed the package, so just see if 6767 // we still know about its settings. 6768 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6769 } 6770 if (bp.packageSetting == null) { 6771 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 6772 + " from package " + bp.sourcePackage); 6773 it.remove(); 6774 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6775 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6776 Slog.i(TAG, "Removing old permission tree: " + bp.name 6777 + " from package " + bp.sourcePackage); 6778 flags |= UPDATE_PERMISSIONS_ALL; 6779 it.remove(); 6780 } 6781 } 6782 } 6783 6784 // Make sure all dynamic permissions have been assigned to a package, 6785 // and make sure there are no dangling permissions. 6786 it = mSettings.mPermissions.values().iterator(); 6787 while (it.hasNext()) { 6788 final BasePermission bp = it.next(); 6789 if (bp.type == BasePermission.TYPE_DYNAMIC) { 6790 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 6791 + bp.name + " pkg=" + bp.sourcePackage 6792 + " info=" + bp.pendingInfo); 6793 if (bp.packageSetting == null && bp.pendingInfo != null) { 6794 final BasePermission tree = findPermissionTreeLP(bp.name); 6795 if (tree != null && tree.perm != null) { 6796 bp.packageSetting = tree.packageSetting; 6797 bp.perm = new PackageParser.Permission(tree.perm.owner, 6798 new PermissionInfo(bp.pendingInfo)); 6799 bp.perm.info.packageName = tree.perm.info.packageName; 6800 bp.perm.info.name = bp.name; 6801 bp.uid = tree.uid; 6802 } 6803 } 6804 } 6805 if (bp.packageSetting == null) { 6806 // We may not yet have parsed the package, so just see if 6807 // we still know about its settings. 6808 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6809 } 6810 if (bp.packageSetting == null) { 6811 Slog.w(TAG, "Removing dangling permission: " + bp.name 6812 + " from package " + bp.sourcePackage); 6813 it.remove(); 6814 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6815 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6816 Slog.i(TAG, "Removing old permission: " + bp.name 6817 + " from package " + bp.sourcePackage); 6818 flags |= UPDATE_PERMISSIONS_ALL; 6819 it.remove(); 6820 } 6821 } 6822 } 6823 6824 // Now update the permissions for all packages, in particular 6825 // replace the granted permissions of the system packages. 6826 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 6827 for (PackageParser.Package pkg : mPackages.values()) { 6828 if (pkg != pkgInfo) { 6829 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0); 6830 } 6831 } 6832 } 6833 6834 if (pkgInfo != null) { 6835 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0); 6836 } 6837 } 6838 6839 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) { 6840 final PackageSetting ps = (PackageSetting) pkg.mExtras; 6841 if (ps == null) { 6842 return; 6843 } 6844 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 6845 HashSet<String> origPermissions = gp.grantedPermissions; 6846 boolean changedPermission = false; 6847 6848 if (replace) { 6849 ps.permissionsFixed = false; 6850 if (gp == ps) { 6851 origPermissions = new HashSet<String>(gp.grantedPermissions); 6852 gp.grantedPermissions.clear(); 6853 gp.gids = mGlobalGids; 6854 } 6855 } 6856 6857 if (gp.gids == null) { 6858 gp.gids = mGlobalGids; 6859 } 6860 6861 final int N = pkg.requestedPermissions.size(); 6862 for (int i=0; i<N; i++) { 6863 final String name = pkg.requestedPermissions.get(i); 6864 final boolean required = pkg.requestedPermissionsRequired.get(i); 6865 final BasePermission bp = mSettings.mPermissions.get(name); 6866 if (DEBUG_INSTALL) { 6867 if (gp != ps) { 6868 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 6869 } 6870 } 6871 6872 if (bp == null || bp.packageSetting == null) { 6873 Slog.w(TAG, "Unknown permission " + name 6874 + " in package " + pkg.packageName); 6875 continue; 6876 } 6877 6878 final String perm = bp.name; 6879 boolean allowed; 6880 boolean allowedSig = false; 6881 if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6882 // Keep track of app op permissions. 6883 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 6884 if (pkgs == null) { 6885 pkgs = new ArraySet<>(); 6886 mAppOpPermissionPackages.put(bp.name, pkgs); 6887 } 6888 pkgs.add(pkg.packageName); 6889 } 6890 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 6891 if (level == PermissionInfo.PROTECTION_NORMAL 6892 || level == PermissionInfo.PROTECTION_DANGEROUS) { 6893 // We grant a normal or dangerous permission if any of the following 6894 // are true: 6895 // 1) The permission is required 6896 // 2) The permission is optional, but was granted in the past 6897 // 3) The permission is optional, but was requested by an 6898 // app in /system (not /data) 6899 // 6900 // Otherwise, reject the permission. 6901 allowed = (required || origPermissions.contains(perm) 6902 || (isSystemApp(ps) && !isUpdatedSystemApp(ps))); 6903 } else if (bp.packageSetting == null) { 6904 // This permission is invalid; skip it. 6905 allowed = false; 6906 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 6907 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions); 6908 if (allowed) { 6909 allowedSig = true; 6910 } 6911 } else { 6912 allowed = false; 6913 } 6914 if (DEBUG_INSTALL) { 6915 if (gp != ps) { 6916 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 6917 } 6918 } 6919 if (allowed) { 6920 if (!isSystemApp(ps) && ps.permissionsFixed) { 6921 // If this is an existing, non-system package, then 6922 // we can't add any new permissions to it. 6923 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 6924 // Except... if this is a permission that was added 6925 // to the platform (note: need to only do this when 6926 // updating the platform). 6927 allowed = isNewPlatformPermissionForPackage(perm, pkg); 6928 } 6929 } 6930 if (allowed) { 6931 if (!gp.grantedPermissions.contains(perm)) { 6932 changedPermission = true; 6933 gp.grantedPermissions.add(perm); 6934 gp.gids = appendInts(gp.gids, bp.gids); 6935 } else if (!ps.haveGids) { 6936 gp.gids = appendInts(gp.gids, bp.gids); 6937 } 6938 } else { 6939 Slog.w(TAG, "Not granting permission " + perm 6940 + " to package " + pkg.packageName 6941 + " because it was previously installed without"); 6942 } 6943 } else { 6944 if (gp.grantedPermissions.remove(perm)) { 6945 changedPermission = true; 6946 gp.gids = removeInts(gp.gids, bp.gids); 6947 Slog.i(TAG, "Un-granting permission " + perm 6948 + " from package " + pkg.packageName 6949 + " (protectionLevel=" + bp.protectionLevel 6950 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6951 + ")"); 6952 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 6953 // Don't print warning for app op permissions, since it is fine for them 6954 // not to be granted, there is a UI for the user to decide. 6955 Slog.w(TAG, "Not granting permission " + perm 6956 + " to package " + pkg.packageName 6957 + " (protectionLevel=" + bp.protectionLevel 6958 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6959 + ")"); 6960 } 6961 } 6962 } 6963 6964 if ((changedPermission || replace) && !ps.permissionsFixed && 6965 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 6966 // This is the first that we have heard about this package, so the 6967 // permissions we have now selected are fixed until explicitly 6968 // changed. 6969 ps.permissionsFixed = true; 6970 } 6971 ps.haveGids = true; 6972 } 6973 6974 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 6975 boolean allowed = false; 6976 final int NP = PackageParser.NEW_PERMISSIONS.length; 6977 for (int ip=0; ip<NP; ip++) { 6978 final PackageParser.NewPermissionInfo npi 6979 = PackageParser.NEW_PERMISSIONS[ip]; 6980 if (npi.name.equals(perm) 6981 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 6982 allowed = true; 6983 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 6984 + pkg.packageName); 6985 break; 6986 } 6987 } 6988 return allowed; 6989 } 6990 6991 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 6992 BasePermission bp, HashSet<String> origPermissions) { 6993 boolean allowed; 6994 allowed = (compareSignatures( 6995 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 6996 == PackageManager.SIGNATURE_MATCH) 6997 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 6998 == PackageManager.SIGNATURE_MATCH); 6999 if (!allowed && (bp.protectionLevel 7000 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 7001 if (isSystemApp(pkg)) { 7002 // For updated system applications, a system permission 7003 // is granted only if it had been defined by the original application. 7004 if (isUpdatedSystemApp(pkg)) { 7005 final PackageSetting sysPs = mSettings 7006 .getDisabledSystemPkgLPr(pkg.packageName); 7007 final GrantedPermissions origGp = sysPs.sharedUser != null 7008 ? sysPs.sharedUser : sysPs; 7009 7010 if (origGp.grantedPermissions.contains(perm)) { 7011 // If the original was granted this permission, we take 7012 // that grant decision as read and propagate it to the 7013 // update. 7014 allowed = true; 7015 } else { 7016 // The system apk may have been updated with an older 7017 // version of the one on the data partition, but which 7018 // granted a new system permission that it didn't have 7019 // before. In this case we do want to allow the app to 7020 // now get the new permission if the ancestral apk is 7021 // privileged to get it. 7022 if (sysPs.pkg != null && sysPs.isPrivileged()) { 7023 for (int j=0; 7024 j<sysPs.pkg.requestedPermissions.size(); j++) { 7025 if (perm.equals( 7026 sysPs.pkg.requestedPermissions.get(j))) { 7027 allowed = true; 7028 break; 7029 } 7030 } 7031 } 7032 } 7033 } else { 7034 allowed = isPrivilegedApp(pkg); 7035 } 7036 } 7037 } 7038 if (!allowed && (bp.protectionLevel 7039 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 7040 // For development permissions, a development permission 7041 // is granted only if it was already granted. 7042 allowed = origPermissions.contains(perm); 7043 } 7044 return allowed; 7045 } 7046 7047 final class ActivityIntentResolver 7048 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 7049 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7050 boolean defaultOnly, int userId) { 7051 if (!sUserManager.exists(userId)) return null; 7052 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7053 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7054 } 7055 7056 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7057 int userId) { 7058 if (!sUserManager.exists(userId)) return null; 7059 mFlags = flags; 7060 return super.queryIntent(intent, resolvedType, 7061 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7062 } 7063 7064 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7065 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 7066 if (!sUserManager.exists(userId)) return null; 7067 if (packageActivities == null) { 7068 return null; 7069 } 7070 mFlags = flags; 7071 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7072 final int N = packageActivities.size(); 7073 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 7074 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 7075 7076 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 7077 for (int i = 0; i < N; ++i) { 7078 intentFilters = packageActivities.get(i).intents; 7079 if (intentFilters != null && intentFilters.size() > 0) { 7080 PackageParser.ActivityIntentInfo[] array = 7081 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 7082 intentFilters.toArray(array); 7083 listCut.add(array); 7084 } 7085 } 7086 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7087 } 7088 7089 public final void addActivity(PackageParser.Activity a, String type) { 7090 final boolean systemApp = isSystemApp(a.info.applicationInfo); 7091 mActivities.put(a.getComponentName(), a); 7092 if (DEBUG_SHOW_INFO) 7093 Log.v( 7094 TAG, " " + type + " " + 7095 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 7096 if (DEBUG_SHOW_INFO) 7097 Log.v(TAG, " Class=" + a.info.name); 7098 final int NI = a.intents.size(); 7099 for (int j=0; j<NI; j++) { 7100 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7101 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 7102 intent.setPriority(0); 7103 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 7104 + a.className + " with priority > 0, forcing to 0"); 7105 } 7106 if (DEBUG_SHOW_INFO) { 7107 Log.v(TAG, " IntentFilter:"); 7108 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7109 } 7110 if (!intent.debugCheck()) { 7111 Log.w(TAG, "==> For Activity " + a.info.name); 7112 } 7113 addFilter(intent); 7114 } 7115 } 7116 7117 public final void removeActivity(PackageParser.Activity a, String type) { 7118 mActivities.remove(a.getComponentName()); 7119 if (DEBUG_SHOW_INFO) { 7120 Log.v(TAG, " " + type + " " 7121 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 7122 : a.info.name) + ":"); 7123 Log.v(TAG, " Class=" + a.info.name); 7124 } 7125 final int NI = a.intents.size(); 7126 for (int j=0; j<NI; j++) { 7127 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7128 if (DEBUG_SHOW_INFO) { 7129 Log.v(TAG, " IntentFilter:"); 7130 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7131 } 7132 removeFilter(intent); 7133 } 7134 } 7135 7136 @Override 7137 protected boolean allowFilterResult( 7138 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 7139 ActivityInfo filterAi = filter.activity.info; 7140 for (int i=dest.size()-1; i>=0; i--) { 7141 ActivityInfo destAi = dest.get(i).activityInfo; 7142 if (destAi.name == filterAi.name 7143 && destAi.packageName == filterAi.packageName) { 7144 return false; 7145 } 7146 } 7147 return true; 7148 } 7149 7150 @Override 7151 protected ActivityIntentInfo[] newArray(int size) { 7152 return new ActivityIntentInfo[size]; 7153 } 7154 7155 @Override 7156 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 7157 if (!sUserManager.exists(userId)) return true; 7158 PackageParser.Package p = filter.activity.owner; 7159 if (p != null) { 7160 PackageSetting ps = (PackageSetting)p.mExtras; 7161 if (ps != null) { 7162 // System apps are never considered stopped for purposes of 7163 // filtering, because there may be no way for the user to 7164 // actually re-launch them. 7165 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 7166 && ps.getStopped(userId); 7167 } 7168 } 7169 return false; 7170 } 7171 7172 @Override 7173 protected boolean isPackageForFilter(String packageName, 7174 PackageParser.ActivityIntentInfo info) { 7175 return packageName.equals(info.activity.owner.packageName); 7176 } 7177 7178 @Override 7179 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7180 int match, int userId) { 7181 if (!sUserManager.exists(userId)) return null; 7182 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7183 return null; 7184 } 7185 final PackageParser.Activity activity = info.activity; 7186 if (mSafeMode && (activity.info.applicationInfo.flags 7187 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7188 return null; 7189 } 7190 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7191 if (ps == null) { 7192 return null; 7193 } 7194 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7195 ps.readUserState(userId), userId); 7196 if (ai == null) { 7197 return null; 7198 } 7199 final ResolveInfo res = new ResolveInfo(); 7200 res.activityInfo = ai; 7201 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7202 res.filter = info; 7203 } 7204 res.priority = info.getPriority(); 7205 res.preferredOrder = activity.owner.mPreferredOrder; 7206 //System.out.println("Result: " + res.activityInfo.className + 7207 // " = " + res.priority); 7208 res.match = match; 7209 res.isDefault = info.hasDefault; 7210 res.labelRes = info.labelRes; 7211 res.nonLocalizedLabel = info.nonLocalizedLabel; 7212 if (userNeedsBadging(userId)) { 7213 res.noResourceId = true; 7214 } else { 7215 res.icon = info.icon; 7216 } 7217 res.system = isSystemApp(res.activityInfo.applicationInfo); 7218 return res; 7219 } 7220 7221 @Override 7222 protected void sortResults(List<ResolveInfo> results) { 7223 Collections.sort(results, mResolvePrioritySorter); 7224 } 7225 7226 @Override 7227 protected void dumpFilter(PrintWriter out, String prefix, 7228 PackageParser.ActivityIntentInfo filter) { 7229 out.print(prefix); out.print( 7230 Integer.toHexString(System.identityHashCode(filter.activity))); 7231 out.print(' '); 7232 filter.activity.printComponentShortName(out); 7233 out.print(" filter "); 7234 out.println(Integer.toHexString(System.identityHashCode(filter))); 7235 } 7236 7237// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7238// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7239// final List<ResolveInfo> retList = Lists.newArrayList(); 7240// while (i.hasNext()) { 7241// final ResolveInfo resolveInfo = i.next(); 7242// if (isEnabledLP(resolveInfo.activityInfo)) { 7243// retList.add(resolveInfo); 7244// } 7245// } 7246// return retList; 7247// } 7248 7249 // Keys are String (activity class name), values are Activity. 7250 private final HashMap<ComponentName, PackageParser.Activity> mActivities 7251 = new HashMap<ComponentName, PackageParser.Activity>(); 7252 private int mFlags; 7253 } 7254 7255 private final class ServiceIntentResolver 7256 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 7257 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7258 boolean defaultOnly, int userId) { 7259 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7260 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7261 } 7262 7263 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7264 int userId) { 7265 if (!sUserManager.exists(userId)) return null; 7266 mFlags = flags; 7267 return super.queryIntent(intent, resolvedType, 7268 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7269 } 7270 7271 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7272 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 7273 if (!sUserManager.exists(userId)) return null; 7274 if (packageServices == null) { 7275 return null; 7276 } 7277 mFlags = flags; 7278 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7279 final int N = packageServices.size(); 7280 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 7281 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 7282 7283 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 7284 for (int i = 0; i < N; ++i) { 7285 intentFilters = packageServices.get(i).intents; 7286 if (intentFilters != null && intentFilters.size() > 0) { 7287 PackageParser.ServiceIntentInfo[] array = 7288 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 7289 intentFilters.toArray(array); 7290 listCut.add(array); 7291 } 7292 } 7293 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7294 } 7295 7296 public final void addService(PackageParser.Service s) { 7297 mServices.put(s.getComponentName(), s); 7298 if (DEBUG_SHOW_INFO) { 7299 Log.v(TAG, " " 7300 + (s.info.nonLocalizedLabel != null 7301 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7302 Log.v(TAG, " Class=" + s.info.name); 7303 } 7304 final int NI = s.intents.size(); 7305 int j; 7306 for (j=0; j<NI; j++) { 7307 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7308 if (DEBUG_SHOW_INFO) { 7309 Log.v(TAG, " IntentFilter:"); 7310 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7311 } 7312 if (!intent.debugCheck()) { 7313 Log.w(TAG, "==> For Service " + s.info.name); 7314 } 7315 addFilter(intent); 7316 } 7317 } 7318 7319 public final void removeService(PackageParser.Service s) { 7320 mServices.remove(s.getComponentName()); 7321 if (DEBUG_SHOW_INFO) { 7322 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 7323 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7324 Log.v(TAG, " Class=" + s.info.name); 7325 } 7326 final int NI = s.intents.size(); 7327 int j; 7328 for (j=0; j<NI; j++) { 7329 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7330 if (DEBUG_SHOW_INFO) { 7331 Log.v(TAG, " IntentFilter:"); 7332 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7333 } 7334 removeFilter(intent); 7335 } 7336 } 7337 7338 @Override 7339 protected boolean allowFilterResult( 7340 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 7341 ServiceInfo filterSi = filter.service.info; 7342 for (int i=dest.size()-1; i>=0; i--) { 7343 ServiceInfo destAi = dest.get(i).serviceInfo; 7344 if (destAi.name == filterSi.name 7345 && destAi.packageName == filterSi.packageName) { 7346 return false; 7347 } 7348 } 7349 return true; 7350 } 7351 7352 @Override 7353 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 7354 return new PackageParser.ServiceIntentInfo[size]; 7355 } 7356 7357 @Override 7358 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 7359 if (!sUserManager.exists(userId)) return true; 7360 PackageParser.Package p = filter.service.owner; 7361 if (p != null) { 7362 PackageSetting ps = (PackageSetting)p.mExtras; 7363 if (ps != null) { 7364 // System apps are never considered stopped for purposes of 7365 // filtering, because there may be no way for the user to 7366 // actually re-launch them. 7367 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7368 && ps.getStopped(userId); 7369 } 7370 } 7371 return false; 7372 } 7373 7374 @Override 7375 protected boolean isPackageForFilter(String packageName, 7376 PackageParser.ServiceIntentInfo info) { 7377 return packageName.equals(info.service.owner.packageName); 7378 } 7379 7380 @Override 7381 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 7382 int match, int userId) { 7383 if (!sUserManager.exists(userId)) return null; 7384 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 7385 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 7386 return null; 7387 } 7388 final PackageParser.Service service = info.service; 7389 if (mSafeMode && (service.info.applicationInfo.flags 7390 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7391 return null; 7392 } 7393 PackageSetting ps = (PackageSetting) service.owner.mExtras; 7394 if (ps == null) { 7395 return null; 7396 } 7397 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 7398 ps.readUserState(userId), userId); 7399 if (si == null) { 7400 return null; 7401 } 7402 final ResolveInfo res = new ResolveInfo(); 7403 res.serviceInfo = si; 7404 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7405 res.filter = filter; 7406 } 7407 res.priority = info.getPriority(); 7408 res.preferredOrder = service.owner.mPreferredOrder; 7409 //System.out.println("Result: " + res.activityInfo.className + 7410 // " = " + res.priority); 7411 res.match = match; 7412 res.isDefault = info.hasDefault; 7413 res.labelRes = info.labelRes; 7414 res.nonLocalizedLabel = info.nonLocalizedLabel; 7415 res.icon = info.icon; 7416 res.system = isSystemApp(res.serviceInfo.applicationInfo); 7417 return res; 7418 } 7419 7420 @Override 7421 protected void sortResults(List<ResolveInfo> results) { 7422 Collections.sort(results, mResolvePrioritySorter); 7423 } 7424 7425 @Override 7426 protected void dumpFilter(PrintWriter out, String prefix, 7427 PackageParser.ServiceIntentInfo filter) { 7428 out.print(prefix); out.print( 7429 Integer.toHexString(System.identityHashCode(filter.service))); 7430 out.print(' '); 7431 filter.service.printComponentShortName(out); 7432 out.print(" filter "); 7433 out.println(Integer.toHexString(System.identityHashCode(filter))); 7434 } 7435 7436// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7437// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7438// final List<ResolveInfo> retList = Lists.newArrayList(); 7439// while (i.hasNext()) { 7440// final ResolveInfo resolveInfo = (ResolveInfo) i; 7441// if (isEnabledLP(resolveInfo.serviceInfo)) { 7442// retList.add(resolveInfo); 7443// } 7444// } 7445// return retList; 7446// } 7447 7448 // Keys are String (activity class name), values are Activity. 7449 private final HashMap<ComponentName, PackageParser.Service> mServices 7450 = new HashMap<ComponentName, PackageParser.Service>(); 7451 private int mFlags; 7452 }; 7453 7454 private final class ProviderIntentResolver 7455 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 7456 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7457 boolean defaultOnly, int userId) { 7458 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7459 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7460 } 7461 7462 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7463 int userId) { 7464 if (!sUserManager.exists(userId)) 7465 return null; 7466 mFlags = flags; 7467 return super.queryIntent(intent, resolvedType, 7468 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7469 } 7470 7471 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7472 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 7473 if (!sUserManager.exists(userId)) 7474 return null; 7475 if (packageProviders == null) { 7476 return null; 7477 } 7478 mFlags = flags; 7479 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 7480 final int N = packageProviders.size(); 7481 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 7482 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 7483 7484 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 7485 for (int i = 0; i < N; ++i) { 7486 intentFilters = packageProviders.get(i).intents; 7487 if (intentFilters != null && intentFilters.size() > 0) { 7488 PackageParser.ProviderIntentInfo[] array = 7489 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 7490 intentFilters.toArray(array); 7491 listCut.add(array); 7492 } 7493 } 7494 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7495 } 7496 7497 public final void addProvider(PackageParser.Provider p) { 7498 if (mProviders.containsKey(p.getComponentName())) { 7499 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 7500 return; 7501 } 7502 7503 mProviders.put(p.getComponentName(), p); 7504 if (DEBUG_SHOW_INFO) { 7505 Log.v(TAG, " " 7506 + (p.info.nonLocalizedLabel != null 7507 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7508 Log.v(TAG, " Class=" + p.info.name); 7509 } 7510 final int NI = p.intents.size(); 7511 int j; 7512 for (j = 0; j < NI; j++) { 7513 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7514 if (DEBUG_SHOW_INFO) { 7515 Log.v(TAG, " IntentFilter:"); 7516 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7517 } 7518 if (!intent.debugCheck()) { 7519 Log.w(TAG, "==> For Provider " + p.info.name); 7520 } 7521 addFilter(intent); 7522 } 7523 } 7524 7525 public final void removeProvider(PackageParser.Provider p) { 7526 mProviders.remove(p.getComponentName()); 7527 if (DEBUG_SHOW_INFO) { 7528 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 7529 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7530 Log.v(TAG, " Class=" + p.info.name); 7531 } 7532 final int NI = p.intents.size(); 7533 int j; 7534 for (j = 0; j < NI; j++) { 7535 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7536 if (DEBUG_SHOW_INFO) { 7537 Log.v(TAG, " IntentFilter:"); 7538 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7539 } 7540 removeFilter(intent); 7541 } 7542 } 7543 7544 @Override 7545 protected boolean allowFilterResult( 7546 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 7547 ProviderInfo filterPi = filter.provider.info; 7548 for (int i = dest.size() - 1; i >= 0; i--) { 7549 ProviderInfo destPi = dest.get(i).providerInfo; 7550 if (destPi.name == filterPi.name 7551 && destPi.packageName == filterPi.packageName) { 7552 return false; 7553 } 7554 } 7555 return true; 7556 } 7557 7558 @Override 7559 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 7560 return new PackageParser.ProviderIntentInfo[size]; 7561 } 7562 7563 @Override 7564 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 7565 if (!sUserManager.exists(userId)) 7566 return true; 7567 PackageParser.Package p = filter.provider.owner; 7568 if (p != null) { 7569 PackageSetting ps = (PackageSetting) p.mExtras; 7570 if (ps != null) { 7571 // System apps are never considered stopped for purposes of 7572 // filtering, because there may be no way for the user to 7573 // actually re-launch them. 7574 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7575 && ps.getStopped(userId); 7576 } 7577 } 7578 return false; 7579 } 7580 7581 @Override 7582 protected boolean isPackageForFilter(String packageName, 7583 PackageParser.ProviderIntentInfo info) { 7584 return packageName.equals(info.provider.owner.packageName); 7585 } 7586 7587 @Override 7588 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 7589 int match, int userId) { 7590 if (!sUserManager.exists(userId)) 7591 return null; 7592 final PackageParser.ProviderIntentInfo info = filter; 7593 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 7594 return null; 7595 } 7596 final PackageParser.Provider provider = info.provider; 7597 if (mSafeMode && (provider.info.applicationInfo.flags 7598 & ApplicationInfo.FLAG_SYSTEM) == 0) { 7599 return null; 7600 } 7601 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 7602 if (ps == null) { 7603 return null; 7604 } 7605 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 7606 ps.readUserState(userId), userId); 7607 if (pi == null) { 7608 return null; 7609 } 7610 final ResolveInfo res = new ResolveInfo(); 7611 res.providerInfo = pi; 7612 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 7613 res.filter = filter; 7614 } 7615 res.priority = info.getPriority(); 7616 res.preferredOrder = provider.owner.mPreferredOrder; 7617 res.match = match; 7618 res.isDefault = info.hasDefault; 7619 res.labelRes = info.labelRes; 7620 res.nonLocalizedLabel = info.nonLocalizedLabel; 7621 res.icon = info.icon; 7622 res.system = isSystemApp(res.providerInfo.applicationInfo); 7623 return res; 7624 } 7625 7626 @Override 7627 protected void sortResults(List<ResolveInfo> results) { 7628 Collections.sort(results, mResolvePrioritySorter); 7629 } 7630 7631 @Override 7632 protected void dumpFilter(PrintWriter out, String prefix, 7633 PackageParser.ProviderIntentInfo filter) { 7634 out.print(prefix); 7635 out.print( 7636 Integer.toHexString(System.identityHashCode(filter.provider))); 7637 out.print(' '); 7638 filter.provider.printComponentShortName(out); 7639 out.print(" filter "); 7640 out.println(Integer.toHexString(System.identityHashCode(filter))); 7641 } 7642 7643 private final HashMap<ComponentName, PackageParser.Provider> mProviders 7644 = new HashMap<ComponentName, PackageParser.Provider>(); 7645 private int mFlags; 7646 }; 7647 7648 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 7649 new Comparator<ResolveInfo>() { 7650 public int compare(ResolveInfo r1, ResolveInfo r2) { 7651 int v1 = r1.priority; 7652 int v2 = r2.priority; 7653 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 7654 if (v1 != v2) { 7655 return (v1 > v2) ? -1 : 1; 7656 } 7657 v1 = r1.preferredOrder; 7658 v2 = r2.preferredOrder; 7659 if (v1 != v2) { 7660 return (v1 > v2) ? -1 : 1; 7661 } 7662 if (r1.isDefault != r2.isDefault) { 7663 return r1.isDefault ? -1 : 1; 7664 } 7665 v1 = r1.match; 7666 v2 = r2.match; 7667 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 7668 if (v1 != v2) { 7669 return (v1 > v2) ? -1 : 1; 7670 } 7671 if (r1.system != r2.system) { 7672 return r1.system ? -1 : 1; 7673 } 7674 return 0; 7675 } 7676 }; 7677 7678 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 7679 new Comparator<ProviderInfo>() { 7680 public int compare(ProviderInfo p1, ProviderInfo p2) { 7681 final int v1 = p1.initOrder; 7682 final int v2 = p2.initOrder; 7683 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 7684 } 7685 }; 7686 7687 static final void sendPackageBroadcast(String action, String pkg, 7688 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 7689 int[] userIds) { 7690 IActivityManager am = ActivityManagerNative.getDefault(); 7691 if (am != null) { 7692 try { 7693 if (userIds == null) { 7694 userIds = am.getRunningUserIds(); 7695 } 7696 for (int id : userIds) { 7697 final Intent intent = new Intent(action, 7698 pkg != null ? Uri.fromParts("package", pkg, null) : null); 7699 if (extras != null) { 7700 intent.putExtras(extras); 7701 } 7702 if (targetPkg != null) { 7703 intent.setPackage(targetPkg); 7704 } 7705 // Modify the UID when posting to other users 7706 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 7707 if (uid > 0 && UserHandle.getUserId(uid) != id) { 7708 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 7709 intent.putExtra(Intent.EXTRA_UID, uid); 7710 } 7711 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 7712 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 7713 if (DEBUG_BROADCASTS) { 7714 RuntimeException here = new RuntimeException("here"); 7715 here.fillInStackTrace(); 7716 Slog.d(TAG, "Sending to user " + id + ": " 7717 + intent.toShortString(false, true, false, false) 7718 + " " + intent.getExtras(), here); 7719 } 7720 am.broadcastIntent(null, intent, null, finishedReceiver, 7721 0, null, null, null, android.app.AppOpsManager.OP_NONE, 7722 finishedReceiver != null, false, id); 7723 } 7724 } catch (RemoteException ex) { 7725 } 7726 } 7727 } 7728 7729 /** 7730 * Check if the external storage media is available. This is true if there 7731 * is a mounted external storage medium or if the external storage is 7732 * emulated. 7733 */ 7734 private boolean isExternalMediaAvailable() { 7735 return mMediaMounted || Environment.isExternalStorageEmulated(); 7736 } 7737 7738 @Override 7739 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 7740 // writer 7741 synchronized (mPackages) { 7742 if (!isExternalMediaAvailable()) { 7743 // If the external storage is no longer mounted at this point, 7744 // the caller may not have been able to delete all of this 7745 // packages files and can not delete any more. Bail. 7746 return null; 7747 } 7748 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 7749 if (lastPackage != null) { 7750 pkgs.remove(lastPackage); 7751 } 7752 if (pkgs.size() > 0) { 7753 return pkgs.get(0); 7754 } 7755 } 7756 return null; 7757 } 7758 7759 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 7760 if (false) { 7761 RuntimeException here = new RuntimeException("here"); 7762 here.fillInStackTrace(); 7763 Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId 7764 + " andCode=" + andCode, here); 7765 } 7766 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, 7767 userId, andCode ? 1 : 0, packageName)); 7768 } 7769 7770 void startCleaningPackages() { 7771 // reader 7772 synchronized (mPackages) { 7773 if (!isExternalMediaAvailable()) { 7774 return; 7775 } 7776 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 7777 return; 7778 } 7779 } 7780 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 7781 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 7782 IActivityManager am = ActivityManagerNative.getDefault(); 7783 if (am != null) { 7784 try { 7785 am.startService(null, intent, null, UserHandle.USER_OWNER); 7786 } catch (RemoteException e) { 7787 } 7788 } 7789 } 7790 7791 @Override 7792 public void installPackage(String originPath, IPackageInstallObserver2 observer, int flags, 7793 String installerPackageName, VerificationParams verificationParams, 7794 String packageAbiOverride) { 7795 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7796 null); 7797 7798 final File originFile = new File(originPath); 7799 final int uid = Binder.getCallingUid(); 7800 if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) { 7801 try { 7802 if (observer != null) { 7803 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 7804 } 7805 } catch (RemoteException re) { 7806 } 7807 return; 7808 } 7809 7810 UserHandle user; 7811 if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) { 7812 user = UserHandle.ALL; 7813 } else { 7814 user = new UserHandle(UserHandle.getUserId(uid)); 7815 } 7816 7817 final int filteredFlags; 7818 if (uid == Process.SHELL_UID || uid == 0) { 7819 if (DEBUG_INSTALL) { 7820 Slog.v(TAG, "Install from ADB"); 7821 } 7822 filteredFlags = flags | PackageManager.INSTALL_FROM_ADB; 7823 } else { 7824 filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB; 7825 } 7826 7827 verificationParams.setInstallerUid(uid); 7828 7829 final Message msg = mHandler.obtainMessage(INIT_COPY); 7830 msg.obj = new InstallParams(originFile, false, observer, filteredFlags, 7831 installerPackageName, verificationParams, user, packageAbiOverride); 7832 mHandler.sendMessage(msg); 7833 } 7834 7835 void installStage(String packageName, File stageDir, IPackageInstallObserver2 observer, 7836 InstallSessionParams params, String installerPackageName, int installerUid, 7837 UserHandle user) { 7838 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 7839 params.referrerUri, installerUid, null); 7840 7841 final Message msg = mHandler.obtainMessage(INIT_COPY); 7842 msg.obj = new InstallParams(stageDir, true, observer, params.installFlags, 7843 installerPackageName, verifParams, user, params.abiOverride); 7844 mHandler.sendMessage(msg); 7845 } 7846 7847 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 7848 Bundle extras = new Bundle(1); 7849 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 7850 7851 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 7852 packageName, extras, null, null, new int[] {userId}); 7853 try { 7854 IActivityManager am = ActivityManagerNative.getDefault(); 7855 final boolean isSystem = 7856 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 7857 if (isSystem && am.isUserRunning(userId, false)) { 7858 // The just-installed/enabled app is bundled on the system, so presumed 7859 // to be able to run automatically without needing an explicit launch. 7860 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 7861 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 7862 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 7863 .setPackage(packageName); 7864 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 7865 android.app.AppOpsManager.OP_NONE, false, false, userId); 7866 } 7867 } catch (RemoteException e) { 7868 // shouldn't happen 7869 Slog.w(TAG, "Unable to bootstrap installed package", e); 7870 } 7871 } 7872 7873 @Override 7874 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 7875 int userId) { 7876 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7877 PackageSetting pkgSetting; 7878 final int uid = Binder.getCallingUid(); 7879 if (UserHandle.getUserId(uid) != userId) { 7880 mContext.enforceCallingOrSelfPermission( 7881 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 7882 "setApplicationHiddenSetting for user " + userId); 7883 } 7884 7885 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 7886 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 7887 return false; 7888 } 7889 7890 long callingId = Binder.clearCallingIdentity(); 7891 try { 7892 boolean sendAdded = false; 7893 boolean sendRemoved = false; 7894 // writer 7895 synchronized (mPackages) { 7896 pkgSetting = mSettings.mPackages.get(packageName); 7897 if (pkgSetting == null) { 7898 return false; 7899 } 7900 if (pkgSetting.getHidden(userId) != hidden) { 7901 pkgSetting.setHidden(hidden, userId); 7902 mSettings.writePackageRestrictionsLPr(userId); 7903 if (hidden) { 7904 sendRemoved = true; 7905 } else { 7906 sendAdded = true; 7907 } 7908 } 7909 } 7910 if (sendAdded) { 7911 sendPackageAddedForUser(packageName, pkgSetting, userId); 7912 return true; 7913 } 7914 if (sendRemoved) { 7915 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 7916 "hiding pkg"); 7917 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 7918 } 7919 } finally { 7920 Binder.restoreCallingIdentity(callingId); 7921 } 7922 return false; 7923 } 7924 7925 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 7926 int userId) { 7927 final PackageRemovedInfo info = new PackageRemovedInfo(); 7928 info.removedPackage = packageName; 7929 info.removedUsers = new int[] {userId}; 7930 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 7931 info.sendBroadcast(false, false, false); 7932 } 7933 7934 /** 7935 * Returns true if application is not found or there was an error. Otherwise it returns 7936 * the hidden state of the package for the given user. 7937 */ 7938 @Override 7939 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 7940 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7941 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 7942 "getApplicationHidden for user " + userId); 7943 PackageSetting pkgSetting; 7944 long callingId = Binder.clearCallingIdentity(); 7945 try { 7946 // writer 7947 synchronized (mPackages) { 7948 pkgSetting = mSettings.mPackages.get(packageName); 7949 if (pkgSetting == null) { 7950 return true; 7951 } 7952 return pkgSetting.getHidden(userId); 7953 } 7954 } finally { 7955 Binder.restoreCallingIdentity(callingId); 7956 } 7957 } 7958 7959 /** 7960 * @hide 7961 */ 7962 @Override 7963 public int installExistingPackageAsUser(String packageName, int userId) { 7964 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7965 null); 7966 PackageSetting pkgSetting; 7967 final int uid = Binder.getCallingUid(); 7968 enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId); 7969 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 7970 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 7971 } 7972 7973 long callingId = Binder.clearCallingIdentity(); 7974 try { 7975 boolean sendAdded = false; 7976 Bundle extras = new Bundle(1); 7977 7978 // writer 7979 synchronized (mPackages) { 7980 pkgSetting = mSettings.mPackages.get(packageName); 7981 if (pkgSetting == null) { 7982 return PackageManager.INSTALL_FAILED_INVALID_URI; 7983 } 7984 if (!pkgSetting.getInstalled(userId)) { 7985 pkgSetting.setInstalled(true, userId); 7986 pkgSetting.setHidden(false, userId); 7987 mSettings.writePackageRestrictionsLPr(userId); 7988 sendAdded = true; 7989 } 7990 } 7991 7992 if (sendAdded) { 7993 sendPackageAddedForUser(packageName, pkgSetting, userId); 7994 } 7995 } finally { 7996 Binder.restoreCallingIdentity(callingId); 7997 } 7998 7999 return PackageManager.INSTALL_SUCCEEDED; 8000 } 8001 8002 boolean isUserRestricted(int userId, String restrictionKey) { 8003 Bundle restrictions = sUserManager.getUserRestrictions(userId); 8004 if (restrictions.getBoolean(restrictionKey, false)) { 8005 Log.w(TAG, "User is restricted: " + restrictionKey); 8006 return true; 8007 } 8008 return false; 8009 } 8010 8011 @Override 8012 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 8013 mContext.enforceCallingOrSelfPermission( 8014 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8015 "Only package verification agents can verify applications"); 8016 8017 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8018 final PackageVerificationResponse response = new PackageVerificationResponse( 8019 verificationCode, Binder.getCallingUid()); 8020 msg.arg1 = id; 8021 msg.obj = response; 8022 mHandler.sendMessage(msg); 8023 } 8024 8025 @Override 8026 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 8027 long millisecondsToDelay) { 8028 mContext.enforceCallingOrSelfPermission( 8029 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8030 "Only package verification agents can extend verification timeouts"); 8031 8032 final PackageVerificationState state = mPendingVerification.get(id); 8033 final PackageVerificationResponse response = new PackageVerificationResponse( 8034 verificationCodeAtTimeout, Binder.getCallingUid()); 8035 8036 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 8037 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 8038 } 8039 if (millisecondsToDelay < 0) { 8040 millisecondsToDelay = 0; 8041 } 8042 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 8043 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 8044 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 8045 } 8046 8047 if ((state != null) && !state.timeoutExtended()) { 8048 state.extendTimeout(); 8049 8050 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8051 msg.arg1 = id; 8052 msg.obj = response; 8053 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 8054 } 8055 } 8056 8057 private void broadcastPackageVerified(int verificationId, Uri packageUri, 8058 int verificationCode, UserHandle user) { 8059 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 8060 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 8061 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8062 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8063 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 8064 8065 mContext.sendBroadcastAsUser(intent, user, 8066 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 8067 } 8068 8069 private ComponentName matchComponentForVerifier(String packageName, 8070 List<ResolveInfo> receivers) { 8071 ActivityInfo targetReceiver = null; 8072 8073 final int NR = receivers.size(); 8074 for (int i = 0; i < NR; i++) { 8075 final ResolveInfo info = receivers.get(i); 8076 if (info.activityInfo == null) { 8077 continue; 8078 } 8079 8080 if (packageName.equals(info.activityInfo.packageName)) { 8081 targetReceiver = info.activityInfo; 8082 break; 8083 } 8084 } 8085 8086 if (targetReceiver == null) { 8087 return null; 8088 } 8089 8090 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8091 } 8092 8093 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8094 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8095 if (pkgInfo.verifiers.length == 0) { 8096 return null; 8097 } 8098 8099 final int N = pkgInfo.verifiers.length; 8100 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8101 for (int i = 0; i < N; i++) { 8102 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8103 8104 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8105 receivers); 8106 if (comp == null) { 8107 continue; 8108 } 8109 8110 final int verifierUid = getUidForVerifier(verifierInfo); 8111 if (verifierUid == -1) { 8112 continue; 8113 } 8114 8115 if (DEBUG_VERIFY) { 8116 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8117 + " with the correct signature"); 8118 } 8119 sufficientVerifiers.add(comp); 8120 verificationState.addSufficientVerifier(verifierUid); 8121 } 8122 8123 return sufficientVerifiers; 8124 } 8125 8126 private int getUidForVerifier(VerifierInfo verifierInfo) { 8127 synchronized (mPackages) { 8128 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8129 if (pkg == null) { 8130 return -1; 8131 } else if (pkg.mSignatures.length != 1) { 8132 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8133 + " has more than one signature; ignoring"); 8134 return -1; 8135 } 8136 8137 /* 8138 * If the public key of the package's signature does not match 8139 * our expected public key, then this is a different package and 8140 * we should skip. 8141 */ 8142 8143 final byte[] expectedPublicKey; 8144 try { 8145 final Signature verifierSig = pkg.mSignatures[0]; 8146 final PublicKey publicKey = verifierSig.getPublicKey(); 8147 expectedPublicKey = publicKey.getEncoded(); 8148 } catch (CertificateException e) { 8149 return -1; 8150 } 8151 8152 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8153 8154 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8155 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8156 + " does not have the expected public key; ignoring"); 8157 return -1; 8158 } 8159 8160 return pkg.applicationInfo.uid; 8161 } 8162 } 8163 8164 @Override 8165 public void finishPackageInstall(int token) { 8166 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8167 8168 if (DEBUG_INSTALL) { 8169 Slog.v(TAG, "BM finishing package install for " + token); 8170 } 8171 8172 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8173 mHandler.sendMessage(msg); 8174 } 8175 8176 /** 8177 * Get the verification agent timeout. 8178 * 8179 * @return verification timeout in milliseconds 8180 */ 8181 private long getVerificationTimeout() { 8182 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8183 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8184 DEFAULT_VERIFICATION_TIMEOUT); 8185 } 8186 8187 /** 8188 * Get the default verification agent response code. 8189 * 8190 * @return default verification response code 8191 */ 8192 private int getDefaultVerificationResponse() { 8193 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8194 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8195 DEFAULT_VERIFICATION_RESPONSE); 8196 } 8197 8198 /** 8199 * Check whether or not package verification has been enabled. 8200 * 8201 * @return true if verification should be performed 8202 */ 8203 private boolean isVerificationEnabled(int userId, int flags) { 8204 if (!DEFAULT_VERIFY_ENABLE) { 8205 return false; 8206 } 8207 8208 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 8209 8210 // Check if installing from ADB 8211 if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) { 8212 // Do not run verification in a test harness environment 8213 if (ActivityManager.isRunningInTestHarness()) { 8214 return false; 8215 } 8216 if (ensureVerifyAppsEnabled) { 8217 return true; 8218 } 8219 // Check if the developer does not want package verification for ADB installs 8220 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8221 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8222 return false; 8223 } 8224 } 8225 8226 if (ensureVerifyAppsEnabled) { 8227 return true; 8228 } 8229 8230 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8231 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8232 } 8233 8234 /** 8235 * Get the "allow unknown sources" setting. 8236 * 8237 * @return the current "allow unknown sources" setting 8238 */ 8239 private int getUnknownSourcesSettings() { 8240 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8241 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 8242 -1); 8243 } 8244 8245 @Override 8246 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 8247 final int uid = Binder.getCallingUid(); 8248 // writer 8249 synchronized (mPackages) { 8250 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 8251 if (targetPackageSetting == null) { 8252 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 8253 } 8254 8255 PackageSetting installerPackageSetting; 8256 if (installerPackageName != null) { 8257 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 8258 if (installerPackageSetting == null) { 8259 throw new IllegalArgumentException("Unknown installer package: " 8260 + installerPackageName); 8261 } 8262 } else { 8263 installerPackageSetting = null; 8264 } 8265 8266 Signature[] callerSignature; 8267 Object obj = mSettings.getUserIdLPr(uid); 8268 if (obj != null) { 8269 if (obj instanceof SharedUserSetting) { 8270 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 8271 } else if (obj instanceof PackageSetting) { 8272 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 8273 } else { 8274 throw new SecurityException("Bad object " + obj + " for uid " + uid); 8275 } 8276 } else { 8277 throw new SecurityException("Unknown calling uid " + uid); 8278 } 8279 8280 // Verify: can't set installerPackageName to a package that is 8281 // not signed with the same cert as the caller. 8282 if (installerPackageSetting != null) { 8283 if (compareSignatures(callerSignature, 8284 installerPackageSetting.signatures.mSignatures) 8285 != PackageManager.SIGNATURE_MATCH) { 8286 throw new SecurityException( 8287 "Caller does not have same cert as new installer package " 8288 + installerPackageName); 8289 } 8290 } 8291 8292 // Verify: if target already has an installer package, it must 8293 // be signed with the same cert as the caller. 8294 if (targetPackageSetting.installerPackageName != null) { 8295 PackageSetting setting = mSettings.mPackages.get( 8296 targetPackageSetting.installerPackageName); 8297 // If the currently set package isn't valid, then it's always 8298 // okay to change it. 8299 if (setting != null) { 8300 if (compareSignatures(callerSignature, 8301 setting.signatures.mSignatures) 8302 != PackageManager.SIGNATURE_MATCH) { 8303 throw new SecurityException( 8304 "Caller does not have same cert as old installer package " 8305 + targetPackageSetting.installerPackageName); 8306 } 8307 } 8308 } 8309 8310 // Okay! 8311 targetPackageSetting.installerPackageName = installerPackageName; 8312 scheduleWriteSettingsLocked(); 8313 } 8314 } 8315 8316 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 8317 // Queue up an async operation since the package installation may take a little while. 8318 mHandler.post(new Runnable() { 8319 public void run() { 8320 mHandler.removeCallbacks(this); 8321 // Result object to be returned 8322 PackageInstalledInfo res = new PackageInstalledInfo(); 8323 res.returnCode = currentStatus; 8324 res.uid = -1; 8325 res.pkg = null; 8326 res.removedInfo = new PackageRemovedInfo(); 8327 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 8328 args.doPreInstall(res.returnCode); 8329 synchronized (mInstallLock) { 8330 installPackageLI(args, true, res); 8331 } 8332 args.doPostInstall(res.returnCode, res.uid); 8333 } 8334 8335 // A restore should be performed at this point if (a) the install 8336 // succeeded, (b) the operation is not an update, and (c) the new 8337 // package has not opted out of backup participation. 8338 final boolean update = res.removedInfo.removedPackage != null; 8339 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 8340 boolean doRestore = !update 8341 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 8342 8343 // Set up the post-install work request bookkeeping. This will be used 8344 // and cleaned up by the post-install event handling regardless of whether 8345 // there's a restore pass performed. Token values are >= 1. 8346 int token; 8347 if (mNextInstallToken < 0) mNextInstallToken = 1; 8348 token = mNextInstallToken++; 8349 8350 PostInstallData data = new PostInstallData(args, res); 8351 mRunningInstalls.put(token, data); 8352 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 8353 8354 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 8355 // Pass responsibility to the Backup Manager. It will perform a 8356 // restore if appropriate, then pass responsibility back to the 8357 // Package Manager to run the post-install observer callbacks 8358 // and broadcasts. 8359 IBackupManager bm = IBackupManager.Stub.asInterface( 8360 ServiceManager.getService(Context.BACKUP_SERVICE)); 8361 if (bm != null) { 8362 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 8363 + " to BM for possible restore"); 8364 try { 8365 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 8366 } catch (RemoteException e) { 8367 // can't happen; the backup manager is local 8368 } catch (Exception e) { 8369 Slog.e(TAG, "Exception trying to enqueue restore", e); 8370 doRestore = false; 8371 } 8372 } else { 8373 Slog.e(TAG, "Backup Manager not found!"); 8374 doRestore = false; 8375 } 8376 } 8377 8378 if (!doRestore) { 8379 // No restore possible, or the Backup Manager was mysteriously not 8380 // available -- just fire the post-install work request directly. 8381 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 8382 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8383 mHandler.sendMessage(msg); 8384 } 8385 } 8386 }); 8387 } 8388 8389 private abstract class HandlerParams { 8390 private static final int MAX_RETRIES = 4; 8391 8392 /** 8393 * Number of times startCopy() has been attempted and had a non-fatal 8394 * error. 8395 */ 8396 private int mRetries = 0; 8397 8398 /** User handle for the user requesting the information or installation. */ 8399 private final UserHandle mUser; 8400 8401 HandlerParams(UserHandle user) { 8402 mUser = user; 8403 } 8404 8405 UserHandle getUser() { 8406 return mUser; 8407 } 8408 8409 final boolean startCopy() { 8410 boolean res; 8411 try { 8412 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 8413 8414 if (++mRetries > MAX_RETRIES) { 8415 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 8416 mHandler.sendEmptyMessage(MCS_GIVE_UP); 8417 handleServiceError(); 8418 return false; 8419 } else { 8420 handleStartCopy(); 8421 res = true; 8422 } 8423 } catch (RemoteException e) { 8424 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 8425 mHandler.sendEmptyMessage(MCS_RECONNECT); 8426 res = false; 8427 } 8428 handleReturnCode(); 8429 return res; 8430 } 8431 8432 final void serviceError() { 8433 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 8434 handleServiceError(); 8435 handleReturnCode(); 8436 } 8437 8438 abstract void handleStartCopy() throws RemoteException; 8439 abstract void handleServiceError(); 8440 abstract void handleReturnCode(); 8441 } 8442 8443 class MeasureParams extends HandlerParams { 8444 private final PackageStats mStats; 8445 private boolean mSuccess; 8446 8447 private final IPackageStatsObserver mObserver; 8448 8449 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 8450 super(new UserHandle(stats.userHandle)); 8451 mObserver = observer; 8452 mStats = stats; 8453 } 8454 8455 @Override 8456 public String toString() { 8457 return "MeasureParams{" 8458 + Integer.toHexString(System.identityHashCode(this)) 8459 + " " + mStats.packageName + "}"; 8460 } 8461 8462 @Override 8463 void handleStartCopy() throws RemoteException { 8464 synchronized (mInstallLock) { 8465 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 8466 } 8467 8468 if (mSuccess) { 8469 final boolean mounted; 8470 if (Environment.isExternalStorageEmulated()) { 8471 mounted = true; 8472 } else { 8473 final String status = Environment.getExternalStorageState(); 8474 mounted = (Environment.MEDIA_MOUNTED.equals(status) 8475 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 8476 } 8477 8478 if (mounted) { 8479 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 8480 8481 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 8482 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 8483 8484 mStats.externalDataSize = calculateDirectorySize(mContainerService, 8485 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 8486 8487 // Always subtract cache size, since it's a subdirectory 8488 mStats.externalDataSize -= mStats.externalCacheSize; 8489 8490 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 8491 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 8492 8493 mStats.externalObbSize = calculateDirectorySize(mContainerService, 8494 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 8495 } 8496 } 8497 } 8498 8499 @Override 8500 void handleReturnCode() { 8501 if (mObserver != null) { 8502 try { 8503 mObserver.onGetStatsCompleted(mStats, mSuccess); 8504 } catch (RemoteException e) { 8505 Slog.i(TAG, "Observer no longer exists."); 8506 } 8507 } 8508 } 8509 8510 @Override 8511 void handleServiceError() { 8512 Slog.e(TAG, "Could not measure application " + mStats.packageName 8513 + " external storage"); 8514 } 8515 } 8516 8517 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 8518 throws RemoteException { 8519 long result = 0; 8520 for (File path : paths) { 8521 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 8522 } 8523 return result; 8524 } 8525 8526 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 8527 for (File path : paths) { 8528 try { 8529 mcs.clearDirectory(path.getAbsolutePath()); 8530 } catch (RemoteException e) { 8531 } 8532 } 8533 } 8534 8535 class InstallParams extends HandlerParams { 8536 /** 8537 * Location where install is coming from, before it has been 8538 * copied/renamed into place. This could be a single monolithic APK 8539 * file, or a cluster directory. This location may be untrusted. 8540 */ 8541 final File originFile; 8542 8543 /** 8544 * Flag indicating that {@link #originFile} has already been staged, 8545 * meaning downstream users don't need to defensively copy the contents. 8546 */ 8547 boolean originStaged; 8548 8549 final IPackageInstallObserver2 observer; 8550 int flags; 8551 final String installerPackageName; 8552 final VerificationParams verificationParams; 8553 private InstallArgs mArgs; 8554 private int mRet; 8555 final String packageAbiOverride; 8556 boolean multiArch; 8557 8558 InstallParams(File originFile, boolean originStaged, IPackageInstallObserver2 observer, 8559 int flags, String installerPackageName, VerificationParams verificationParams, 8560 UserHandle user, String packageAbiOverride) { 8561 super(user); 8562 this.originFile = Preconditions.checkNotNull(originFile); 8563 this.originStaged = originStaged; 8564 this.observer = observer; 8565 this.flags = flags; 8566 this.installerPackageName = installerPackageName; 8567 this.verificationParams = verificationParams; 8568 this.packageAbiOverride = packageAbiOverride; 8569 } 8570 8571 @Override 8572 public String toString() { 8573 return "InstallParams{" 8574 + Integer.toHexString(System.identityHashCode(this)) 8575 + " " + originFile + "}"; 8576 } 8577 8578 public ManifestDigest getManifestDigest() { 8579 if (verificationParams == null) { 8580 return null; 8581 } 8582 return verificationParams.getManifestDigest(); 8583 } 8584 8585 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) { 8586 String packageName = pkgLite.packageName; 8587 int installLocation = pkgLite.installLocation; 8588 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8589 // reader 8590 synchronized (mPackages) { 8591 PackageParser.Package pkg = mPackages.get(packageName); 8592 if (pkg != null) { 8593 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 8594 // Check for downgrading. 8595 if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 8596 if (pkgLite.versionCode < pkg.mVersionCode) { 8597 Slog.w(TAG, "Can't install update of " + packageName 8598 + " update version " + pkgLite.versionCode 8599 + " is older than installed version " 8600 + pkg.mVersionCode); 8601 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 8602 } 8603 } 8604 // Check for updated system application. 8605 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8606 if (onSd) { 8607 Slog.w(TAG, "Cannot install update to system app on sdcard"); 8608 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 8609 } 8610 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8611 } else { 8612 if (onSd) { 8613 // Install flag overrides everything. 8614 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8615 } 8616 // If current upgrade specifies particular preference 8617 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 8618 // Application explicitly specified internal. 8619 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8620 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 8621 // App explictly prefers external. Let policy decide 8622 } else { 8623 // Prefer previous location 8624 if (isExternal(pkg)) { 8625 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8626 } 8627 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8628 } 8629 } 8630 } else { 8631 // Invalid install. Return error code 8632 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 8633 } 8634 } 8635 } 8636 // All the special cases have been taken care of. 8637 // Return result based on recommended install location. 8638 if (onSd) { 8639 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8640 } 8641 return pkgLite.recommendedInstallLocation; 8642 } 8643 8644 private long getMemoryLowThreshold() { 8645 final DeviceStorageMonitorInternal 8646 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 8647 if (dsm == null) { 8648 return 0L; 8649 } 8650 return dsm.getMemoryLowThreshold(); 8651 } 8652 8653 /* 8654 * Invoke remote method to get package information and install 8655 * location values. Override install location based on default 8656 * policy if needed and then create install arguments based 8657 * on the install location. 8658 */ 8659 public void handleStartCopy() throws RemoteException { 8660 int ret = PackageManager.INSTALL_SUCCEEDED; 8661 final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8662 final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0; 8663 PackageInfoLite pkgLite = null; 8664 8665 if (onInt && onSd) { 8666 // Check if both bits are set. 8667 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 8668 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8669 } else { 8670 final long lowThreshold = getMemoryLowThreshold(); 8671 if (lowThreshold == 0L) { 8672 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 8673 } 8674 8675 // Remote call to find out default install location 8676 final String originPath = originFile.getAbsolutePath(); 8677 pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags, lowThreshold, 8678 packageAbiOverride); 8679 // Keep track of whether this package is a multiArch package until 8680 // we perform a full scan of it. We need to do this because we might 8681 // end up extracting the package shared libraries before we perform 8682 // a full scan. 8683 multiArch = pkgLite.multiArch; 8684 8685 /* 8686 * If we have too little free space, try to free cache 8687 * before giving up. 8688 */ 8689 if (pkgLite.recommendedInstallLocation 8690 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8691 final long size = mContainerService.calculateInstalledSize( 8692 originPath, isForwardLocked(), packageAbiOverride); 8693 if (mInstaller.freeCache(size + lowThreshold) >= 0) { 8694 pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags, 8695 lowThreshold, packageAbiOverride); 8696 } 8697 /* 8698 * The cache free must have deleted the file we 8699 * downloaded to install. 8700 * 8701 * TODO: fix the "freeCache" call to not delete 8702 * the file we care about. 8703 */ 8704 if (pkgLite.recommendedInstallLocation 8705 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8706 pkgLite.recommendedInstallLocation 8707 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 8708 } 8709 } 8710 } 8711 8712 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8713 int loc = pkgLite.recommendedInstallLocation; 8714 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 8715 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8716 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 8717 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 8718 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8719 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8720 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 8721 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 8722 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8723 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 8724 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 8725 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 8726 } else { 8727 // Override with defaults if needed. 8728 loc = installLocationPolicy(pkgLite, flags); 8729 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 8730 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 8731 } else if (!onSd && !onInt) { 8732 // Override install location with flags 8733 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 8734 // Set the flag to install on external media. 8735 flags |= PackageManager.INSTALL_EXTERNAL; 8736 flags &= ~PackageManager.INSTALL_INTERNAL; 8737 } else { 8738 // Make sure the flag for installing on external 8739 // media is unset 8740 flags |= PackageManager.INSTALL_INTERNAL; 8741 flags &= ~PackageManager.INSTALL_EXTERNAL; 8742 } 8743 } 8744 } 8745 } 8746 8747 final InstallArgs args = createInstallArgs(this); 8748 mArgs = args; 8749 8750 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8751 /* 8752 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 8753 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 8754 */ 8755 int userIdentifier = getUser().getIdentifier(); 8756 if (userIdentifier == UserHandle.USER_ALL 8757 && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) { 8758 userIdentifier = UserHandle.USER_OWNER; 8759 } 8760 8761 /* 8762 * Determine if we have any installed package verifiers. If we 8763 * do, then we'll defer to them to verify the packages. 8764 */ 8765 final int requiredUid = mRequiredVerifierPackage == null ? -1 8766 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 8767 if (requiredUid != -1 && isVerificationEnabled(userIdentifier, flags)) { 8768 // TODO: send verifier the install session instead of uri 8769 final Intent verification = new Intent( 8770 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 8771 verification.setDataAndType(Uri.fromFile(originFile), PACKAGE_MIME_TYPE); 8772 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8773 8774 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 8775 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 8776 0 /* TODO: Which userId? */); 8777 8778 if (DEBUG_VERIFY) { 8779 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 8780 + verification.toString() + " with " + pkgLite.verifiers.length 8781 + " optional verifiers"); 8782 } 8783 8784 final int verificationId = mPendingVerificationToken++; 8785 8786 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8787 8788 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 8789 installerPackageName); 8790 8791 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags); 8792 8793 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 8794 pkgLite.packageName); 8795 8796 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 8797 pkgLite.versionCode); 8798 8799 if (verificationParams != null) { 8800 if (verificationParams.getVerificationURI() != null) { 8801 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 8802 verificationParams.getVerificationURI()); 8803 } 8804 if (verificationParams.getOriginatingURI() != null) { 8805 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 8806 verificationParams.getOriginatingURI()); 8807 } 8808 if (verificationParams.getReferrer() != null) { 8809 verification.putExtra(Intent.EXTRA_REFERRER, 8810 verificationParams.getReferrer()); 8811 } 8812 if (verificationParams.getOriginatingUid() >= 0) { 8813 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 8814 verificationParams.getOriginatingUid()); 8815 } 8816 if (verificationParams.getInstallerUid() >= 0) { 8817 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 8818 verificationParams.getInstallerUid()); 8819 } 8820 } 8821 8822 final PackageVerificationState verificationState = new PackageVerificationState( 8823 requiredUid, args); 8824 8825 mPendingVerification.append(verificationId, verificationState); 8826 8827 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 8828 receivers, verificationState); 8829 8830 /* 8831 * If any sufficient verifiers were listed in the package 8832 * manifest, attempt to ask them. 8833 */ 8834 if (sufficientVerifiers != null) { 8835 final int N = sufficientVerifiers.size(); 8836 if (N == 0) { 8837 Slog.i(TAG, "Additional verifiers required, but none installed."); 8838 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 8839 } else { 8840 for (int i = 0; i < N; i++) { 8841 final ComponentName verifierComponent = sufficientVerifiers.get(i); 8842 8843 final Intent sufficientIntent = new Intent(verification); 8844 sufficientIntent.setComponent(verifierComponent); 8845 8846 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 8847 } 8848 } 8849 } 8850 8851 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 8852 mRequiredVerifierPackage, receivers); 8853 if (ret == PackageManager.INSTALL_SUCCEEDED 8854 && mRequiredVerifierPackage != null) { 8855 /* 8856 * Send the intent to the required verification agent, 8857 * but only start the verification timeout after the 8858 * target BroadcastReceivers have run. 8859 */ 8860 verification.setComponent(requiredVerifierComponent); 8861 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 8862 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8863 new BroadcastReceiver() { 8864 @Override 8865 public void onReceive(Context context, Intent intent) { 8866 final Message msg = mHandler 8867 .obtainMessage(CHECK_PENDING_VERIFICATION); 8868 msg.arg1 = verificationId; 8869 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 8870 } 8871 }, null, 0, null, null); 8872 8873 /* 8874 * We don't want the copy to proceed until verification 8875 * succeeds, so null out this field. 8876 */ 8877 mArgs = null; 8878 } 8879 } else { 8880 /* 8881 * No package verification is enabled, so immediately start 8882 * the remote call to initiate copy using temporary file. 8883 */ 8884 ret = args.copyApk(mContainerService, true); 8885 } 8886 } 8887 8888 mRet = ret; 8889 } 8890 8891 @Override 8892 void handleReturnCode() { 8893 // If mArgs is null, then MCS couldn't be reached. When it 8894 // reconnects, it will try again to install. At that point, this 8895 // will succeed. 8896 if (mArgs != null) { 8897 processPendingInstall(mArgs, mRet); 8898 } 8899 } 8900 8901 @Override 8902 void handleServiceError() { 8903 mArgs = createInstallArgs(this); 8904 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8905 } 8906 8907 public boolean isForwardLocked() { 8908 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8909 } 8910 } 8911 8912 /* 8913 * Utility class used in movePackage api. 8914 * srcArgs and targetArgs are not set for invalid flags and make 8915 * sure to do null checks when invoking methods on them. 8916 * We probably want to return ErrorPrams for both failed installs 8917 * and moves. 8918 */ 8919 class MoveParams extends HandlerParams { 8920 final IPackageMoveObserver observer; 8921 final int flags; 8922 final String packageName; 8923 final InstallArgs srcArgs; 8924 final InstallArgs targetArgs; 8925 int uid; 8926 int mRet; 8927 8928 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags, 8929 String packageName, String[] instructionSets, int uid, UserHandle user, 8930 boolean isMultiArch) { 8931 super(user); 8932 this.srcArgs = srcArgs; 8933 this.observer = observer; 8934 this.flags = flags; 8935 this.packageName = packageName; 8936 this.uid = uid; 8937 if (srcArgs != null) { 8938 final String codePath = srcArgs.getCodePath(); 8939 targetArgs = createInstallArgsForMoveTarget(codePath, flags, packageName, 8940 instructionSets, isMultiArch); 8941 } else { 8942 targetArgs = null; 8943 } 8944 } 8945 8946 @Override 8947 public String toString() { 8948 return "MoveParams{" 8949 + Integer.toHexString(System.identityHashCode(this)) 8950 + " " + packageName + "}"; 8951 } 8952 8953 public void handleStartCopy() throws RemoteException { 8954 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8955 // Check for storage space on target medium 8956 if (!targetArgs.checkFreeStorage(mContainerService)) { 8957 Log.w(TAG, "Insufficient storage to install"); 8958 return; 8959 } 8960 8961 mRet = srcArgs.doPreCopy(); 8962 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8963 return; 8964 } 8965 8966 mRet = targetArgs.copyApk(mContainerService, false); 8967 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8968 srcArgs.doPostCopy(uid); 8969 return; 8970 } 8971 8972 mRet = srcArgs.doPostCopy(uid); 8973 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8974 return; 8975 } 8976 8977 mRet = targetArgs.doPreInstall(mRet); 8978 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8979 return; 8980 } 8981 8982 if (DEBUG_SD_INSTALL) { 8983 StringBuilder builder = new StringBuilder(); 8984 if (srcArgs != null) { 8985 builder.append("src: "); 8986 builder.append(srcArgs.getCodePath()); 8987 } 8988 if (targetArgs != null) { 8989 builder.append(" target : "); 8990 builder.append(targetArgs.getCodePath()); 8991 } 8992 Log.i(TAG, builder.toString()); 8993 } 8994 } 8995 8996 @Override 8997 void handleReturnCode() { 8998 targetArgs.doPostInstall(mRet, uid); 8999 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 9000 if (mRet == PackageManager.INSTALL_SUCCEEDED) { 9001 currentStatus = PackageManager.MOVE_SUCCEEDED; 9002 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){ 9003 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 9004 } 9005 processPendingMove(this, currentStatus); 9006 } 9007 9008 @Override 9009 void handleServiceError() { 9010 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9011 } 9012 } 9013 9014 /** 9015 * Used during creation of InstallArgs 9016 * 9017 * @param flags package installation flags 9018 * @return true if should be installed on external storage 9019 */ 9020 private static boolean installOnSd(int flags) { 9021 if ((flags & PackageManager.INSTALL_INTERNAL) != 0) { 9022 return false; 9023 } 9024 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) { 9025 return true; 9026 } 9027 return false; 9028 } 9029 9030 /** 9031 * Used during creation of InstallArgs 9032 * 9033 * @param flags package installation flags 9034 * @return true if should be installed as forward locked 9035 */ 9036 private static boolean installForwardLocked(int flags) { 9037 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9038 } 9039 9040 private InstallArgs createInstallArgs(InstallParams params) { 9041 // TODO: extend to support incoming zero-copy locations 9042 9043 if (installOnSd(params.flags) || params.isForwardLocked()) { 9044 return new AsecInstallArgs(params); 9045 } else { 9046 return new FileInstallArgs(params); 9047 } 9048 } 9049 9050 /** 9051 * Create args that describe an existing installed package. Typically used 9052 * when cleaning up old installs, or used as a move source. 9053 */ 9054 private InstallArgs createInstallArgsForExisting(int flags, String codePath, 9055 String resourcePath, String nativeLibraryRoot, String[] instructionSets, 9056 boolean isMultiArch) { 9057 final boolean isInAsec; 9058 if (installOnSd(flags)) { 9059 /* Apps on SD card are always in ASEC containers. */ 9060 isInAsec = true; 9061 } else if (installForwardLocked(flags) 9062 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 9063 /* 9064 * Forward-locked apps are only in ASEC containers if they're the 9065 * new style 9066 */ 9067 isInAsec = true; 9068 } else { 9069 isInAsec = false; 9070 } 9071 9072 if (isInAsec) { 9073 return new AsecInstallArgs(codePath, instructionSets, 9074 installOnSd(flags), installForwardLocked(flags), isMultiArch); 9075 } else { 9076 return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot, 9077 instructionSets, isMultiArch); 9078 } 9079 } 9080 9081 private InstallArgs createInstallArgsForMoveTarget(String codePath, int flags, String pkgName, 9082 String[] instructionSets, boolean isMultiArch) { 9083 final File codeFile = new File(codePath); 9084 if (installOnSd(flags) || installForwardLocked(flags)) { 9085 String cid = getNextCodePath(codePath, pkgName, "/" 9086 + AsecInstallArgs.RES_FILE_NAME); 9087 return new AsecInstallArgs(codeFile, cid, instructionSets, installOnSd(flags), 9088 installForwardLocked(flags), isMultiArch); 9089 } else { 9090 return new FileInstallArgs(codeFile, instructionSets, isMultiArch); 9091 } 9092 } 9093 9094 static abstract class InstallArgs { 9095 /** @see InstallParams#originFile */ 9096 final File originFile; 9097 /** @see InstallParams#originStaged */ 9098 final boolean originStaged; 9099 9100 // TODO: define inherit location 9101 9102 final IPackageInstallObserver2 observer; 9103 // Always refers to PackageManager flags only 9104 final int flags; 9105 final String installerPackageName; 9106 final ManifestDigest manifestDigest; 9107 final UserHandle user; 9108 final String abiOverride; 9109 final boolean multiArch; 9110 9111 // The list of instruction sets supported by this app. This is currently 9112 // only used during the rmdex() phase to clean up resources. We can get rid of this 9113 // if we move dex files under the common app path. 9114 /* nullable */ String[] instructionSets; 9115 9116 InstallArgs(File originFile, boolean originStaged, IPackageInstallObserver2 observer, 9117 int flags, String installerPackageName, ManifestDigest manifestDigest, 9118 UserHandle user, String[] instructionSets, 9119 String abiOverride, boolean multiArch) { 9120 this.originFile = originFile; 9121 this.originStaged = originStaged; 9122 this.flags = flags; 9123 this.observer = observer; 9124 this.installerPackageName = installerPackageName; 9125 this.manifestDigest = manifestDigest; 9126 this.user = user; 9127 this.instructionSets = instructionSets; 9128 this.abiOverride = abiOverride; 9129 this.multiArch = multiArch; 9130 } 9131 9132 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 9133 abstract int doPreInstall(int status); 9134 9135 /** 9136 * Rename package into final resting place. All paths on the given 9137 * scanned package should be updated to reflect the rename. 9138 */ 9139 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 9140 abstract int doPostInstall(int status, int uid); 9141 9142 /** @see PackageSettingBase#codePathString */ 9143 abstract String getCodePath(); 9144 /** @see PackageSettingBase#resourcePathString */ 9145 abstract String getResourcePath(); 9146 abstract String getLegacyNativeLibraryPath(); 9147 9148 // Need installer lock especially for dex file removal. 9149 abstract void cleanUpResourcesLI(); 9150 abstract boolean doPostDeleteLI(boolean delete); 9151 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9152 9153 /** 9154 * Called before the source arguments are copied. This is used mostly 9155 * for MoveParams when it needs to read the source file to put it in the 9156 * destination. 9157 */ 9158 int doPreCopy() { 9159 return PackageManager.INSTALL_SUCCEEDED; 9160 } 9161 9162 /** 9163 * Called after the source arguments are copied. This is used mostly for 9164 * MoveParams when it needs to read the source file to put it in the 9165 * destination. 9166 * 9167 * @return 9168 */ 9169 int doPostCopy(int uid) { 9170 return PackageManager.INSTALL_SUCCEEDED; 9171 } 9172 9173 protected boolean isFwdLocked() { 9174 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9175 } 9176 9177 UserHandle getUser() { 9178 return user; 9179 } 9180 } 9181 9182 /** 9183 * Logic to handle installation of non-ASEC applications, including copying 9184 * and renaming logic. 9185 */ 9186 class FileInstallArgs extends InstallArgs { 9187 private File codeFile; 9188 private File resourceFile; 9189 private File legacyNativeLibraryPath; 9190 9191 // Example topology: 9192 // /data/app/com.example/base.apk 9193 // /data/app/com.example/split_foo.apk 9194 // /data/app/com.example/lib/arm/libfoo.so 9195 // /data/app/com.example/lib/arm64/libfoo.so 9196 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 9197 9198 /** New install */ 9199 FileInstallArgs(InstallParams params) { 9200 super(params.originFile, params.originStaged, params.observer, params.flags, 9201 params.installerPackageName, params.getManifestDigest(), params.getUser(), 9202 null /* instruction sets */, params.packageAbiOverride, 9203 params.multiArch); 9204 if (isFwdLocked()) { 9205 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 9206 } 9207 } 9208 9209 /** Existing install */ 9210 FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath, 9211 String[] instructionSets, boolean isMultiArch) { 9212 super(null, false, null, 0, null, null, null, instructionSets, null, isMultiArch); 9213 this.codeFile = (codePath != null) ? new File(codePath) : null; 9214 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 9215 this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ? 9216 new File(legacyNativeLibraryPath) : null; 9217 } 9218 9219 /** New install from existing */ 9220 FileInstallArgs(File originFile, String[] instructionSets, boolean isMultiArch) { 9221 super(originFile, false, null, 0, null, null, null, instructionSets, null, 9222 isMultiArch); 9223 } 9224 9225 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9226 final long lowThreshold; 9227 9228 final DeviceStorageMonitorInternal 9229 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 9230 if (dsm == null) { 9231 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 9232 lowThreshold = 0L; 9233 } else { 9234 if (dsm.isMemoryLow()) { 9235 Log.w(TAG, "Memory is reported as being too low; aborting package install"); 9236 return false; 9237 } 9238 9239 lowThreshold = dsm.getMemoryLowThreshold(); 9240 } 9241 9242 return imcs.checkInternalFreeStorage(originFile.getAbsolutePath(), isFwdLocked(), 9243 lowThreshold); 9244 } 9245 9246 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9247 int ret = PackageManager.INSTALL_SUCCEEDED; 9248 9249 if (originStaged) { 9250 Slog.d(TAG, originFile + " already staged; skipping copy"); 9251 codeFile = originFile; 9252 resourceFile = originFile; 9253 } else { 9254 try { 9255 final File tempDir = mInstallerService.allocateSessionDir(); 9256 codeFile = tempDir; 9257 resourceFile = tempDir; 9258 } catch (IOException e) { 9259 Slog.w(TAG, "Failed to create copy file: " + e); 9260 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9261 } 9262 9263 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 9264 @Override 9265 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 9266 if (!FileUtils.isValidExtFilename(name)) { 9267 throw new IllegalArgumentException("Invalid filename: " + name); 9268 } 9269 try { 9270 final File file = new File(codeFile, name); 9271 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 9272 O_RDWR | O_CREAT, 0644); 9273 Os.chmod(file.getAbsolutePath(), 0644); 9274 return new ParcelFileDescriptor(fd); 9275 } catch (ErrnoException e) { 9276 throw new RemoteException("Failed to open: " + e.getMessage()); 9277 } 9278 } 9279 }; 9280 9281 ret = imcs.copyPackage(originFile.getAbsolutePath(), target); 9282 if (ret != PackageManager.INSTALL_SUCCEEDED) { 9283 Slog.e(TAG, "Failed to copy package"); 9284 return ret; 9285 } 9286 } 9287 9288 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 9289 NativeLibraryHelper.Handle handle = null; 9290 try { 9291 handle = NativeLibraryHelper.Handle.create(codeFile); 9292 if (multiArch) { 9293 // Warn if we've set an abiOverride for multi-lib packages.. 9294 // By definition, we need to copy both 32 and 64 bit libraries for 9295 // such packages. 9296 if (abiOverride != null && !CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 9297 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 9298 } 9299 9300 int copyRet = PackageManager.NO_NATIVE_LIBRARIES; 9301 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 9302 copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot, 9303 Build.SUPPORTED_32_BIT_ABIS, true /* use isa specific subdirs */); 9304 maybeThrowExceptionForMultiArchCopy("Failure copying 32 bit native libraries", copyRet); 9305 } 9306 9307 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 9308 copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot, 9309 Build.SUPPORTED_64_BIT_ABIS, true /* use isa specific subdirs */); 9310 maybeThrowExceptionForMultiArchCopy("Failure copying 64 bit native libraries", copyRet); 9311 } 9312 } else { 9313 final String cpuAbiOverride = deriveAbiOverride(this.abiOverride, null /* package setting */); 9314 String[] abiList = (cpuAbiOverride != null) ? 9315 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 9316 9317 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 9318 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9319 abiList = Build.SUPPORTED_32_BIT_ABIS; 9320 } 9321 9322 int copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot, abiList, 9323 true /* use isa specific subdirs */); 9324 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9325 Slog.w(TAG, "Failure copying native libraries [errorCode=" + copyRet + "]"); 9326 return copyRet; 9327 } 9328 } 9329 } catch (IOException e) { 9330 Slog.e(TAG, "Copying native libraries failed", e); 9331 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9332 } catch (PackageManagerException pme) { 9333 Slog.e(TAG, "Copying native libraries failed", pme); 9334 ret = pme.error; 9335 } finally { 9336 IoUtils.closeQuietly(handle); 9337 } 9338 9339 return ret; 9340 } 9341 9342 int doPreInstall(int status) { 9343 if (status != PackageManager.INSTALL_SUCCEEDED) { 9344 cleanUp(); 9345 } 9346 return status; 9347 } 9348 9349 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9350 if (status != PackageManager.INSTALL_SUCCEEDED) { 9351 cleanUp(); 9352 return false; 9353 } else { 9354 final File beforeCodeFile = codeFile; 9355 final File afterCodeFile = getNextCodePath(pkg.packageName); 9356 9357 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 9358 try { 9359 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 9360 } catch (ErrnoException e) { 9361 Slog.d(TAG, "Failed to rename", e); 9362 return false; 9363 } 9364 9365 if (!SELinux.restoreconRecursive(afterCodeFile)) { 9366 Slog.d(TAG, "Failed to restorecon"); 9367 return false; 9368 } 9369 9370 // Reflect the rename internally 9371 codeFile = afterCodeFile; 9372 resourceFile = afterCodeFile; 9373 9374 // Reflect the rename in scanned details 9375 pkg.codePath = afterCodeFile.getAbsolutePath(); 9376 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9377 pkg.baseCodePath); 9378 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9379 pkg.splitCodePaths); 9380 9381 // Reflect the rename in app info 9382 pkg.applicationInfo.setCodePath(pkg.codePath); 9383 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9384 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9385 pkg.applicationInfo.setResourcePath(pkg.codePath); 9386 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9387 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9388 9389 return true; 9390 } 9391 } 9392 9393 int doPostInstall(int status, int uid) { 9394 if (status != PackageManager.INSTALL_SUCCEEDED) { 9395 cleanUp(); 9396 } 9397 return status; 9398 } 9399 9400 @Override 9401 String getCodePath() { 9402 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 9403 } 9404 9405 @Override 9406 String getResourcePath() { 9407 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 9408 } 9409 9410 @Override 9411 String getLegacyNativeLibraryPath() { 9412 return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null; 9413 } 9414 9415 private boolean cleanUp() { 9416 if (codeFile == null || !codeFile.exists()) { 9417 return false; 9418 } 9419 9420 if (codeFile.isDirectory()) { 9421 FileUtils.deleteContents(codeFile); 9422 } 9423 codeFile.delete(); 9424 9425 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 9426 resourceFile.delete(); 9427 } 9428 9429 if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) { 9430 if (!FileUtils.deleteContents(legacyNativeLibraryPath)) { 9431 Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath); 9432 } 9433 legacyNativeLibraryPath.delete(); 9434 } 9435 9436 return true; 9437 } 9438 9439 void cleanUpResourcesLI() { 9440 // Try enumerating all code paths before deleting 9441 List<String> allCodePaths = Collections.EMPTY_LIST; 9442 if (codeFile != null && codeFile.exists()) { 9443 try { 9444 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9445 allCodePaths = pkg.getAllCodePaths(); 9446 } catch (PackageParserException e) { 9447 // Ignored; we tried our best 9448 } 9449 } 9450 9451 cleanUp(); 9452 9453 if (!allCodePaths.isEmpty()) { 9454 if (instructionSets == null) { 9455 throw new IllegalStateException("instructionSet == null"); 9456 } 9457 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9458 for (String codePath : allCodePaths) { 9459 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9460 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9461 if (retCode < 0) { 9462 Slog.w(TAG, "Couldn't remove dex file for package: " 9463 + " at location " + codePath + ", retcode=" + retCode); 9464 // we don't consider this to be a failure of the core package deletion 9465 } 9466 } 9467 } 9468 } 9469 } 9470 9471 boolean doPostDeleteLI(boolean delete) { 9472 // XXX err, shouldn't we respect the delete flag? 9473 cleanUpResourcesLI(); 9474 return true; 9475 } 9476 } 9477 9478 private boolean isAsecExternal(String cid) { 9479 final String asecPath = PackageHelper.getSdFilesystem(cid); 9480 return !asecPath.startsWith(mAsecInternalPath); 9481 } 9482 9483 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 9484 PackageManagerException { 9485 if (copyRet < 0) { 9486 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 9487 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 9488 throw new PackageManagerException(copyRet, message); 9489 } 9490 } 9491 } 9492 9493 /** 9494 * Extract the MountService "container ID" from the full code path of an 9495 * .apk. 9496 */ 9497 static String cidFromCodePath(String fullCodePath) { 9498 int eidx = fullCodePath.lastIndexOf("/"); 9499 String subStr1 = fullCodePath.substring(0, eidx); 9500 int sidx = subStr1.lastIndexOf("/"); 9501 return subStr1.substring(sidx+1, eidx); 9502 } 9503 9504 /** 9505 * Logic to handle installation of ASEC applications, including copying and 9506 * renaming logic. 9507 */ 9508 class AsecInstallArgs extends InstallArgs { 9509 // TODO: teach about handling cluster directories 9510 9511 static final String RES_FILE_NAME = "pkg.apk"; 9512 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 9513 9514 String cid; 9515 String packagePath; 9516 String resourcePath; 9517 String legacyNativeLibraryDir; 9518 9519 /** New install */ 9520 AsecInstallArgs(InstallParams params) { 9521 super(params.originFile, params.originStaged, params.observer, params.flags, 9522 params.installerPackageName, params.getManifestDigest(), 9523 params.getUser(), null /* instruction sets */, 9524 params.packageAbiOverride, params.multiArch); 9525 } 9526 9527 /** Existing install */ 9528 AsecInstallArgs(String fullCodePath, String[] instructionSets, 9529 boolean isExternal, boolean isForwardLocked, boolean isMultiArch) { 9530 super(null, false, null, (isExternal ? INSTALL_EXTERNAL : 0) 9531 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9532 instructionSets, null, isMultiArch); 9533 // Extract cid from fullCodePath 9534 int eidx = fullCodePath.lastIndexOf("/"); 9535 String subStr1 = fullCodePath.substring(0, eidx); 9536 int sidx = subStr1.lastIndexOf("/"); 9537 cid = subStr1.substring(sidx+1, eidx); 9538 setCachePath(subStr1); 9539 } 9540 9541 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked, 9542 boolean isMultiArch) { 9543 super(null, false, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 9544 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9545 instructionSets, null, isMultiArch); 9546 this.cid = cid; 9547 setCachePath(PackageHelper.getSdDir(cid)); 9548 } 9549 9550 /** New install from existing */ 9551 AsecInstallArgs(File originPackageFile, String cid, String[] instructionSets, 9552 boolean isExternal, boolean isForwardLocked, boolean isMultiArch) { 9553 super(originPackageFile, false, null, (isExternal ? INSTALL_EXTERNAL : 0) 9554 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9555 instructionSets, null, isMultiArch); 9556 this.cid = cid; 9557 } 9558 9559 void createCopyFile() { 9560 cid = getTempContainerId(); 9561 } 9562 9563 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9564 return imcs.checkExternalFreeStorage(originFile.getAbsolutePath(), isFwdLocked(), 9565 abiOverride); 9566 } 9567 9568 private final boolean isExternal() { 9569 return (flags & PackageManager.INSTALL_EXTERNAL) != 0; 9570 } 9571 9572 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9573 if (temp) { 9574 createCopyFile(); 9575 } else { 9576 /* 9577 * Pre-emptively destroy the container since it's destroyed if 9578 * copying fails due to it existing anyway. 9579 */ 9580 PackageHelper.destroySdDir(cid); 9581 } 9582 9583 final String newCachePath = imcs.copyPackageToContainer( 9584 originFile.getAbsolutePath(), cid, getEncryptKey(), isExternal(), 9585 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 9586 9587 if (newCachePath != null) { 9588 setCachePath(newCachePath); 9589 return PackageManager.INSTALL_SUCCEEDED; 9590 } else { 9591 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9592 } 9593 } 9594 9595 @Override 9596 String getCodePath() { 9597 return packagePath; 9598 } 9599 9600 @Override 9601 String getResourcePath() { 9602 return resourcePath; 9603 } 9604 9605 @Override 9606 String getLegacyNativeLibraryPath() { 9607 return legacyNativeLibraryDir; 9608 } 9609 9610 int doPreInstall(int status) { 9611 if (status != PackageManager.INSTALL_SUCCEEDED) { 9612 // Destroy container 9613 PackageHelper.destroySdDir(cid); 9614 } else { 9615 boolean mounted = PackageHelper.isContainerMounted(cid); 9616 if (!mounted) { 9617 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), 9618 Process.SYSTEM_UID); 9619 if (newCachePath != null) { 9620 setCachePath(newCachePath); 9621 } else { 9622 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9623 } 9624 } 9625 } 9626 return status; 9627 } 9628 9629 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9630 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 9631 String newCachePath = null; 9632 if (PackageHelper.isContainerMounted(cid)) { 9633 // Unmount the container 9634 if (!PackageHelper.unMountSdDir(cid)) { 9635 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9636 return false; 9637 } 9638 } 9639 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9640 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9641 " which might be stale. Will try to clean up."); 9642 // Clean up the stale container and proceed to recreate. 9643 if (!PackageHelper.destroySdDir(newCacheId)) { 9644 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9645 return false; 9646 } 9647 // Successfully cleaned up stale container. Try to rename again. 9648 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9649 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9650 + " inspite of cleaning it up."); 9651 return false; 9652 } 9653 } 9654 if (!PackageHelper.isContainerMounted(newCacheId)) { 9655 Slog.w(TAG, "Mounting container " + newCacheId); 9656 newCachePath = PackageHelper.mountSdDir(newCacheId, 9657 getEncryptKey(), Process.SYSTEM_UID); 9658 } else { 9659 newCachePath = PackageHelper.getSdDir(newCacheId); 9660 } 9661 if (newCachePath == null) { 9662 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9663 return false; 9664 } 9665 Log.i(TAG, "Succesfully renamed " + cid + 9666 " to " + newCacheId + 9667 " at new path: " + newCachePath); 9668 cid = newCacheId; 9669 setCachePath(newCachePath); 9670 9671 // TODO: extend to support split APKs 9672 pkg.codePath = getCodePath(); 9673 pkg.baseCodePath = getCodePath(); 9674 pkg.splitCodePaths = null; 9675 9676 pkg.applicationInfo.setCodePath(getCodePath()); 9677 pkg.applicationInfo.setBaseCodePath(getCodePath()); 9678 pkg.applicationInfo.setSplitCodePaths(null); 9679 pkg.applicationInfo.setResourcePath(getResourcePath()); 9680 pkg.applicationInfo.setBaseResourcePath(getResourcePath()); 9681 pkg.applicationInfo.setSplitResourcePaths(null); 9682 9683 return true; 9684 } 9685 9686 private void setCachePath(String newCachePath) { 9687 File cachePath = new File(newCachePath); 9688 legacyNativeLibraryDir = new File(cachePath, LIB_DIR_NAME).getPath(); 9689 packagePath = new File(cachePath, RES_FILE_NAME).getPath(); 9690 9691 if (isFwdLocked()) { 9692 resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath(); 9693 } else { 9694 resourcePath = packagePath; 9695 } 9696 } 9697 9698 int doPostInstall(int status, int uid) { 9699 if (status != PackageManager.INSTALL_SUCCEEDED) { 9700 cleanUp(); 9701 } else { 9702 final int groupOwner; 9703 final String protectedFile; 9704 if (isFwdLocked()) { 9705 groupOwner = UserHandle.getSharedAppGid(uid); 9706 protectedFile = RES_FILE_NAME; 9707 } else { 9708 groupOwner = -1; 9709 protectedFile = null; 9710 } 9711 9712 if (uid < Process.FIRST_APPLICATION_UID 9713 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9714 Slog.e(TAG, "Failed to finalize " + cid); 9715 PackageHelper.destroySdDir(cid); 9716 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9717 } 9718 9719 boolean mounted = PackageHelper.isContainerMounted(cid); 9720 if (!mounted) { 9721 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9722 } 9723 } 9724 return status; 9725 } 9726 9727 private void cleanUp() { 9728 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9729 9730 // Destroy secure container 9731 PackageHelper.destroySdDir(cid); 9732 } 9733 9734 void cleanUpResourcesLI() { 9735 String sourceFile = getCodePath(); 9736 // Remove dex file 9737 if (instructionSets == null) { 9738 throw new IllegalStateException("instructionSet == null"); 9739 } 9740 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9741 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9742 int retCode = mInstaller.rmdex(sourceFile, dexCodeInstructionSet); 9743 if (retCode < 0) { 9744 Slog.w(TAG, "Couldn't remove dex file for package: " 9745 + " at location " 9746 + sourceFile.toString() + ", retcode=" + retCode); 9747 // we don't consider this to be a failure of the core package deletion 9748 } 9749 } 9750 cleanUp(); 9751 } 9752 9753 boolean matchContainer(String app) { 9754 if (cid.startsWith(app)) { 9755 return true; 9756 } 9757 return false; 9758 } 9759 9760 String getPackageName() { 9761 return getAsecPackageName(cid); 9762 } 9763 9764 boolean doPostDeleteLI(boolean delete) { 9765 boolean ret = false; 9766 boolean mounted = PackageHelper.isContainerMounted(cid); 9767 if (mounted) { 9768 // Unmount first 9769 ret = PackageHelper.unMountSdDir(cid); 9770 } 9771 if (ret && delete) { 9772 cleanUpResourcesLI(); 9773 } 9774 return ret; 9775 } 9776 9777 @Override 9778 int doPreCopy() { 9779 if (isFwdLocked()) { 9780 if (!PackageHelper.fixSdPermissions(cid, 9781 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 9782 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9783 } 9784 } 9785 9786 return PackageManager.INSTALL_SUCCEEDED; 9787 } 9788 9789 @Override 9790 int doPostCopy(int uid) { 9791 if (isFwdLocked()) { 9792 if (uid < Process.FIRST_APPLICATION_UID 9793 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 9794 RES_FILE_NAME)) { 9795 Slog.e(TAG, "Failed to finalize " + cid); 9796 PackageHelper.destroySdDir(cid); 9797 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9798 } 9799 } 9800 9801 return PackageManager.INSTALL_SUCCEEDED; 9802 } 9803 } 9804 9805 static String getAsecPackageName(String packageCid) { 9806 int idx = packageCid.lastIndexOf("-"); 9807 if (idx == -1) { 9808 return packageCid; 9809 } 9810 return packageCid.substring(0, idx); 9811 } 9812 9813 // Utility method used to create code paths based on package name and available index. 9814 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 9815 String idxStr = ""; 9816 int idx = 1; 9817 // Fall back to default value of idx=1 if prefix is not 9818 // part of oldCodePath 9819 if (oldCodePath != null) { 9820 String subStr = oldCodePath; 9821 // Drop the suffix right away 9822 if (suffix != null && subStr.endsWith(suffix)) { 9823 subStr = subStr.substring(0, subStr.length() - suffix.length()); 9824 } 9825 // If oldCodePath already contains prefix find out the 9826 // ending index to either increment or decrement. 9827 int sidx = subStr.lastIndexOf(prefix); 9828 if (sidx != -1) { 9829 subStr = subStr.substring(sidx + prefix.length()); 9830 if (subStr != null) { 9831 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 9832 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 9833 } 9834 try { 9835 idx = Integer.parseInt(subStr); 9836 if (idx <= 1) { 9837 idx++; 9838 } else { 9839 idx--; 9840 } 9841 } catch(NumberFormatException e) { 9842 } 9843 } 9844 } 9845 } 9846 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 9847 return prefix + idxStr; 9848 } 9849 9850 private File getNextCodePath(String packageName) { 9851 int suffix = 1; 9852 File result; 9853 do { 9854 result = new File(mAppInstallDir, packageName + "-" + suffix); 9855 suffix++; 9856 } while (result.exists()); 9857 return result; 9858 } 9859 9860 // Utility method used to ignore ADD/REMOVE events 9861 // by directory observer. 9862 private static boolean ignoreCodePath(String fullPathStr) { 9863 String apkName = deriveCodePathName(fullPathStr); 9864 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 9865 if (idx != -1 && ((idx+1) < apkName.length())) { 9866 // Make sure the package ends with a numeral 9867 String version = apkName.substring(idx+1); 9868 try { 9869 Integer.parseInt(version); 9870 return true; 9871 } catch (NumberFormatException e) {} 9872 } 9873 return false; 9874 } 9875 9876 // Utility method that returns the relative package path with respect 9877 // to the installation directory. Like say for /data/data/com.test-1.apk 9878 // string com.test-1 is returned. 9879 static String deriveCodePathName(String codePath) { 9880 if (codePath == null) { 9881 return null; 9882 } 9883 final File codeFile = new File(codePath); 9884 final String name = codeFile.getName(); 9885 if (codeFile.isDirectory()) { 9886 return name; 9887 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 9888 final int lastDot = name.lastIndexOf('.'); 9889 return name.substring(0, lastDot); 9890 } else { 9891 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 9892 return null; 9893 } 9894 } 9895 9896 class PackageInstalledInfo { 9897 String name; 9898 int uid; 9899 // The set of users that originally had this package installed. 9900 int[] origUsers; 9901 // The set of users that now have this package installed. 9902 int[] newUsers; 9903 PackageParser.Package pkg; 9904 int returnCode; 9905 String returnMsg; 9906 PackageRemovedInfo removedInfo; 9907 9908 public void setError(int code, String msg) { 9909 returnCode = code; 9910 returnMsg = msg; 9911 Slog.w(TAG, msg); 9912 } 9913 9914 public void setError(String msg, PackageParserException e) { 9915 returnCode = e.error; 9916 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9917 Slog.w(TAG, msg, e); 9918 } 9919 9920 public void setError(String msg, PackageManagerException e) { 9921 returnCode = e.error; 9922 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9923 Slog.w(TAG, msg, e); 9924 } 9925 9926 // In some error cases we want to convey more info back to the observer 9927 String origPackage; 9928 String origPermission; 9929 } 9930 9931 /* 9932 * Install a non-existing package. 9933 */ 9934 private void installNewPackageLI(PackageParser.Package pkg, 9935 int parseFlags, int scanMode, UserHandle user, 9936 String installerPackageName, PackageInstalledInfo res) { 9937 // Remember this for later, in case we need to rollback this install 9938 String pkgName = pkg.packageName; 9939 9940 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 9941 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 9942 synchronized(mPackages) { 9943 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 9944 // A package with the same name is already installed, though 9945 // it has been renamed to an older name. The package we 9946 // are trying to install should be installed as an update to 9947 // the existing one, but that has not been requested, so bail. 9948 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9949 + " without first uninstalling package running as " 9950 + mSettings.mRenamedPackages.get(pkgName)); 9951 return; 9952 } 9953 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.codePath)) { 9954 // Don't allow installation over an existing package with the same name. 9955 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9956 + " without first uninstalling."); 9957 return; 9958 } 9959 } 9960 9961 try { 9962 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode, 9963 System.currentTimeMillis(), user); 9964 9965 updateSettingsLI(newPackage, installerPackageName, null, null, res); 9966 // delete the partially installed application. the data directory will have to be 9967 // restored if it was already existing 9968 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9969 // remove package from internal structures. Note that we want deletePackageX to 9970 // delete the package data and cache directories that it created in 9971 // scanPackageLocked, unless those directories existed before we even tried to 9972 // install. 9973 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 9974 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 9975 res.removedInfo, true); 9976 } 9977 9978 } catch (PackageManagerException e) { 9979 res.setError("Package couldn't be installed in " + pkg.codePath, e); 9980 } 9981 } 9982 9983 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 9984 // Upgrade keysets are being used. Determine if new package has a superset of the 9985 // required keys. 9986 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 9987 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9988 for (int i = 0; i < upgradeKeySets.length; i++) { 9989 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 9990 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 9991 return true; 9992 } 9993 } 9994 return false; 9995 } 9996 9997 private void replacePackageLI(PackageParser.Package pkg, 9998 int parseFlags, int scanMode, UserHandle user, 9999 String installerPackageName, PackageInstalledInfo res) { 10000 PackageParser.Package oldPackage; 10001 String pkgName = pkg.packageName; 10002 int[] allUsers; 10003 boolean[] perUserInstalled; 10004 10005 // First find the old package info and check signatures 10006 synchronized(mPackages) { 10007 oldPackage = mPackages.get(pkgName); 10008 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 10009 PackageSetting ps = mSettings.mPackages.get(pkgName); 10010 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 10011 // default to original signature matching 10012 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 10013 != PackageManager.SIGNATURE_MATCH) { 10014 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 10015 "New package has a different signature: " + pkgName); 10016 return; 10017 } 10018 } else { 10019 if(!checkUpgradeKeySetLP(ps, pkg)) { 10020 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 10021 "New package not signed by keys specified by upgrade-keysets: " 10022 + pkgName); 10023 return; 10024 } 10025 } 10026 10027 // In case of rollback, remember per-user/profile install state 10028 allUsers = sUserManager.getUserIds(); 10029 perUserInstalled = new boolean[allUsers.length]; 10030 for (int i = 0; i < allUsers.length; i++) { 10031 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10032 } 10033 } 10034 10035 boolean sysPkg = (isSystemApp(oldPackage)); 10036 if (sysPkg) { 10037 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 10038 user, allUsers, perUserInstalled, installerPackageName, res); 10039 } else { 10040 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 10041 user, allUsers, perUserInstalled, installerPackageName, res); 10042 } 10043 } 10044 10045 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 10046 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 10047 int[] allUsers, boolean[] perUserInstalled, 10048 String installerPackageName, PackageInstalledInfo res) { 10049 String pkgName = deletedPackage.packageName; 10050 boolean deletedPkg = true; 10051 boolean updatedSettings = false; 10052 10053 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 10054 + deletedPackage); 10055 long origUpdateTime; 10056 if (pkg.mExtras != null) { 10057 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 10058 } else { 10059 origUpdateTime = 0; 10060 } 10061 10062 // First delete the existing package while retaining the data directory 10063 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 10064 res.removedInfo, true)) { 10065 // If the existing package wasn't successfully deleted 10066 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 10067 deletedPkg = false; 10068 } else { 10069 // Successfully deleted the old package. Now proceed with re-installation 10070 deleteCodeCacheDirsLI(pkgName); 10071 try { 10072 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 10073 scanMode | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 10074 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10075 updatedSettings = true; 10076 } catch (PackageManagerException e) { 10077 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10078 } 10079 } 10080 10081 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10082 // remove package from internal structures. Note that we want deletePackageX to 10083 // delete the package data and cache directories that it created in 10084 // scanPackageLocked, unless those directories existed before we even tried to 10085 // install. 10086 if(updatedSettings) { 10087 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 10088 deletePackageLI( 10089 pkgName, null, true, allUsers, perUserInstalled, 10090 PackageManager.DELETE_KEEP_DATA, 10091 res.removedInfo, true); 10092 } 10093 // Since we failed to install the new package we need to restore the old 10094 // package that we deleted. 10095 if (deletedPkg) { 10096 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 10097 File restoreFile = new File(deletedPackage.codePath); 10098 // Parse old package 10099 boolean oldOnSd = isExternal(deletedPackage); 10100 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 10101 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) | 10102 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 10103 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE 10104 | SCAN_UPDATE_TIME; 10105 try { 10106 scanPackageLI(restoreFile, oldParseFlags, oldScanMode, origUpdateTime, null); 10107 } catch (PackageManagerException e) { 10108 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 10109 + e.getMessage()); 10110 return; 10111 } 10112 // Restore of old package succeeded. Update permissions. 10113 // writer 10114 synchronized (mPackages) { 10115 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 10116 UPDATE_PERMISSIONS_ALL); 10117 // can downgrade to reader 10118 mSettings.writeLPr(); 10119 } 10120 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 10121 } 10122 } 10123 } 10124 10125 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 10126 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 10127 int[] allUsers, boolean[] perUserInstalled, 10128 String installerPackageName, PackageInstalledInfo res) { 10129 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 10130 + ", old=" + deletedPackage); 10131 boolean updatedSettings = false; 10132 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING | 10133 PackageParser.PARSE_IS_SYSTEM; 10134 if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) { 10135 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10136 } 10137 String packageName = deletedPackage.packageName; 10138 if (packageName == null) { 10139 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10140 "Attempt to delete null packageName."); 10141 return; 10142 } 10143 PackageParser.Package oldPkg; 10144 PackageSetting oldPkgSetting; 10145 // reader 10146 synchronized (mPackages) { 10147 oldPkg = mPackages.get(packageName); 10148 oldPkgSetting = mSettings.mPackages.get(packageName); 10149 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 10150 (oldPkgSetting == null)) { 10151 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10152 "Couldn't find package:" + packageName + " information"); 10153 return; 10154 } 10155 } 10156 10157 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 10158 10159 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10160 res.removedInfo.removedPackage = packageName; 10161 // Remove existing system package 10162 removePackageLI(oldPkgSetting, true); 10163 // writer 10164 synchronized (mPackages) { 10165 if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) { 10166 // We didn't need to disable the .apk as a current system package, 10167 // which means we are replacing another update that is already 10168 // installed. We need to make sure to delete the older one's .apk. 10169 res.removedInfo.args = createInstallArgsForExisting(0, 10170 deletedPackage.applicationInfo.getCodePath(), 10171 deletedPackage.applicationInfo.getResourcePath(), 10172 deletedPackage.applicationInfo.nativeLibraryRootDir, 10173 getAppDexInstructionSets(deletedPackage.applicationInfo), 10174 isMultiArch(deletedPackage.applicationInfo)); 10175 } else { 10176 res.removedInfo.args = null; 10177 } 10178 } 10179 10180 // Successfully disabled the old package. Now proceed with re-installation 10181 deleteCodeCacheDirsLI(packageName); 10182 10183 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10184 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10185 10186 PackageParser.Package newPackage = null; 10187 try { 10188 newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user); 10189 if (newPackage.mExtras != null) { 10190 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 10191 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10192 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10193 10194 // is the update attempting to change shared user? that isn't going to work... 10195 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10196 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 10197 "Forbidding shared user change from " + oldPkgSetting.sharedUser 10198 + " to " + newPkgSetting.sharedUser); 10199 updatedSettings = true; 10200 } 10201 } 10202 10203 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10204 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10205 updatedSettings = true; 10206 } 10207 10208 } catch (PackageManagerException e) { 10209 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10210 } 10211 10212 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10213 // Re installation failed. Restore old information 10214 // Remove new pkg information 10215 if (newPackage != null) { 10216 removeInstalledPackageLI(newPackage, true); 10217 } 10218 // Add back the old system package 10219 try { 10220 scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user); 10221 } catch (PackageManagerException e) { 10222 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 10223 } 10224 // Restore the old system information in Settings 10225 synchronized(mPackages) { 10226 if (updatedSettings) { 10227 mSettings.enableSystemPackageLPw(packageName); 10228 mSettings.setInstallerPackageName(packageName, 10229 oldPkgSetting.installerPackageName); 10230 } 10231 mSettings.writeLPr(); 10232 } 10233 } 10234 } 10235 10236 // Utility method used to move dex files during install. 10237 private int moveDexFilesLI(String oldCodePath, PackageParser.Package newPackage) { 10238 // TODO: extend to move split APK dex files 10239 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) { 10240 final String[] instructionSets = getAppDexInstructionSets(newPackage.applicationInfo); 10241 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10242 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10243 int retCode = mInstaller.movedex(oldCodePath, newPackage.baseCodePath, 10244 dexCodeInstructionSet); 10245 if (retCode != 0) { 10246 /* 10247 * Programs may be lazily run through dexopt, so the 10248 * source may not exist. However, something seems to 10249 * have gone wrong, so note that dexopt needs to be 10250 * run again and remove the source file. In addition, 10251 * remove the target to make sure there isn't a stale 10252 * file from a previous version of the package. 10253 */ 10254 newPackage.mDexOptPerformed.clear(); 10255 mInstaller.rmdex(oldCodePath, dexCodeInstructionSet); 10256 mInstaller.rmdex(newPackage.baseCodePath, dexCodeInstructionSet); 10257 } 10258 } 10259 } 10260 return PackageManager.INSTALL_SUCCEEDED; 10261 } 10262 10263 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10264 int[] allUsers, boolean[] perUserInstalled, 10265 PackageInstalledInfo res) { 10266 String pkgName = newPackage.packageName; 10267 synchronized (mPackages) { 10268 //write settings. the installStatus will be incomplete at this stage. 10269 //note that the new package setting would have already been 10270 //added to mPackages. It hasn't been persisted yet. 10271 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10272 mSettings.writeLPr(); 10273 } 10274 10275 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10276 10277 synchronized (mPackages) { 10278 updatePermissionsLPw(newPackage.packageName, newPackage, 10279 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10280 ? UPDATE_PERMISSIONS_ALL : 0)); 10281 // For system-bundled packages, we assume that installing an upgraded version 10282 // of the package implies that the user actually wants to run that new code, 10283 // so we enable the package. 10284 if (isSystemApp(newPackage)) { 10285 // NB: implicit assumption that system package upgrades apply to all users 10286 if (DEBUG_INSTALL) { 10287 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10288 } 10289 PackageSetting ps = mSettings.mPackages.get(pkgName); 10290 if (ps != null) { 10291 if (res.origUsers != null) { 10292 for (int userHandle : res.origUsers) { 10293 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10294 userHandle, installerPackageName); 10295 } 10296 } 10297 // Also convey the prior install/uninstall state 10298 if (allUsers != null && perUserInstalled != null) { 10299 for (int i = 0; i < allUsers.length; i++) { 10300 if (DEBUG_INSTALL) { 10301 Slog.d(TAG, " user " + allUsers[i] 10302 + " => " + perUserInstalled[i]); 10303 } 10304 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10305 } 10306 // these install state changes will be persisted in the 10307 // upcoming call to mSettings.writeLPr(). 10308 } 10309 } 10310 } 10311 res.name = pkgName; 10312 res.uid = newPackage.applicationInfo.uid; 10313 res.pkg = newPackage; 10314 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10315 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10316 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10317 //to update install status 10318 mSettings.writeLPr(); 10319 } 10320 } 10321 10322 private void installPackageLI(InstallArgs args, boolean newInstall, PackageInstalledInfo res) { 10323 int pFlags = args.flags; 10324 String installerPackageName = args.installerPackageName; 10325 File tmpPackageFile = new File(args.getCodePath()); 10326 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10327 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0); 10328 boolean replace = false; 10329 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE 10330 | (newInstall ? SCAN_NEW_INSTALL : 0); 10331 // Result object to be returned 10332 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10333 10334 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10335 // Retrieve PackageSettings and parse package 10336 int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10337 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10338 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 10339 PackageParser pp = new PackageParser(); 10340 pp.setSeparateProcesses(mSeparateProcesses); 10341 pp.setDisplayMetrics(mMetrics); 10342 10343 final PackageParser.Package pkg; 10344 try { 10345 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 10346 } catch (PackageParserException e) { 10347 res.setError("Failed parse during installPackageLI", e); 10348 return; 10349 } 10350 10351 // Mark that we have an install time CPU ABI override. 10352 pkg.cpuAbiOverride = args.abiOverride; 10353 10354 String pkgName = res.name = pkg.packageName; 10355 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 10356 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) { 10357 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 10358 return; 10359 } 10360 } 10361 10362 try { 10363 pp.collectCertificates(pkg, parseFlags); 10364 pp.collectManifestDigest(pkg); 10365 } catch (PackageParserException e) { 10366 res.setError("Failed collect during installPackageLI", e); 10367 return; 10368 } 10369 10370 /* If the installer passed in a manifest digest, compare it now. */ 10371 if (args.manifestDigest != null) { 10372 if (DEBUG_INSTALL) { 10373 final String parsedManifest = pkg.manifestDigest == null ? "null" 10374 : pkg.manifestDigest.toString(); 10375 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 10376 + parsedManifest); 10377 } 10378 10379 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 10380 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 10381 return; 10382 } 10383 } else if (DEBUG_INSTALL) { 10384 final String parsedManifest = pkg.manifestDigest == null 10385 ? "null" : pkg.manifestDigest.toString(); 10386 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 10387 } 10388 10389 // Get rid of all references to package scan path via parser. 10390 pp = null; 10391 String oldCodePath = null; 10392 boolean systemApp = false; 10393 synchronized (mPackages) { 10394 // Check whether the newly-scanned package wants to define an already-defined perm 10395 int N = pkg.permissions.size(); 10396 for (int i = N-1; i >= 0; i--) { 10397 PackageParser.Permission perm = pkg.permissions.get(i); 10398 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 10399 if (bp != null) { 10400 // If the defining package is signed with our cert, it's okay. This 10401 // also includes the "updating the same package" case, of course. 10402 if (compareSignatures(bp.packageSetting.signatures.mSignatures, 10403 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 10404 // If the owning package is the system itself, we log but allow 10405 // install to proceed; we fail the install on all other permission 10406 // redefinitions. 10407 if (!bp.sourcePackage.equals("android")) { 10408 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 10409 + pkg.packageName + " attempting to redeclare permission " 10410 + perm.info.name + " already owned by " + bp.sourcePackage); 10411 res.origPermission = perm.info.name; 10412 res.origPackage = bp.sourcePackage; 10413 return; 10414 } else { 10415 Slog.w(TAG, "Package " + pkg.packageName 10416 + " attempting to redeclare system permission " 10417 + perm.info.name + "; ignoring new declaration"); 10418 pkg.permissions.remove(i); 10419 } 10420 } 10421 } 10422 } 10423 10424 // Check if installing already existing package 10425 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10426 String oldName = mSettings.mRenamedPackages.get(pkgName); 10427 if (pkg.mOriginalPackages != null 10428 && pkg.mOriginalPackages.contains(oldName) 10429 && mPackages.containsKey(oldName)) { 10430 // This package is derived from an original package, 10431 // and this device has been updating from that original 10432 // name. We must continue using the original name, so 10433 // rename the new package here. 10434 pkg.setPackageName(oldName); 10435 pkgName = pkg.packageName; 10436 replace = true; 10437 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 10438 + oldName + " pkgName=" + pkgName); 10439 } else if (mPackages.containsKey(pkgName)) { 10440 // This package, under its official name, already exists 10441 // on the device; we should replace it. 10442 replace = true; 10443 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 10444 } 10445 } 10446 PackageSetting ps = mSettings.mPackages.get(pkgName); 10447 if (ps != null) { 10448 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 10449 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 10450 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 10451 systemApp = (ps.pkg.applicationInfo.flags & 10452 ApplicationInfo.FLAG_SYSTEM) != 0; 10453 } 10454 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10455 } 10456 } 10457 10458 if (systemApp && onSd) { 10459 // Disable updates to system apps on sdcard 10460 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 10461 "Cannot install updates to system apps on sdcard"); 10462 return; 10463 } 10464 10465 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 10466 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 10467 return; 10468 } 10469 10470 if (replace) { 10471 replacePackageLI(pkg, parseFlags, scanMode, args.user, 10472 installerPackageName, res); 10473 } else { 10474 installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user, 10475 installerPackageName, res); 10476 } 10477 synchronized (mPackages) { 10478 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10479 if (ps != null) { 10480 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10481 } 10482 } 10483 } 10484 10485 private static boolean isForwardLocked(PackageParser.Package pkg) { 10486 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10487 } 10488 10489 private static boolean isForwardLocked(ApplicationInfo info) { 10490 return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10491 } 10492 10493 private boolean isForwardLocked(PackageSetting ps) { 10494 return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10495 } 10496 10497 private static boolean isMultiArch(PackageSetting ps) { 10498 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10499 } 10500 10501 private static boolean isMultiArch(ApplicationInfo info) { 10502 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10503 } 10504 10505 private static boolean isExternal(PackageParser.Package pkg) { 10506 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10507 } 10508 10509 private static boolean isExternal(PackageSetting ps) { 10510 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10511 } 10512 10513 private static boolean isExternal(ApplicationInfo info) { 10514 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10515 } 10516 10517 private static boolean isSystemApp(PackageParser.Package pkg) { 10518 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10519 } 10520 10521 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 10522 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0; 10523 } 10524 10525 private static boolean isSystemApp(ApplicationInfo info) { 10526 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10527 } 10528 10529 private static boolean isSystemApp(PackageSetting ps) { 10530 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 10531 } 10532 10533 private static boolean isUpdatedSystemApp(PackageSetting ps) { 10534 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10535 } 10536 10537 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 10538 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10539 } 10540 10541 private static boolean isUpdatedSystemApp(ApplicationInfo info) { 10542 return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10543 } 10544 10545 private int packageFlagsToInstallFlags(PackageSetting ps) { 10546 int installFlags = 0; 10547 if (isExternal(ps)) { 10548 installFlags |= PackageManager.INSTALL_EXTERNAL; 10549 } 10550 if (isForwardLocked(ps)) { 10551 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 10552 } 10553 return installFlags; 10554 } 10555 10556 private void deleteTempPackageFiles() { 10557 final FilenameFilter filter = new FilenameFilter() { 10558 public boolean accept(File dir, String name) { 10559 return name.startsWith("vmdl") && name.endsWith(".tmp"); 10560 } 10561 }; 10562 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 10563 file.delete(); 10564 } 10565 } 10566 10567 @Override 10568 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 10569 int flags) { 10570 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 10571 flags); 10572 } 10573 10574 @Override 10575 public void deletePackage(final String packageName, 10576 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 10577 mContext.enforceCallingOrSelfPermission( 10578 android.Manifest.permission.DELETE_PACKAGES, null); 10579 final int uid = Binder.getCallingUid(); 10580 if (UserHandle.getUserId(uid) != userId) { 10581 mContext.enforceCallingPermission( 10582 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 10583 "deletePackage for user " + userId); 10584 } 10585 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 10586 try { 10587 observer.onPackageDeleted(packageName, 10588 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 10589 } catch (RemoteException re) { 10590 } 10591 return; 10592 } 10593 10594 boolean uninstallBlocked = false; 10595 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 10596 int[] users = sUserManager.getUserIds(); 10597 for (int i = 0; i < users.length; ++i) { 10598 if (getBlockUninstallForUser(packageName, users[i])) { 10599 uninstallBlocked = true; 10600 break; 10601 } 10602 } 10603 } else { 10604 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 10605 } 10606 if (uninstallBlocked) { 10607 try { 10608 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 10609 null); 10610 } catch (RemoteException re) { 10611 } 10612 return; 10613 } 10614 10615 if (DEBUG_REMOVE) { 10616 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 10617 } 10618 // Queue up an async operation since the package deletion may take a little while. 10619 mHandler.post(new Runnable() { 10620 public void run() { 10621 mHandler.removeCallbacks(this); 10622 final int returnCode = deletePackageX(packageName, userId, flags); 10623 if (observer != null) { 10624 try { 10625 observer.onPackageDeleted(packageName, returnCode, null); 10626 } catch (RemoteException e) { 10627 Log.i(TAG, "Observer no longer exists."); 10628 } //end catch 10629 } //end if 10630 } //end run 10631 }); 10632 } 10633 10634 private boolean isPackageDeviceAdmin(String packageName, int userId) { 10635 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 10636 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 10637 try { 10638 if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId) 10639 || dpm.isDeviceOwner(packageName))) { 10640 return true; 10641 } 10642 } catch (RemoteException e) { 10643 } 10644 return false; 10645 } 10646 10647 /** 10648 * This method is an internal method that could be get invoked either 10649 * to delete an installed package or to clean up a failed installation. 10650 * After deleting an installed package, a broadcast is sent to notify any 10651 * listeners that the package has been installed. For cleaning up a failed 10652 * installation, the broadcast is not necessary since the package's 10653 * installation wouldn't have sent the initial broadcast either 10654 * The key steps in deleting a package are 10655 * deleting the package information in internal structures like mPackages, 10656 * deleting the packages base directories through installd 10657 * updating mSettings to reflect current status 10658 * persisting settings for later use 10659 * sending a broadcast if necessary 10660 */ 10661 private int deletePackageX(String packageName, int userId, int flags) { 10662 final PackageRemovedInfo info = new PackageRemovedInfo(); 10663 final boolean res; 10664 10665 if (isPackageDeviceAdmin(packageName, userId)) { 10666 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 10667 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 10668 } 10669 10670 boolean removedForAllUsers = false; 10671 boolean systemUpdate = false; 10672 10673 // for the uninstall-updates case and restricted profiles, remember the per- 10674 // userhandle installed state 10675 int[] allUsers; 10676 boolean[] perUserInstalled; 10677 synchronized (mPackages) { 10678 PackageSetting ps = mSettings.mPackages.get(packageName); 10679 allUsers = sUserManager.getUserIds(); 10680 perUserInstalled = new boolean[allUsers.length]; 10681 for (int i = 0; i < allUsers.length; i++) { 10682 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10683 } 10684 } 10685 10686 synchronized (mInstallLock) { 10687 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 10688 res = deletePackageLI(packageName, 10689 (flags & PackageManager.DELETE_ALL_USERS) != 0 10690 ? UserHandle.ALL : new UserHandle(userId), 10691 true, allUsers, perUserInstalled, 10692 flags | REMOVE_CHATTY, info, true); 10693 systemUpdate = info.isRemovedPackageSystemUpdate; 10694 if (res && !systemUpdate && mPackages.get(packageName) == null) { 10695 removedForAllUsers = true; 10696 } 10697 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 10698 + " removedForAllUsers=" + removedForAllUsers); 10699 } 10700 10701 if (res) { 10702 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 10703 10704 // If the removed package was a system update, the old system package 10705 // was re-enabled; we need to broadcast this information 10706 if (systemUpdate) { 10707 Bundle extras = new Bundle(1); 10708 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 10709 ? info.removedAppId : info.uid); 10710 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10711 10712 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 10713 extras, null, null, null); 10714 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 10715 extras, null, null, null); 10716 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 10717 null, packageName, null, null); 10718 } 10719 } 10720 // Force a gc here. 10721 Runtime.getRuntime().gc(); 10722 // Delete the resources here after sending the broadcast to let 10723 // other processes clean up before deleting resources. 10724 if (info.args != null) { 10725 synchronized (mInstallLock) { 10726 info.args.doPostDeleteLI(true); 10727 } 10728 } 10729 10730 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10731 } 10732 10733 static class PackageRemovedInfo { 10734 String removedPackage; 10735 int uid = -1; 10736 int removedAppId = -1; 10737 int[] removedUsers = null; 10738 boolean isRemovedPackageSystemUpdate = false; 10739 // Clean up resources deleted packages. 10740 InstallArgs args = null; 10741 10742 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 10743 Bundle extras = new Bundle(1); 10744 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 10745 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 10746 if (replacing) { 10747 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10748 } 10749 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 10750 if (removedPackage != null) { 10751 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 10752 extras, null, null, removedUsers); 10753 if (fullRemove && !replacing) { 10754 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 10755 extras, null, null, removedUsers); 10756 } 10757 } 10758 if (removedAppId >= 0) { 10759 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 10760 removedUsers); 10761 } 10762 } 10763 } 10764 10765 /* 10766 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 10767 * flag is not set, the data directory is removed as well. 10768 * make sure this flag is set for partially installed apps. If not its meaningless to 10769 * delete a partially installed application. 10770 */ 10771 private void removePackageDataLI(PackageSetting ps, 10772 int[] allUserHandles, boolean[] perUserInstalled, 10773 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 10774 String packageName = ps.name; 10775 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 10776 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 10777 // Retrieve object to delete permissions for shared user later on 10778 final PackageSetting deletedPs; 10779 // reader 10780 synchronized (mPackages) { 10781 deletedPs = mSettings.mPackages.get(packageName); 10782 if (outInfo != null) { 10783 outInfo.removedPackage = packageName; 10784 outInfo.removedUsers = deletedPs != null 10785 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 10786 : null; 10787 } 10788 } 10789 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10790 removeDataDirsLI(packageName); 10791 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 10792 } 10793 // writer 10794 synchronized (mPackages) { 10795 if (deletedPs != null) { 10796 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10797 if (outInfo != null) { 10798 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 10799 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 10800 } 10801 if (deletedPs != null) { 10802 updatePermissionsLPw(deletedPs.name, null, 0); 10803 if (deletedPs.sharedUser != null) { 10804 // remove permissions associated with package 10805 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 10806 } 10807 } 10808 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 10809 } 10810 // make sure to preserve per-user disabled state if this removal was just 10811 // a downgrade of a system app to the factory package 10812 if (allUserHandles != null && perUserInstalled != null) { 10813 if (DEBUG_REMOVE) { 10814 Slog.d(TAG, "Propagating install state across downgrade"); 10815 } 10816 for (int i = 0; i < allUserHandles.length; i++) { 10817 if (DEBUG_REMOVE) { 10818 Slog.d(TAG, " user " + allUserHandles[i] 10819 + " => " + perUserInstalled[i]); 10820 } 10821 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10822 } 10823 } 10824 } 10825 // can downgrade to reader 10826 if (writeSettings) { 10827 // Save settings now 10828 mSettings.writeLPr(); 10829 } 10830 } 10831 if (outInfo != null) { 10832 // A user ID was deleted here. Go through all users and remove it 10833 // from KeyStore. 10834 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 10835 } 10836 } 10837 10838 static boolean locationIsPrivileged(File path) { 10839 try { 10840 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 10841 .getCanonicalPath(); 10842 return path.getCanonicalPath().startsWith(privilegedAppDir); 10843 } catch (IOException e) { 10844 Slog.e(TAG, "Unable to access code path " + path); 10845 } 10846 return false; 10847 } 10848 10849 /* 10850 * Tries to delete system package. 10851 */ 10852 private boolean deleteSystemPackageLI(PackageSetting newPs, 10853 int[] allUserHandles, boolean[] perUserInstalled, 10854 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 10855 final boolean applyUserRestrictions 10856 = (allUserHandles != null) && (perUserInstalled != null); 10857 PackageSetting disabledPs = null; 10858 // Confirm if the system package has been updated 10859 // An updated system app can be deleted. This will also have to restore 10860 // the system pkg from system partition 10861 // reader 10862 synchronized (mPackages) { 10863 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 10864 } 10865 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 10866 + " disabledPs=" + disabledPs); 10867 if (disabledPs == null) { 10868 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 10869 return false; 10870 } else if (DEBUG_REMOVE) { 10871 Slog.d(TAG, "Deleting system pkg from data partition"); 10872 } 10873 if (DEBUG_REMOVE) { 10874 if (applyUserRestrictions) { 10875 Slog.d(TAG, "Remembering install states:"); 10876 for (int i = 0; i < allUserHandles.length; i++) { 10877 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 10878 } 10879 } 10880 } 10881 // Delete the updated package 10882 outInfo.isRemovedPackageSystemUpdate = true; 10883 if (disabledPs.versionCode < newPs.versionCode) { 10884 // Delete data for downgrades 10885 flags &= ~PackageManager.DELETE_KEEP_DATA; 10886 } else { 10887 // Preserve data by setting flag 10888 flags |= PackageManager.DELETE_KEEP_DATA; 10889 } 10890 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 10891 allUserHandles, perUserInstalled, outInfo, writeSettings); 10892 if (!ret) { 10893 return false; 10894 } 10895 // writer 10896 synchronized (mPackages) { 10897 // Reinstate the old system package 10898 mSettings.enableSystemPackageLPw(newPs.name); 10899 // Remove any native libraries from the upgraded package. 10900 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 10901 } 10902 // Install the system package 10903 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 10904 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 10905 if (locationIsPrivileged(disabledPs.codePath)) { 10906 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10907 } 10908 10909 final PackageParser.Package newPkg; 10910 try { 10911 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, null); 10912 } catch (PackageManagerException e) { 10913 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 10914 return false; 10915 } 10916 10917 // writer 10918 synchronized (mPackages) { 10919 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 10920 updatePermissionsLPw(newPkg.packageName, newPkg, 10921 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 10922 if (applyUserRestrictions) { 10923 if (DEBUG_REMOVE) { 10924 Slog.d(TAG, "Propagating install state across reinstall"); 10925 } 10926 for (int i = 0; i < allUserHandles.length; i++) { 10927 if (DEBUG_REMOVE) { 10928 Slog.d(TAG, " user " + allUserHandles[i] 10929 + " => " + perUserInstalled[i]); 10930 } 10931 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10932 } 10933 // Regardless of writeSettings we need to ensure that this restriction 10934 // state propagation is persisted 10935 mSettings.writeAllUsersPackageRestrictionsLPr(); 10936 } 10937 // can downgrade to reader here 10938 if (writeSettings) { 10939 mSettings.writeLPr(); 10940 } 10941 } 10942 return true; 10943 } 10944 10945 private boolean deleteInstalledPackageLI(PackageSetting ps, 10946 boolean deleteCodeAndResources, int flags, 10947 int[] allUserHandles, boolean[] perUserInstalled, 10948 PackageRemovedInfo outInfo, boolean writeSettings) { 10949 if (outInfo != null) { 10950 outInfo.uid = ps.appId; 10951 } 10952 10953 // Delete package data from internal structures and also remove data if flag is set 10954 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 10955 10956 // Delete application code and resources 10957 if (deleteCodeAndResources && (outInfo != null)) { 10958 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 10959 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 10960 getAppDexInstructionSets(ps), isMultiArch(ps)); 10961 } 10962 return true; 10963 } 10964 10965 @Override 10966 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 10967 int userId) { 10968 mContext.enforceCallingOrSelfPermission( 10969 android.Manifest.permission.DELETE_PACKAGES, null); 10970 synchronized (mPackages) { 10971 PackageSetting ps = mSettings.mPackages.get(packageName); 10972 if (ps == null) { 10973 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 10974 return false; 10975 } 10976 if (!ps.getInstalled(userId)) { 10977 // Can't block uninstall for an app that is not installed or enabled. 10978 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 10979 return false; 10980 } 10981 ps.setBlockUninstall(blockUninstall, userId); 10982 mSettings.writePackageRestrictionsLPr(userId); 10983 } 10984 return true; 10985 } 10986 10987 @Override 10988 public boolean getBlockUninstallForUser(String packageName, int userId) { 10989 synchronized (mPackages) { 10990 PackageSetting ps = mSettings.mPackages.get(packageName); 10991 if (ps == null) { 10992 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 10993 return false; 10994 } 10995 return ps.getBlockUninstall(userId); 10996 } 10997 } 10998 10999 /* 11000 * This method handles package deletion in general 11001 */ 11002 private boolean deletePackageLI(String packageName, UserHandle user, 11003 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 11004 int flags, PackageRemovedInfo outInfo, 11005 boolean writeSettings) { 11006 if (packageName == null) { 11007 Slog.w(TAG, "Attempt to delete null packageName."); 11008 return false; 11009 } 11010 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 11011 PackageSetting ps; 11012 boolean dataOnly = false; 11013 int removeUser = -1; 11014 int appId = -1; 11015 synchronized (mPackages) { 11016 ps = mSettings.mPackages.get(packageName); 11017 if (ps == null) { 11018 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11019 return false; 11020 } 11021 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 11022 && user.getIdentifier() != UserHandle.USER_ALL) { 11023 // The caller is asking that the package only be deleted for a single 11024 // user. To do this, we just mark its uninstalled state and delete 11025 // its data. If this is a system app, we only allow this to happen if 11026 // they have set the special DELETE_SYSTEM_APP which requests different 11027 // semantics than normal for uninstalling system apps. 11028 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 11029 ps.setUserState(user.getIdentifier(), 11030 COMPONENT_ENABLED_STATE_DEFAULT, 11031 false, //installed 11032 true, //stopped 11033 true, //notLaunched 11034 false, //hidden 11035 null, null, null, 11036 false // blockUninstall 11037 ); 11038 if (!isSystemApp(ps)) { 11039 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 11040 // Other user still have this package installed, so all 11041 // we need to do is clear this user's data and save that 11042 // it is uninstalled. 11043 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 11044 removeUser = user.getIdentifier(); 11045 appId = ps.appId; 11046 mSettings.writePackageRestrictionsLPr(removeUser); 11047 } else { 11048 // We need to set it back to 'installed' so the uninstall 11049 // broadcasts will be sent correctly. 11050 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 11051 ps.setInstalled(true, user.getIdentifier()); 11052 } 11053 } else { 11054 // This is a system app, so we assume that the 11055 // other users still have this package installed, so all 11056 // we need to do is clear this user's data and save that 11057 // it is uninstalled. 11058 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 11059 removeUser = user.getIdentifier(); 11060 appId = ps.appId; 11061 mSettings.writePackageRestrictionsLPr(removeUser); 11062 } 11063 } 11064 } 11065 11066 if (removeUser >= 0) { 11067 // From above, we determined that we are deleting this only 11068 // for a single user. Continue the work here. 11069 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 11070 if (outInfo != null) { 11071 outInfo.removedPackage = packageName; 11072 outInfo.removedAppId = appId; 11073 outInfo.removedUsers = new int[] {removeUser}; 11074 } 11075 mInstaller.clearUserData(packageName, removeUser); 11076 removeKeystoreDataIfNeeded(removeUser, appId); 11077 schedulePackageCleaning(packageName, removeUser, false); 11078 return true; 11079 } 11080 11081 if (dataOnly) { 11082 // Delete application data first 11083 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 11084 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 11085 return true; 11086 } 11087 11088 boolean ret = false; 11089 if (isSystemApp(ps)) { 11090 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 11091 // When an updated system application is deleted we delete the existing resources as well and 11092 // fall back to existing code in system partition 11093 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 11094 flags, outInfo, writeSettings); 11095 } else { 11096 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 11097 // Kill application pre-emptively especially for apps on sd. 11098 killApplication(packageName, ps.appId, "uninstall pkg"); 11099 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 11100 allUserHandles, perUserInstalled, 11101 outInfo, writeSettings); 11102 } 11103 11104 return ret; 11105 } 11106 11107 private final class ClearStorageConnection implements ServiceConnection { 11108 IMediaContainerService mContainerService; 11109 11110 @Override 11111 public void onServiceConnected(ComponentName name, IBinder service) { 11112 synchronized (this) { 11113 mContainerService = IMediaContainerService.Stub.asInterface(service); 11114 notifyAll(); 11115 } 11116 } 11117 11118 @Override 11119 public void onServiceDisconnected(ComponentName name) { 11120 } 11121 } 11122 11123 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 11124 final boolean mounted; 11125 if (Environment.isExternalStorageEmulated()) { 11126 mounted = true; 11127 } else { 11128 final String status = Environment.getExternalStorageState(); 11129 11130 mounted = status.equals(Environment.MEDIA_MOUNTED) 11131 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 11132 } 11133 11134 if (!mounted) { 11135 return; 11136 } 11137 11138 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 11139 int[] users; 11140 if (userId == UserHandle.USER_ALL) { 11141 users = sUserManager.getUserIds(); 11142 } else { 11143 users = new int[] { userId }; 11144 } 11145 final ClearStorageConnection conn = new ClearStorageConnection(); 11146 if (mContext.bindServiceAsUser( 11147 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 11148 try { 11149 for (int curUser : users) { 11150 long timeout = SystemClock.uptimeMillis() + 5000; 11151 synchronized (conn) { 11152 long now = SystemClock.uptimeMillis(); 11153 while (conn.mContainerService == null && now < timeout) { 11154 try { 11155 conn.wait(timeout - now); 11156 } catch (InterruptedException e) { 11157 } 11158 } 11159 } 11160 if (conn.mContainerService == null) { 11161 return; 11162 } 11163 11164 final UserEnvironment userEnv = new UserEnvironment(curUser); 11165 clearDirectory(conn.mContainerService, 11166 userEnv.buildExternalStorageAppCacheDirs(packageName)); 11167 if (allData) { 11168 clearDirectory(conn.mContainerService, 11169 userEnv.buildExternalStorageAppDataDirs(packageName)); 11170 clearDirectory(conn.mContainerService, 11171 userEnv.buildExternalStorageAppMediaDirs(packageName)); 11172 } 11173 } 11174 } finally { 11175 mContext.unbindService(conn); 11176 } 11177 } 11178 } 11179 11180 @Override 11181 public void clearApplicationUserData(final String packageName, 11182 final IPackageDataObserver observer, final int userId) { 11183 mContext.enforceCallingOrSelfPermission( 11184 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 11185 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data"); 11186 // Queue up an async operation since the package deletion may take a little while. 11187 mHandler.post(new Runnable() { 11188 public void run() { 11189 mHandler.removeCallbacks(this); 11190 final boolean succeeded; 11191 synchronized (mInstallLock) { 11192 succeeded = clearApplicationUserDataLI(packageName, userId); 11193 } 11194 clearExternalStorageDataSync(packageName, userId, true); 11195 if (succeeded) { 11196 // invoke DeviceStorageMonitor's update method to clear any notifications 11197 DeviceStorageMonitorInternal 11198 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 11199 if (dsm != null) { 11200 dsm.checkMemory(); 11201 } 11202 } 11203 if(observer != null) { 11204 try { 11205 observer.onRemoveCompleted(packageName, succeeded); 11206 } catch (RemoteException e) { 11207 Log.i(TAG, "Observer no longer exists."); 11208 } 11209 } //end if observer 11210 } //end run 11211 }); 11212 } 11213 11214 private boolean clearApplicationUserDataLI(String packageName, int userId) { 11215 if (packageName == null) { 11216 Slog.w(TAG, "Attempt to delete null packageName."); 11217 return false; 11218 } 11219 PackageParser.Package p; 11220 boolean dataOnly = false; 11221 final int appId; 11222 synchronized (mPackages) { 11223 p = mPackages.get(packageName); 11224 if (p == null) { 11225 dataOnly = true; 11226 PackageSetting ps = mSettings.mPackages.get(packageName); 11227 if ((ps == null) || (ps.pkg == null)) { 11228 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11229 return false; 11230 } 11231 p = ps.pkg; 11232 } 11233 if (!dataOnly) { 11234 // need to check this only for fully installed applications 11235 if (p == null) { 11236 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11237 return false; 11238 } 11239 final ApplicationInfo applicationInfo = p.applicationInfo; 11240 if (applicationInfo == null) { 11241 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11242 return false; 11243 } 11244 } 11245 if (p != null && p.applicationInfo != null) { 11246 appId = p.applicationInfo.uid; 11247 } else { 11248 appId = -1; 11249 } 11250 } 11251 int retCode = mInstaller.clearUserData(packageName, userId); 11252 if (retCode < 0) { 11253 Slog.w(TAG, "Couldn't remove cache files for package: " 11254 + packageName); 11255 return false; 11256 } 11257 removeKeystoreDataIfNeeded(userId, appId); 11258 return true; 11259 } 11260 11261 /** 11262 * Remove entries from the keystore daemon. Will only remove it if the 11263 * {@code appId} is valid. 11264 */ 11265 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 11266 if (appId < 0) { 11267 return; 11268 } 11269 11270 final KeyStore keyStore = KeyStore.getInstance(); 11271 if (keyStore != null) { 11272 if (userId == UserHandle.USER_ALL) { 11273 for (final int individual : sUserManager.getUserIds()) { 11274 keyStore.clearUid(UserHandle.getUid(individual, appId)); 11275 } 11276 } else { 11277 keyStore.clearUid(UserHandle.getUid(userId, appId)); 11278 } 11279 } else { 11280 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 11281 } 11282 } 11283 11284 @Override 11285 public void deleteApplicationCacheFiles(final String packageName, 11286 final IPackageDataObserver observer) { 11287 mContext.enforceCallingOrSelfPermission( 11288 android.Manifest.permission.DELETE_CACHE_FILES, null); 11289 // Queue up an async operation since the package deletion may take a little while. 11290 final int userId = UserHandle.getCallingUserId(); 11291 mHandler.post(new Runnable() { 11292 public void run() { 11293 mHandler.removeCallbacks(this); 11294 final boolean succeded; 11295 synchronized (mInstallLock) { 11296 succeded = deleteApplicationCacheFilesLI(packageName, userId); 11297 } 11298 clearExternalStorageDataSync(packageName, userId, false); 11299 if(observer != null) { 11300 try { 11301 observer.onRemoveCompleted(packageName, succeded); 11302 } catch (RemoteException e) { 11303 Log.i(TAG, "Observer no longer exists."); 11304 } 11305 } //end if observer 11306 } //end run 11307 }); 11308 } 11309 11310 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 11311 if (packageName == null) { 11312 Slog.w(TAG, "Attempt to delete null packageName."); 11313 return false; 11314 } 11315 PackageParser.Package p; 11316 synchronized (mPackages) { 11317 p = mPackages.get(packageName); 11318 } 11319 if (p == null) { 11320 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11321 return false; 11322 } 11323 final ApplicationInfo applicationInfo = p.applicationInfo; 11324 if (applicationInfo == null) { 11325 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11326 return false; 11327 } 11328 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 11329 if (retCode < 0) { 11330 Slog.w(TAG, "Couldn't remove cache files for package: " 11331 + packageName + " u" + userId); 11332 return false; 11333 } 11334 return true; 11335 } 11336 11337 @Override 11338 public void getPackageSizeInfo(final String packageName, int userHandle, 11339 final IPackageStatsObserver observer) { 11340 mContext.enforceCallingOrSelfPermission( 11341 android.Manifest.permission.GET_PACKAGE_SIZE, null); 11342 if (packageName == null) { 11343 throw new IllegalArgumentException("Attempt to get size of null packageName"); 11344 } 11345 11346 PackageStats stats = new PackageStats(packageName, userHandle); 11347 11348 /* 11349 * Queue up an async operation since the package measurement may take a 11350 * little while. 11351 */ 11352 Message msg = mHandler.obtainMessage(INIT_COPY); 11353 msg.obj = new MeasureParams(stats, observer); 11354 mHandler.sendMessage(msg); 11355 } 11356 11357 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 11358 PackageStats pStats) { 11359 if (packageName == null) { 11360 Slog.w(TAG, "Attempt to get size of null packageName."); 11361 return false; 11362 } 11363 PackageParser.Package p; 11364 boolean dataOnly = false; 11365 String libDirRoot = null; 11366 String asecPath = null; 11367 PackageSetting ps = null; 11368 synchronized (mPackages) { 11369 p = mPackages.get(packageName); 11370 ps = mSettings.mPackages.get(packageName); 11371 if(p == null) { 11372 dataOnly = true; 11373 if((ps == null) || (ps.pkg == null)) { 11374 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11375 return false; 11376 } 11377 p = ps.pkg; 11378 } 11379 if (ps != null) { 11380 libDirRoot = ps.legacyNativeLibraryPathString; 11381 } 11382 if (p != null && (isExternal(p) || isForwardLocked(p))) { 11383 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 11384 if (secureContainerId != null) { 11385 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 11386 } 11387 } 11388 } 11389 String publicSrcDir = null; 11390 if(!dataOnly) { 11391 final ApplicationInfo applicationInfo = p.applicationInfo; 11392 if (applicationInfo == null) { 11393 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11394 return false; 11395 } 11396 if (isForwardLocked(p)) { 11397 publicSrcDir = applicationInfo.getBaseResourcePath(); 11398 } 11399 } 11400 // TODO: extend to measure size of split APKs 11401 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 11402 // not just the first level. 11403 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 11404 // just the primary. 11405 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 11406 int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot, 11407 publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 11408 if (res < 0) { 11409 return false; 11410 } 11411 11412 // Fix-up for forward-locked applications in ASEC containers. 11413 if (!isExternal(p)) { 11414 pStats.codeSize += pStats.externalCodeSize; 11415 pStats.externalCodeSize = 0L; 11416 } 11417 11418 return true; 11419 } 11420 11421 11422 @Override 11423 public void addPackageToPreferred(String packageName) { 11424 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 11425 } 11426 11427 @Override 11428 public void removePackageFromPreferred(String packageName) { 11429 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 11430 } 11431 11432 @Override 11433 public List<PackageInfo> getPreferredPackages(int flags) { 11434 return new ArrayList<PackageInfo>(); 11435 } 11436 11437 private int getUidTargetSdkVersionLockedLPr(int uid) { 11438 Object obj = mSettings.getUserIdLPr(uid); 11439 if (obj instanceof SharedUserSetting) { 11440 final SharedUserSetting sus = (SharedUserSetting) obj; 11441 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 11442 final Iterator<PackageSetting> it = sus.packages.iterator(); 11443 while (it.hasNext()) { 11444 final PackageSetting ps = it.next(); 11445 if (ps.pkg != null) { 11446 int v = ps.pkg.applicationInfo.targetSdkVersion; 11447 if (v < vers) vers = v; 11448 } 11449 } 11450 return vers; 11451 } else if (obj instanceof PackageSetting) { 11452 final PackageSetting ps = (PackageSetting) obj; 11453 if (ps.pkg != null) { 11454 return ps.pkg.applicationInfo.targetSdkVersion; 11455 } 11456 } 11457 return Build.VERSION_CODES.CUR_DEVELOPMENT; 11458 } 11459 11460 @Override 11461 public void addPreferredActivity(IntentFilter filter, int match, 11462 ComponentName[] set, ComponentName activity, int userId) { 11463 addPreferredActivityInternal(filter, match, set, activity, true, userId); 11464 } 11465 11466 private void addPreferredActivityInternal(IntentFilter filter, int match, 11467 ComponentName[] set, ComponentName activity, boolean always, int userId) { 11468 // writer 11469 int callingUid = Binder.getCallingUid(); 11470 enforceCrossUserPermission(callingUid, userId, true, "add preferred activity"); 11471 if (filter.countActions() == 0) { 11472 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11473 return; 11474 } 11475 synchronized (mPackages) { 11476 if (mContext.checkCallingOrSelfPermission( 11477 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11478 != PackageManager.PERMISSION_GRANTED) { 11479 if (getUidTargetSdkVersionLockedLPr(callingUid) 11480 < Build.VERSION_CODES.FROYO) { 11481 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 11482 + callingUid); 11483 return; 11484 } 11485 mContext.enforceCallingOrSelfPermission( 11486 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11487 } 11488 11489 Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :"); 11490 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11491 mSettings.editPreferredActivitiesLPw(userId).addFilter( 11492 new PreferredActivity(filter, match, set, activity, always)); 11493 mSettings.writePackageRestrictionsLPr(userId); 11494 } 11495 } 11496 11497 @Override 11498 public void replacePreferredActivity(IntentFilter filter, int match, 11499 ComponentName[] set, ComponentName activity, int userId) { 11500 if (filter.countActions() != 1) { 11501 throw new IllegalArgumentException( 11502 "replacePreferredActivity expects filter to have only 1 action."); 11503 } 11504 if (filter.countDataAuthorities() != 0 11505 || filter.countDataPaths() != 0 11506 || filter.countDataSchemes() > 1 11507 || filter.countDataTypes() != 0) { 11508 throw new IllegalArgumentException( 11509 "replacePreferredActivity expects filter to have no data authorities, " + 11510 "paths, or types; and at most one scheme."); 11511 } 11512 11513 final int callingUid = Binder.getCallingUid(); 11514 enforceCrossUserPermission(callingUid, userId, true, "replace preferred activity"); 11515 final int callingUserId = UserHandle.getUserId(callingUid); 11516 synchronized (mPackages) { 11517 if (mContext.checkCallingOrSelfPermission( 11518 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11519 != PackageManager.PERMISSION_GRANTED) { 11520 if (getUidTargetSdkVersionLockedLPr(callingUid) 11521 < Build.VERSION_CODES.FROYO) { 11522 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 11523 + Binder.getCallingUid()); 11524 return; 11525 } 11526 mContext.enforceCallingOrSelfPermission( 11527 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11528 } 11529 11530 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId); 11531 if (pir != null) { 11532 Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0)); 11533 if (filter.countDataSchemes() == 1) { 11534 Uri.Builder builder = new Uri.Builder(); 11535 builder.scheme(filter.getDataScheme(0)); 11536 intent.setData(builder.build()); 11537 } 11538 List<PreferredActivity> matches = pir.queryIntent( 11539 intent, null, true, callingUserId); 11540 if (DEBUG_PREFERRED) { 11541 Slog.i(TAG, matches.size() + " preferred matches for " + intent); 11542 } 11543 for (int i = 0; i < matches.size(); i++) { 11544 PreferredActivity pa = matches.get(i); 11545 if (DEBUG_PREFERRED) { 11546 Slog.i(TAG, "Removing preferred activity " 11547 + pa.mPref.mComponent + ":"); 11548 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11549 } 11550 pir.removeFilter(pa); 11551 } 11552 } 11553 addPreferredActivityInternal(filter, match, set, activity, true, callingUserId); 11554 } 11555 } 11556 11557 @Override 11558 public void clearPackagePreferredActivities(String packageName) { 11559 final int uid = Binder.getCallingUid(); 11560 // writer 11561 synchronized (mPackages) { 11562 PackageParser.Package pkg = mPackages.get(packageName); 11563 if (pkg == null || pkg.applicationInfo.uid != uid) { 11564 if (mContext.checkCallingOrSelfPermission( 11565 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11566 != PackageManager.PERMISSION_GRANTED) { 11567 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11568 < Build.VERSION_CODES.FROYO) { 11569 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 11570 + Binder.getCallingUid()); 11571 return; 11572 } 11573 mContext.enforceCallingOrSelfPermission( 11574 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11575 } 11576 } 11577 11578 int user = UserHandle.getCallingUserId(); 11579 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 11580 mSettings.writePackageRestrictionsLPr(user); 11581 scheduleWriteSettingsLocked(); 11582 } 11583 } 11584 } 11585 11586 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 11587 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 11588 ArrayList<PreferredActivity> removed = null; 11589 boolean changed = false; 11590 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11591 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 11592 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11593 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 11594 continue; 11595 } 11596 Iterator<PreferredActivity> it = pir.filterIterator(); 11597 while (it.hasNext()) { 11598 PreferredActivity pa = it.next(); 11599 // Mark entry for removal only if it matches the package name 11600 // and the entry is of type "always". 11601 if (packageName == null || 11602 (pa.mPref.mComponent.getPackageName().equals(packageName) 11603 && pa.mPref.mAlways)) { 11604 if (removed == null) { 11605 removed = new ArrayList<PreferredActivity>(); 11606 } 11607 removed.add(pa); 11608 } 11609 } 11610 if (removed != null) { 11611 for (int j=0; j<removed.size(); j++) { 11612 PreferredActivity pa = removed.get(j); 11613 pir.removeFilter(pa); 11614 } 11615 changed = true; 11616 } 11617 } 11618 return changed; 11619 } 11620 11621 @Override 11622 public void resetPreferredActivities(int userId) { 11623 mContext.enforceCallingOrSelfPermission( 11624 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11625 // writer 11626 synchronized (mPackages) { 11627 int user = UserHandle.getCallingUserId(); 11628 clearPackagePreferredActivitiesLPw(null, user); 11629 mSettings.readDefaultPreferredAppsLPw(this, user); 11630 mSettings.writePackageRestrictionsLPr(user); 11631 scheduleWriteSettingsLocked(); 11632 } 11633 } 11634 11635 @Override 11636 public int getPreferredActivities(List<IntentFilter> outFilters, 11637 List<ComponentName> outActivities, String packageName) { 11638 11639 int num = 0; 11640 final int userId = UserHandle.getCallingUserId(); 11641 // reader 11642 synchronized (mPackages) { 11643 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11644 if (pir != null) { 11645 final Iterator<PreferredActivity> it = pir.filterIterator(); 11646 while (it.hasNext()) { 11647 final PreferredActivity pa = it.next(); 11648 if (packageName == null 11649 || (pa.mPref.mComponent.getPackageName().equals(packageName) 11650 && pa.mPref.mAlways)) { 11651 if (outFilters != null) { 11652 outFilters.add(new IntentFilter(pa)); 11653 } 11654 if (outActivities != null) { 11655 outActivities.add(pa.mPref.mComponent); 11656 } 11657 } 11658 } 11659 } 11660 } 11661 11662 return num; 11663 } 11664 11665 @Override 11666 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 11667 int userId) { 11668 int callingUid = Binder.getCallingUid(); 11669 if (callingUid != Process.SYSTEM_UID) { 11670 throw new SecurityException( 11671 "addPersistentPreferredActivity can only be run by the system"); 11672 } 11673 if (filter.countActions() == 0) { 11674 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11675 return; 11676 } 11677 synchronized (mPackages) { 11678 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 11679 " :"); 11680 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11681 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 11682 new PersistentPreferredActivity(filter, activity)); 11683 mSettings.writePackageRestrictionsLPr(userId); 11684 } 11685 } 11686 11687 @Override 11688 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 11689 int callingUid = Binder.getCallingUid(); 11690 if (callingUid != Process.SYSTEM_UID) { 11691 throw new SecurityException( 11692 "clearPackagePersistentPreferredActivities can only be run by the system"); 11693 } 11694 ArrayList<PersistentPreferredActivity> removed = null; 11695 boolean changed = false; 11696 synchronized (mPackages) { 11697 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 11698 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 11699 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 11700 .valueAt(i); 11701 if (userId != thisUserId) { 11702 continue; 11703 } 11704 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 11705 while (it.hasNext()) { 11706 PersistentPreferredActivity ppa = it.next(); 11707 // Mark entry for removal only if it matches the package name. 11708 if (ppa.mComponent.getPackageName().equals(packageName)) { 11709 if (removed == null) { 11710 removed = new ArrayList<PersistentPreferredActivity>(); 11711 } 11712 removed.add(ppa); 11713 } 11714 } 11715 if (removed != null) { 11716 for (int j=0; j<removed.size(); j++) { 11717 PersistentPreferredActivity ppa = removed.get(j); 11718 ppir.removeFilter(ppa); 11719 } 11720 changed = true; 11721 } 11722 } 11723 11724 if (changed) { 11725 mSettings.writePackageRestrictionsLPr(userId); 11726 } 11727 } 11728 } 11729 11730 @Override 11731 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 11732 int ownerUserId, int sourceUserId, int targetUserId, int flags) { 11733 mContext.enforceCallingOrSelfPermission( 11734 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11735 int callingUid = Binder.getCallingUid(); 11736 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11737 if (intentFilter.countActions() == 0) { 11738 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 11739 return; 11740 } 11741 synchronized (mPackages) { 11742 CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter, 11743 ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags); 11744 mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter); 11745 mSettings.writePackageRestrictionsLPr(sourceUserId); 11746 } 11747 } 11748 11749 @Override 11750 public void addCrossProfileIntentsForPackage(String packageName, 11751 int sourceUserId, int targetUserId) { 11752 mContext.enforceCallingOrSelfPermission( 11753 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11754 mSettings.addCrossProfilePackage(packageName, sourceUserId, targetUserId); 11755 mSettings.writePackageRestrictionsLPr(sourceUserId); 11756 } 11757 11758 @Override 11759 public void removeCrossProfileIntentsForPackage(String packageName, 11760 int sourceUserId, int targetUserId) { 11761 mContext.enforceCallingOrSelfPermission( 11762 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11763 mSettings.removeCrossProfilePackage(packageName, sourceUserId, targetUserId); 11764 mSettings.writePackageRestrictionsLPr(sourceUserId); 11765 } 11766 11767 @Override 11768 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage, 11769 int ownerUserId) { 11770 mContext.enforceCallingOrSelfPermission( 11771 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11772 int callingUid = Binder.getCallingUid(); 11773 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11774 int callingUserId = UserHandle.getUserId(callingUid); 11775 synchronized (mPackages) { 11776 CrossProfileIntentResolver resolver = 11777 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11778 HashSet<CrossProfileIntentFilter> set = 11779 new HashSet<CrossProfileIntentFilter>(resolver.filterSet()); 11780 for (CrossProfileIntentFilter filter : set) { 11781 if (filter.getOwnerPackage().equals(ownerPackage) 11782 && filter.getOwnerUserId() == callingUserId) { 11783 resolver.removeFilter(filter); 11784 } 11785 } 11786 mSettings.writePackageRestrictionsLPr(sourceUserId); 11787 } 11788 } 11789 11790 // Enforcing that callingUid is owning pkg on userId 11791 private void enforceOwnerRights(String pkg, int userId, int callingUid) { 11792 // The system owns everything. 11793 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 11794 return; 11795 } 11796 int callingUserId = UserHandle.getUserId(callingUid); 11797 if (callingUserId != userId) { 11798 throw new SecurityException("calling uid " + callingUid 11799 + " pretends to own " + pkg + " on user " + userId + " but belongs to user " 11800 + callingUserId); 11801 } 11802 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 11803 if (pi == null) { 11804 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 11805 + callingUserId); 11806 } 11807 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 11808 throw new SecurityException("Calling uid " + callingUid 11809 + " does not own package " + pkg); 11810 } 11811 } 11812 11813 @Override 11814 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 11815 Intent intent = new Intent(Intent.ACTION_MAIN); 11816 intent.addCategory(Intent.CATEGORY_HOME); 11817 11818 final int callingUserId = UserHandle.getCallingUserId(); 11819 List<ResolveInfo> list = queryIntentActivities(intent, null, 11820 PackageManager.GET_META_DATA, callingUserId); 11821 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 11822 true, false, false, callingUserId); 11823 11824 allHomeCandidates.clear(); 11825 if (list != null) { 11826 for (ResolveInfo ri : list) { 11827 allHomeCandidates.add(ri); 11828 } 11829 } 11830 return (preferred == null || preferred.activityInfo == null) 11831 ? null 11832 : new ComponentName(preferred.activityInfo.packageName, 11833 preferred.activityInfo.name); 11834 } 11835 11836 /** 11837 * Check if calling UID is the current home app. This handles both the case 11838 * where the user has selected a specific home app, and where there is only 11839 * one home app. 11840 */ 11841 public boolean checkCallerIsHomeApp() { 11842 final Intent intent = new Intent(Intent.ACTION_MAIN); 11843 intent.addCategory(Intent.CATEGORY_HOME); 11844 11845 final int callingUid = Binder.getCallingUid(); 11846 final int callingUserId = UserHandle.getCallingUserId(); 11847 final List<ResolveInfo> allHomes = queryIntentActivities(intent, null, 0, callingUserId); 11848 final ResolveInfo preferredHome = findPreferredActivity(intent, null, 0, allHomes, 0, true, 11849 false, false, callingUserId); 11850 11851 if (preferredHome != null) { 11852 if (callingUid == preferredHome.activityInfo.applicationInfo.uid) { 11853 return true; 11854 } 11855 } else { 11856 for (ResolveInfo info : allHomes) { 11857 if (callingUid == info.activityInfo.applicationInfo.uid) { 11858 return true; 11859 } 11860 } 11861 } 11862 11863 return false; 11864 } 11865 11866 /** 11867 * Enforce that calling UID is the current home app. This handles both the 11868 * case where the user has selected a specific home app, and where there is 11869 * only one home app. 11870 */ 11871 public void enforceCallerIsHomeApp() { 11872 if (!checkCallerIsHomeApp()) { 11873 throw new SecurityException("Caller is not currently selected home app"); 11874 } 11875 } 11876 11877 @Override 11878 public void setApplicationEnabledSetting(String appPackageName, 11879 int newState, int flags, int userId, String callingPackage) { 11880 if (!sUserManager.exists(userId)) return; 11881 if (callingPackage == null) { 11882 callingPackage = Integer.toString(Binder.getCallingUid()); 11883 } 11884 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 11885 } 11886 11887 @Override 11888 public void setComponentEnabledSetting(ComponentName componentName, 11889 int newState, int flags, int userId) { 11890 if (!sUserManager.exists(userId)) return; 11891 setEnabledSetting(componentName.getPackageName(), 11892 componentName.getClassName(), newState, flags, userId, null); 11893 } 11894 11895 private void setEnabledSetting(final String packageName, String className, int newState, 11896 final int flags, int userId, String callingPackage) { 11897 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 11898 || newState == COMPONENT_ENABLED_STATE_ENABLED 11899 || newState == COMPONENT_ENABLED_STATE_DISABLED 11900 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 11901 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 11902 throw new IllegalArgumentException("Invalid new component state: " 11903 + newState); 11904 } 11905 PackageSetting pkgSetting; 11906 final int uid = Binder.getCallingUid(); 11907 final int permission = mContext.checkCallingOrSelfPermission( 11908 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11909 enforceCrossUserPermission(uid, userId, false, "set enabled"); 11910 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11911 boolean sendNow = false; 11912 boolean isApp = (className == null); 11913 String componentName = isApp ? packageName : className; 11914 int packageUid = -1; 11915 ArrayList<String> components; 11916 11917 // writer 11918 synchronized (mPackages) { 11919 pkgSetting = mSettings.mPackages.get(packageName); 11920 if (pkgSetting == null) { 11921 if (className == null) { 11922 throw new IllegalArgumentException( 11923 "Unknown package: " + packageName); 11924 } 11925 throw new IllegalArgumentException( 11926 "Unknown component: " + packageName 11927 + "/" + className); 11928 } 11929 // Allow root and verify that userId is not being specified by a different user 11930 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 11931 throw new SecurityException( 11932 "Permission Denial: attempt to change component state from pid=" 11933 + Binder.getCallingPid() 11934 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 11935 } 11936 if (className == null) { 11937 // We're dealing with an application/package level state change 11938 if (pkgSetting.getEnabled(userId) == newState) { 11939 // Nothing to do 11940 return; 11941 } 11942 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 11943 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 11944 // Don't care about who enables an app. 11945 callingPackage = null; 11946 } 11947 pkgSetting.setEnabled(newState, userId, callingPackage); 11948 // pkgSetting.pkg.mSetEnabled = newState; 11949 } else { 11950 // We're dealing with a component level state change 11951 // First, verify that this is a valid class name. 11952 PackageParser.Package pkg = pkgSetting.pkg; 11953 if (pkg == null || !pkg.hasComponentClassName(className)) { 11954 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 11955 throw new IllegalArgumentException("Component class " + className 11956 + " does not exist in " + packageName); 11957 } else { 11958 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 11959 + className + " does not exist in " + packageName); 11960 } 11961 } 11962 switch (newState) { 11963 case COMPONENT_ENABLED_STATE_ENABLED: 11964 if (!pkgSetting.enableComponentLPw(className, userId)) { 11965 return; 11966 } 11967 break; 11968 case COMPONENT_ENABLED_STATE_DISABLED: 11969 if (!pkgSetting.disableComponentLPw(className, userId)) { 11970 return; 11971 } 11972 break; 11973 case COMPONENT_ENABLED_STATE_DEFAULT: 11974 if (!pkgSetting.restoreComponentLPw(className, userId)) { 11975 return; 11976 } 11977 break; 11978 default: 11979 Slog.e(TAG, "Invalid new component state: " + newState); 11980 return; 11981 } 11982 } 11983 mSettings.writePackageRestrictionsLPr(userId); 11984 components = mPendingBroadcasts.get(userId, packageName); 11985 final boolean newPackage = components == null; 11986 if (newPackage) { 11987 components = new ArrayList<String>(); 11988 } 11989 if (!components.contains(componentName)) { 11990 components.add(componentName); 11991 } 11992 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 11993 sendNow = true; 11994 // Purge entry from pending broadcast list if another one exists already 11995 // since we are sending one right away. 11996 mPendingBroadcasts.remove(userId, packageName); 11997 } else { 11998 if (newPackage) { 11999 mPendingBroadcasts.put(userId, packageName, components); 12000 } 12001 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 12002 // Schedule a message 12003 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 12004 } 12005 } 12006 } 12007 12008 long callingId = Binder.clearCallingIdentity(); 12009 try { 12010 if (sendNow) { 12011 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 12012 sendPackageChangedBroadcast(packageName, 12013 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 12014 } 12015 } finally { 12016 Binder.restoreCallingIdentity(callingId); 12017 } 12018 } 12019 12020 private void sendPackageChangedBroadcast(String packageName, 12021 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 12022 if (DEBUG_INSTALL) 12023 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 12024 + componentNames); 12025 Bundle extras = new Bundle(4); 12026 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 12027 String nameList[] = new String[componentNames.size()]; 12028 componentNames.toArray(nameList); 12029 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 12030 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 12031 extras.putInt(Intent.EXTRA_UID, packageUid); 12032 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 12033 new int[] {UserHandle.getUserId(packageUid)}); 12034 } 12035 12036 @Override 12037 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 12038 if (!sUserManager.exists(userId)) return; 12039 final int uid = Binder.getCallingUid(); 12040 final int permission = mContext.checkCallingOrSelfPermission( 12041 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 12042 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 12043 enforceCrossUserPermission(uid, userId, true, "stop package"); 12044 // writer 12045 synchronized (mPackages) { 12046 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 12047 uid, userId)) { 12048 scheduleWritePackageRestrictionsLocked(userId); 12049 } 12050 } 12051 } 12052 12053 @Override 12054 public String getInstallerPackageName(String packageName) { 12055 // reader 12056 synchronized (mPackages) { 12057 return mSettings.getInstallerPackageNameLPr(packageName); 12058 } 12059 } 12060 12061 @Override 12062 public int getApplicationEnabledSetting(String packageName, int userId) { 12063 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12064 int uid = Binder.getCallingUid(); 12065 enforceCrossUserPermission(uid, userId, false, "get enabled"); 12066 // reader 12067 synchronized (mPackages) { 12068 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 12069 } 12070 } 12071 12072 @Override 12073 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 12074 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12075 int uid = Binder.getCallingUid(); 12076 enforceCrossUserPermission(uid, userId, false, "get component enabled"); 12077 // reader 12078 synchronized (mPackages) { 12079 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 12080 } 12081 } 12082 12083 @Override 12084 public void enterSafeMode() { 12085 enforceSystemOrRoot("Only the system can request entering safe mode"); 12086 12087 if (!mSystemReady) { 12088 mSafeMode = true; 12089 } 12090 } 12091 12092 @Override 12093 public void systemReady() { 12094 mSystemReady = true; 12095 12096 // Read the compatibilty setting when the system is ready. 12097 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 12098 mContext.getContentResolver(), 12099 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 12100 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 12101 if (DEBUG_SETTINGS) { 12102 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 12103 } 12104 12105 synchronized (mPackages) { 12106 // Verify that all of the preferred activity components actually 12107 // exist. It is possible for applications to be updated and at 12108 // that point remove a previously declared activity component that 12109 // had been set as a preferred activity. We try to clean this up 12110 // the next time we encounter that preferred activity, but it is 12111 // possible for the user flow to never be able to return to that 12112 // situation so here we do a sanity check to make sure we haven't 12113 // left any junk around. 12114 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 12115 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12116 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12117 removed.clear(); 12118 for (PreferredActivity pa : pir.filterSet()) { 12119 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 12120 removed.add(pa); 12121 } 12122 } 12123 if (removed.size() > 0) { 12124 for (int r=0; r<removed.size(); r++) { 12125 PreferredActivity pa = removed.get(r); 12126 Slog.w(TAG, "Removing dangling preferred activity: " 12127 + pa.mPref.mComponent); 12128 pir.removeFilter(pa); 12129 } 12130 mSettings.writePackageRestrictionsLPr( 12131 mSettings.mPreferredActivities.keyAt(i)); 12132 } 12133 } 12134 } 12135 sUserManager.systemReady(); 12136 } 12137 12138 @Override 12139 public boolean isSafeMode() { 12140 return mSafeMode; 12141 } 12142 12143 @Override 12144 public boolean hasSystemUidErrors() { 12145 return mHasSystemUidErrors; 12146 } 12147 12148 static String arrayToString(int[] array) { 12149 StringBuffer buf = new StringBuffer(128); 12150 buf.append('['); 12151 if (array != null) { 12152 for (int i=0; i<array.length; i++) { 12153 if (i > 0) buf.append(", "); 12154 buf.append(array[i]); 12155 } 12156 } 12157 buf.append(']'); 12158 return buf.toString(); 12159 } 12160 12161 static class DumpState { 12162 public static final int DUMP_LIBS = 1 << 0; 12163 public static final int DUMP_FEATURES = 1 << 1; 12164 public static final int DUMP_RESOLVERS = 1 << 2; 12165 public static final int DUMP_PERMISSIONS = 1 << 3; 12166 public static final int DUMP_PACKAGES = 1 << 4; 12167 public static final int DUMP_SHARED_USERS = 1 << 5; 12168 public static final int DUMP_MESSAGES = 1 << 6; 12169 public static final int DUMP_PROVIDERS = 1 << 7; 12170 public static final int DUMP_VERIFIERS = 1 << 8; 12171 public static final int DUMP_PREFERRED = 1 << 9; 12172 public static final int DUMP_PREFERRED_XML = 1 << 10; 12173 public static final int DUMP_KEYSETS = 1 << 11; 12174 public static final int DUMP_VERSION = 1 << 12; 12175 public static final int DUMP_INSTALLS = 1 << 13; 12176 12177 public static final int OPTION_SHOW_FILTERS = 1 << 0; 12178 12179 private int mTypes; 12180 12181 private int mOptions; 12182 12183 private boolean mTitlePrinted; 12184 12185 private SharedUserSetting mSharedUser; 12186 12187 public boolean isDumping(int type) { 12188 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 12189 return true; 12190 } 12191 12192 return (mTypes & type) != 0; 12193 } 12194 12195 public void setDump(int type) { 12196 mTypes |= type; 12197 } 12198 12199 public boolean isOptionEnabled(int option) { 12200 return (mOptions & option) != 0; 12201 } 12202 12203 public void setOptionEnabled(int option) { 12204 mOptions |= option; 12205 } 12206 12207 public boolean onTitlePrinted() { 12208 final boolean printed = mTitlePrinted; 12209 mTitlePrinted = true; 12210 return printed; 12211 } 12212 12213 public boolean getTitlePrinted() { 12214 return mTitlePrinted; 12215 } 12216 12217 public void setTitlePrinted(boolean enabled) { 12218 mTitlePrinted = enabled; 12219 } 12220 12221 public SharedUserSetting getSharedUser() { 12222 return mSharedUser; 12223 } 12224 12225 public void setSharedUser(SharedUserSetting user) { 12226 mSharedUser = user; 12227 } 12228 } 12229 12230 @Override 12231 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 12232 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 12233 != PackageManager.PERMISSION_GRANTED) { 12234 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 12235 + Binder.getCallingPid() 12236 + ", uid=" + Binder.getCallingUid() 12237 + " without permission " 12238 + android.Manifest.permission.DUMP); 12239 return; 12240 } 12241 12242 DumpState dumpState = new DumpState(); 12243 boolean fullPreferred = false; 12244 boolean checkin = false; 12245 12246 String packageName = null; 12247 12248 int opti = 0; 12249 while (opti < args.length) { 12250 String opt = args[opti]; 12251 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 12252 break; 12253 } 12254 opti++; 12255 if ("-a".equals(opt)) { 12256 // Right now we only know how to print all. 12257 } else if ("-h".equals(opt)) { 12258 pw.println("Package manager dump options:"); 12259 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 12260 pw.println(" --checkin: dump for a checkin"); 12261 pw.println(" -f: print details of intent filters"); 12262 pw.println(" -h: print this help"); 12263 pw.println(" cmd may be one of:"); 12264 pw.println(" l[ibraries]: list known shared libraries"); 12265 pw.println(" f[ibraries]: list device features"); 12266 pw.println(" k[eysets]: print known keysets"); 12267 pw.println(" r[esolvers]: dump intent resolvers"); 12268 pw.println(" perm[issions]: dump permissions"); 12269 pw.println(" pref[erred]: print preferred package settings"); 12270 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 12271 pw.println(" prov[iders]: dump content providers"); 12272 pw.println(" p[ackages]: dump installed packages"); 12273 pw.println(" s[hared-users]: dump shared user IDs"); 12274 pw.println(" m[essages]: print collected runtime messages"); 12275 pw.println(" v[erifiers]: print package verifier info"); 12276 pw.println(" version: print database version info"); 12277 pw.println(" write: write current settings now"); 12278 pw.println(" <package.name>: info about given package"); 12279 pw.println(" installs: details about install sessions"); 12280 return; 12281 } else if ("--checkin".equals(opt)) { 12282 checkin = true; 12283 } else if ("-f".equals(opt)) { 12284 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12285 } else { 12286 pw.println("Unknown argument: " + opt + "; use -h for help"); 12287 } 12288 } 12289 12290 // Is the caller requesting to dump a particular piece of data? 12291 if (opti < args.length) { 12292 String cmd = args[opti]; 12293 opti++; 12294 // Is this a package name? 12295 if ("android".equals(cmd) || cmd.contains(".")) { 12296 packageName = cmd; 12297 // When dumping a single package, we always dump all of its 12298 // filter information since the amount of data will be reasonable. 12299 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12300 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 12301 dumpState.setDump(DumpState.DUMP_LIBS); 12302 } else if ("f".equals(cmd) || "features".equals(cmd)) { 12303 dumpState.setDump(DumpState.DUMP_FEATURES); 12304 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 12305 dumpState.setDump(DumpState.DUMP_RESOLVERS); 12306 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 12307 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 12308 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 12309 dumpState.setDump(DumpState.DUMP_PREFERRED); 12310 } else if ("preferred-xml".equals(cmd)) { 12311 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 12312 if (opti < args.length && "--full".equals(args[opti])) { 12313 fullPreferred = true; 12314 opti++; 12315 } 12316 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 12317 dumpState.setDump(DumpState.DUMP_PACKAGES); 12318 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 12319 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 12320 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 12321 dumpState.setDump(DumpState.DUMP_PROVIDERS); 12322 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 12323 dumpState.setDump(DumpState.DUMP_MESSAGES); 12324 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 12325 dumpState.setDump(DumpState.DUMP_VERIFIERS); 12326 } else if ("version".equals(cmd)) { 12327 dumpState.setDump(DumpState.DUMP_VERSION); 12328 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 12329 dumpState.setDump(DumpState.DUMP_KEYSETS); 12330 } else if ("write".equals(cmd)) { 12331 synchronized (mPackages) { 12332 mSettings.writeLPr(); 12333 pw.println("Settings written."); 12334 return; 12335 } 12336 } else if ("installs".equals(cmd)) { 12337 dumpState.setDump(DumpState.DUMP_INSTALLS); 12338 } 12339 } 12340 12341 if (checkin) { 12342 pw.println("vers,1"); 12343 } 12344 12345 // reader 12346 synchronized (mPackages) { 12347 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 12348 if (!checkin) { 12349 if (dumpState.onTitlePrinted()) 12350 pw.println(); 12351 pw.println("Database versions:"); 12352 pw.print(" SDK Version:"); 12353 pw.print(" internal="); 12354 pw.print(mSettings.mInternalSdkPlatform); 12355 pw.print(" external="); 12356 pw.println(mSettings.mExternalSdkPlatform); 12357 pw.print(" DB Version:"); 12358 pw.print(" internal="); 12359 pw.print(mSettings.mInternalDatabaseVersion); 12360 pw.print(" external="); 12361 pw.println(mSettings.mExternalDatabaseVersion); 12362 } 12363 } 12364 12365 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 12366 if (!checkin) { 12367 if (dumpState.onTitlePrinted()) 12368 pw.println(); 12369 pw.println("Verifiers:"); 12370 pw.print(" Required: "); 12371 pw.print(mRequiredVerifierPackage); 12372 pw.print(" (uid="); 12373 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 12374 pw.println(")"); 12375 } else if (mRequiredVerifierPackage != null) { 12376 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 12377 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 12378 } 12379 } 12380 12381 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 12382 boolean printedHeader = false; 12383 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 12384 while (it.hasNext()) { 12385 String name = it.next(); 12386 SharedLibraryEntry ent = mSharedLibraries.get(name); 12387 if (!checkin) { 12388 if (!printedHeader) { 12389 if (dumpState.onTitlePrinted()) 12390 pw.println(); 12391 pw.println("Libraries:"); 12392 printedHeader = true; 12393 } 12394 pw.print(" "); 12395 } else { 12396 pw.print("lib,"); 12397 } 12398 pw.print(name); 12399 if (!checkin) { 12400 pw.print(" -> "); 12401 } 12402 if (ent.path != null) { 12403 if (!checkin) { 12404 pw.print("(jar) "); 12405 pw.print(ent.path); 12406 } else { 12407 pw.print(",jar,"); 12408 pw.print(ent.path); 12409 } 12410 } else { 12411 if (!checkin) { 12412 pw.print("(apk) "); 12413 pw.print(ent.apk); 12414 } else { 12415 pw.print(",apk,"); 12416 pw.print(ent.apk); 12417 } 12418 } 12419 pw.println(); 12420 } 12421 } 12422 12423 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 12424 if (dumpState.onTitlePrinted()) 12425 pw.println(); 12426 if (!checkin) { 12427 pw.println("Features:"); 12428 } 12429 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 12430 while (it.hasNext()) { 12431 String name = it.next(); 12432 if (!checkin) { 12433 pw.print(" "); 12434 } else { 12435 pw.print("feat,"); 12436 } 12437 pw.println(name); 12438 } 12439 } 12440 12441 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 12442 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 12443 : "Activity Resolver Table:", " ", packageName, 12444 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12445 dumpState.setTitlePrinted(true); 12446 } 12447 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 12448 : "Receiver Resolver Table:", " ", packageName, 12449 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12450 dumpState.setTitlePrinted(true); 12451 } 12452 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 12453 : "Service Resolver Table:", " ", packageName, 12454 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12455 dumpState.setTitlePrinted(true); 12456 } 12457 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 12458 : "Provider Resolver Table:", " ", packageName, 12459 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12460 dumpState.setTitlePrinted(true); 12461 } 12462 } 12463 12464 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 12465 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12466 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12467 int user = mSettings.mPreferredActivities.keyAt(i); 12468 if (pir.dump(pw, 12469 dumpState.getTitlePrinted() 12470 ? "\nPreferred Activities User " + user + ":" 12471 : "Preferred Activities User " + user + ":", " ", 12472 packageName, true)) { 12473 dumpState.setTitlePrinted(true); 12474 } 12475 } 12476 } 12477 12478 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 12479 pw.flush(); 12480 FileOutputStream fout = new FileOutputStream(fd); 12481 BufferedOutputStream str = new BufferedOutputStream(fout); 12482 XmlSerializer serializer = new FastXmlSerializer(); 12483 try { 12484 serializer.setOutput(str, "utf-8"); 12485 serializer.startDocument(null, true); 12486 serializer.setFeature( 12487 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 12488 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 12489 serializer.endDocument(); 12490 serializer.flush(); 12491 } catch (IllegalArgumentException e) { 12492 pw.println("Failed writing: " + e); 12493 } catch (IllegalStateException e) { 12494 pw.println("Failed writing: " + e); 12495 } catch (IOException e) { 12496 pw.println("Failed writing: " + e); 12497 } 12498 } 12499 12500 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 12501 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 12502 if (packageName == null) { 12503 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 12504 if (iperm == 0) { 12505 if (dumpState.onTitlePrinted()) 12506 pw.println(); 12507 pw.println("AppOp Permissions:"); 12508 } 12509 pw.print(" AppOp Permission "); 12510 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 12511 pw.println(":"); 12512 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 12513 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 12514 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 12515 } 12516 } 12517 } 12518 } 12519 12520 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 12521 boolean printedSomething = false; 12522 for (PackageParser.Provider p : mProviders.mProviders.values()) { 12523 if (packageName != null && !packageName.equals(p.info.packageName)) { 12524 continue; 12525 } 12526 if (!printedSomething) { 12527 if (dumpState.onTitlePrinted()) 12528 pw.println(); 12529 pw.println("Registered ContentProviders:"); 12530 printedSomething = true; 12531 } 12532 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 12533 pw.print(" "); pw.println(p.toString()); 12534 } 12535 printedSomething = false; 12536 for (Map.Entry<String, PackageParser.Provider> entry : 12537 mProvidersByAuthority.entrySet()) { 12538 PackageParser.Provider p = entry.getValue(); 12539 if (packageName != null && !packageName.equals(p.info.packageName)) { 12540 continue; 12541 } 12542 if (!printedSomething) { 12543 if (dumpState.onTitlePrinted()) 12544 pw.println(); 12545 pw.println("ContentProvider Authorities:"); 12546 printedSomething = true; 12547 } 12548 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 12549 pw.print(" "); pw.println(p.toString()); 12550 if (p.info != null && p.info.applicationInfo != null) { 12551 final String appInfo = p.info.applicationInfo.toString(); 12552 pw.print(" applicationInfo="); pw.println(appInfo); 12553 } 12554 } 12555 } 12556 12557 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 12558 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 12559 } 12560 12561 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 12562 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 12563 } 12564 12565 if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 12566 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState); 12567 } 12568 12569 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS)) { 12570 if (dumpState.onTitlePrinted()) pw.println(); 12571 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 12572 } 12573 12574 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 12575 if (dumpState.onTitlePrinted()) pw.println(); 12576 mSettings.dumpReadMessagesLPr(pw, dumpState); 12577 12578 pw.println(); 12579 pw.println("Package warning messages:"); 12580 final File fname = getSettingsProblemFile(); 12581 FileInputStream in = null; 12582 try { 12583 in = new FileInputStream(fname); 12584 final int avail = in.available(); 12585 final byte[] data = new byte[avail]; 12586 in.read(data); 12587 pw.print(new String(data)); 12588 } catch (FileNotFoundException e) { 12589 } catch (IOException e) { 12590 } finally { 12591 if (in != null) { 12592 try { 12593 in.close(); 12594 } catch (IOException e) { 12595 } 12596 } 12597 } 12598 } 12599 } 12600 } 12601 12602 // ------- apps on sdcard specific code ------- 12603 static final boolean DEBUG_SD_INSTALL = false; 12604 12605 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 12606 12607 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 12608 12609 private boolean mMediaMounted = false; 12610 12611 private String getEncryptKey() { 12612 try { 12613 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 12614 SD_ENCRYPTION_KEYSTORE_NAME); 12615 if (sdEncKey == null) { 12616 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 12617 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 12618 if (sdEncKey == null) { 12619 Slog.e(TAG, "Failed to create encryption keys"); 12620 return null; 12621 } 12622 } 12623 return sdEncKey; 12624 } catch (NoSuchAlgorithmException nsae) { 12625 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 12626 return null; 12627 } catch (IOException ioe) { 12628 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 12629 return null; 12630 } 12631 12632 } 12633 12634 /* package */static String getTempContainerId() { 12635 int tmpIdx = 1; 12636 String list[] = PackageHelper.getSecureContainerList(); 12637 if (list != null) { 12638 for (final String name : list) { 12639 // Ignore null and non-temporary container entries 12640 if (name == null || !name.startsWith(mTempContainerPrefix)) { 12641 continue; 12642 } 12643 12644 String subStr = name.substring(mTempContainerPrefix.length()); 12645 try { 12646 int cid = Integer.parseInt(subStr); 12647 if (cid >= tmpIdx) { 12648 tmpIdx = cid + 1; 12649 } 12650 } catch (NumberFormatException e) { 12651 } 12652 } 12653 } 12654 return mTempContainerPrefix + tmpIdx; 12655 } 12656 12657 /* 12658 * Update media status on PackageManager. 12659 */ 12660 @Override 12661 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 12662 int callingUid = Binder.getCallingUid(); 12663 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 12664 throw new SecurityException("Media status can only be updated by the system"); 12665 } 12666 // reader; this apparently protects mMediaMounted, but should probably 12667 // be a different lock in that case. 12668 synchronized (mPackages) { 12669 Log.i(TAG, "Updating external media status from " 12670 + (mMediaMounted ? "mounted" : "unmounted") + " to " 12671 + (mediaStatus ? "mounted" : "unmounted")); 12672 if (DEBUG_SD_INSTALL) 12673 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 12674 + ", mMediaMounted=" + mMediaMounted); 12675 if (mediaStatus == mMediaMounted) { 12676 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 12677 : 0, -1); 12678 mHandler.sendMessage(msg); 12679 return; 12680 } 12681 mMediaMounted = mediaStatus; 12682 } 12683 // Queue up an async operation since the package installation may take a 12684 // little while. 12685 mHandler.post(new Runnable() { 12686 public void run() { 12687 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 12688 } 12689 }); 12690 } 12691 12692 /** 12693 * Called by MountService when the initial ASECs to scan are available. 12694 * Should block until all the ASEC containers are finished being scanned. 12695 */ 12696 public void scanAvailableAsecs() { 12697 updateExternalMediaStatusInner(true, false, false); 12698 if (mShouldRestoreconData) { 12699 SELinuxMMAC.setRestoreconDone(); 12700 mShouldRestoreconData = false; 12701 } 12702 } 12703 12704 /* 12705 * Collect information of applications on external media, map them against 12706 * existing containers and update information based on current mount status. 12707 * Please note that we always have to report status if reportStatus has been 12708 * set to true especially when unloading packages. 12709 */ 12710 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 12711 boolean externalStorage) { 12712 // Collection of uids 12713 int uidArr[] = null; 12714 // Collection of stale containers 12715 HashSet<String> removeCids = new HashSet<String>(); 12716 // Collection of packages on external media with valid containers. 12717 HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>(); 12718 // Get list of secure containers. 12719 final String list[] = PackageHelper.getSecureContainerList(); 12720 if (list == null || list.length == 0) { 12721 Log.i(TAG, "No secure containers on sdcard"); 12722 } else { 12723 // Process list of secure containers and categorize them 12724 // as active or stale based on their package internal state. 12725 int uidList[] = new int[list.length]; 12726 int num = 0; 12727 // reader 12728 synchronized (mPackages) { 12729 for (String cid : list) { 12730 if (DEBUG_SD_INSTALL) 12731 Log.i(TAG, "Processing container " + cid); 12732 String pkgName = getAsecPackageName(cid); 12733 if (pkgName == null) { 12734 if (DEBUG_SD_INSTALL) 12735 Log.i(TAG, "Container : " + cid + " stale"); 12736 removeCids.add(cid); 12737 continue; 12738 } 12739 if (DEBUG_SD_INSTALL) 12740 Log.i(TAG, "Looking for pkg : " + pkgName); 12741 12742 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12743 if (ps == null) { 12744 Log.i(TAG, "Deleting container with no matching settings " + cid); 12745 removeCids.add(cid); 12746 continue; 12747 } 12748 12749 /* 12750 * Skip packages that are not external if we're unmounting 12751 * external storage. 12752 */ 12753 if (externalStorage && !isMounted && !isExternal(ps)) { 12754 continue; 12755 } 12756 12757 final AsecInstallArgs args = new AsecInstallArgs(cid, 12758 getAppDexInstructionSets(ps), isForwardLocked(ps), isMultiArch(ps)); 12759 // The package status is changed only if the code path 12760 // matches between settings and the container id. 12761 if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) { 12762 if (DEBUG_SD_INSTALL) { 12763 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 12764 + " at code path: " + ps.codePathString); 12765 } 12766 12767 // We do have a valid package installed on sdcard 12768 processCids.put(args, ps.codePathString); 12769 final int uid = ps.appId; 12770 if (uid != -1) { 12771 uidList[num++] = uid; 12772 } 12773 } else { 12774 Log.i(TAG, "Deleting stale container for " + cid); 12775 removeCids.add(cid); 12776 } 12777 } 12778 } 12779 12780 if (num > 0) { 12781 // Sort uid list 12782 Arrays.sort(uidList, 0, num); 12783 // Throw away duplicates 12784 uidArr = new int[num]; 12785 uidArr[0] = uidList[0]; 12786 int di = 0; 12787 for (int i = 1; i < num; i++) { 12788 if (uidList[i - 1] != uidList[i]) { 12789 uidArr[di++] = uidList[i]; 12790 } 12791 } 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, removeCids); 12799 startCleaningPackages(); 12800 } else { 12801 if (DEBUG_SD_INSTALL) 12802 Log.i(TAG, "Unloading packages"); 12803 unloadMediaPackages(processCids, uidArr, reportStatus); 12804 } 12805 } 12806 12807 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 12808 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 12809 int size = pkgList.size(); 12810 if (size > 0) { 12811 // Send broadcasts here 12812 Bundle extras = new Bundle(); 12813 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 12814 .toArray(new String[size])); 12815 if (uidArr != null) { 12816 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 12817 } 12818 if (replacing) { 12819 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 12820 } 12821 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 12822 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 12823 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 12824 } 12825 } 12826 12827 /* 12828 * Look at potentially valid container ids from processCids If package 12829 * information doesn't match the one on record or package scanning fails, 12830 * the cid is added to list of removeCids. We currently don't delete stale 12831 * containers. 12832 */ 12833 private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 12834 HashSet<String> removeCids) { 12835 ArrayList<String> pkgList = new ArrayList<String>(); 12836 Set<AsecInstallArgs> keys = processCids.keySet(); 12837 boolean doGc = false; 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 doGc = true; 12866 synchronized (mInstallLock) { 12867 PackageParser.Package pkg = null; 12868 try { 12869 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 12870 } catch (PackageManagerException e) { 12871 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 12872 } 12873 // Scan the package 12874 if (pkg != null) { 12875 /* 12876 * TODO why is the lock being held? doPostInstall is 12877 * called in other places without the lock. This needs 12878 * to be straightened out. 12879 */ 12880 // writer 12881 synchronized (mPackages) { 12882 retCode = PackageManager.INSTALL_SUCCEEDED; 12883 pkgList.add(pkg.packageName); 12884 // Post process args 12885 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 12886 pkg.applicationInfo.uid); 12887 } 12888 } else { 12889 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 12890 } 12891 } 12892 12893 } finally { 12894 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 12895 // Don't destroy container here. Wait till gc clears things 12896 // up. 12897 removeCids.add(args.cid); 12898 } 12899 } 12900 } 12901 // writer 12902 synchronized (mPackages) { 12903 // If the platform SDK has changed since the last time we booted, 12904 // we need to re-grant app permission to catch any new ones that 12905 // appear. This is really a hack, and means that apps can in some 12906 // cases get permissions that the user didn't initially explicitly 12907 // allow... it would be nice to have some better way to handle 12908 // this situation. 12909 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 12910 if (regrantPermissions) 12911 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 12912 + mSdkVersion + "; regranting permissions for external storage"); 12913 mSettings.mExternalSdkPlatform = mSdkVersion; 12914 12915 // Make sure group IDs have been assigned, and any permission 12916 // changes in other apps are accounted for 12917 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 12918 | (regrantPermissions 12919 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 12920 : 0)); 12921 12922 mSettings.updateExternalDatabaseVersion(); 12923 12924 // can downgrade to reader 12925 // Persist settings 12926 mSettings.writeLPr(); 12927 } 12928 // Send a broadcast to let everyone know we are done processing 12929 if (pkgList.size() > 0) { 12930 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12931 } 12932 // Force gc to avoid any stale parser references that we might have. 12933 if (doGc) { 12934 Runtime.getRuntime().gc(); 12935 } 12936 // List stale containers and destroy stale temporary containers. 12937 if (removeCids != null) { 12938 for (String cid : removeCids) { 12939 if (cid.startsWith(mTempContainerPrefix)) { 12940 Log.i(TAG, "Destroying stale temporary container " + cid); 12941 PackageHelper.destroySdDir(cid); 12942 } else { 12943 Log.w(TAG, "Container " + cid + " is stale"); 12944 } 12945 } 12946 } 12947 } 12948 12949 /* 12950 * Utility method to unload a list of specified containers 12951 */ 12952 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 12953 // Just unmount all valid containers. 12954 for (AsecInstallArgs arg : cidArgs) { 12955 synchronized (mInstallLock) { 12956 arg.doPostDeleteLI(false); 12957 } 12958 } 12959 } 12960 12961 /* 12962 * Unload packages mounted on external media. This involves deleting package 12963 * data from internal structures, sending broadcasts about diabled packages, 12964 * gc'ing to free up references, unmounting all secure containers 12965 * corresponding to packages on external media, and posting a 12966 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 12967 * that we always have to post this message if status has been requested no 12968 * matter what. 12969 */ 12970 private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 12971 final boolean reportStatus) { 12972 if (DEBUG_SD_INSTALL) 12973 Log.i(TAG, "unloading media packages"); 12974 ArrayList<String> pkgList = new ArrayList<String>(); 12975 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 12976 final Set<AsecInstallArgs> keys = processCids.keySet(); 12977 for (AsecInstallArgs args : keys) { 12978 String pkgName = args.getPackageName(); 12979 if (DEBUG_SD_INSTALL) 12980 Log.i(TAG, "Trying to unload pkg : " + pkgName); 12981 // Delete package internally 12982 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 12983 synchronized (mInstallLock) { 12984 boolean res = deletePackageLI(pkgName, null, false, null, null, 12985 PackageManager.DELETE_KEEP_DATA, outInfo, false); 12986 if (res) { 12987 pkgList.add(pkgName); 12988 } else { 12989 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 12990 failedList.add(args); 12991 } 12992 } 12993 } 12994 12995 // reader 12996 synchronized (mPackages) { 12997 // We didn't update the settings after removing each package; 12998 // write them now for all packages. 12999 mSettings.writeLPr(); 13000 } 13001 13002 // We have to absolutely send UPDATED_MEDIA_STATUS only 13003 // after confirming that all the receivers processed the ordered 13004 // broadcast when packages get disabled, force a gc to clean things up. 13005 // and unload all the containers. 13006 if (pkgList.size() > 0) { 13007 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 13008 new IIntentReceiver.Stub() { 13009 public void performReceive(Intent intent, int resultCode, String data, 13010 Bundle extras, boolean ordered, boolean sticky, 13011 int sendingUser) throws RemoteException { 13012 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 13013 reportStatus ? 1 : 0, 1, keys); 13014 mHandler.sendMessage(msg); 13015 } 13016 }); 13017 } else { 13018 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 13019 keys); 13020 mHandler.sendMessage(msg); 13021 } 13022 } 13023 13024 /** Binder call */ 13025 @Override 13026 public void movePackage(final String packageName, final IPackageMoveObserver observer, 13027 final int flags) { 13028 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 13029 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 13030 int returnCode = PackageManager.MOVE_SUCCEEDED; 13031 int currFlags = 0; 13032 int newFlags = 0; 13033 // reader 13034 synchronized (mPackages) { 13035 PackageParser.Package pkg = mPackages.get(packageName); 13036 if (pkg == null) { 13037 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 13038 } else { 13039 // Disable moving fwd locked apps and system packages 13040 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 13041 Slog.w(TAG, "Cannot move system application"); 13042 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 13043 } else if (pkg.mOperationPending) { 13044 Slog.w(TAG, "Attempt to move package which has pending operations"); 13045 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 13046 } else { 13047 // Find install location first 13048 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 13049 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 13050 Slog.w(TAG, "Ambigous flags specified for move location."); 13051 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 13052 } else { 13053 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL 13054 : PackageManager.INSTALL_INTERNAL; 13055 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL 13056 : PackageManager.INSTALL_INTERNAL; 13057 13058 if (newFlags == currFlags) { 13059 Slog.w(TAG, "No move required. Trying to move to same location"); 13060 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 13061 } else { 13062 if (isForwardLocked(pkg)) { 13063 currFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13064 newFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13065 } 13066 } 13067 } 13068 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13069 pkg.mOperationPending = true; 13070 } 13071 } 13072 } 13073 13074 /* 13075 * TODO this next block probably shouldn't be inside the lock. We 13076 * can't guarantee these won't change after this is fired off 13077 * anyway. 13078 */ 13079 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 13080 processPendingMove(new MoveParams(null, observer, 0, packageName, null, -1, user, false), 13081 returnCode); 13082 } else { 13083 Message msg = mHandler.obtainMessage(INIT_COPY); 13084 final String[] instructionSets = getAppDexInstructionSets(pkg.applicationInfo); 13085 final boolean multiArch = isMultiArch(pkg.applicationInfo); 13086 InstallArgs srcArgs = createInstallArgsForExisting(currFlags, 13087 pkg.applicationInfo.getCodePath(), pkg.applicationInfo.getResourcePath(), 13088 pkg.applicationInfo.nativeLibraryRootDir, instructionSets, multiArch); 13089 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName, 13090 instructionSets, pkg.applicationInfo.uid, user, multiArch); 13091 msg.obj = mp; 13092 mHandler.sendMessage(msg); 13093 } 13094 } 13095 } 13096 13097 private void processPendingMove(final MoveParams mp, final int currentStatus) { 13098 // Queue up an async operation since the package deletion may take a 13099 // little while. 13100 mHandler.post(new Runnable() { 13101 public void run() { 13102 // TODO fix this; this does nothing. 13103 mHandler.removeCallbacks(this); 13104 int returnCode = currentStatus; 13105 if (currentStatus == PackageManager.MOVE_SUCCEEDED) { 13106 int uidArr[] = null; 13107 ArrayList<String> pkgList = null; 13108 synchronized (mPackages) { 13109 PackageParser.Package pkg = mPackages.get(mp.packageName); 13110 if (pkg == null) { 13111 Slog.w(TAG, " Package " + mp.packageName 13112 + " doesn't exist. Aborting move"); 13113 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 13114 } else if (!mp.srcArgs.getCodePath().equals( 13115 pkg.applicationInfo.getCodePath())) { 13116 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " 13117 + mp.srcArgs.getCodePath() + " to " 13118 + pkg.applicationInfo.getCodePath() 13119 + " Aborting move and returning error"); 13120 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 13121 } else { 13122 uidArr = new int[] { 13123 pkg.applicationInfo.uid 13124 }; 13125 pkgList = new ArrayList<String>(); 13126 pkgList.add(mp.packageName); 13127 } 13128 } 13129 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13130 // Send resources unavailable broadcast 13131 sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null); 13132 // Update package code and resource paths 13133 synchronized (mInstallLock) { 13134 synchronized (mPackages) { 13135 PackageParser.Package pkg = mPackages.get(mp.packageName); 13136 // Recheck for package again. 13137 if (pkg == null) { 13138 Slog.w(TAG, " Package " + mp.packageName 13139 + " doesn't exist. Aborting move"); 13140 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 13141 } else if (!mp.srcArgs.getCodePath().equals( 13142 pkg.applicationInfo.getCodePath())) { 13143 Slog.w(TAG, "Package " + mp.packageName 13144 + " code path changed from " + mp.srcArgs.getCodePath() 13145 + " to " + pkg.applicationInfo.getCodePath() 13146 + " Aborting move and returning error"); 13147 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 13148 } else { 13149 final String oldCodePath = pkg.codePath; 13150 final String newCodePath = mp.targetArgs.getCodePath(); 13151 final String newResPath = mp.targetArgs.getResourcePath(); 13152 // TODO: This assumes the new style of installation. 13153 // should we look at legacyNativeLibraryPath ? 13154 final String newNativeRoot = new File(pkg.codePath, LIB_DIR_NAME).getAbsolutePath(); 13155 final File newNativeDir = new File(newNativeRoot); 13156 13157 if (!isForwardLocked(pkg) && !isExternal(pkg)) { 13158 // TODO(multiArch): Fix this so that it looks at the existing 13159 // recorded CPU abis from the package. There's no need for a separate 13160 // round of ABI scanning here. 13161 NativeLibraryHelper.Handle handle = null; 13162 try { 13163 handle = NativeLibraryHelper.Handle.create( 13164 new File(newCodePath)); 13165 final int abi = NativeLibraryHelper.findSupportedAbi( 13166 handle, Build.SUPPORTED_ABIS); 13167 if (abi >= 0) { 13168 NativeLibraryHelper.copyNativeBinariesIfNeededLI( 13169 handle, newNativeDir, Build.SUPPORTED_ABIS[abi]); 13170 } 13171 } catch (IOException ioe) { 13172 Slog.w(TAG, "Unable to extract native libs for package :" 13173 + mp.packageName, ioe); 13174 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 13175 } finally { 13176 IoUtils.closeQuietly(handle); 13177 } 13178 } 13179 13180 final int[] users = sUserManager.getUserIds(); 13181 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13182 for (int user : users) { 13183 // TODO(multiArch): Fix this so that it links to the 13184 // correct directory. We're currently pointing to root. but we 13185 // must point to the arch specific subdirectory (if applicable). 13186 // 13187 // TODO(multiArch): Bogus reference to nativeLibraryDir. 13188 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, 13189 newNativeRoot, user) < 0) { 13190 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 13191 } 13192 } 13193 } 13194 13195 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13196 pkg.codePath = newCodePath; 13197 pkg.baseCodePath = newCodePath; 13198 // Move dex files around 13199 if (moveDexFilesLI(oldCodePath, pkg) != PackageManager.INSTALL_SUCCEEDED) { 13200 // Moving of dex files failed. Set 13201 // error code and abort move. 13202 pkg.codePath = oldCodePath; 13203 pkg.baseCodePath = oldCodePath; 13204 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 13205 } 13206 } 13207 13208 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13209 pkg.applicationInfo.setCodePath(newCodePath); 13210 pkg.applicationInfo.setBaseCodePath(newCodePath); 13211 pkg.applicationInfo.setSplitCodePaths(null); 13212 pkg.applicationInfo.setResourcePath(newResPath); 13213 pkg.applicationInfo.setBaseResourcePath(newResPath); 13214 pkg.applicationInfo.setSplitResourcePaths(null); 13215 13216 PackageSetting ps = (PackageSetting) pkg.mExtras; 13217 ps.codePath = new File(pkg.applicationInfo.getCodePath()); 13218 ps.codePathString = ps.codePath.getPath(); 13219 ps.resourcePath = new File(pkg.applicationInfo.getResourcePath()); 13220 ps.resourcePathString = ps.resourcePath.getPath(); 13221 13222 // Note that we don't have to recalculate the primary and secondary 13223 // CPU ABIs because they must already have been calculated during the 13224 // initial install of the app. 13225 ps.legacyNativeLibraryPathString = null; 13226 13227 // Set the application info flag 13228 // correctly. 13229 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) { 13230 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE; 13231 } else { 13232 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE; 13233 } 13234 ps.setFlags(pkg.applicationInfo.flags); 13235 mAppDirs.remove(oldCodePath); 13236 mAppDirs.put(newCodePath, pkg); 13237 // Persist settings 13238 mSettings.writeLPr(); 13239 } 13240 } 13241 } 13242 } 13243 // Send resources available broadcast 13244 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 13245 } 13246 } 13247 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 13248 // Clean up failed installation 13249 if (mp.targetArgs != null) { 13250 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR, 13251 -1); 13252 } 13253 } else { 13254 // Force a gc to clear things up. 13255 Runtime.getRuntime().gc(); 13256 // Delete older code 13257 synchronized (mInstallLock) { 13258 mp.srcArgs.doPostDeleteLI(true); 13259 } 13260 } 13261 13262 // Allow more operations on this file if we didn't fail because 13263 // an operation was already pending for this package. 13264 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) { 13265 synchronized (mPackages) { 13266 PackageParser.Package pkg = mPackages.get(mp.packageName); 13267 if (pkg != null) { 13268 pkg.mOperationPending = false; 13269 } 13270 } 13271 } 13272 13273 IPackageMoveObserver observer = mp.observer; 13274 if (observer != null) { 13275 try { 13276 observer.packageMoved(mp.packageName, returnCode); 13277 } catch (RemoteException e) { 13278 Log.i(TAG, "Observer no longer exists."); 13279 } 13280 } 13281 } 13282 }); 13283 } 13284 13285 @Override 13286 public boolean setInstallLocation(int loc) { 13287 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 13288 null); 13289 if (getInstallLocation() == loc) { 13290 return true; 13291 } 13292 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 13293 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 13294 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 13295 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 13296 return true; 13297 } 13298 return false; 13299 } 13300 13301 @Override 13302 public int getInstallLocation() { 13303 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13304 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 13305 PackageHelper.APP_INSTALL_AUTO); 13306 } 13307 13308 /** Called by UserManagerService */ 13309 void cleanUpUserLILPw(int userHandle) { 13310 mDirtyUsers.remove(userHandle); 13311 mSettings.removeUserLPw(userHandle); 13312 mPendingBroadcasts.remove(userHandle); 13313 if (mInstaller != null) { 13314 // Technically, we shouldn't be doing this with the package lock 13315 // held. However, this is very rare, and there is already so much 13316 // other disk I/O going on, that we'll let it slide for now. 13317 mInstaller.removeUserDataDirs(userHandle); 13318 } 13319 mUserNeedsBadging.delete(userHandle); 13320 } 13321 13322 /** Called by UserManagerService */ 13323 void createNewUserLILPw(int userHandle, File path) { 13324 if (mInstaller != null) { 13325 mInstaller.createUserConfig(userHandle); 13326 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 13327 } 13328 } 13329 13330 @Override 13331 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 13332 mContext.enforceCallingOrSelfPermission( 13333 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13334 "Only package verification agents can read the verifier device identity"); 13335 13336 synchronized (mPackages) { 13337 return mSettings.getVerifierDeviceIdentityLPw(); 13338 } 13339 } 13340 13341 @Override 13342 public void setPermissionEnforced(String permission, boolean enforced) { 13343 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 13344 if (READ_EXTERNAL_STORAGE.equals(permission)) { 13345 synchronized (mPackages) { 13346 if (mSettings.mReadExternalStorageEnforced == null 13347 || mSettings.mReadExternalStorageEnforced != enforced) { 13348 mSettings.mReadExternalStorageEnforced = enforced; 13349 mSettings.writeLPr(); 13350 } 13351 } 13352 // kill any non-foreground processes so we restart them and 13353 // grant/revoke the GID. 13354 final IActivityManager am = ActivityManagerNative.getDefault(); 13355 if (am != null) { 13356 final long token = Binder.clearCallingIdentity(); 13357 try { 13358 am.killProcessesBelowForeground("setPermissionEnforcement"); 13359 } catch (RemoteException e) { 13360 } finally { 13361 Binder.restoreCallingIdentity(token); 13362 } 13363 } 13364 } else { 13365 throw new IllegalArgumentException("No selective enforcement for " + permission); 13366 } 13367 } 13368 13369 @Override 13370 @Deprecated 13371 public boolean isPermissionEnforced(String permission) { 13372 return true; 13373 } 13374 13375 @Override 13376 public boolean isStorageLow() { 13377 final long token = Binder.clearCallingIdentity(); 13378 try { 13379 final DeviceStorageMonitorInternal 13380 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13381 if (dsm != null) { 13382 return dsm.isMemoryLow(); 13383 } else { 13384 return false; 13385 } 13386 } finally { 13387 Binder.restoreCallingIdentity(token); 13388 } 13389 } 13390 13391 @Override 13392 public IPackageInstaller getPackageInstaller() { 13393 return mInstallerService; 13394 } 13395 13396 private boolean userNeedsBadging(int userId) { 13397 int index = mUserNeedsBadging.indexOfKey(userId); 13398 if (index < 0) { 13399 final UserInfo userInfo; 13400 final long token = Binder.clearCallingIdentity(); 13401 try { 13402 userInfo = sUserManager.getUserInfo(userId); 13403 } finally { 13404 Binder.restoreCallingIdentity(token); 13405 } 13406 final boolean b; 13407 if (userInfo != null && userInfo.isManagedProfile()) { 13408 b = true; 13409 } else { 13410 b = false; 13411 } 13412 mUserNeedsBadging.put(userId, b); 13413 return b; 13414 } 13415 return mUserNeedsBadging.valueAt(index); 13416 } 13417 13418 @Override 13419 public KeySetHandle getKeySetByAlias(String packageName, String alias) { 13420 if (packageName == null || alias == null) { 13421 return null; 13422 } 13423 synchronized(mPackages) { 13424 final PackageParser.Package pkg = mPackages.get(packageName); 13425 if (pkg == null) { 13426 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13427 throw new IllegalArgumentException("Unknown package: " + packageName); 13428 } 13429 if (pkg.applicationInfo.uid != Binder.getCallingUid() 13430 && Process.SYSTEM_UID != Binder.getCallingUid()) { 13431 throw new SecurityException("May not access KeySets defined by" 13432 + " aliases in other applications."); 13433 } 13434 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13435 return ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias); 13436 } 13437 } 13438 13439 @Override 13440 public KeySetHandle getSigningKeySet(String packageName) { 13441 if (packageName == null) { 13442 return null; 13443 } 13444 synchronized(mPackages) { 13445 final PackageParser.Package pkg = mPackages.get(packageName); 13446 if (pkg == null) { 13447 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13448 throw new IllegalArgumentException("Unknown package: " + packageName); 13449 } 13450 if (pkg.applicationInfo.uid != Binder.getCallingUid() 13451 && Process.SYSTEM_UID != Binder.getCallingUid()) { 13452 throw new SecurityException("May not access signing KeySet of other apps."); 13453 } 13454 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13455 return ksms.getSigningKeySetByPackageNameLPr(packageName); 13456 } 13457 } 13458 13459 @Override 13460 public boolean isPackageSignedByKeySet(String packageName, IBinder ks) { 13461 if (packageName == null || ks == null) { 13462 return false; 13463 } 13464 synchronized(mPackages) { 13465 final PackageParser.Package pkg = mPackages.get(packageName); 13466 if (pkg == null) { 13467 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13468 throw new IllegalArgumentException("Unknown package: " + packageName); 13469 } 13470 if (ks instanceof KeySetHandle) { 13471 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13472 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ks); 13473 } 13474 return false; 13475 } 13476 } 13477 13478 @Override 13479 public boolean isPackageSignedByKeySetExactly(String packageName, IBinder ks) { 13480 if (packageName == null || ks == null) { 13481 return false; 13482 } 13483 synchronized(mPackages) { 13484 final PackageParser.Package pkg = mPackages.get(packageName); 13485 if (pkg == null) { 13486 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13487 throw new IllegalArgumentException("Unknown package: " + packageName); 13488 } 13489 if (ks instanceof KeySetHandle) { 13490 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13491 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ks); 13492 } 13493 return false; 13494 } 13495 } 13496} 13497