PackageManagerService.java revision 941a8ba1a6043cf84a7bf622e44a0b4f7abd0178
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS; 20import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 21import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 26import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 27import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 28import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 29import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 30import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 32import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 33import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 34import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 36import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 37import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 38import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 39import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 41import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 42import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 44import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 45import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 46import static android.content.pm.PackageParser.isApkFile; 47import static android.os.Process.PACKAGE_INFO_GID; 48import static android.os.Process.SYSTEM_UID; 49import static android.system.OsConstants.O_CREAT; 50import static android.system.OsConstants.O_RDWR; 51import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 52import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 53import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 54import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 55import static com.android.internal.util.ArrayUtils.appendInt; 56import static com.android.internal.util.ArrayUtils.removeInt; 57 58import android.util.ArrayMap; 59 60import com.android.internal.R; 61import com.android.internal.app.IMediaContainerService; 62import com.android.internal.app.ResolverActivity; 63import com.android.internal.content.NativeLibraryHelper; 64import com.android.internal.content.PackageHelper; 65import com.android.internal.os.IParcelFileDescriptorFactory; 66import com.android.internal.util.ArrayUtils; 67import com.android.internal.util.FastPrintWriter; 68import com.android.internal.util.FastXmlSerializer; 69import com.android.internal.util.IndentingPrintWriter; 70import com.android.server.EventLogTags; 71import com.android.server.IntentResolver; 72import com.android.server.LocalServices; 73import com.android.server.ServiceThread; 74import com.android.server.SystemConfig; 75import com.android.server.Watchdog; 76import com.android.server.pm.Settings.DatabaseVersion; 77import com.android.server.storage.DeviceStorageMonitorInternal; 78 79import org.xmlpull.v1.XmlSerializer; 80 81import android.app.ActivityManager; 82import android.app.ActivityManagerNative; 83import android.app.IActivityManager; 84import android.app.admin.IDevicePolicyManager; 85import android.app.backup.IBackupManager; 86import android.content.BroadcastReceiver; 87import android.content.ComponentName; 88import android.content.Context; 89import android.content.IIntentReceiver; 90import android.content.Intent; 91import android.content.IntentFilter; 92import android.content.IntentSender; 93import android.content.IntentSender.SendIntentException; 94import android.content.ServiceConnection; 95import android.content.pm.ActivityInfo; 96import android.content.pm.ApplicationInfo; 97import android.content.pm.FeatureInfo; 98import android.content.pm.IPackageDataObserver; 99import android.content.pm.IPackageDeleteObserver; 100import android.content.pm.IPackageDeleteObserver2; 101import android.content.pm.IPackageInstallObserver2; 102import android.content.pm.IPackageInstaller; 103import android.content.pm.IPackageManager; 104import android.content.pm.IPackageMoveObserver; 105import android.content.pm.IPackageStatsObserver; 106import android.content.pm.InstrumentationInfo; 107import android.content.pm.ManifestDigest; 108import android.content.pm.PackageCleanItem; 109import android.content.pm.PackageInfo; 110import android.content.pm.PackageInfoLite; 111import android.content.pm.PackageInstaller; 112import android.content.pm.PackageManager; 113import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 114import android.content.pm.PackageParser.ActivityIntentInfo; 115import android.content.pm.PackageParser.PackageLite; 116import android.content.pm.PackageParser.PackageParserException; 117import android.content.pm.PackageParser; 118import android.content.pm.PackageStats; 119import android.content.pm.PackageUserState; 120import android.content.pm.ParceledListSlice; 121import android.content.pm.PermissionGroupInfo; 122import android.content.pm.PermissionInfo; 123import android.content.pm.ProviderInfo; 124import android.content.pm.ResolveInfo; 125import android.content.pm.ServiceInfo; 126import android.content.pm.Signature; 127import android.content.pm.UserInfo; 128import android.content.pm.VerificationParams; 129import android.content.pm.VerifierDeviceIdentity; 130import android.content.pm.VerifierInfo; 131import android.content.res.Resources; 132import android.hardware.display.DisplayManager; 133import android.net.Uri; 134import android.os.Binder; 135import android.os.Build; 136import android.os.Bundle; 137import android.os.Environment; 138import android.os.Environment.UserEnvironment; 139import android.os.storage.StorageManager; 140import android.os.FileUtils; 141import android.os.Handler; 142import android.os.IBinder; 143import android.os.Looper; 144import android.os.Message; 145import android.os.Parcel; 146import android.os.ParcelFileDescriptor; 147import android.os.Process; 148import android.os.RemoteException; 149import android.os.SELinux; 150import android.os.ServiceManager; 151import android.os.SystemClock; 152import android.os.SystemProperties; 153import android.os.UserHandle; 154import android.os.UserManager; 155import android.security.KeyStore; 156import android.security.SystemKeyStore; 157import android.system.ErrnoException; 158import android.system.Os; 159import android.system.StructStat; 160import android.text.TextUtils; 161import android.util.ArraySet; 162import android.util.AtomicFile; 163import android.util.DisplayMetrics; 164import android.util.EventLog; 165import android.util.ExceptionUtils; 166import android.util.Log; 167import android.util.LogPrinter; 168import android.util.PrintStreamPrinter; 169import android.util.Slog; 170import android.util.SparseArray; 171import android.util.SparseBooleanArray; 172import android.view.Display; 173 174import java.io.BufferedInputStream; 175import java.io.BufferedOutputStream; 176import java.io.File; 177import java.io.FileDescriptor; 178import java.io.FileInputStream; 179import java.io.FileNotFoundException; 180import java.io.FileOutputStream; 181import java.io.FilenameFilter; 182import java.io.IOException; 183import java.io.InputStream; 184import java.io.PrintWriter; 185import java.nio.charset.StandardCharsets; 186import java.security.NoSuchAlgorithmException; 187import java.security.PublicKey; 188import java.security.cert.CertificateEncodingException; 189import java.security.cert.CertificateException; 190import java.text.SimpleDateFormat; 191import java.util.ArrayList; 192import java.util.Arrays; 193import java.util.Collection; 194import java.util.Collections; 195import java.util.Comparator; 196import java.util.Date; 197import java.util.HashMap; 198import java.util.HashSet; 199import java.util.Iterator; 200import java.util.List; 201import java.util.Map; 202import java.util.Set; 203import java.util.concurrent.atomic.AtomicBoolean; 204import java.util.concurrent.atomic.AtomicLong; 205 206import dalvik.system.DexFile; 207import dalvik.system.StaleDexCacheError; 208import dalvik.system.VMRuntime; 209 210import libcore.io.IoUtils; 211import libcore.util.EmptyArray; 212 213/** 214 * Keep track of all those .apks everywhere. 215 * 216 * This is very central to the platform's security; please run the unit 217 * tests whenever making modifications here: 218 * 219mmm frameworks/base/tests/AndroidTests 220adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 221adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 222 * 223 * {@hide} 224 */ 225public class PackageManagerService extends IPackageManager.Stub { 226 static final String TAG = "PackageManager"; 227 static final boolean DEBUG_SETTINGS = false; 228 static final boolean DEBUG_PREFERRED = false; 229 static final boolean DEBUG_UPGRADE = false; 230 private static final boolean DEBUG_INSTALL = false; 231 private static final boolean DEBUG_REMOVE = false; 232 private static final boolean DEBUG_BROADCASTS = false; 233 private static final boolean DEBUG_SHOW_INFO = false; 234 private static final boolean DEBUG_PACKAGE_INFO = false; 235 private static final boolean DEBUG_INTENT_MATCHING = false; 236 private static final boolean DEBUG_PACKAGE_SCANNING = false; 237 private static final boolean DEBUG_VERIFY = false; 238 private static final boolean DEBUG_DEXOPT = false; 239 private static final boolean DEBUG_ABI_SELECTION = false; 240 241 private static final int RADIO_UID = Process.PHONE_UID; 242 private static final int LOG_UID = Process.LOG_UID; 243 private static final int NFC_UID = Process.NFC_UID; 244 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 245 private static final int SHELL_UID = Process.SHELL_UID; 246 247 // Cap the size of permission trees that 3rd party apps can define 248 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 249 250 // Suffix used during package installation when copying/moving 251 // package apks to install directory. 252 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 253 254 static final int SCAN_MONITOR = 1<<0; 255 static final int SCAN_NO_DEX = 1<<1; 256 static final int SCAN_FORCE_DEX = 1<<2; 257 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 258 static final int SCAN_NEW_INSTALL = 1<<4; 259 static final int SCAN_NO_PATHS = 1<<5; 260 static final int SCAN_UPDATE_TIME = 1<<6; 261 static final int SCAN_DEFER_DEX = 1<<7; 262 static final int SCAN_BOOTING = 1<<8; 263 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 264 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 265 266 static final int REMOVE_CHATTY = 1<<16; 267 268 /** 269 * Timeout (in milliseconds) after which the watchdog should declare that 270 * our handler thread is wedged. The usual default for such things is one 271 * minute but we sometimes do very lengthy I/O operations on this thread, 272 * such as installing multi-gigabyte applications, so ours needs to be longer. 273 */ 274 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 275 276 /** 277 * Whether verification is enabled by default. 278 */ 279 private static final boolean DEFAULT_VERIFY_ENABLE = true; 280 281 /** 282 * The default maximum time to wait for the verification agent to return in 283 * milliseconds. 284 */ 285 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 286 287 /** 288 * The default response for package verification timeout. 289 * 290 * This can be either PackageManager.VERIFICATION_ALLOW or 291 * PackageManager.VERIFICATION_REJECT. 292 */ 293 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 294 295 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 296 297 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 298 DEFAULT_CONTAINER_PACKAGE, 299 "com.android.defcontainer.DefaultContainerService"); 300 301 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 302 303 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 304 305 private static String sPreferredInstructionSet; 306 307 final ServiceThread mHandlerThread; 308 309 private static final String IDMAP_PREFIX = "/data/resource-cache/"; 310 private static final String IDMAP_SUFFIX = "@idmap"; 311 312 final PackageHandler mHandler; 313 314 final int mSdkVersion = Build.VERSION.SDK_INT; 315 316 final Context mContext; 317 final boolean mFactoryTest; 318 final boolean mOnlyCore; 319 final DisplayMetrics mMetrics; 320 final int mDefParseFlags; 321 final String[] mSeparateProcesses; 322 323 // This is where all application persistent data goes. 324 final File mAppDataDir; 325 326 // This is where all application persistent data goes for secondary users. 327 final File mUserAppDataDir; 328 329 /** The location for ASEC container files on internal storage. */ 330 final String mAsecInternalPath; 331 332 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 333 // LOCK HELD. Can be called with mInstallLock held. 334 final Installer mInstaller; 335 336 /** Directory where installed third-party apps stored */ 337 final File mAppInstallDir; 338 339 /** 340 * Directory to which applications installed internally have their 341 * 32 bit native libraries copied. 342 */ 343 private File mAppLib32InstallDir; 344 345 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 346 // apps. 347 final File mDrmAppPrivateInstallDir; 348 349 // ---------------------------------------------------------------- 350 351 // Lock for state used when installing and doing other long running 352 // operations. Methods that must be called with this lock held have 353 // the suffix "LI". 354 final Object mInstallLock = new Object(); 355 356 // These are the directories in the 3rd party applications installed dir 357 // that we have currently loaded packages from. Keys are the application's 358 // installed zip file (absolute codePath), and values are Package. 359 final HashMap<String, PackageParser.Package> mAppDirs = 360 new HashMap<String, PackageParser.Package>(); 361 362 // ---------------------------------------------------------------- 363 364 // Keys are String (package name), values are Package. This also serves 365 // as the lock for the global state. Methods that must be called with 366 // this lock held have the prefix "LP". 367 final HashMap<String, PackageParser.Package> mPackages = 368 new HashMap<String, PackageParser.Package>(); 369 370 // Tracks available target package names -> overlay package paths. 371 final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays = 372 new HashMap<String, HashMap<String, PackageParser.Package>>(); 373 374 final Settings mSettings; 375 boolean mRestoredSettings; 376 377 // System configuration read by SystemConfig. 378 final int[] mGlobalGids; 379 final SparseArray<HashSet<String>> mSystemPermissions; 380 final HashMap<String, FeatureInfo> mAvailableFeatures; 381 382 // If mac_permissions.xml was found for seinfo labeling. 383 boolean mFoundPolicyFile; 384 385 // If a recursive restorecon of /data/data/<pkg> is needed. 386 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 387 388 public static final class SharedLibraryEntry { 389 public final String path; 390 public final String apk; 391 392 SharedLibraryEntry(String _path, String _apk) { 393 path = _path; 394 apk = _apk; 395 } 396 } 397 398 // Currently known shared libraries. 399 final HashMap<String, SharedLibraryEntry> mSharedLibraries = 400 new HashMap<String, SharedLibraryEntry>(); 401 402 // All available activities, for your resolving pleasure. 403 final ActivityIntentResolver mActivities = 404 new ActivityIntentResolver(); 405 406 // All available receivers, for your resolving pleasure. 407 final ActivityIntentResolver mReceivers = 408 new ActivityIntentResolver(); 409 410 // All available services, for your resolving pleasure. 411 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 412 413 // All available providers, for your resolving pleasure. 414 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 415 416 // Mapping from provider base names (first directory in content URI codePath) 417 // to the provider information. 418 final HashMap<String, PackageParser.Provider> mProvidersByAuthority = 419 new HashMap<String, PackageParser.Provider>(); 420 421 // Mapping from instrumentation class names to info about them. 422 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 423 new HashMap<ComponentName, PackageParser.Instrumentation>(); 424 425 // Mapping from permission names to info about them. 426 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups = 427 new HashMap<String, PackageParser.PermissionGroup>(); 428 429 // Packages whose data we have transfered into another package, thus 430 // should no longer exist. 431 final HashSet<String> mTransferedPackages = new HashSet<String>(); 432 433 // Broadcast actions that are only available to the system. 434 final HashSet<String> mProtectedBroadcasts = new HashSet<String>(); 435 436 /** List of packages waiting for verification. */ 437 final SparseArray<PackageVerificationState> mPendingVerification 438 = new SparseArray<PackageVerificationState>(); 439 440 /** Set of packages associated with each app op permission. */ 441 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 442 443 final PackageInstallerService mInstallerService; 444 445 HashSet<PackageParser.Package> mDeferredDexOpt = null; 446 447 // Cache of users who need badging. 448 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 449 450 /** Token for keys in mPendingVerification. */ 451 private int mPendingVerificationToken = 0; 452 453 boolean mSystemReady; 454 boolean mSafeMode; 455 boolean mHasSystemUidErrors; 456 457 ApplicationInfo mAndroidApplication; 458 final ActivityInfo mResolveActivity = new ActivityInfo(); 459 final ResolveInfo mResolveInfo = new ResolveInfo(); 460 ComponentName mResolveComponentName; 461 PackageParser.Package mPlatformPackage; 462 ComponentName mCustomResolverComponentName; 463 464 boolean mResolverReplaced = false; 465 466 // Set of pending broadcasts for aggregating enable/disable of components. 467 static class PendingPackageBroadcasts { 468 // for each user id, a map of <package name -> components within that package> 469 final SparseArray<HashMap<String, ArrayList<String>>> mUidMap; 470 471 public PendingPackageBroadcasts() { 472 mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2); 473 } 474 475 public ArrayList<String> get(int userId, String packageName) { 476 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 477 return packages.get(packageName); 478 } 479 480 public void put(int userId, String packageName, ArrayList<String> components) { 481 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 482 packages.put(packageName, components); 483 } 484 485 public void remove(int userId, String packageName) { 486 HashMap<String, ArrayList<String>> packages = mUidMap.get(userId); 487 if (packages != null) { 488 packages.remove(packageName); 489 } 490 } 491 492 public void remove(int userId) { 493 mUidMap.remove(userId); 494 } 495 496 public int userIdCount() { 497 return mUidMap.size(); 498 } 499 500 public int userIdAt(int n) { 501 return mUidMap.keyAt(n); 502 } 503 504 public HashMap<String, ArrayList<String>> packagesForUserId(int userId) { 505 return mUidMap.get(userId); 506 } 507 508 public int size() { 509 // total number of pending broadcast entries across all userIds 510 int num = 0; 511 for (int i = 0; i< mUidMap.size(); i++) { 512 num += mUidMap.valueAt(i).size(); 513 } 514 return num; 515 } 516 517 public void clear() { 518 mUidMap.clear(); 519 } 520 521 private HashMap<String, ArrayList<String>> getOrAllocate(int userId) { 522 HashMap<String, ArrayList<String>> map = mUidMap.get(userId); 523 if (map == null) { 524 map = new HashMap<String, ArrayList<String>>(); 525 mUidMap.put(userId, map); 526 } 527 return map; 528 } 529 } 530 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 531 532 // Service Connection to remote media container service to copy 533 // package uri's from external media onto secure containers 534 // or internal storage. 535 private IMediaContainerService mContainerService = null; 536 537 static final int SEND_PENDING_BROADCAST = 1; 538 static final int MCS_BOUND = 3; 539 static final int END_COPY = 4; 540 static final int INIT_COPY = 5; 541 static final int MCS_UNBIND = 6; 542 static final int START_CLEANING_PACKAGE = 7; 543 static final int FIND_INSTALL_LOC = 8; 544 static final int POST_INSTALL = 9; 545 static final int MCS_RECONNECT = 10; 546 static final int MCS_GIVE_UP = 11; 547 static final int UPDATED_MEDIA_STATUS = 12; 548 static final int WRITE_SETTINGS = 13; 549 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 550 static final int PACKAGE_VERIFIED = 15; 551 static final int CHECK_PENDING_VERIFICATION = 16; 552 553 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 554 555 // Delay time in millisecs 556 static final int BROADCAST_DELAY = 10 * 1000; 557 558 static UserManagerService sUserManager; 559 560 // Stores a list of users whose package restrictions file needs to be updated 561 private HashSet<Integer> mDirtyUsers = new HashSet<Integer>(); 562 563 final private DefaultContainerConnection mDefContainerConn = 564 new DefaultContainerConnection(); 565 class DefaultContainerConnection implements ServiceConnection { 566 public void onServiceConnected(ComponentName name, IBinder service) { 567 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 568 IMediaContainerService imcs = 569 IMediaContainerService.Stub.asInterface(service); 570 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 571 } 572 573 public void onServiceDisconnected(ComponentName name) { 574 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 575 } 576 }; 577 578 // Recordkeeping of restore-after-install operations that are currently in flight 579 // between the Package Manager and the Backup Manager 580 class PostInstallData { 581 public InstallArgs args; 582 public PackageInstalledInfo res; 583 584 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 585 args = _a; 586 res = _r; 587 } 588 }; 589 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 590 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 591 592 private final String mRequiredVerifierPackage; 593 594 private final PackageUsage mPackageUsage = new PackageUsage(); 595 596 private class PackageUsage { 597 private static final int WRITE_INTERVAL 598 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 599 600 private final Object mFileLock = new Object(); 601 private final AtomicLong mLastWritten = new AtomicLong(0); 602 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 603 604 private boolean mIsHistoricalPackageUsageAvailable = true; 605 606 boolean isHistoricalPackageUsageAvailable() { 607 return mIsHistoricalPackageUsageAvailable; 608 } 609 610 void write(boolean force) { 611 if (force) { 612 writeInternal(); 613 return; 614 } 615 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 616 && !DEBUG_DEXOPT) { 617 return; 618 } 619 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 620 new Thread("PackageUsage_DiskWriter") { 621 @Override 622 public void run() { 623 try { 624 writeInternal(); 625 } finally { 626 mBackgroundWriteRunning.set(false); 627 } 628 } 629 }.start(); 630 } 631 } 632 633 private void writeInternal() { 634 synchronized (mPackages) { 635 synchronized (mFileLock) { 636 AtomicFile file = getFile(); 637 FileOutputStream f = null; 638 try { 639 f = file.startWrite(); 640 BufferedOutputStream out = new BufferedOutputStream(f); 641 FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID); 642 StringBuilder sb = new StringBuilder(); 643 for (PackageParser.Package pkg : mPackages.values()) { 644 if (pkg.mLastPackageUsageTimeInMills == 0) { 645 continue; 646 } 647 sb.setLength(0); 648 sb.append(pkg.packageName); 649 sb.append(' '); 650 sb.append((long)pkg.mLastPackageUsageTimeInMills); 651 sb.append('\n'); 652 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 653 } 654 out.flush(); 655 file.finishWrite(f); 656 } catch (IOException e) { 657 if (f != null) { 658 file.failWrite(f); 659 } 660 Log.e(TAG, "Failed to write package usage times", e); 661 } 662 } 663 } 664 mLastWritten.set(SystemClock.elapsedRealtime()); 665 } 666 667 void readLP() { 668 synchronized (mFileLock) { 669 AtomicFile file = getFile(); 670 BufferedInputStream in = null; 671 try { 672 in = new BufferedInputStream(file.openRead()); 673 StringBuffer sb = new StringBuffer(); 674 while (true) { 675 String packageName = readToken(in, sb, ' '); 676 if (packageName == null) { 677 break; 678 } 679 String timeInMillisString = readToken(in, sb, '\n'); 680 if (timeInMillisString == null) { 681 throw new IOException("Failed to find last usage time for package " 682 + packageName); 683 } 684 PackageParser.Package pkg = mPackages.get(packageName); 685 if (pkg == null) { 686 continue; 687 } 688 long timeInMillis; 689 try { 690 timeInMillis = Long.parseLong(timeInMillisString.toString()); 691 } catch (NumberFormatException e) { 692 throw new IOException("Failed to parse " + timeInMillisString 693 + " as a long.", e); 694 } 695 pkg.mLastPackageUsageTimeInMills = timeInMillis; 696 } 697 } catch (FileNotFoundException expected) { 698 mIsHistoricalPackageUsageAvailable = false; 699 } catch (IOException e) { 700 Log.w(TAG, "Failed to read package usage times", e); 701 } finally { 702 IoUtils.closeQuietly(in); 703 } 704 } 705 mLastWritten.set(SystemClock.elapsedRealtime()); 706 } 707 708 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 709 throws IOException { 710 sb.setLength(0); 711 while (true) { 712 int ch = in.read(); 713 if (ch == -1) { 714 if (sb.length() == 0) { 715 return null; 716 } 717 throw new IOException("Unexpected EOF"); 718 } 719 if (ch == endOfToken) { 720 return sb.toString(); 721 } 722 sb.append((char)ch); 723 } 724 } 725 726 private AtomicFile getFile() { 727 File dataDir = Environment.getDataDirectory(); 728 File systemDir = new File(dataDir, "system"); 729 File fname = new File(systemDir, "package-usage.list"); 730 return new AtomicFile(fname); 731 } 732 } 733 734 class PackageHandler extends Handler { 735 private boolean mBound = false; 736 final ArrayList<HandlerParams> mPendingInstalls = 737 new ArrayList<HandlerParams>(); 738 739 private boolean connectToService() { 740 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 741 " DefaultContainerService"); 742 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 743 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 744 if (mContext.bindServiceAsUser(service, mDefContainerConn, 745 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 746 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 747 mBound = true; 748 return true; 749 } 750 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 751 return false; 752 } 753 754 private void disconnectService() { 755 mContainerService = null; 756 mBound = false; 757 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 758 mContext.unbindService(mDefContainerConn); 759 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 760 } 761 762 PackageHandler(Looper looper) { 763 super(looper); 764 } 765 766 public void handleMessage(Message msg) { 767 try { 768 doHandleMessage(msg); 769 } finally { 770 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 771 } 772 } 773 774 void doHandleMessage(Message msg) { 775 switch (msg.what) { 776 case INIT_COPY: { 777 HandlerParams params = (HandlerParams) msg.obj; 778 int idx = mPendingInstalls.size(); 779 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 780 // If a bind was already initiated we dont really 781 // need to do anything. The pending install 782 // will be processed later on. 783 if (!mBound) { 784 // If this is the only one pending we might 785 // have to bind to the service again. 786 if (!connectToService()) { 787 Slog.e(TAG, "Failed to bind to media container service"); 788 params.serviceError(); 789 return; 790 } else { 791 // Once we bind to the service, the first 792 // pending request will be processed. 793 mPendingInstalls.add(idx, params); 794 } 795 } else { 796 mPendingInstalls.add(idx, params); 797 // Already bound to the service. Just make 798 // sure we trigger off processing the first request. 799 if (idx == 0) { 800 mHandler.sendEmptyMessage(MCS_BOUND); 801 } 802 } 803 break; 804 } 805 case MCS_BOUND: { 806 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 807 if (msg.obj != null) { 808 mContainerService = (IMediaContainerService) msg.obj; 809 } 810 if (mContainerService == null) { 811 // Something seriously wrong. Bail out 812 Slog.e(TAG, "Cannot bind to media container service"); 813 for (HandlerParams params : mPendingInstalls) { 814 // Indicate service bind error 815 params.serviceError(); 816 } 817 mPendingInstalls.clear(); 818 } else if (mPendingInstalls.size() > 0) { 819 HandlerParams params = mPendingInstalls.get(0); 820 if (params != null) { 821 if (params.startCopy()) { 822 // We are done... look for more work or to 823 // go idle. 824 if (DEBUG_SD_INSTALL) Log.i(TAG, 825 "Checking for more work or unbind..."); 826 // Delete pending install 827 if (mPendingInstalls.size() > 0) { 828 mPendingInstalls.remove(0); 829 } 830 if (mPendingInstalls.size() == 0) { 831 if (mBound) { 832 if (DEBUG_SD_INSTALL) Log.i(TAG, 833 "Posting delayed MCS_UNBIND"); 834 removeMessages(MCS_UNBIND); 835 Message ubmsg = obtainMessage(MCS_UNBIND); 836 // Unbind after a little delay, to avoid 837 // continual thrashing. 838 sendMessageDelayed(ubmsg, 10000); 839 } 840 } else { 841 // There are more pending requests in queue. 842 // Just post MCS_BOUND message to trigger processing 843 // of next pending install. 844 if (DEBUG_SD_INSTALL) Log.i(TAG, 845 "Posting MCS_BOUND for next work"); 846 mHandler.sendEmptyMessage(MCS_BOUND); 847 } 848 } 849 } 850 } else { 851 // Should never happen ideally. 852 Slog.w(TAG, "Empty queue"); 853 } 854 break; 855 } 856 case MCS_RECONNECT: { 857 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 858 if (mPendingInstalls.size() > 0) { 859 if (mBound) { 860 disconnectService(); 861 } 862 if (!connectToService()) { 863 Slog.e(TAG, "Failed to bind to media container service"); 864 for (HandlerParams params : mPendingInstalls) { 865 // Indicate service bind error 866 params.serviceError(); 867 } 868 mPendingInstalls.clear(); 869 } 870 } 871 break; 872 } 873 case MCS_UNBIND: { 874 // If there is no actual work left, then time to unbind. 875 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 876 877 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 878 if (mBound) { 879 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 880 881 disconnectService(); 882 } 883 } else if (mPendingInstalls.size() > 0) { 884 // There are more pending requests in queue. 885 // Just post MCS_BOUND message to trigger processing 886 // of next pending install. 887 mHandler.sendEmptyMessage(MCS_BOUND); 888 } 889 890 break; 891 } 892 case MCS_GIVE_UP: { 893 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 894 mPendingInstalls.remove(0); 895 break; 896 } 897 case SEND_PENDING_BROADCAST: { 898 String packages[]; 899 ArrayList<String> components[]; 900 int size = 0; 901 int uids[]; 902 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 903 synchronized (mPackages) { 904 if (mPendingBroadcasts == null) { 905 return; 906 } 907 size = mPendingBroadcasts.size(); 908 if (size <= 0) { 909 // Nothing to be done. Just return 910 return; 911 } 912 packages = new String[size]; 913 components = new ArrayList[size]; 914 uids = new int[size]; 915 int i = 0; // filling out the above arrays 916 917 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 918 int packageUserId = mPendingBroadcasts.userIdAt(n); 919 Iterator<Map.Entry<String, ArrayList<String>>> it 920 = mPendingBroadcasts.packagesForUserId(packageUserId) 921 .entrySet().iterator(); 922 while (it.hasNext() && i < size) { 923 Map.Entry<String, ArrayList<String>> ent = it.next(); 924 packages[i] = ent.getKey(); 925 components[i] = ent.getValue(); 926 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 927 uids[i] = (ps != null) 928 ? UserHandle.getUid(packageUserId, ps.appId) 929 : -1; 930 i++; 931 } 932 } 933 size = i; 934 mPendingBroadcasts.clear(); 935 } 936 // Send broadcasts 937 for (int i = 0; i < size; i++) { 938 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 939 } 940 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 941 break; 942 } 943 case START_CLEANING_PACKAGE: { 944 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 945 final String packageName = (String)msg.obj; 946 final int userId = msg.arg1; 947 final boolean andCode = msg.arg2 != 0; 948 synchronized (mPackages) { 949 if (userId == UserHandle.USER_ALL) { 950 int[] users = sUserManager.getUserIds(); 951 for (int user : users) { 952 mSettings.addPackageToCleanLPw( 953 new PackageCleanItem(user, packageName, andCode)); 954 } 955 } else { 956 mSettings.addPackageToCleanLPw( 957 new PackageCleanItem(userId, packageName, andCode)); 958 } 959 } 960 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 961 startCleaningPackages(); 962 } break; 963 case POST_INSTALL: { 964 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 965 PostInstallData data = mRunningInstalls.get(msg.arg1); 966 mRunningInstalls.delete(msg.arg1); 967 boolean deleteOld = false; 968 969 if (data != null) { 970 InstallArgs args = data.args; 971 PackageInstalledInfo res = data.res; 972 973 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 974 res.removedInfo.sendBroadcast(false, true, false); 975 Bundle extras = new Bundle(1); 976 extras.putInt(Intent.EXTRA_UID, res.uid); 977 // Determine the set of users who are adding this 978 // package for the first time vs. those who are seeing 979 // an update. 980 int[] firstUsers; 981 int[] updateUsers = new int[0]; 982 if (res.origUsers == null || res.origUsers.length == 0) { 983 firstUsers = res.newUsers; 984 } else { 985 firstUsers = new int[0]; 986 for (int i=0; i<res.newUsers.length; i++) { 987 int user = res.newUsers[i]; 988 boolean isNew = true; 989 for (int j=0; j<res.origUsers.length; j++) { 990 if (res.origUsers[j] == user) { 991 isNew = false; 992 break; 993 } 994 } 995 if (isNew) { 996 int[] newFirst = new int[firstUsers.length+1]; 997 System.arraycopy(firstUsers, 0, newFirst, 0, 998 firstUsers.length); 999 newFirst[firstUsers.length] = user; 1000 firstUsers = newFirst; 1001 } else { 1002 int[] newUpdate = new int[updateUsers.length+1]; 1003 System.arraycopy(updateUsers, 0, newUpdate, 0, 1004 updateUsers.length); 1005 newUpdate[updateUsers.length] = user; 1006 updateUsers = newUpdate; 1007 } 1008 } 1009 } 1010 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1011 res.pkg.applicationInfo.packageName, 1012 extras, null, null, firstUsers); 1013 final boolean update = res.removedInfo.removedPackage != null; 1014 if (update) { 1015 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1016 } 1017 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1018 res.pkg.applicationInfo.packageName, 1019 extras, null, null, updateUsers); 1020 if (update) { 1021 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1022 res.pkg.applicationInfo.packageName, 1023 extras, null, null, updateUsers); 1024 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1025 null, null, 1026 res.pkg.applicationInfo.packageName, null, updateUsers); 1027 1028 // treat asec-hosted packages like removable media on upgrade 1029 if (isForwardLocked(res.pkg) || isExternal(res.pkg)) { 1030 if (DEBUG_INSTALL) { 1031 Slog.i(TAG, "upgrading pkg " + res.pkg 1032 + " is ASEC-hosted -> AVAILABLE"); 1033 } 1034 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1035 ArrayList<String> pkgList = new ArrayList<String>(1); 1036 pkgList.add(res.pkg.applicationInfo.packageName); 1037 sendResourcesChangedBroadcast(true, true, 1038 pkgList,uidArray, null); 1039 } 1040 } 1041 if (res.removedInfo.args != null) { 1042 // Remove the replaced package's older resources safely now 1043 deleteOld = true; 1044 } 1045 1046 // Log current value of "unknown sources" setting 1047 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1048 getUnknownSourcesSettings()); 1049 } 1050 // Force a gc to clear up things 1051 Runtime.getRuntime().gc(); 1052 // We delete after a gc for applications on sdcard. 1053 if (deleteOld) { 1054 synchronized (mInstallLock) { 1055 res.removedInfo.args.doPostDeleteLI(true); 1056 } 1057 } 1058 if (args.observer != null) { 1059 try { 1060 Bundle extras = extrasForInstallResult(res); 1061 args.observer.onPackageInstalled(res.name, res.returnCode, 1062 res.returnMsg, extras); 1063 } catch (RemoteException e) { 1064 Slog.i(TAG, "Observer no longer exists."); 1065 } 1066 } 1067 } else { 1068 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1069 } 1070 } break; 1071 case UPDATED_MEDIA_STATUS: { 1072 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1073 boolean reportStatus = msg.arg1 == 1; 1074 boolean doGc = msg.arg2 == 1; 1075 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1076 if (doGc) { 1077 // Force a gc to clear up stale containers. 1078 Runtime.getRuntime().gc(); 1079 } 1080 if (msg.obj != null) { 1081 @SuppressWarnings("unchecked") 1082 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1083 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1084 // Unload containers 1085 unloadAllContainers(args); 1086 } 1087 if (reportStatus) { 1088 try { 1089 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1090 PackageHelper.getMountService().finishMediaUpdate(); 1091 } catch (RemoteException e) { 1092 Log.e(TAG, "MountService not running?"); 1093 } 1094 } 1095 } break; 1096 case WRITE_SETTINGS: { 1097 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1098 synchronized (mPackages) { 1099 removeMessages(WRITE_SETTINGS); 1100 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1101 mSettings.writeLPr(); 1102 mDirtyUsers.clear(); 1103 } 1104 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1105 } break; 1106 case WRITE_PACKAGE_RESTRICTIONS: { 1107 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1108 synchronized (mPackages) { 1109 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1110 for (int userId : mDirtyUsers) { 1111 mSettings.writePackageRestrictionsLPr(userId); 1112 } 1113 mDirtyUsers.clear(); 1114 } 1115 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1116 } break; 1117 case CHECK_PENDING_VERIFICATION: { 1118 final int verificationId = msg.arg1; 1119 final PackageVerificationState state = mPendingVerification.get(verificationId); 1120 1121 if ((state != null) && !state.timeoutExtended()) { 1122 final InstallArgs args = state.getInstallArgs(); 1123 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1124 1125 Slog.i(TAG, "Verification timed out for " + originUri); 1126 mPendingVerification.remove(verificationId); 1127 1128 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1129 1130 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1131 Slog.i(TAG, "Continuing with installation of " + originUri); 1132 state.setVerifierResponse(Binder.getCallingUid(), 1133 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1134 broadcastPackageVerified(verificationId, originUri, 1135 PackageManager.VERIFICATION_ALLOW, 1136 state.getInstallArgs().getUser()); 1137 try { 1138 ret = args.copyApk(mContainerService, true); 1139 } catch (RemoteException e) { 1140 Slog.e(TAG, "Could not contact the ContainerService"); 1141 } 1142 } else { 1143 broadcastPackageVerified(verificationId, originUri, 1144 PackageManager.VERIFICATION_REJECT, 1145 state.getInstallArgs().getUser()); 1146 } 1147 1148 processPendingInstall(args, ret); 1149 mHandler.sendEmptyMessage(MCS_UNBIND); 1150 } 1151 break; 1152 } 1153 case PACKAGE_VERIFIED: { 1154 final int verificationId = msg.arg1; 1155 1156 final PackageVerificationState state = mPendingVerification.get(verificationId); 1157 if (state == null) { 1158 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1159 break; 1160 } 1161 1162 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1163 1164 state.setVerifierResponse(response.callerUid, response.code); 1165 1166 if (state.isVerificationComplete()) { 1167 mPendingVerification.remove(verificationId); 1168 1169 final InstallArgs args = state.getInstallArgs(); 1170 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1171 1172 int ret; 1173 if (state.isInstallAllowed()) { 1174 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1175 broadcastPackageVerified(verificationId, originUri, 1176 response.code, state.getInstallArgs().getUser()); 1177 try { 1178 ret = args.copyApk(mContainerService, true); 1179 } catch (RemoteException e) { 1180 Slog.e(TAG, "Could not contact the ContainerService"); 1181 } 1182 } else { 1183 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1184 } 1185 1186 processPendingInstall(args, ret); 1187 1188 mHandler.sendEmptyMessage(MCS_UNBIND); 1189 } 1190 1191 break; 1192 } 1193 } 1194 } 1195 } 1196 1197 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1198 Bundle extras = null; 1199 switch (res.returnCode) { 1200 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1201 extras = new Bundle(); 1202 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1203 res.origPermission); 1204 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1205 res.origPackage); 1206 break; 1207 } 1208 } 1209 return extras; 1210 } 1211 1212 void scheduleWriteSettingsLocked() { 1213 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1214 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1215 } 1216 } 1217 1218 void scheduleWritePackageRestrictionsLocked(int userId) { 1219 if (!sUserManager.exists(userId)) return; 1220 mDirtyUsers.add(userId); 1221 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1222 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1223 } 1224 } 1225 1226 public static final PackageManagerService main(Context context, Installer installer, 1227 boolean factoryTest, boolean onlyCore) { 1228 PackageManagerService m = new PackageManagerService(context, installer, 1229 factoryTest, onlyCore); 1230 ServiceManager.addService("package", m); 1231 return m; 1232 } 1233 1234 static String[] splitString(String str, char sep) { 1235 int count = 1; 1236 int i = 0; 1237 while ((i=str.indexOf(sep, i)) >= 0) { 1238 count++; 1239 i++; 1240 } 1241 1242 String[] res = new String[count]; 1243 i=0; 1244 count = 0; 1245 int lastI=0; 1246 while ((i=str.indexOf(sep, i)) >= 0) { 1247 res[count] = str.substring(lastI, i); 1248 count++; 1249 i++; 1250 lastI = i; 1251 } 1252 res[count] = str.substring(lastI, str.length()); 1253 return res; 1254 } 1255 1256 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1257 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1258 Context.DISPLAY_SERVICE); 1259 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1260 } 1261 1262 public PackageManagerService(Context context, Installer installer, 1263 boolean factoryTest, boolean onlyCore) { 1264 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1265 SystemClock.uptimeMillis()); 1266 1267 if (mSdkVersion <= 0) { 1268 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1269 } 1270 1271 mContext = context; 1272 mFactoryTest = factoryTest; 1273 mOnlyCore = onlyCore; 1274 mMetrics = new DisplayMetrics(); 1275 mSettings = new Settings(context); 1276 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1277 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1278 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1279 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1280 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1281 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1282 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1283 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1284 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1285 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1286 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1287 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1288 1289 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1290 if (separateProcesses != null && separateProcesses.length() > 0) { 1291 if ("*".equals(separateProcesses)) { 1292 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1293 mSeparateProcesses = null; 1294 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1295 } else { 1296 mDefParseFlags = 0; 1297 mSeparateProcesses = separateProcesses.split(","); 1298 Slog.w(TAG, "Running with debug.separate_processes: " 1299 + separateProcesses); 1300 } 1301 } else { 1302 mDefParseFlags = 0; 1303 mSeparateProcesses = null; 1304 } 1305 1306 mInstaller = installer; 1307 1308 getDefaultDisplayMetrics(context, mMetrics); 1309 1310 SystemConfig systemConfig = SystemConfig.getInstance(); 1311 mGlobalGids = systemConfig.getGlobalGids(); 1312 mSystemPermissions = systemConfig.getSystemPermissions(); 1313 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1314 1315 synchronized (mInstallLock) { 1316 // writer 1317 synchronized (mPackages) { 1318 mHandlerThread = new ServiceThread(TAG, 1319 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1320 mHandlerThread.start(); 1321 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1322 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1323 1324 File dataDir = Environment.getDataDirectory(); 1325 mAppDataDir = new File(dataDir, "data"); 1326 mAppInstallDir = new File(dataDir, "app"); 1327 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1328 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1329 mUserAppDataDir = new File(dataDir, "user"); 1330 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1331 1332 sUserManager = new UserManagerService(context, this, 1333 mInstallLock, mPackages); 1334 1335 // Propagate permission configuration in to package manager. 1336 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1337 = systemConfig.getPermissions(); 1338 for (int i=0; i<permConfig.size(); i++) { 1339 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1340 BasePermission bp = mSettings.mPermissions.get(perm.name); 1341 if (bp == null) { 1342 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1343 mSettings.mPermissions.put(perm.name, bp); 1344 } 1345 if (perm.gids != null) { 1346 bp.gids = appendInts(bp.gids, perm.gids); 1347 } 1348 } 1349 1350 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1351 for (int i=0; i<libConfig.size(); i++) { 1352 mSharedLibraries.put(libConfig.keyAt(i), 1353 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1354 } 1355 1356 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1357 1358 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1359 mSdkVersion, mOnlyCore); 1360 1361 String customResolverActivity = Resources.getSystem().getString( 1362 R.string.config_customResolverActivity); 1363 if (TextUtils.isEmpty(customResolverActivity)) { 1364 customResolverActivity = null; 1365 } else { 1366 mCustomResolverComponentName = ComponentName.unflattenFromString( 1367 customResolverActivity); 1368 } 1369 1370 long startTime = SystemClock.uptimeMillis(); 1371 1372 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1373 startTime); 1374 1375 // Set flag to monitor and not change apk file paths when 1376 // scanning install directories. 1377 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1378 1379 final HashSet<String> alreadyDexOpted = new HashSet<String>(); 1380 1381 /** 1382 * Add everything in the in the boot class path to the 1383 * list of process files because dexopt will have been run 1384 * if necessary during zygote startup. 1385 */ 1386 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1387 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1388 1389 if (bootClassPath != null) { 1390 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1391 for (String element : bootClassPathElements) { 1392 alreadyDexOpted.add(element); 1393 } 1394 } else { 1395 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1396 } 1397 1398 if (systemServerClassPath != null) { 1399 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1400 for (String element : systemServerClassPathElements) { 1401 alreadyDexOpted.add(element); 1402 } 1403 } else { 1404 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH 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 "Setting last chosen"); 2925 } 2926 2927 @Override 2928 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 2929 final int userId = UserHandle.getCallingUserId(); 2930 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 2931 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2932 return findPreferredActivity(intent, resolvedType, flags, query, 0, 2933 false, false, false, userId); 2934 } 2935 2936 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 2937 int flags, List<ResolveInfo> query, int userId) { 2938 if (query != null) { 2939 final int N = query.size(); 2940 if (N == 1) { 2941 return query.get(0); 2942 } else if (N > 1) { 2943 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 2944 // If there is more than one activity with the same priority, 2945 // then let the user decide between them. 2946 ResolveInfo r0 = query.get(0); 2947 ResolveInfo r1 = query.get(1); 2948 if (DEBUG_INTENT_MATCHING || debug) { 2949 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 2950 + r1.activityInfo.name + "=" + r1.priority); 2951 } 2952 // If the first activity has a higher priority, or a different 2953 // default, then it is always desireable to pick it. 2954 if (r0.priority != r1.priority 2955 || r0.preferredOrder != r1.preferredOrder 2956 || r0.isDefault != r1.isDefault) { 2957 return query.get(0); 2958 } 2959 // If we have saved a preference for a preferred activity for 2960 // this Intent, use that. 2961 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 2962 flags, query, r0.priority, true, false, debug, userId); 2963 if (ri != null) { 2964 return ri; 2965 } 2966 if (userId != 0) { 2967 ri = new ResolveInfo(mResolveInfo); 2968 ri.activityInfo = new ActivityInfo(ri.activityInfo); 2969 ri.activityInfo.applicationInfo = new ApplicationInfo( 2970 ri.activityInfo.applicationInfo); 2971 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 2972 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 2973 return ri; 2974 } 2975 return mResolveInfo; 2976 } 2977 } 2978 return null; 2979 } 2980 2981 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 2982 int flags, List<ResolveInfo> query, boolean debug, int userId) { 2983 final int N = query.size(); 2984 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 2985 .get(userId); 2986 // Get the list of persistent preferred activities that handle the intent 2987 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 2988 List<PersistentPreferredActivity> pprefs = ppir != null 2989 ? ppir.queryIntent(intent, resolvedType, 2990 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 2991 : null; 2992 if (pprefs != null && pprefs.size() > 0) { 2993 final int M = pprefs.size(); 2994 for (int i=0; i<M; i++) { 2995 final PersistentPreferredActivity ppa = pprefs.get(i); 2996 if (DEBUG_PREFERRED || debug) { 2997 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 2998 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 2999 + "\n component=" + ppa.mComponent); 3000 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3001 } 3002 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3003 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3004 if (DEBUG_PREFERRED || debug) { 3005 Slog.v(TAG, "Found persistent preferred activity:"); 3006 if (ai != null) { 3007 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3008 } else { 3009 Slog.v(TAG, " null"); 3010 } 3011 } 3012 if (ai == null) { 3013 // This previously registered persistent preferred activity 3014 // component is no longer known. Ignore it and do NOT remove it. 3015 continue; 3016 } 3017 for (int j=0; j<N; j++) { 3018 final ResolveInfo ri = query.get(j); 3019 if (!ri.activityInfo.applicationInfo.packageName 3020 .equals(ai.applicationInfo.packageName)) { 3021 continue; 3022 } 3023 if (!ri.activityInfo.name.equals(ai.name)) { 3024 continue; 3025 } 3026 // Found a persistent preference that can handle the intent. 3027 if (DEBUG_PREFERRED || debug) { 3028 Slog.v(TAG, "Returning persistent preferred activity: " + 3029 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3030 } 3031 return ri; 3032 } 3033 } 3034 } 3035 return null; 3036 } 3037 3038 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3039 List<ResolveInfo> query, int priority, boolean always, 3040 boolean removeMatches, boolean debug, int userId) { 3041 if (!sUserManager.exists(userId)) return null; 3042 // writer 3043 synchronized (mPackages) { 3044 if (intent.getSelector() != null) { 3045 intent = intent.getSelector(); 3046 } 3047 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3048 3049 // Try to find a matching persistent preferred activity. 3050 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3051 debug, userId); 3052 3053 // If a persistent preferred activity matched, use it. 3054 if (pri != null) { 3055 return pri; 3056 } 3057 3058 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3059 // Get the list of preferred activities that handle the intent 3060 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3061 List<PreferredActivity> prefs = pir != null 3062 ? pir.queryIntent(intent, resolvedType, 3063 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3064 : null; 3065 if (prefs != null && prefs.size() > 0) { 3066 // First figure out how good the original match set is. 3067 // We will only allow preferred activities that came 3068 // from the same match quality. 3069 int match = 0; 3070 3071 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3072 3073 final int N = query.size(); 3074 for (int j=0; j<N; j++) { 3075 final ResolveInfo ri = query.get(j); 3076 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3077 + ": 0x" + Integer.toHexString(match)); 3078 if (ri.match > match) { 3079 match = ri.match; 3080 } 3081 } 3082 3083 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3084 + Integer.toHexString(match)); 3085 3086 match &= IntentFilter.MATCH_CATEGORY_MASK; 3087 final int M = prefs.size(); 3088 for (int i=0; i<M; i++) { 3089 final PreferredActivity pa = prefs.get(i); 3090 if (DEBUG_PREFERRED || debug) { 3091 Slog.v(TAG, "Checking PreferredActivity ds=" 3092 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3093 + "\n component=" + pa.mPref.mComponent); 3094 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3095 } 3096 if (pa.mPref.mMatch != match) { 3097 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3098 + Integer.toHexString(pa.mPref.mMatch)); 3099 continue; 3100 } 3101 // If it's not an "always" type preferred activity and that's what we're 3102 // looking for, skip it. 3103 if (always && !pa.mPref.mAlways) { 3104 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3105 continue; 3106 } 3107 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3108 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3109 if (DEBUG_PREFERRED || debug) { 3110 Slog.v(TAG, "Found preferred activity:"); 3111 if (ai != null) { 3112 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3113 } else { 3114 Slog.v(TAG, " null"); 3115 } 3116 } 3117 if (ai == null) { 3118 // This previously registered preferred activity 3119 // component is no longer known. Most likely an update 3120 // to the app was installed and in the new version this 3121 // component no longer exists. Clean it up by removing 3122 // it from the preferred activities list, and skip it. 3123 Slog.w(TAG, "Removing dangling preferred activity: " 3124 + pa.mPref.mComponent); 3125 pir.removeFilter(pa); 3126 continue; 3127 } 3128 for (int j=0; j<N; j++) { 3129 final ResolveInfo ri = query.get(j); 3130 if (!ri.activityInfo.applicationInfo.packageName 3131 .equals(ai.applicationInfo.packageName)) { 3132 continue; 3133 } 3134 if (!ri.activityInfo.name.equals(ai.name)) { 3135 continue; 3136 } 3137 3138 if (removeMatches) { 3139 pir.removeFilter(pa); 3140 if (DEBUG_PREFERRED) { 3141 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3142 } 3143 break; 3144 } 3145 3146 // Okay we found a previously set preferred or last chosen app. 3147 // If the result set is different from when this 3148 // was created, we need to clear it and re-ask the 3149 // user their preference, if we're looking for an "always" type entry. 3150 if (always && !pa.mPref.sameSet(query, priority)) { 3151 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3152 + intent + " type " + resolvedType); 3153 if (DEBUG_PREFERRED) { 3154 Slog.v(TAG, "Removing preferred activity since set changed " 3155 + pa.mPref.mComponent); 3156 } 3157 pir.removeFilter(pa); 3158 // Re-add the filter as a "last chosen" entry (!always) 3159 PreferredActivity lastChosen = new PreferredActivity( 3160 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3161 pir.addFilter(lastChosen); 3162 mSettings.writePackageRestrictionsLPr(userId); 3163 return null; 3164 } 3165 3166 // Yay! Either the set matched or we're looking for the last chosen 3167 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3168 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3169 mSettings.writePackageRestrictionsLPr(userId); 3170 return ri; 3171 } 3172 } 3173 } 3174 mSettings.writePackageRestrictionsLPr(userId); 3175 } 3176 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3177 return null; 3178 } 3179 3180 /* 3181 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3182 */ 3183 @Override 3184 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3185 int targetUserId) { 3186 mContext.enforceCallingOrSelfPermission( 3187 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3188 List<CrossProfileIntentFilter> matches = 3189 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3190 if (matches != null) { 3191 int size = matches.size(); 3192 for (int i = 0; i < size; i++) { 3193 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3194 } 3195 } 3196 ArrayList<String> packageNames = null; 3197 SparseArray<ArrayList<String>> fromSource = 3198 mSettings.mCrossProfilePackageInfo.get(sourceUserId); 3199 if (fromSource != null) { 3200 packageNames = fromSource.get(targetUserId); 3201 if (packageNames != null) { 3202 // We need the package name, so we try to resolve with the loosest flags possible 3203 List<ResolveInfo> resolveInfos = mActivities.queryIntent(intent, resolvedType, 3204 PackageManager.GET_UNINSTALLED_PACKAGES, targetUserId); 3205 int count = resolveInfos.size(); 3206 for (int i = 0; i < count; i++) { 3207 ResolveInfo resolveInfo = resolveInfos.get(i); 3208 if (packageNames.contains(resolveInfo.activityInfo.packageName)) { 3209 return true; 3210 } 3211 } 3212 } 3213 } 3214 return false; 3215 } 3216 3217 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3218 String resolvedType, int userId) { 3219 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3220 if (resolver != null) { 3221 return resolver.queryIntent(intent, resolvedType, false, userId); 3222 } 3223 return null; 3224 } 3225 3226 @Override 3227 public List<ResolveInfo> queryIntentActivities(Intent intent, 3228 String resolvedType, int flags, int userId) { 3229 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3230 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities"); 3231 ComponentName comp = intent.getComponent(); 3232 if (comp == null) { 3233 if (intent.getSelector() != null) { 3234 intent = intent.getSelector(); 3235 comp = intent.getComponent(); 3236 } 3237 } 3238 3239 if (comp != null) { 3240 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3241 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3242 if (ai != null) { 3243 final ResolveInfo ri = new ResolveInfo(); 3244 ri.activityInfo = ai; 3245 list.add(ri); 3246 } 3247 return list; 3248 } 3249 3250 // reader 3251 synchronized (mPackages) { 3252 final String pkgName = intent.getPackage(); 3253 boolean queryCrossProfile = (flags & PackageManager.NO_CROSS_PROFILE) == 0; 3254 if (pkgName == null) { 3255 ResolveInfo resolveInfo = null; 3256 if (queryCrossProfile) { 3257 // Check if the intent needs to be forwarded to another user for this package 3258 ArrayList<ResolveInfo> crossProfileResult = 3259 queryIntentActivitiesCrossProfilePackage( 3260 intent, resolvedType, flags, userId); 3261 if (!crossProfileResult.isEmpty()) { 3262 // Skip the current profile 3263 return crossProfileResult; 3264 } 3265 List<CrossProfileIntentFilter> matchingFilters = 3266 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3267 // Check for results that need to skip the current profile. 3268 resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3269 resolvedType, flags, userId); 3270 if (resolveInfo != null) { 3271 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3272 result.add(resolveInfo); 3273 return result; 3274 } 3275 // Check for cross profile results. 3276 resolveInfo = queryCrossProfileIntents( 3277 matchingFilters, intent, resolvedType, flags, userId); 3278 } 3279 // Check for results in the current profile. 3280 List<ResolveInfo> result = mActivities.queryIntent( 3281 intent, resolvedType, flags, userId); 3282 if (resolveInfo != null) { 3283 result.add(resolveInfo); 3284 Collections.sort(result, mResolvePrioritySorter); 3285 } 3286 return result; 3287 } 3288 final PackageParser.Package pkg = mPackages.get(pkgName); 3289 if (pkg != null) { 3290 if (queryCrossProfile) { 3291 ArrayList<ResolveInfo> crossProfileResult = 3292 queryIntentActivitiesCrossProfilePackage( 3293 intent, resolvedType, flags, userId, pkg, pkgName); 3294 if (!crossProfileResult.isEmpty()) { 3295 // Skip the current profile 3296 return crossProfileResult; 3297 } 3298 } 3299 return mActivities.queryIntentForPackage(intent, resolvedType, flags, 3300 pkg.activities, userId); 3301 } 3302 return new ArrayList<ResolveInfo>(); 3303 } 3304 } 3305 3306 private ResolveInfo querySkipCurrentProfileIntents( 3307 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3308 int flags, int sourceUserId) { 3309 if (matchingFilters != null) { 3310 int size = matchingFilters.size(); 3311 for (int i = 0; i < size; i ++) { 3312 CrossProfileIntentFilter filter = matchingFilters.get(i); 3313 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 3314 // Checking if there are activities in the target user that can handle the 3315 // intent. 3316 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3317 flags, sourceUserId); 3318 if (resolveInfo != null) { 3319 return resolveInfo; 3320 } 3321 } 3322 } 3323 } 3324 return null; 3325 } 3326 3327 private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage( 3328 Intent intent, String resolvedType, int flags, int userId) { 3329 ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>(); 3330 SparseArray<ArrayList<String>> sourceForwardingInfo = 3331 mSettings.mCrossProfilePackageInfo.get(userId); 3332 if (sourceForwardingInfo != null) { 3333 int NI = sourceForwardingInfo.size(); 3334 for (int i = 0; i < NI; i++) { 3335 int targetUserId = sourceForwardingInfo.keyAt(i); 3336 ArrayList<String> packageNames = sourceForwardingInfo.valueAt(i); 3337 List<ResolveInfo> resolveInfos = mActivities.queryIntent( 3338 intent, resolvedType, flags, targetUserId); 3339 int NJ = resolveInfos.size(); 3340 for (int j = 0; j < NJ; j++) { 3341 ResolveInfo resolveInfo = resolveInfos.get(j); 3342 if (packageNames.contains(resolveInfo.activityInfo.packageName)) { 3343 matchingResolveInfos.add(createForwardingResolveInfo( 3344 resolveInfo.filter, userId, targetUserId)); 3345 } 3346 } 3347 } 3348 } 3349 return matchingResolveInfos; 3350 } 3351 3352 private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage( 3353 Intent intent, String resolvedType, int flags, int userId, PackageParser.Package pkg, 3354 String packageName) { 3355 ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>(); 3356 SparseArray<ArrayList<String>> sourceForwardingInfo = 3357 mSettings.mCrossProfilePackageInfo.get(userId); 3358 if (sourceForwardingInfo != null) { 3359 int NI = sourceForwardingInfo.size(); 3360 for (int i = 0; i < NI; i++) { 3361 int targetUserId = sourceForwardingInfo.keyAt(i); 3362 if (sourceForwardingInfo.valueAt(i).contains(packageName)) { 3363 List<ResolveInfo> resolveInfos = mActivities.queryIntentForPackage( 3364 intent, resolvedType, flags, pkg.activities, targetUserId); 3365 int NJ = resolveInfos.size(); 3366 for (int j = 0; j < NJ; j++) { 3367 ResolveInfo resolveInfo = resolveInfos.get(j); 3368 matchingResolveInfos.add(createForwardingResolveInfo( 3369 resolveInfo.filter, userId, targetUserId)); 3370 } 3371 } 3372 } 3373 } 3374 return matchingResolveInfos; 3375 } 3376 3377 // Return matching ResolveInfo if any for skip current profile intent filters. 3378 private ResolveInfo queryCrossProfileIntents( 3379 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3380 int flags, int sourceUserId) { 3381 if (matchingFilters != null) { 3382 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 3383 // match the same intent. For performance reasons, it is better not to 3384 // run queryIntent twice for the same userId 3385 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 3386 int size = matchingFilters.size(); 3387 for (int i = 0; i < size; i++) { 3388 CrossProfileIntentFilter filter = matchingFilters.get(i); 3389 int targetUserId = filter.getTargetUserId(); 3390 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 3391 && !alreadyTriedUserIds.get(targetUserId)) { 3392 // Checking if there are activities in the target user that can handle the 3393 // intent. 3394 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3395 flags, sourceUserId); 3396 if (resolveInfo != null) return resolveInfo; 3397 alreadyTriedUserIds.put(targetUserId, true); 3398 } 3399 } 3400 } 3401 return null; 3402 } 3403 3404 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 3405 String resolvedType, int flags, int sourceUserId) { 3406 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 3407 resolvedType, flags, filter.getTargetUserId()); 3408 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 3409 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 3410 } 3411 return null; 3412 } 3413 3414 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 3415 int sourceUserId, int targetUserId) { 3416 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 3417 String className; 3418 if (targetUserId == UserHandle.USER_OWNER) { 3419 className = FORWARD_INTENT_TO_USER_OWNER; 3420 } else { 3421 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 3422 } 3423 ComponentName forwardingActivityComponentName = new ComponentName( 3424 mAndroidApplication.packageName, className); 3425 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 3426 sourceUserId); 3427 if (targetUserId == UserHandle.USER_OWNER) { 3428 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 3429 forwardingResolveInfo.noResourceId = true; 3430 } 3431 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 3432 forwardingResolveInfo.priority = 0; 3433 forwardingResolveInfo.preferredOrder = 0; 3434 forwardingResolveInfo.match = 0; 3435 forwardingResolveInfo.isDefault = true; 3436 forwardingResolveInfo.filter = filter; 3437 forwardingResolveInfo.targetUserId = targetUserId; 3438 return forwardingResolveInfo; 3439 } 3440 3441 @Override 3442 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 3443 Intent[] specifics, String[] specificTypes, Intent intent, 3444 String resolvedType, int flags, int userId) { 3445 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3446 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 3447 "query intent activity options"); 3448 final String resultsAction = intent.getAction(); 3449 3450 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 3451 | PackageManager.GET_RESOLVED_FILTER, userId); 3452 3453 if (DEBUG_INTENT_MATCHING) { 3454 Log.v(TAG, "Query " + intent + ": " + results); 3455 } 3456 3457 int specificsPos = 0; 3458 int N; 3459 3460 // todo: note that the algorithm used here is O(N^2). This 3461 // isn't a problem in our current environment, but if we start running 3462 // into situations where we have more than 5 or 10 matches then this 3463 // should probably be changed to something smarter... 3464 3465 // First we go through and resolve each of the specific items 3466 // that were supplied, taking care of removing any corresponding 3467 // duplicate items in the generic resolve list. 3468 if (specifics != null) { 3469 for (int i=0; i<specifics.length; i++) { 3470 final Intent sintent = specifics[i]; 3471 if (sintent == null) { 3472 continue; 3473 } 3474 3475 if (DEBUG_INTENT_MATCHING) { 3476 Log.v(TAG, "Specific #" + i + ": " + sintent); 3477 } 3478 3479 String action = sintent.getAction(); 3480 if (resultsAction != null && resultsAction.equals(action)) { 3481 // If this action was explicitly requested, then don't 3482 // remove things that have it. 3483 action = null; 3484 } 3485 3486 ResolveInfo ri = null; 3487 ActivityInfo ai = null; 3488 3489 ComponentName comp = sintent.getComponent(); 3490 if (comp == null) { 3491 ri = resolveIntent( 3492 sintent, 3493 specificTypes != null ? specificTypes[i] : null, 3494 flags, userId); 3495 if (ri == null) { 3496 continue; 3497 } 3498 if (ri == mResolveInfo) { 3499 // ACK! Must do something better with this. 3500 } 3501 ai = ri.activityInfo; 3502 comp = new ComponentName(ai.applicationInfo.packageName, 3503 ai.name); 3504 } else { 3505 ai = getActivityInfo(comp, flags, userId); 3506 if (ai == null) { 3507 continue; 3508 } 3509 } 3510 3511 // Look for any generic query activities that are duplicates 3512 // of this specific one, and remove them from the results. 3513 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 3514 N = results.size(); 3515 int j; 3516 for (j=specificsPos; j<N; j++) { 3517 ResolveInfo sri = results.get(j); 3518 if ((sri.activityInfo.name.equals(comp.getClassName()) 3519 && sri.activityInfo.applicationInfo.packageName.equals( 3520 comp.getPackageName())) 3521 || (action != null && sri.filter.matchAction(action))) { 3522 results.remove(j); 3523 if (DEBUG_INTENT_MATCHING) Log.v( 3524 TAG, "Removing duplicate item from " + j 3525 + " due to specific " + specificsPos); 3526 if (ri == null) { 3527 ri = sri; 3528 } 3529 j--; 3530 N--; 3531 } 3532 } 3533 3534 // Add this specific item to its proper place. 3535 if (ri == null) { 3536 ri = new ResolveInfo(); 3537 ri.activityInfo = ai; 3538 } 3539 results.add(specificsPos, ri); 3540 ri.specificIndex = i; 3541 specificsPos++; 3542 } 3543 } 3544 3545 // Now we go through the remaining generic results and remove any 3546 // duplicate actions that are found here. 3547 N = results.size(); 3548 for (int i=specificsPos; i<N-1; i++) { 3549 final ResolveInfo rii = results.get(i); 3550 if (rii.filter == null) { 3551 continue; 3552 } 3553 3554 // Iterate over all of the actions of this result's intent 3555 // filter... typically this should be just one. 3556 final Iterator<String> it = rii.filter.actionsIterator(); 3557 if (it == null) { 3558 continue; 3559 } 3560 while (it.hasNext()) { 3561 final String action = it.next(); 3562 if (resultsAction != null && resultsAction.equals(action)) { 3563 // If this action was explicitly requested, then don't 3564 // remove things that have it. 3565 continue; 3566 } 3567 for (int j=i+1; j<N; j++) { 3568 final ResolveInfo rij = results.get(j); 3569 if (rij.filter != null && rij.filter.hasAction(action)) { 3570 results.remove(j); 3571 if (DEBUG_INTENT_MATCHING) Log.v( 3572 TAG, "Removing duplicate item from " + j 3573 + " due to action " + action + " at " + i); 3574 j--; 3575 N--; 3576 } 3577 } 3578 } 3579 3580 // If the caller didn't request filter information, drop it now 3581 // so we don't have to marshall/unmarshall it. 3582 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3583 rii.filter = null; 3584 } 3585 } 3586 3587 // Filter out the caller activity if so requested. 3588 if (caller != null) { 3589 N = results.size(); 3590 for (int i=0; i<N; i++) { 3591 ActivityInfo ainfo = results.get(i).activityInfo; 3592 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 3593 && caller.getClassName().equals(ainfo.name)) { 3594 results.remove(i); 3595 break; 3596 } 3597 } 3598 } 3599 3600 // If the caller didn't request filter information, 3601 // drop them now so we don't have to 3602 // marshall/unmarshall it. 3603 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3604 N = results.size(); 3605 for (int i=0; i<N; i++) { 3606 results.get(i).filter = null; 3607 } 3608 } 3609 3610 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 3611 return results; 3612 } 3613 3614 @Override 3615 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 3616 int userId) { 3617 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3618 ComponentName comp = intent.getComponent(); 3619 if (comp == null) { 3620 if (intent.getSelector() != null) { 3621 intent = intent.getSelector(); 3622 comp = intent.getComponent(); 3623 } 3624 } 3625 if (comp != null) { 3626 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3627 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 3628 if (ai != null) { 3629 ResolveInfo ri = new ResolveInfo(); 3630 ri.activityInfo = ai; 3631 list.add(ri); 3632 } 3633 return list; 3634 } 3635 3636 // reader 3637 synchronized (mPackages) { 3638 String pkgName = intent.getPackage(); 3639 if (pkgName == null) { 3640 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 3641 } 3642 final PackageParser.Package pkg = mPackages.get(pkgName); 3643 if (pkg != null) { 3644 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 3645 userId); 3646 } 3647 return null; 3648 } 3649 } 3650 3651 @Override 3652 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 3653 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 3654 if (!sUserManager.exists(userId)) return null; 3655 if (query != null) { 3656 if (query.size() >= 1) { 3657 // If there is more than one service with the same priority, 3658 // just arbitrarily pick the first one. 3659 return query.get(0); 3660 } 3661 } 3662 return null; 3663 } 3664 3665 @Override 3666 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 3667 int userId) { 3668 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3669 ComponentName comp = intent.getComponent(); 3670 if (comp == null) { 3671 if (intent.getSelector() != null) { 3672 intent = intent.getSelector(); 3673 comp = intent.getComponent(); 3674 } 3675 } 3676 if (comp != null) { 3677 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3678 final ServiceInfo si = getServiceInfo(comp, flags, userId); 3679 if (si != null) { 3680 final ResolveInfo ri = new ResolveInfo(); 3681 ri.serviceInfo = si; 3682 list.add(ri); 3683 } 3684 return list; 3685 } 3686 3687 // reader 3688 synchronized (mPackages) { 3689 String pkgName = intent.getPackage(); 3690 if (pkgName == null) { 3691 return mServices.queryIntent(intent, resolvedType, flags, userId); 3692 } 3693 final PackageParser.Package pkg = mPackages.get(pkgName); 3694 if (pkg != null) { 3695 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 3696 userId); 3697 } 3698 return null; 3699 } 3700 } 3701 3702 @Override 3703 public List<ResolveInfo> queryIntentContentProviders( 3704 Intent intent, String resolvedType, int flags, int userId) { 3705 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3706 ComponentName comp = intent.getComponent(); 3707 if (comp == null) { 3708 if (intent.getSelector() != null) { 3709 intent = intent.getSelector(); 3710 comp = intent.getComponent(); 3711 } 3712 } 3713 if (comp != null) { 3714 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3715 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 3716 if (pi != null) { 3717 final ResolveInfo ri = new ResolveInfo(); 3718 ri.providerInfo = pi; 3719 list.add(ri); 3720 } 3721 return list; 3722 } 3723 3724 // reader 3725 synchronized (mPackages) { 3726 String pkgName = intent.getPackage(); 3727 if (pkgName == null) { 3728 return mProviders.queryIntent(intent, resolvedType, flags, userId); 3729 } 3730 final PackageParser.Package pkg = mPackages.get(pkgName); 3731 if (pkg != null) { 3732 return mProviders.queryIntentForPackage( 3733 intent, resolvedType, flags, pkg.providers, userId); 3734 } 3735 return null; 3736 } 3737 } 3738 3739 @Override 3740 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 3741 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3742 3743 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages"); 3744 3745 // writer 3746 synchronized (mPackages) { 3747 ArrayList<PackageInfo> list; 3748 if (listUninstalled) { 3749 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 3750 for (PackageSetting ps : mSettings.mPackages.values()) { 3751 PackageInfo pi; 3752 if (ps.pkg != null) { 3753 pi = generatePackageInfo(ps.pkg, flags, userId); 3754 } else { 3755 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3756 } 3757 if (pi != null) { 3758 list.add(pi); 3759 } 3760 } 3761 } else { 3762 list = new ArrayList<PackageInfo>(mPackages.size()); 3763 for (PackageParser.Package p : mPackages.values()) { 3764 PackageInfo pi = generatePackageInfo(p, flags, userId); 3765 if (pi != null) { 3766 list.add(pi); 3767 } 3768 } 3769 } 3770 3771 return new ParceledListSlice<PackageInfo>(list); 3772 } 3773 } 3774 3775 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 3776 String[] permissions, boolean[] tmp, int flags, int userId) { 3777 int numMatch = 0; 3778 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 3779 for (int i=0; i<permissions.length; i++) { 3780 if (gp.grantedPermissions.contains(permissions[i])) { 3781 tmp[i] = true; 3782 numMatch++; 3783 } else { 3784 tmp[i] = false; 3785 } 3786 } 3787 if (numMatch == 0) { 3788 return; 3789 } 3790 PackageInfo pi; 3791 if (ps.pkg != null) { 3792 pi = generatePackageInfo(ps.pkg, flags, userId); 3793 } else { 3794 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3795 } 3796 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 3797 if (numMatch == permissions.length) { 3798 pi.requestedPermissions = permissions; 3799 } else { 3800 pi.requestedPermissions = new String[numMatch]; 3801 numMatch = 0; 3802 for (int i=0; i<permissions.length; i++) { 3803 if (tmp[i]) { 3804 pi.requestedPermissions[numMatch] = permissions[i]; 3805 numMatch++; 3806 } 3807 } 3808 } 3809 } 3810 list.add(pi); 3811 } 3812 3813 @Override 3814 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 3815 String[] permissions, int flags, int userId) { 3816 if (!sUserManager.exists(userId)) return null; 3817 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3818 3819 // writer 3820 synchronized (mPackages) { 3821 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 3822 boolean[] tmpBools = new boolean[permissions.length]; 3823 if (listUninstalled) { 3824 for (PackageSetting ps : mSettings.mPackages.values()) { 3825 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 3826 } 3827 } else { 3828 for (PackageParser.Package pkg : mPackages.values()) { 3829 PackageSetting ps = (PackageSetting)pkg.mExtras; 3830 if (ps != null) { 3831 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 3832 userId); 3833 } 3834 } 3835 } 3836 3837 return new ParceledListSlice<PackageInfo>(list); 3838 } 3839 } 3840 3841 @Override 3842 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 3843 if (!sUserManager.exists(userId)) return null; 3844 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3845 3846 // writer 3847 synchronized (mPackages) { 3848 ArrayList<ApplicationInfo> list; 3849 if (listUninstalled) { 3850 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 3851 for (PackageSetting ps : mSettings.mPackages.values()) { 3852 ApplicationInfo ai; 3853 if (ps.pkg != null) { 3854 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3855 ps.readUserState(userId), userId); 3856 } else { 3857 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 3858 } 3859 if (ai != null) { 3860 list.add(ai); 3861 } 3862 } 3863 } else { 3864 list = new ArrayList<ApplicationInfo>(mPackages.size()); 3865 for (PackageParser.Package p : mPackages.values()) { 3866 if (p.mExtras != null) { 3867 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3868 ((PackageSetting)p.mExtras).readUserState(userId), userId); 3869 if (ai != null) { 3870 list.add(ai); 3871 } 3872 } 3873 } 3874 } 3875 3876 return new ParceledListSlice<ApplicationInfo>(list); 3877 } 3878 } 3879 3880 public List<ApplicationInfo> getPersistentApplications(int flags) { 3881 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 3882 3883 // reader 3884 synchronized (mPackages) { 3885 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 3886 final int userId = UserHandle.getCallingUserId(); 3887 while (i.hasNext()) { 3888 final PackageParser.Package p = i.next(); 3889 if (p.applicationInfo != null 3890 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 3891 && (!mSafeMode || isSystemApp(p))) { 3892 PackageSetting ps = mSettings.mPackages.get(p.packageName); 3893 if (ps != null) { 3894 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3895 ps.readUserState(userId), userId); 3896 if (ai != null) { 3897 finalList.add(ai); 3898 } 3899 } 3900 } 3901 } 3902 } 3903 3904 return finalList; 3905 } 3906 3907 @Override 3908 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 3909 if (!sUserManager.exists(userId)) return null; 3910 // reader 3911 synchronized (mPackages) { 3912 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 3913 PackageSetting ps = provider != null 3914 ? mSettings.mPackages.get(provider.owner.packageName) 3915 : null; 3916 return ps != null 3917 && mSettings.isEnabledLPr(provider.info, flags, userId) 3918 && (!mSafeMode || (provider.info.applicationInfo.flags 3919 &ApplicationInfo.FLAG_SYSTEM) != 0) 3920 ? PackageParser.generateProviderInfo(provider, flags, 3921 ps.readUserState(userId), userId) 3922 : null; 3923 } 3924 } 3925 3926 /** 3927 * @deprecated 3928 */ 3929 @Deprecated 3930 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 3931 // reader 3932 synchronized (mPackages) { 3933 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 3934 .entrySet().iterator(); 3935 final int userId = UserHandle.getCallingUserId(); 3936 while (i.hasNext()) { 3937 Map.Entry<String, PackageParser.Provider> entry = i.next(); 3938 PackageParser.Provider p = entry.getValue(); 3939 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3940 3941 if (ps != null && p.syncable 3942 && (!mSafeMode || (p.info.applicationInfo.flags 3943 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 3944 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 3945 ps.readUserState(userId), userId); 3946 if (info != null) { 3947 outNames.add(entry.getKey()); 3948 outInfo.add(info); 3949 } 3950 } 3951 } 3952 } 3953 } 3954 3955 @Override 3956 public List<ProviderInfo> queryContentProviders(String processName, 3957 int uid, int flags) { 3958 ArrayList<ProviderInfo> finalList = null; 3959 // reader 3960 synchronized (mPackages) { 3961 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 3962 final int userId = processName != null ? 3963 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 3964 while (i.hasNext()) { 3965 final PackageParser.Provider p = i.next(); 3966 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3967 if (ps != null && p.info.authority != null 3968 && (processName == null 3969 || (p.info.processName.equals(processName) 3970 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 3971 && mSettings.isEnabledLPr(p.info, flags, userId) 3972 && (!mSafeMode 3973 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 3974 if (finalList == null) { 3975 finalList = new ArrayList<ProviderInfo>(3); 3976 } 3977 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 3978 ps.readUserState(userId), userId); 3979 if (info != null) { 3980 finalList.add(info); 3981 } 3982 } 3983 } 3984 } 3985 3986 if (finalList != null) { 3987 Collections.sort(finalList, mProviderInitOrderSorter); 3988 } 3989 3990 return finalList; 3991 } 3992 3993 @Override 3994 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 3995 int flags) { 3996 // reader 3997 synchronized (mPackages) { 3998 final PackageParser.Instrumentation i = mInstrumentation.get(name); 3999 return PackageParser.generateInstrumentationInfo(i, flags); 4000 } 4001 } 4002 4003 @Override 4004 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4005 int flags) { 4006 ArrayList<InstrumentationInfo> finalList = 4007 new ArrayList<InstrumentationInfo>(); 4008 4009 // reader 4010 synchronized (mPackages) { 4011 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4012 while (i.hasNext()) { 4013 final PackageParser.Instrumentation p = i.next(); 4014 if (targetPackage == null 4015 || targetPackage.equals(p.info.targetPackage)) { 4016 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4017 flags); 4018 if (ii != null) { 4019 finalList.add(ii); 4020 } 4021 } 4022 } 4023 } 4024 4025 return finalList; 4026 } 4027 4028 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4029 HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4030 if (overlays == null) { 4031 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4032 return; 4033 } 4034 for (PackageParser.Package opkg : overlays.values()) { 4035 // Not much to do if idmap fails: we already logged the error 4036 // and we certainly don't want to abort installation of pkg simply 4037 // because an overlay didn't fit properly. For these reasons, 4038 // ignore the return value of createIdmapForPackagePairLI. 4039 createIdmapForPackagePairLI(pkg, opkg); 4040 } 4041 } 4042 4043 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4044 PackageParser.Package opkg) { 4045 if (!opkg.mTrustedOverlay) { 4046 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4047 opkg.baseCodePath + ": overlay not trusted"); 4048 return false; 4049 } 4050 HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4051 if (overlaySet == null) { 4052 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4053 opkg.baseCodePath + " but target package has no known overlays"); 4054 return false; 4055 } 4056 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4057 // TODO: generate idmap for split APKs 4058 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4059 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4060 + opkg.baseCodePath); 4061 return false; 4062 } 4063 PackageParser.Package[] overlayArray = 4064 overlaySet.values().toArray(new PackageParser.Package[0]); 4065 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4066 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4067 return p1.mOverlayPriority - p2.mOverlayPriority; 4068 } 4069 }; 4070 Arrays.sort(overlayArray, cmp); 4071 4072 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4073 int i = 0; 4074 for (PackageParser.Package p : overlayArray) { 4075 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4076 } 4077 return true; 4078 } 4079 4080 private void scanDirLI(File dir, int flags, int scanMode, long currentTime) { 4081 final File[] files = dir.listFiles(); 4082 if (ArrayUtils.isEmpty(files)) { 4083 Log.d(TAG, "No files in app dir " + dir); 4084 return; 4085 } 4086 4087 if (DEBUG_PACKAGE_SCANNING) { 4088 Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode 4089 + " flags=0x" + Integer.toHexString(flags)); 4090 } 4091 4092 for (File file : files) { 4093 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 4094 && !PackageInstallerService.isStageName(file.getName()); 4095 if (!isPackage) { 4096 // Ignore entries which are not packages 4097 continue; 4098 } 4099 try { 4100 scanPackageLI(file, flags | PackageParser.PARSE_MUST_BE_APK, 4101 scanMode, currentTime, null); 4102 } catch (PackageManagerException e) { 4103 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4104 4105 // Delete invalid userdata apps 4106 if ((flags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4107 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4108 Slog.w(TAG, "Deleting invalid package at " + file); 4109 if (file.isDirectory()) { 4110 FileUtils.deleteContents(file); 4111 } 4112 file.delete(); 4113 } 4114 } 4115 } 4116 } 4117 4118 private static File getSettingsProblemFile() { 4119 File dataDir = Environment.getDataDirectory(); 4120 File systemDir = new File(dataDir, "system"); 4121 File fname = new File(systemDir, "uiderrors.txt"); 4122 return fname; 4123 } 4124 4125 static void reportSettingsProblem(int priority, String msg) { 4126 try { 4127 File fname = getSettingsProblemFile(); 4128 FileOutputStream out = new FileOutputStream(fname, true); 4129 PrintWriter pw = new FastPrintWriter(out); 4130 SimpleDateFormat formatter = new SimpleDateFormat(); 4131 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4132 pw.println(dateString + ": " + msg); 4133 pw.close(); 4134 FileUtils.setPermissions( 4135 fname.toString(), 4136 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4137 -1, -1); 4138 } catch (java.io.IOException e) { 4139 } 4140 Slog.println(priority, TAG, msg); 4141 } 4142 4143 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 4144 PackageParser.Package pkg, File srcFile, int parseFlags) 4145 throws PackageManagerException { 4146 if (ps != null 4147 && ps.codePath.equals(srcFile) 4148 && ps.timeStamp == srcFile.lastModified() 4149 && !isCompatSignatureUpdateNeeded(pkg)) { 4150 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4151 if (ps.signatures.mSignatures != null 4152 && ps.signatures.mSignatures.length != 0 4153 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4154 // Optimization: reuse the existing cached certificates 4155 // if the package appears to be unchanged. 4156 pkg.mSignatures = ps.signatures.mSignatures; 4157 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4158 synchronized (mPackages) { 4159 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 4160 } 4161 return; 4162 } 4163 4164 Slog.w(TAG, "PackageSetting for " + ps.name 4165 + " is missing signatures. Collecting certs again to recover them."); 4166 } else { 4167 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4168 } 4169 4170 try { 4171 pp.collectCertificates(pkg, parseFlags); 4172 pp.collectManifestDigest(pkg); 4173 } catch (PackageParserException e) { 4174 throw new PackageManagerException(e.error, "Failed to collect certificates for " 4175 + pkg.packageName + ": " + e.getMessage()); 4176 } 4177 } 4178 4179 /* 4180 * Scan a package and return the newly parsed package. 4181 * Returns null in case of errors and the error code is stored in mLastScanError 4182 */ 4183 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanMode, 4184 long currentTime, UserHandle user) throws PackageManagerException { 4185 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4186 parseFlags |= mDefParseFlags; 4187 PackageParser pp = new PackageParser(); 4188 pp.setSeparateProcesses(mSeparateProcesses); 4189 pp.setOnlyCoreApps(mOnlyCore); 4190 pp.setDisplayMetrics(mMetrics); 4191 4192 if ((scanMode & SCAN_TRUSTED_OVERLAY) != 0) { 4193 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4194 } 4195 4196 final PackageParser.Package pkg; 4197 try { 4198 pkg = pp.parsePackage(scanFile, parseFlags); 4199 } catch (PackageParserException e) { 4200 throw new PackageManagerException(e.error, 4201 "Failed to scan " + scanFile + ": " + e.getMessage()); 4202 } 4203 4204 PackageSetting ps = null; 4205 PackageSetting updatedPkg; 4206 // reader 4207 synchronized (mPackages) { 4208 // Look to see if we already know about this package. 4209 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4210 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4211 // This package has been renamed to its original name. Let's 4212 // use that. 4213 ps = mSettings.peekPackageLPr(oldName); 4214 } 4215 // If there was no original package, see one for the real package name. 4216 if (ps == null) { 4217 ps = mSettings.peekPackageLPr(pkg.packageName); 4218 } 4219 // Check to see if this package could be hiding/updating a system 4220 // package. Must look for it either under the original or real 4221 // package name depending on our state. 4222 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4223 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4224 } 4225 boolean updatedPkgBetter = false; 4226 // First check if this is a system package that may involve an update 4227 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4228 if (ps != null && !ps.codePath.equals(scanFile)) { 4229 // The path has changed from what was last scanned... check the 4230 // version of the new path against what we have stored to determine 4231 // what to do. 4232 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4233 if (pkg.mVersionCode < ps.versionCode) { 4234 // The system package has been updated and the code path does not match 4235 // Ignore entry. Skip it. 4236 Log.i(TAG, "Package " + ps.name + " at " + scanFile 4237 + " ignored: updated version " + ps.versionCode 4238 + " better than this " + pkg.mVersionCode); 4239 if (!updatedPkg.codePath.equals(scanFile)) { 4240 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4241 + ps.name + " changing from " + updatedPkg.codePathString 4242 + " to " + scanFile); 4243 updatedPkg.codePath = scanFile; 4244 updatedPkg.codePathString = scanFile.toString(); 4245 // This is the point at which we know that the system-disk APK 4246 // for this package has moved during a reboot (e.g. due to an OTA), 4247 // so we need to reevaluate it for privilege policy. 4248 if (locationIsPrivileged(scanFile)) { 4249 updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED; 4250 } 4251 } 4252 updatedPkg.pkg = pkg; 4253 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 4254 } else { 4255 // The current app on the system partition is better than 4256 // what we have updated to on the data partition; switch 4257 // back to the system partition version. 4258 // At this point, its safely assumed that package installation for 4259 // apps in system partition will go through. If not there won't be a working 4260 // version of the app 4261 // writer 4262 synchronized (mPackages) { 4263 // Just remove the loaded entries from package lists. 4264 mPackages.remove(ps.name); 4265 } 4266 Slog.w(TAG, "Package " + ps.name + " at " + scanFile 4267 + "reverting from " + ps.codePathString 4268 + ": new version " + pkg.mVersionCode 4269 + " better than installed " + ps.versionCode); 4270 4271 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4272 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4273 getAppDexInstructionSets(ps)); 4274 synchronized (mInstallLock) { 4275 args.cleanUpResourcesLI(); 4276 } 4277 synchronized (mPackages) { 4278 mSettings.enableSystemPackageLPw(ps.name); 4279 } 4280 updatedPkgBetter = true; 4281 } 4282 } 4283 } 4284 4285 if (updatedPkg != null) { 4286 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4287 // initially 4288 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4289 4290 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4291 // flag set initially 4292 if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) { 4293 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4294 } 4295 } 4296 4297 // Verify certificates against what was last scanned 4298 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 4299 4300 /* 4301 * A new system app appeared, but we already had a non-system one of the 4302 * same name installed earlier. 4303 */ 4304 boolean shouldHideSystemApp = false; 4305 if (updatedPkg == null && ps != null 4306 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4307 /* 4308 * Check to make sure the signatures match first. If they don't, 4309 * wipe the installed application and its data. 4310 */ 4311 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4312 != PackageManager.SIGNATURE_MATCH) { 4313 if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!"); 4314 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4315 ps = null; 4316 } else { 4317 /* 4318 * If the newly-added system app is an older version than the 4319 * already installed version, hide it. It will be scanned later 4320 * and re-added like an update. 4321 */ 4322 if (pkg.mVersionCode < ps.versionCode) { 4323 shouldHideSystemApp = true; 4324 } else { 4325 /* 4326 * The newly found system app is a newer version that the 4327 * one previously installed. Simply remove the 4328 * already-installed application and replace it with our own 4329 * while keeping the application data. 4330 */ 4331 Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from " 4332 + ps.codePathString + ": new version " + pkg.mVersionCode 4333 + " better than installed " + ps.versionCode); 4334 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4335 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4336 getAppDexInstructionSets(ps)); 4337 synchronized (mInstallLock) { 4338 args.cleanUpResourcesLI(); 4339 } 4340 } 4341 } 4342 } 4343 4344 // The apk is forward locked (not public) if its code and resources 4345 // are kept in different files. (except for app in either system or 4346 // vendor path). 4347 // TODO grab this value from PackageSettings 4348 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4349 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4350 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 4351 } 4352 } 4353 4354 // TODO: extend to support forward-locked splits 4355 String resourcePath = null; 4356 String baseResourcePath = null; 4357 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 4358 if (ps != null && ps.resourcePathString != null) { 4359 resourcePath = ps.resourcePathString; 4360 baseResourcePath = ps.resourcePathString; 4361 } else { 4362 // Should not happen at all. Just log an error. 4363 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 4364 } 4365 } else { 4366 resourcePath = pkg.codePath; 4367 baseResourcePath = pkg.baseCodePath; 4368 } 4369 4370 // Set application objects path explicitly. 4371 pkg.applicationInfo.setCodePath(pkg.codePath); 4372 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 4373 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 4374 pkg.applicationInfo.setResourcePath(resourcePath); 4375 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 4376 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 4377 4378 // Note that we invoke the following method only if we are about to unpack an application 4379 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode 4380 | SCAN_UPDATE_SIGNATURE, currentTime, user); 4381 4382 /* 4383 * If the system app should be overridden by a previously installed 4384 * data, hide the system app now and let the /data/app scan pick it up 4385 * again. 4386 */ 4387 if (shouldHideSystemApp) { 4388 synchronized (mPackages) { 4389 /* 4390 * We have to grant systems permissions before we hide, because 4391 * grantPermissions will assume the package update is trying to 4392 * expand its permissions. 4393 */ 4394 grantPermissionsLPw(pkg, true); 4395 mSettings.disableSystemPackageLPw(pkg.packageName); 4396 } 4397 } 4398 4399 return scannedPkg; 4400 } 4401 4402 private static String fixProcessName(String defProcessName, 4403 String processName, int uid) { 4404 if (processName == null) { 4405 return defProcessName; 4406 } 4407 return processName; 4408 } 4409 4410 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 4411 throws PackageManagerException { 4412 if (pkgSetting.signatures.mSignatures != null) { 4413 // Already existing package. Make sure signatures match 4414 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 4415 == PackageManager.SIGNATURE_MATCH; 4416 if (!match) { 4417 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 4418 == PackageManager.SIGNATURE_MATCH; 4419 } 4420 if (!match) { 4421 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 4422 + pkg.packageName + " signatures do not match the " 4423 + "previously installed version; ignoring!"); 4424 } 4425 } 4426 4427 // Check for shared user signatures 4428 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 4429 // Already existing package. Make sure signatures match 4430 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4431 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 4432 if (!match) { 4433 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 4434 == PackageManager.SIGNATURE_MATCH; 4435 } 4436 if (!match) { 4437 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 4438 "Package " + pkg.packageName 4439 + " has no signatures that match those in shared user " 4440 + pkgSetting.sharedUser.name + "; ignoring!"); 4441 } 4442 } 4443 } 4444 4445 /** 4446 * Enforces that only the system UID or root's UID can call a method exposed 4447 * via Binder. 4448 * 4449 * @param message used as message if SecurityException is thrown 4450 * @throws SecurityException if the caller is not system or root 4451 */ 4452 private static final void enforceSystemOrRoot(String message) { 4453 final int uid = Binder.getCallingUid(); 4454 if (uid != Process.SYSTEM_UID && uid != 0) { 4455 throw new SecurityException(message); 4456 } 4457 } 4458 4459 @Override 4460 public void performBootDexOpt() { 4461 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4462 4463 final HashSet<PackageParser.Package> pkgs; 4464 synchronized (mPackages) { 4465 pkgs = mDeferredDexOpt; 4466 mDeferredDexOpt = null; 4467 } 4468 4469 if (pkgs != null) { 4470 // Filter out packages that aren't recently used. 4471 // 4472 // The exception is first boot of a non-eng device, which 4473 // should do a full dexopt. 4474 boolean eng = "eng".equals(SystemProperties.get("ro.build.type")); 4475 if (eng || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 4476 // TODO: add a property to control this? 4477 long dexOptLRUThresholdInMinutes; 4478 if (eng) { 4479 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 4480 } else { 4481 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 4482 } 4483 long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 4484 4485 int total = pkgs.size(); 4486 int skipped = 0; 4487 long now = System.currentTimeMillis(); 4488 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 4489 PackageParser.Package pkg = i.next(); 4490 long then = pkg.mLastPackageUsageTimeInMills; 4491 if (then + dexOptLRUThresholdInMills < now) { 4492 if (DEBUG_DEXOPT) { 4493 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 4494 ((then == 0) ? "never" : new Date(then))); 4495 } 4496 i.remove(); 4497 skipped++; 4498 } 4499 } 4500 if (DEBUG_DEXOPT) { 4501 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 4502 } 4503 } 4504 4505 int i = 0; 4506 for (PackageParser.Package pkg : pkgs) { 4507 i++; 4508 if (DEBUG_DEXOPT) { 4509 Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size() 4510 + ": " + pkg.packageName); 4511 } 4512 if (!isFirstBoot()) { 4513 try { 4514 ActivityManagerNative.getDefault().showBootMessage( 4515 mContext.getResources().getString( 4516 R.string.android_upgrading_apk, 4517 i, pkgs.size()), true); 4518 } catch (RemoteException e) { 4519 } 4520 } 4521 PackageParser.Package p = pkg; 4522 synchronized (mInstallLock) { 4523 performDexOptLI(p, null /* instruction sets */, false /* force dex */, false /* defer */, 4524 true /* include dependencies */); 4525 } 4526 } 4527 } 4528 } 4529 4530 @Override 4531 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 4532 return performDexOpt(packageName, instructionSet, true); 4533 } 4534 4535 private static String getPrimaryInstructionSet(ApplicationInfo info) { 4536 if (info.primaryCpuAbi == null) { 4537 return getPreferredInstructionSet(); 4538 } 4539 4540 return VMRuntime.getInstructionSet(info.primaryCpuAbi); 4541 } 4542 4543 public boolean performDexOpt(String packageName, String instructionSet, boolean updateUsage) { 4544 PackageParser.Package p; 4545 final String targetInstructionSet; 4546 synchronized (mPackages) { 4547 p = mPackages.get(packageName); 4548 if (p == null) { 4549 return false; 4550 } 4551 if (updateUsage) { 4552 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 4553 } 4554 mPackageUsage.write(false); 4555 4556 targetInstructionSet = instructionSet != null ? instructionSet : 4557 getPrimaryInstructionSet(p.applicationInfo); 4558 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 4559 return false; 4560 } 4561 } 4562 4563 synchronized (mInstallLock) { 4564 final String[] instructionSets = new String[] { targetInstructionSet }; 4565 return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */, 4566 true /* include dependencies */) == DEX_OPT_PERFORMED; 4567 } 4568 } 4569 4570 public HashSet<String> getPackagesThatNeedDexOpt() { 4571 HashSet<String> pkgs = null; 4572 synchronized (mPackages) { 4573 for (PackageParser.Package p : mPackages.values()) { 4574 if (DEBUG_DEXOPT) { 4575 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 4576 } 4577 if (!p.mDexOptPerformed.isEmpty()) { 4578 continue; 4579 } 4580 if (pkgs == null) { 4581 pkgs = new HashSet<String>(); 4582 } 4583 pkgs.add(p.packageName); 4584 } 4585 } 4586 return pkgs; 4587 } 4588 4589 public void shutdown() { 4590 mPackageUsage.write(true); 4591 } 4592 4593 private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets, 4594 boolean forceDex, boolean defer, HashSet<String> done) { 4595 for (int i=0; i<libs.size(); i++) { 4596 PackageParser.Package libPkg; 4597 String libName; 4598 synchronized (mPackages) { 4599 libName = libs.get(i); 4600 SharedLibraryEntry lib = mSharedLibraries.get(libName); 4601 if (lib != null && lib.apk != null) { 4602 libPkg = mPackages.get(lib.apk); 4603 } else { 4604 libPkg = null; 4605 } 4606 } 4607 if (libPkg != null && !done.contains(libName)) { 4608 performDexOptLI(libPkg, instructionSets, forceDex, defer, done); 4609 } 4610 } 4611 } 4612 4613 static final int DEX_OPT_SKIPPED = 0; 4614 static final int DEX_OPT_PERFORMED = 1; 4615 static final int DEX_OPT_DEFERRED = 2; 4616 static final int DEX_OPT_FAILED = -1; 4617 4618 private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets, 4619 boolean forceDex, boolean defer, HashSet<String> done) { 4620 final String[] instructionSets = targetInstructionSets != null ? 4621 targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo); 4622 4623 if (done != null) { 4624 done.add(pkg.packageName); 4625 if (pkg.usesLibraries != null) { 4626 performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done); 4627 } 4628 if (pkg.usesOptionalLibraries != null) { 4629 performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done); 4630 } 4631 } 4632 4633 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) { 4634 return DEX_OPT_SKIPPED; 4635 } 4636 4637 final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly(); 4638 boolean performedDexOpt = false; 4639 // There are three basic cases here: 4640 // 1.) we need to dexopt, either because we are forced or it is needed 4641 // 2.) we are defering a needed dexopt 4642 // 3.) we are skipping an unneeded dexopt 4643 final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 4644 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 4645 if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) { 4646 continue; 4647 } 4648 4649 for (String path : paths) { 4650 try { 4651 // This will return DEXOPT_NEEDED if we either cannot find any odex file for this 4652 // patckage or the one we find does not match the image checksum (i.e. it was 4653 // compiled against an old image). It will return PATCHOAT_NEEDED if we can find a 4654 // odex file and it matches the checksum of the image but not its base address, 4655 // meaning we need to move it. 4656 final byte isDexOptNeeded = DexFile.isDexOptNeededInternal(path, 4657 pkg.packageName, dexCodeInstructionSet, defer); 4658 if (forceDex || (!defer && isDexOptNeeded == DexFile.DEXOPT_NEEDED)) { 4659 Log.i(TAG, "Running dexopt on: " + path + " pkg=" 4660 + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet); 4661 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4662 final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg), 4663 pkg.packageName, dexCodeInstructionSet); 4664 4665 if (ret < 0) { 4666 // Don't bother running dexopt again if we failed, it will probably 4667 // just result in an error again. Also, don't bother dexopting for other 4668 // paths & ISAs. 4669 return DEX_OPT_FAILED; 4670 } 4671 4672 performedDexOpt = true; 4673 } else if (!defer && isDexOptNeeded == DexFile.PATCHOAT_NEEDED) { 4674 Log.i(TAG, "Running patchoat on: " + pkg.applicationInfo.packageName); 4675 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4676 final int ret = mInstaller.patchoat(path, sharedGid, !isForwardLocked(pkg), 4677 pkg.packageName, dexCodeInstructionSet); 4678 4679 if (ret < 0) { 4680 // Don't bother running patchoat again if we failed, it will probably 4681 // just result in an error again. Also, don't bother dexopting for other 4682 // paths & ISAs. 4683 return DEX_OPT_FAILED; 4684 } 4685 4686 performedDexOpt = true; 4687 } 4688 4689 // We're deciding to defer a needed dexopt. Don't bother dexopting for other 4690 // paths and instruction sets. We'll deal with them all together when we process 4691 // our list of deferred dexopts. 4692 if (defer && isDexOptNeeded != DexFile.UP_TO_DATE) { 4693 if (mDeferredDexOpt == null) { 4694 mDeferredDexOpt = new HashSet<PackageParser.Package>(); 4695 } 4696 mDeferredDexOpt.add(pkg); 4697 return DEX_OPT_DEFERRED; 4698 } 4699 } catch (FileNotFoundException e) { 4700 Slog.w(TAG, "Apk not found for dexopt: " + path); 4701 return DEX_OPT_FAILED; 4702 } catch (IOException e) { 4703 Slog.w(TAG, "IOException reading apk: " + path, e); 4704 return DEX_OPT_FAILED; 4705 } catch (StaleDexCacheError e) { 4706 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e); 4707 return DEX_OPT_FAILED; 4708 } catch (Exception e) { 4709 Slog.w(TAG, "Exception when doing dexopt : ", e); 4710 return DEX_OPT_FAILED; 4711 } 4712 } 4713 4714 // At this point we haven't failed dexopt and we haven't deferred dexopt. We must 4715 // either have either succeeded dexopt, or have had isDexOptNeededInternal tell us 4716 // it isn't required. We therefore mark that this package doesn't need dexopt unless 4717 // it's forced. performedDexOpt will tell us whether we performed dex-opt or skipped 4718 // it. 4719 pkg.mDexOptPerformed.add(dexCodeInstructionSet); 4720 } 4721 4722 // If we've gotten here, we're sure that no error occurred and that we haven't 4723 // deferred dex-opt. We've either dex-opted one more paths or instruction sets or 4724 // we've skipped all of them because they are up to date. In both cases this 4725 // package doesn't need dexopt any longer. 4726 return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED; 4727 } 4728 4729 private static String[] getAppDexInstructionSets(ApplicationInfo info) { 4730 if (info.primaryCpuAbi != null) { 4731 if (info.secondaryCpuAbi != null) { 4732 return new String[] { 4733 VMRuntime.getInstructionSet(info.primaryCpuAbi), 4734 VMRuntime.getInstructionSet(info.secondaryCpuAbi) }; 4735 } else { 4736 return new String[] { 4737 VMRuntime.getInstructionSet(info.primaryCpuAbi) }; 4738 } 4739 } 4740 4741 return new String[] { getPreferredInstructionSet() }; 4742 } 4743 4744 private static String[] getAppDexInstructionSets(PackageSetting ps) { 4745 if (ps.primaryCpuAbiString != null) { 4746 if (ps.secondaryCpuAbiString != null) { 4747 return new String[] { 4748 VMRuntime.getInstructionSet(ps.primaryCpuAbiString), 4749 VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) }; 4750 } else { 4751 return new String[] { 4752 VMRuntime.getInstructionSet(ps.primaryCpuAbiString) }; 4753 } 4754 } 4755 4756 return new String[] { getPreferredInstructionSet() }; 4757 } 4758 4759 private static String getPreferredInstructionSet() { 4760 if (sPreferredInstructionSet == null) { 4761 sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]); 4762 } 4763 4764 return sPreferredInstructionSet; 4765 } 4766 4767 private static List<String> getAllInstructionSets() { 4768 final String[] allAbis = Build.SUPPORTED_ABIS; 4769 final List<String> allInstructionSets = new ArrayList<String>(allAbis.length); 4770 4771 for (String abi : allAbis) { 4772 final String instructionSet = VMRuntime.getInstructionSet(abi); 4773 if (!allInstructionSets.contains(instructionSet)) { 4774 allInstructionSets.add(instructionSet); 4775 } 4776 } 4777 4778 return allInstructionSets; 4779 } 4780 4781 /** 4782 * Returns the instruction set that should be used to compile dex code. In the presence of 4783 * a native bridge this might be different than the one shared libraries use. 4784 */ 4785 private static String getDexCodeInstructionSet(String sharedLibraryIsa) { 4786 String dexCodeIsa = SystemProperties.get("ro.dalvik.vm.isa." + sharedLibraryIsa); 4787 return (dexCodeIsa.isEmpty() ? sharedLibraryIsa : dexCodeIsa); 4788 } 4789 4790 private static String[] getDexCodeInstructionSets(String[] instructionSets) { 4791 HashSet<String> dexCodeInstructionSets = new HashSet<String>(instructionSets.length); 4792 for (String instructionSet : instructionSets) { 4793 dexCodeInstructionSets.add(getDexCodeInstructionSet(instructionSet)); 4794 } 4795 return dexCodeInstructionSets.toArray(new String[dexCodeInstructionSets.size()]); 4796 } 4797 4798 @Override 4799 public void forceDexOpt(String packageName) { 4800 enforceSystemOrRoot("forceDexOpt"); 4801 4802 PackageParser.Package pkg; 4803 synchronized (mPackages) { 4804 pkg = mPackages.get(packageName); 4805 if (pkg == null) { 4806 throw new IllegalArgumentException("Missing package: " + packageName); 4807 } 4808 } 4809 4810 synchronized (mInstallLock) { 4811 final String[] instructionSets = new String[] { 4812 getPrimaryInstructionSet(pkg.applicationInfo) }; 4813 final int res = performDexOptLI(pkg, instructionSets, true, false, true); 4814 if (res != DEX_OPT_PERFORMED) { 4815 throw new IllegalStateException("Failed to dexopt: " + res); 4816 } 4817 } 4818 } 4819 4820 private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets, 4821 boolean forceDex, boolean defer, boolean inclDependencies) { 4822 HashSet<String> done; 4823 if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) { 4824 done = new HashSet<String>(); 4825 done.add(pkg.packageName); 4826 } else { 4827 done = null; 4828 } 4829 return performDexOptLI(pkg, instructionSets, forceDex, defer, done); 4830 } 4831 4832 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 4833 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 4834 Slog.w(TAG, "Unable to update from " + oldPkg.name 4835 + " to " + newPkg.packageName 4836 + ": old package not in system partition"); 4837 return false; 4838 } else if (mPackages.get(oldPkg.name) != null) { 4839 Slog.w(TAG, "Unable to update from " + oldPkg.name 4840 + " to " + newPkg.packageName 4841 + ": old package still exists"); 4842 return false; 4843 } 4844 return true; 4845 } 4846 4847 File getDataPathForUser(int userId) { 4848 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId); 4849 } 4850 4851 private File getDataPathForPackage(String packageName, int userId) { 4852 /* 4853 * Until we fully support multiple users, return the directory we 4854 * previously would have. The PackageManagerTests will need to be 4855 * revised when this is changed back.. 4856 */ 4857 if (userId == 0) { 4858 return new File(mAppDataDir, packageName); 4859 } else { 4860 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 4861 + File.separator + packageName); 4862 } 4863 } 4864 4865 private int createDataDirsLI(String packageName, int uid, String seinfo) { 4866 int[] users = sUserManager.getUserIds(); 4867 int res = mInstaller.install(packageName, uid, uid, seinfo); 4868 if (res < 0) { 4869 return res; 4870 } 4871 for (int user : users) { 4872 if (user != 0) { 4873 res = mInstaller.createUserData(packageName, 4874 UserHandle.getUid(user, uid), user, seinfo); 4875 if (res < 0) { 4876 return res; 4877 } 4878 } 4879 } 4880 return res; 4881 } 4882 4883 private int removeDataDirsLI(String packageName) { 4884 int[] users = sUserManager.getUserIds(); 4885 int res = 0; 4886 for (int user : users) { 4887 int resInner = mInstaller.remove(packageName, user); 4888 if (resInner < 0) { 4889 res = resInner; 4890 } 4891 } 4892 4893 return res; 4894 } 4895 4896 private int deleteCodeCacheDirsLI(String packageName) { 4897 int[] users = sUserManager.getUserIds(); 4898 int res = 0; 4899 for (int user : users) { 4900 int resInner = mInstaller.deleteCodeCacheFiles(packageName, user); 4901 if (resInner < 0) { 4902 res = resInner; 4903 } 4904 } 4905 return res; 4906 } 4907 4908 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 4909 PackageParser.Package changingLib) { 4910 if (file.path != null) { 4911 usesLibraryFiles.add(file.path); 4912 return; 4913 } 4914 PackageParser.Package p = mPackages.get(file.apk); 4915 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 4916 // If we are doing this while in the middle of updating a library apk, 4917 // then we need to make sure to use that new apk for determining the 4918 // dependencies here. (We haven't yet finished committing the new apk 4919 // to the package manager state.) 4920 if (p == null || p.packageName.equals(changingLib.packageName)) { 4921 p = changingLib; 4922 } 4923 } 4924 if (p != null) { 4925 usesLibraryFiles.addAll(p.getAllCodePaths()); 4926 } 4927 } 4928 4929 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 4930 PackageParser.Package changingLib) throws PackageManagerException { 4931 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 4932 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 4933 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 4934 for (int i=0; i<N; i++) { 4935 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 4936 if (file == null) { 4937 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 4938 "Package " + pkg.packageName + " requires unavailable shared library " 4939 + pkg.usesLibraries.get(i) + "; failing!"); 4940 } 4941 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4942 } 4943 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 4944 for (int i=0; i<N; i++) { 4945 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 4946 if (file == null) { 4947 Slog.w(TAG, "Package " + pkg.packageName 4948 + " desires unavailable shared library " 4949 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 4950 } else { 4951 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4952 } 4953 } 4954 N = usesLibraryFiles.size(); 4955 if (N > 0) { 4956 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 4957 } else { 4958 pkg.usesLibraryFiles = null; 4959 } 4960 } 4961 } 4962 4963 private static boolean hasString(List<String> list, List<String> which) { 4964 if (list == null) { 4965 return false; 4966 } 4967 for (int i=list.size()-1; i>=0; i--) { 4968 for (int j=which.size()-1; j>=0; j--) { 4969 if (which.get(j).equals(list.get(i))) { 4970 return true; 4971 } 4972 } 4973 } 4974 return false; 4975 } 4976 4977 private void updateAllSharedLibrariesLPw() { 4978 for (PackageParser.Package pkg : mPackages.values()) { 4979 try { 4980 updateSharedLibrariesLPw(pkg, null); 4981 } catch (PackageManagerException e) { 4982 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 4983 } 4984 } 4985 } 4986 4987 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 4988 PackageParser.Package changingPkg) { 4989 ArrayList<PackageParser.Package> res = null; 4990 for (PackageParser.Package pkg : mPackages.values()) { 4991 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 4992 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 4993 if (res == null) { 4994 res = new ArrayList<PackageParser.Package>(); 4995 } 4996 res.add(pkg); 4997 try { 4998 updateSharedLibrariesLPw(pkg, changingPkg); 4999 } catch (PackageManagerException e) { 5000 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5001 } 5002 } 5003 } 5004 return res; 5005 } 5006 5007 /** 5008 * Derive the value of the {@code cpuAbiOverride} based on the provided 5009 * value and an optional stored value from the package settings. 5010 */ 5011 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5012 String cpuAbiOverride = null; 5013 5014 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5015 cpuAbiOverride = null; 5016 } else if (abiOverride != null) { 5017 cpuAbiOverride = abiOverride; 5018 } else if (settings != null) { 5019 cpuAbiOverride = settings.cpuAbiOverrideString; 5020 } 5021 5022 return cpuAbiOverride; 5023 } 5024 5025 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5026 int scanMode, long currentTime, UserHandle user) 5027 throws PackageManagerException { 5028 final File scanFile = new File(pkg.codePath); 5029 if (pkg.applicationInfo.getCodePath() == null || 5030 pkg.applicationInfo.getResourcePath() == null) { 5031 // Bail out. The resource and code paths haven't been set. 5032 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5033 "Code and resource paths haven't been set correctly"); 5034 } 5035 5036 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5037 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5038 } 5039 5040 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5041 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED; 5042 } 5043 5044 if (mCustomResolverComponentName != null && 5045 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5046 setUpCustomResolverActivity(pkg); 5047 } 5048 5049 if (pkg.packageName.equals("android")) { 5050 synchronized (mPackages) { 5051 if (mAndroidApplication != null) { 5052 Slog.w(TAG, "*************************************************"); 5053 Slog.w(TAG, "Core android package being redefined. Skipping."); 5054 Slog.w(TAG, " file=" + scanFile); 5055 Slog.w(TAG, "*************************************************"); 5056 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5057 "Core android package being redefined. Skipping."); 5058 } 5059 5060 // Set up information for our fall-back user intent resolution activity. 5061 mPlatformPackage = pkg; 5062 pkg.mVersionCode = mSdkVersion; 5063 mAndroidApplication = pkg.applicationInfo; 5064 5065 if (!mResolverReplaced) { 5066 mResolveActivity.applicationInfo = mAndroidApplication; 5067 mResolveActivity.name = ResolverActivity.class.getName(); 5068 mResolveActivity.packageName = mAndroidApplication.packageName; 5069 mResolveActivity.processName = "system:ui"; 5070 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5071 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5072 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5073 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5074 mResolveActivity.exported = true; 5075 mResolveActivity.enabled = true; 5076 mResolveInfo.activityInfo = mResolveActivity; 5077 mResolveInfo.priority = 0; 5078 mResolveInfo.preferredOrder = 0; 5079 mResolveInfo.match = 0; 5080 mResolveComponentName = new ComponentName( 5081 mAndroidApplication.packageName, mResolveActivity.name); 5082 } 5083 } 5084 } 5085 5086 if (DEBUG_PACKAGE_SCANNING) { 5087 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5088 Log.d(TAG, "Scanning package " + pkg.packageName); 5089 } 5090 5091 if (mPackages.containsKey(pkg.packageName) 5092 || mSharedLibraries.containsKey(pkg.packageName)) { 5093 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5094 "Application package " + pkg.packageName 5095 + " already installed. Skipping duplicate."); 5096 } 5097 5098 // Initialize package source and resource directories 5099 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5100 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5101 5102 SharedUserSetting suid = null; 5103 PackageSetting pkgSetting = null; 5104 5105 if (!isSystemApp(pkg)) { 5106 // Only system apps can use these features. 5107 pkg.mOriginalPackages = null; 5108 pkg.mRealPackage = null; 5109 pkg.mAdoptPermissions = null; 5110 } 5111 5112 // writer 5113 synchronized (mPackages) { 5114 if (pkg.mSharedUserId != null) { 5115 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true); 5116 if (suid == null) { 5117 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5118 "Creating application package " + pkg.packageName 5119 + " for shared user failed"); 5120 } 5121 if (DEBUG_PACKAGE_SCANNING) { 5122 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5123 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5124 + "): packages=" + suid.packages); 5125 } 5126 } 5127 5128 // Check if we are renaming from an original package name. 5129 PackageSetting origPackage = null; 5130 String realName = null; 5131 if (pkg.mOriginalPackages != null) { 5132 // This package may need to be renamed to a previously 5133 // installed name. Let's check on that... 5134 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5135 if (pkg.mOriginalPackages.contains(renamed)) { 5136 // This package had originally been installed as the 5137 // original name, and we have already taken care of 5138 // transitioning to the new one. Just update the new 5139 // one to continue using the old name. 5140 realName = pkg.mRealPackage; 5141 if (!pkg.packageName.equals(renamed)) { 5142 // Callers into this function may have already taken 5143 // care of renaming the package; only do it here if 5144 // it is not already done. 5145 pkg.setPackageName(renamed); 5146 } 5147 5148 } else { 5149 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5150 if ((origPackage = mSettings.peekPackageLPr( 5151 pkg.mOriginalPackages.get(i))) != null) { 5152 // We do have the package already installed under its 5153 // original name... should we use it? 5154 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5155 // New package is not compatible with original. 5156 origPackage = null; 5157 continue; 5158 } else if (origPackage.sharedUser != null) { 5159 // Make sure uid is compatible between packages. 5160 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5161 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5162 + " to " + pkg.packageName + ": old uid " 5163 + origPackage.sharedUser.name 5164 + " differs from " + pkg.mSharedUserId); 5165 origPackage = null; 5166 continue; 5167 } 5168 } else { 5169 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5170 + pkg.packageName + " to old name " + origPackage.name); 5171 } 5172 break; 5173 } 5174 } 5175 } 5176 } 5177 5178 if (mTransferedPackages.contains(pkg.packageName)) { 5179 Slog.w(TAG, "Package " + pkg.packageName 5180 + " was transferred to another, but its .apk remains"); 5181 } 5182 5183 // Just create the setting, don't add it yet. For already existing packages 5184 // the PkgSetting exists already and doesn't have to be created. 5185 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5186 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 5187 pkg.applicationInfo.primaryCpuAbi, 5188 pkg.applicationInfo.secondaryCpuAbi, 5189 pkg.applicationInfo.flags, user, false); 5190 if (pkgSetting == null) { 5191 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5192 "Creating application package " + pkg.packageName + " failed"); 5193 } 5194 5195 if (pkgSetting.origPackage != null) { 5196 // If we are first transitioning from an original package, 5197 // fix up the new package's name now. We need to do this after 5198 // looking up the package under its new name, so getPackageLP 5199 // can take care of fiddling things correctly. 5200 pkg.setPackageName(origPackage.name); 5201 5202 // File a report about this. 5203 String msg = "New package " + pkgSetting.realName 5204 + " renamed to replace old package " + pkgSetting.name; 5205 reportSettingsProblem(Log.WARN, msg); 5206 5207 // Make a note of it. 5208 mTransferedPackages.add(origPackage.name); 5209 5210 // No longer need to retain this. 5211 pkgSetting.origPackage = null; 5212 } 5213 5214 if (realName != null) { 5215 // Make a note of it. 5216 mTransferedPackages.add(pkg.packageName); 5217 } 5218 5219 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5220 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5221 } 5222 5223 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5224 // Check all shared libraries and map to their actual file path. 5225 // We only do this here for apps not on a system dir, because those 5226 // are the only ones that can fail an install due to this. We 5227 // will take care of the system apps by updating all of their 5228 // library paths after the scan is done. 5229 updateSharedLibrariesLPw(pkg, null); 5230 } 5231 5232 if (mFoundPolicyFile) { 5233 SELinuxMMAC.assignSeinfoValue(pkg); 5234 } 5235 5236 pkg.applicationInfo.uid = pkgSetting.appId; 5237 pkg.mExtras = pkgSetting; 5238 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5239 try { 5240 verifySignaturesLP(pkgSetting, pkg); 5241 } catch (PackageManagerException e) { 5242 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5243 throw e; 5244 } 5245 // The signature has changed, but this package is in the system 5246 // image... let's recover! 5247 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5248 // However... if this package is part of a shared user, but it 5249 // doesn't match the signature of the shared user, let's fail. 5250 // What this means is that you can't change the signatures 5251 // associated with an overall shared user, which doesn't seem all 5252 // that unreasonable. 5253 if (pkgSetting.sharedUser != null) { 5254 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5255 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5256 throw new PackageManagerException( 5257 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 5258 "Signature mismatch for shared user : " 5259 + pkgSetting.sharedUser); 5260 } 5261 } 5262 // File a report about this. 5263 String msg = "System package " + pkg.packageName 5264 + " signature changed; retaining data."; 5265 reportSettingsProblem(Log.WARN, msg); 5266 } 5267 } else { 5268 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 5269 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5270 + pkg.packageName + " upgrade keys do not match the " 5271 + "previously installed version"); 5272 } else { 5273 // signatures may have changed as result of upgrade 5274 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5275 } 5276 } 5277 // Verify that this new package doesn't have any content providers 5278 // that conflict with existing packages. Only do this if the 5279 // package isn't already installed, since we don't want to break 5280 // things that are installed. 5281 if ((scanMode&SCAN_NEW_INSTALL) != 0) { 5282 final int N = pkg.providers.size(); 5283 int i; 5284 for (i=0; i<N; i++) { 5285 PackageParser.Provider p = pkg.providers.get(i); 5286 if (p.info.authority != null) { 5287 String names[] = p.info.authority.split(";"); 5288 for (int j = 0; j < names.length; j++) { 5289 if (mProvidersByAuthority.containsKey(names[j])) { 5290 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5291 final String otherPackageName = 5292 ((other != null && other.getComponentName() != null) ? 5293 other.getComponentName().getPackageName() : "?"); 5294 throw new PackageManagerException( 5295 INSTALL_FAILED_CONFLICTING_PROVIDER, 5296 "Can't install because provider name " + names[j] 5297 + " (in package " + pkg.applicationInfo.packageName 5298 + ") is already used by " + otherPackageName); 5299 } 5300 } 5301 } 5302 } 5303 } 5304 5305 if (pkg.mAdoptPermissions != null) { 5306 // This package wants to adopt ownership of permissions from 5307 // another package. 5308 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 5309 final String origName = pkg.mAdoptPermissions.get(i); 5310 final PackageSetting orig = mSettings.peekPackageLPr(origName); 5311 if (orig != null) { 5312 if (verifyPackageUpdateLPr(orig, pkg)) { 5313 Slog.i(TAG, "Adopting permissions from " + origName + " to " 5314 + pkg.packageName); 5315 mSettings.transferPermissionsLPw(origName, pkg.packageName); 5316 } 5317 } 5318 } 5319 } 5320 } 5321 5322 final String pkgName = pkg.packageName; 5323 5324 final long scanFileTime = scanFile.lastModified(); 5325 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0; 5326 pkg.applicationInfo.processName = fixProcessName( 5327 pkg.applicationInfo.packageName, 5328 pkg.applicationInfo.processName, 5329 pkg.applicationInfo.uid); 5330 5331 File dataPath; 5332 if (mPlatformPackage == pkg) { 5333 // The system package is special. 5334 dataPath = new File (Environment.getDataDirectory(), "system"); 5335 pkg.applicationInfo.dataDir = dataPath.getPath(); 5336 5337 } else { 5338 // This is a normal package, need to make its data directory. 5339 dataPath = getDataPathForPackage(pkg.packageName, 0); 5340 5341 boolean uidError = false; 5342 5343 if (dataPath.exists()) { 5344 int currentUid = 0; 5345 try { 5346 StructStat stat = Os.stat(dataPath.getPath()); 5347 currentUid = stat.st_uid; 5348 } catch (ErrnoException e) { 5349 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 5350 } 5351 5352 // If we have mismatched owners for the data path, we have a problem. 5353 if (currentUid != pkg.applicationInfo.uid) { 5354 boolean recovered = false; 5355 if (currentUid == 0) { 5356 // The directory somehow became owned by root. Wow. 5357 // This is probably because the system was stopped while 5358 // installd was in the middle of messing with its libs 5359 // directory. Ask installd to fix that. 5360 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 5361 pkg.applicationInfo.uid); 5362 if (ret >= 0) { 5363 recovered = true; 5364 String msg = "Package " + pkg.packageName 5365 + " unexpectedly changed to uid 0; recovered to " + 5366 + pkg.applicationInfo.uid; 5367 reportSettingsProblem(Log.WARN, msg); 5368 } 5369 } 5370 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5371 || (scanMode&SCAN_BOOTING) != 0)) { 5372 // If this is a system app, we can at least delete its 5373 // current data so the application will still work. 5374 int ret = removeDataDirsLI(pkgName); 5375 if (ret >= 0) { 5376 // TODO: Kill the processes first 5377 // Old data gone! 5378 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5379 ? "System package " : "Third party package "; 5380 String msg = prefix + pkg.packageName 5381 + " has changed from uid: " 5382 + currentUid + " to " 5383 + pkg.applicationInfo.uid + "; old data erased"; 5384 reportSettingsProblem(Log.WARN, msg); 5385 recovered = true; 5386 5387 // And now re-install the app. 5388 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5389 pkg.applicationInfo.seinfo); 5390 if (ret == -1) { 5391 // Ack should not happen! 5392 msg = prefix + pkg.packageName 5393 + " could not have data directory re-created after delete."; 5394 reportSettingsProblem(Log.WARN, msg); 5395 throw new PackageManagerException( 5396 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 5397 } 5398 } 5399 if (!recovered) { 5400 mHasSystemUidErrors = true; 5401 } 5402 } else if (!recovered) { 5403 // If we allow this install to proceed, we will be broken. 5404 // Abort, abort! 5405 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 5406 "scanPackageLI"); 5407 } 5408 if (!recovered) { 5409 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 5410 + pkg.applicationInfo.uid + "/fs_" 5411 + currentUid; 5412 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 5413 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 5414 String msg = "Package " + pkg.packageName 5415 + " has mismatched uid: " 5416 + currentUid + " on disk, " 5417 + pkg.applicationInfo.uid + " in settings"; 5418 // writer 5419 synchronized (mPackages) { 5420 mSettings.mReadMessages.append(msg); 5421 mSettings.mReadMessages.append('\n'); 5422 uidError = true; 5423 if (!pkgSetting.uidError) { 5424 reportSettingsProblem(Log.ERROR, msg); 5425 } 5426 } 5427 } 5428 } 5429 pkg.applicationInfo.dataDir = dataPath.getPath(); 5430 if (mShouldRestoreconData) { 5431 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 5432 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 5433 pkg.applicationInfo.uid); 5434 } 5435 } else { 5436 if (DEBUG_PACKAGE_SCANNING) { 5437 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5438 Log.v(TAG, "Want this data dir: " + dataPath); 5439 } 5440 //invoke installer to do the actual installation 5441 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5442 pkg.applicationInfo.seinfo); 5443 if (ret < 0) { 5444 // Error from installer 5445 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5446 "Unable to create data dirs [errorCode=" + ret + "]"); 5447 } 5448 5449 if (dataPath.exists()) { 5450 pkg.applicationInfo.dataDir = dataPath.getPath(); 5451 } else { 5452 Slog.w(TAG, "Unable to create data directory: " + dataPath); 5453 pkg.applicationInfo.dataDir = null; 5454 } 5455 } 5456 5457 pkgSetting.uidError = uidError; 5458 } 5459 5460 final String path = scanFile.getPath(); 5461 final String codePath = pkg.applicationInfo.getCodePath(); 5462 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 5463 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 5464 setBundledAppAbisAndRoots(pkg, pkgSetting); 5465 5466 // If we haven't found any native libraries for the app, check if it has 5467 // renderscript code. We'll need to force the app to 32 bit if it has 5468 // renderscript bitcode. 5469 if (pkg.applicationInfo.primaryCpuAbi == null 5470 && pkg.applicationInfo.secondaryCpuAbi == null 5471 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5472 NativeLibraryHelper.Handle handle = null; 5473 try { 5474 handle = NativeLibraryHelper.Handle.create(scanFile); 5475 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5476 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 5477 } 5478 } catch (IOException ioe) { 5479 Slog.w(TAG, "Error scanning system app : " + ioe); 5480 } finally { 5481 IoUtils.closeQuietly(handle); 5482 } 5483 } 5484 5485 setNativeLibraryPaths(pkg); 5486 } else { 5487 // TODO: We can probably be smarter about this stuff. For installed apps, 5488 // we can calculate this information at install time once and for all. For 5489 // system apps, we can probably assume that this information doesn't change 5490 // after the first boot scan. As things stand, we do lots of unnecessary work. 5491 5492 // Give ourselves some initial paths; we'll come back for another 5493 // pass once we've determined ABI below. 5494 setNativeLibraryPaths(pkg); 5495 5496 final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg); 5497 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 5498 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 5499 5500 NativeLibraryHelper.Handle handle = null; 5501 try { 5502 handle = NativeLibraryHelper.Handle.create(scanFile); 5503 // TODO(multiArch): This can be null for apps that didn't go through the 5504 // usual installation process. We can calculate it again, like we 5505 // do during install time. 5506 // 5507 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 5508 // unnecessary. 5509 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 5510 5511 // Null out the abis so that they can be recalculated. 5512 pkg.applicationInfo.primaryCpuAbi = null; 5513 pkg.applicationInfo.secondaryCpuAbi = null; 5514 if (isMultiArch(pkg.applicationInfo)) { 5515 // Warn if we've set an abiOverride for multi-lib packages.. 5516 // By definition, we need to copy both 32 and 64 bit libraries for 5517 // such packages. 5518 if (pkg.cpuAbiOverride != null 5519 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 5520 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 5521 } 5522 5523 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 5524 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 5525 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 5526 if (isAsec) { 5527 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 5528 } else { 5529 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5530 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 5531 useIsaSpecificSubdirs); 5532 } 5533 } 5534 5535 maybeThrowExceptionForMultiArchCopy( 5536 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 5537 5538 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5539 if (isAsec) { 5540 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 5541 } else { 5542 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5543 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 5544 useIsaSpecificSubdirs); 5545 } 5546 } 5547 5548 maybeThrowExceptionForMultiArchCopy( 5549 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 5550 5551 if (abi64 >= 0) { 5552 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 5553 } 5554 5555 if (abi32 >= 0) { 5556 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 5557 if (abi64 >= 0) { 5558 pkg.applicationInfo.secondaryCpuAbi = abi; 5559 } else { 5560 pkg.applicationInfo.primaryCpuAbi = abi; 5561 } 5562 } 5563 } else { 5564 String[] abiList = (cpuAbiOverride != null) ? 5565 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 5566 5567 // Enable gross and lame hacks for apps that are built with old 5568 // SDK tools. We must scan their APKs for renderscript bitcode and 5569 // not launch them if it's present. Don't bother checking on devices 5570 // that don't have 64 bit support. 5571 boolean needsRenderScriptOverride = false; 5572 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 5573 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5574 abiList = Build.SUPPORTED_32_BIT_ABIS; 5575 needsRenderScriptOverride = true; 5576 } 5577 5578 final int copyRet; 5579 if (isAsec) { 5580 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 5581 } else { 5582 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5583 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 5584 } 5585 5586 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5587 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5588 "Error unpackaging native libs for app, errorCode=" + copyRet); 5589 } 5590 5591 if (copyRet >= 0) { 5592 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 5593 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 5594 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 5595 } else if (needsRenderScriptOverride) { 5596 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 5597 } 5598 } 5599 } catch (IOException ioe) { 5600 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 5601 } finally { 5602 IoUtils.closeQuietly(handle); 5603 } 5604 5605 // Now that we've calculated the ABIs and determined if it's an internal app, 5606 // we will go ahead and populate the nativeLibraryPath. 5607 setNativeLibraryPaths(pkg); 5608 5609 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 5610 final int[] userIds = sUserManager.getUserIds(); 5611 synchronized (mInstallLock) { 5612 // Create a native library symlink only if we have native libraries 5613 // and if the native libraries are 32 bit libraries. We do not provide 5614 // this symlink for 64 bit libraries. 5615 if (pkg.applicationInfo.primaryCpuAbi != null && 5616 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 5617 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 5618 for (int userId : userIds) { 5619 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 5620 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5621 "Failed linking native library dir (user=" + userId + ")"); 5622 } 5623 } 5624 } 5625 } 5626 } 5627 5628 // This is a special case for the "system" package, where the ABI is 5629 // dictated by the zygote configuration (and init.rc). We should keep track 5630 // of this ABI so that we can deal with "normal" applications that run under 5631 // the same UID correctly. 5632 if (mPlatformPackage == pkg) { 5633 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 5634 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 5635 } 5636 5637 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 5638 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 5639 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 5640 // Copy the derived override back to the parsed package, so that we can 5641 // update the package settings accordingly. 5642 pkg.cpuAbiOverride = cpuAbiOverride; 5643 5644 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 5645 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 5646 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 5647 5648 // Push the derived path down into PackageSettings so we know what to 5649 // clean up at uninstall time. 5650 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 5651 5652 if (DEBUG_ABI_SELECTION) { 5653 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 5654 " primary=" + pkg.applicationInfo.primaryCpuAbi + 5655 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 5656 } 5657 5658 if ((scanMode&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 5659 // We don't do this here during boot because we can do it all 5660 // at once after scanning all existing packages. 5661 // 5662 // We also do this *before* we perform dexopt on this package, so that 5663 // we can avoid redundant dexopts, and also to make sure we've got the 5664 // code and package path correct. 5665 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 5666 pkg, forceDex, (scanMode & SCAN_DEFER_DEX) != 0); 5667 } 5668 5669 if ((scanMode&SCAN_NO_DEX) == 0) { 5670 if (performDexOptLI(pkg, null /* instruction sets */, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5671 == DEX_OPT_FAILED) { 5672 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5673 removeDataDirsLI(pkg.packageName); 5674 } 5675 5676 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 5677 } 5678 } 5679 5680 if (mFactoryTest && pkg.requestedPermissions.contains( 5681 android.Manifest.permission.FACTORY_TEST)) { 5682 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 5683 } 5684 5685 ArrayList<PackageParser.Package> clientLibPkgs = null; 5686 5687 // writer 5688 synchronized (mPackages) { 5689 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5690 // Only system apps can add new shared libraries. 5691 if (pkg.libraryNames != null) { 5692 for (int i=0; i<pkg.libraryNames.size(); i++) { 5693 String name = pkg.libraryNames.get(i); 5694 boolean allowed = false; 5695 if (isUpdatedSystemApp(pkg)) { 5696 // New library entries can only be added through the 5697 // system image. This is important to get rid of a lot 5698 // of nasty edge cases: for example if we allowed a non- 5699 // system update of the app to add a library, then uninstalling 5700 // the update would make the library go away, and assumptions 5701 // we made such as through app install filtering would now 5702 // have allowed apps on the device which aren't compatible 5703 // with it. Better to just have the restriction here, be 5704 // conservative, and create many fewer cases that can negatively 5705 // impact the user experience. 5706 final PackageSetting sysPs = mSettings 5707 .getDisabledSystemPkgLPr(pkg.packageName); 5708 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 5709 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 5710 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 5711 allowed = true; 5712 allowed = true; 5713 break; 5714 } 5715 } 5716 } 5717 } else { 5718 allowed = true; 5719 } 5720 if (allowed) { 5721 if (!mSharedLibraries.containsKey(name)) { 5722 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 5723 } else if (!name.equals(pkg.packageName)) { 5724 Slog.w(TAG, "Package " + pkg.packageName + " library " 5725 + name + " already exists; skipping"); 5726 } 5727 } else { 5728 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 5729 + name + " that is not declared on system image; skipping"); 5730 } 5731 } 5732 if ((scanMode&SCAN_BOOTING) == 0) { 5733 // If we are not booting, we need to update any applications 5734 // that are clients of our shared library. If we are booting, 5735 // this will all be done once the scan is complete. 5736 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 5737 } 5738 } 5739 } 5740 } 5741 5742 // We also need to dexopt any apps that are dependent on this library. Note that 5743 // if these fail, we should abort the install since installing the library will 5744 // result in some apps being broken. 5745 if (clientLibPkgs != null) { 5746 if ((scanMode&SCAN_NO_DEX) == 0) { 5747 for (int i=0; i<clientLibPkgs.size(); i++) { 5748 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5749 if (performDexOptLI(clientPkg, null /* instruction sets */, 5750 forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5751 == DEX_OPT_FAILED) { 5752 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5753 removeDataDirsLI(pkg.packageName); 5754 } 5755 5756 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 5757 "scanPackageLI failed to dexopt clientLibPkgs"); 5758 } 5759 } 5760 } 5761 } 5762 5763 // Request the ActivityManager to kill the process(only for existing packages) 5764 // so that we do not end up in a confused state while the user is still using the older 5765 // version of the application while the new one gets installed. 5766 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 5767 // If the package lives in an asec, tell everyone that the container is going 5768 // away so they can clean up any references to its resources (which would prevent 5769 // vold from being able to unmount the asec) 5770 if (isForwardLocked(pkg) || isExternal(pkg)) { 5771 if (DEBUG_INSTALL) { 5772 Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE"); 5773 } 5774 final int[] uidArray = new int[] { pkg.applicationInfo.uid }; 5775 final ArrayList<String> pkgList = new ArrayList<String>(1); 5776 pkgList.add(pkg.applicationInfo.packageName); 5777 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 5778 } 5779 5780 // Post the request that it be killed now that the going-away broadcast is en route 5781 killApplication(pkg.applicationInfo.packageName, 5782 pkg.applicationInfo.uid, "update pkg"); 5783 } 5784 5785 // Also need to kill any apps that are dependent on the library. 5786 if (clientLibPkgs != null) { 5787 for (int i=0; i<clientLibPkgs.size(); i++) { 5788 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5789 killApplication(clientPkg.applicationInfo.packageName, 5790 clientPkg.applicationInfo.uid, "update lib"); 5791 } 5792 } 5793 5794 // writer 5795 synchronized (mPackages) { 5796 // We don't expect installation to fail beyond this point, 5797 if ((scanMode&SCAN_MONITOR) != 0) { 5798 mAppDirs.put(pkg.codePath, pkg); 5799 } 5800 // Add the new setting to mSettings 5801 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 5802 // Add the new setting to mPackages 5803 mPackages.put(pkg.applicationInfo.packageName, pkg); 5804 // Make sure we don't accidentally delete its data. 5805 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 5806 while (iter.hasNext()) { 5807 PackageCleanItem item = iter.next(); 5808 if (pkgName.equals(item.packageName)) { 5809 iter.remove(); 5810 } 5811 } 5812 5813 // Take care of first install / last update times. 5814 if (currentTime != 0) { 5815 if (pkgSetting.firstInstallTime == 0) { 5816 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 5817 } else if ((scanMode&SCAN_UPDATE_TIME) != 0) { 5818 pkgSetting.lastUpdateTime = currentTime; 5819 } 5820 } else if (pkgSetting.firstInstallTime == 0) { 5821 // We need *something*. Take time time stamp of the file. 5822 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 5823 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 5824 if (scanFileTime != pkgSetting.timeStamp) { 5825 // A package on the system image has changed; consider this 5826 // to be an update. 5827 pkgSetting.lastUpdateTime = scanFileTime; 5828 } 5829 } 5830 5831 // Add the package's KeySets to the global KeySetManagerService 5832 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5833 try { 5834 // Old KeySetData no longer valid. 5835 ksms.removeAppKeySetDataLPw(pkg.packageName); 5836 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 5837 if (pkg.mKeySetMapping != null) { 5838 for (Map.Entry<String, ArraySet<PublicKey>> entry : 5839 pkg.mKeySetMapping.entrySet()) { 5840 if (entry.getValue() != null) { 5841 ksms.addDefinedKeySetToPackageLPw(pkg.packageName, 5842 entry.getValue(), entry.getKey()); 5843 } 5844 } 5845 if (pkg.mUpgradeKeySets != null) { 5846 for (String upgradeAlias : pkg.mUpgradeKeySets) { 5847 ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias); 5848 } 5849 } 5850 } 5851 } catch (NullPointerException e) { 5852 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 5853 } catch (IllegalArgumentException e) { 5854 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 5855 } 5856 5857 int N = pkg.providers.size(); 5858 StringBuilder r = null; 5859 int i; 5860 for (i=0; i<N; i++) { 5861 PackageParser.Provider p = pkg.providers.get(i); 5862 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 5863 p.info.processName, pkg.applicationInfo.uid); 5864 mProviders.addProvider(p); 5865 p.syncable = p.info.isSyncable; 5866 if (p.info.authority != null) { 5867 String names[] = p.info.authority.split(";"); 5868 p.info.authority = null; 5869 for (int j = 0; j < names.length; j++) { 5870 if (j == 1 && p.syncable) { 5871 // We only want the first authority for a provider to possibly be 5872 // syncable, so if we already added this provider using a different 5873 // authority clear the syncable flag. We copy the provider before 5874 // changing it because the mProviders object contains a reference 5875 // to a provider that we don't want to change. 5876 // Only do this for the second authority since the resulting provider 5877 // object can be the same for all future authorities for this provider. 5878 p = new PackageParser.Provider(p); 5879 p.syncable = false; 5880 } 5881 if (!mProvidersByAuthority.containsKey(names[j])) { 5882 mProvidersByAuthority.put(names[j], p); 5883 if (p.info.authority == null) { 5884 p.info.authority = names[j]; 5885 } else { 5886 p.info.authority = p.info.authority + ";" + names[j]; 5887 } 5888 if (DEBUG_PACKAGE_SCANNING) { 5889 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5890 Log.d(TAG, "Registered content provider: " + names[j] 5891 + ", className = " + p.info.name + ", isSyncable = " 5892 + p.info.isSyncable); 5893 } 5894 } else { 5895 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5896 Slog.w(TAG, "Skipping provider name " + names[j] + 5897 " (in package " + pkg.applicationInfo.packageName + 5898 "): name already used by " 5899 + ((other != null && other.getComponentName() != null) 5900 ? other.getComponentName().getPackageName() : "?")); 5901 } 5902 } 5903 } 5904 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5905 if (r == null) { 5906 r = new StringBuilder(256); 5907 } else { 5908 r.append(' '); 5909 } 5910 r.append(p.info.name); 5911 } 5912 } 5913 if (r != null) { 5914 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 5915 } 5916 5917 N = pkg.services.size(); 5918 r = null; 5919 for (i=0; i<N; i++) { 5920 PackageParser.Service s = pkg.services.get(i); 5921 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 5922 s.info.processName, pkg.applicationInfo.uid); 5923 mServices.addService(s); 5924 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5925 if (r == null) { 5926 r = new StringBuilder(256); 5927 } else { 5928 r.append(' '); 5929 } 5930 r.append(s.info.name); 5931 } 5932 } 5933 if (r != null) { 5934 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 5935 } 5936 5937 N = pkg.receivers.size(); 5938 r = null; 5939 for (i=0; i<N; i++) { 5940 PackageParser.Activity a = pkg.receivers.get(i); 5941 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5942 a.info.processName, pkg.applicationInfo.uid); 5943 mReceivers.addActivity(a, "receiver"); 5944 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5945 if (r == null) { 5946 r = new StringBuilder(256); 5947 } else { 5948 r.append(' '); 5949 } 5950 r.append(a.info.name); 5951 } 5952 } 5953 if (r != null) { 5954 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 5955 } 5956 5957 N = pkg.activities.size(); 5958 r = null; 5959 for (i=0; i<N; i++) { 5960 PackageParser.Activity a = pkg.activities.get(i); 5961 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5962 a.info.processName, pkg.applicationInfo.uid); 5963 mActivities.addActivity(a, "activity"); 5964 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5965 if (r == null) { 5966 r = new StringBuilder(256); 5967 } else { 5968 r.append(' '); 5969 } 5970 r.append(a.info.name); 5971 } 5972 } 5973 if (r != null) { 5974 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 5975 } 5976 5977 N = pkg.permissionGroups.size(); 5978 r = null; 5979 for (i=0; i<N; i++) { 5980 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 5981 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 5982 if (cur == null) { 5983 mPermissionGroups.put(pg.info.name, pg); 5984 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5985 if (r == null) { 5986 r = new StringBuilder(256); 5987 } else { 5988 r.append(' '); 5989 } 5990 r.append(pg.info.name); 5991 } 5992 } else { 5993 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 5994 + pg.info.packageName + " ignored: original from " 5995 + cur.info.packageName); 5996 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5997 if (r == null) { 5998 r = new StringBuilder(256); 5999 } else { 6000 r.append(' '); 6001 } 6002 r.append("DUP:"); 6003 r.append(pg.info.name); 6004 } 6005 } 6006 } 6007 if (r != null) { 6008 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6009 } 6010 6011 N = pkg.permissions.size(); 6012 r = null; 6013 for (i=0; i<N; i++) { 6014 PackageParser.Permission p = pkg.permissions.get(i); 6015 HashMap<String, BasePermission> permissionMap = 6016 p.tree ? mSettings.mPermissionTrees 6017 : mSettings.mPermissions; 6018 p.group = mPermissionGroups.get(p.info.group); 6019 if (p.info.group == null || p.group != null) { 6020 BasePermission bp = permissionMap.get(p.info.name); 6021 if (bp == null) { 6022 bp = new BasePermission(p.info.name, p.info.packageName, 6023 BasePermission.TYPE_NORMAL); 6024 permissionMap.put(p.info.name, bp); 6025 } 6026 if (bp.perm == null) { 6027 if (bp.sourcePackage != null 6028 && !bp.sourcePackage.equals(p.info.packageName)) { 6029 // If this is a permission that was formerly defined by a non-system 6030 // app, but is now defined by a system app (following an upgrade), 6031 // discard the previous declaration and consider the system's to be 6032 // canonical. 6033 if (isSystemApp(p.owner)) { 6034 String msg = "New decl " + p.owner + " of permission " 6035 + p.info.name + " is system"; 6036 reportSettingsProblem(Log.WARN, msg); 6037 bp.sourcePackage = null; 6038 } 6039 } 6040 if (bp.sourcePackage == null 6041 || bp.sourcePackage.equals(p.info.packageName)) { 6042 BasePermission tree = findPermissionTreeLP(p.info.name); 6043 if (tree == null 6044 || tree.sourcePackage.equals(p.info.packageName)) { 6045 bp.packageSetting = pkgSetting; 6046 bp.perm = p; 6047 bp.uid = pkg.applicationInfo.uid; 6048 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6049 if (r == null) { 6050 r = new StringBuilder(256); 6051 } else { 6052 r.append(' '); 6053 } 6054 r.append(p.info.name); 6055 } 6056 } else { 6057 Slog.w(TAG, "Permission " + p.info.name + " from package " 6058 + p.info.packageName + " ignored: base tree " 6059 + tree.name + " is from package " 6060 + tree.sourcePackage); 6061 } 6062 } else { 6063 Slog.w(TAG, "Permission " + p.info.name + " from package " 6064 + p.info.packageName + " ignored: original from " 6065 + bp.sourcePackage); 6066 } 6067 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6068 if (r == null) { 6069 r = new StringBuilder(256); 6070 } else { 6071 r.append(' '); 6072 } 6073 r.append("DUP:"); 6074 r.append(p.info.name); 6075 } 6076 if (bp.perm == p) { 6077 bp.protectionLevel = p.info.protectionLevel; 6078 } 6079 } else { 6080 Slog.w(TAG, "Permission " + p.info.name + " from package " 6081 + p.info.packageName + " ignored: no group " 6082 + p.group); 6083 } 6084 } 6085 if (r != null) { 6086 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6087 } 6088 6089 N = pkg.instrumentation.size(); 6090 r = null; 6091 for (i=0; i<N; i++) { 6092 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6093 a.info.packageName = pkg.applicationInfo.packageName; 6094 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6095 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6096 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6097 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6098 a.info.dataDir = pkg.applicationInfo.dataDir; 6099 6100 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6101 // need other information about the application, like the ABI and what not ? 6102 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6103 mInstrumentation.put(a.getComponentName(), a); 6104 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6105 if (r == null) { 6106 r = new StringBuilder(256); 6107 } else { 6108 r.append(' '); 6109 } 6110 r.append(a.info.name); 6111 } 6112 } 6113 if (r != null) { 6114 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6115 } 6116 6117 if (pkg.protectedBroadcasts != null) { 6118 N = pkg.protectedBroadcasts.size(); 6119 for (i=0; i<N; i++) { 6120 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6121 } 6122 } 6123 6124 pkgSetting.setTimeStamp(scanFileTime); 6125 6126 // Create idmap files for pairs of (packages, overlay packages). 6127 // Note: "android", ie framework-res.apk, is handled by native layers. 6128 if (pkg.mOverlayTarget != null) { 6129 // This is an overlay package. 6130 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6131 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6132 mOverlays.put(pkg.mOverlayTarget, 6133 new HashMap<String, PackageParser.Package>()); 6134 } 6135 HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6136 map.put(pkg.packageName, pkg); 6137 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6138 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6139 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6140 "scanPackageLI failed to createIdmap"); 6141 } 6142 } 6143 } else if (mOverlays.containsKey(pkg.packageName) && 6144 !pkg.packageName.equals("android")) { 6145 // This is a regular package, with one or more known overlay packages. 6146 createIdmapsForPackageLI(pkg); 6147 } 6148 } 6149 6150 return pkg; 6151 } 6152 6153 /** 6154 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6155 * i.e, so that all packages can be run inside a single process if required. 6156 * 6157 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6158 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6159 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6160 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6161 * updating a package that belongs to a shared user. 6162 * 6163 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6164 * adds unnecessary complexity. 6165 */ 6166 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6167 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6168 String requiredInstructionSet = null; 6169 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6170 requiredInstructionSet = VMRuntime.getInstructionSet( 6171 scannedPackage.applicationInfo.primaryCpuAbi); 6172 } 6173 6174 PackageSetting requirer = null; 6175 for (PackageSetting ps : packagesForUser) { 6176 // If packagesForUser contains scannedPackage, we skip it. This will happen 6177 // when scannedPackage is an update of an existing package. Without this check, 6178 // we will never be able to change the ABI of any package belonging to a shared 6179 // user, even if it's compatible with other packages. 6180 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6181 if (ps.primaryCpuAbiString == null) { 6182 continue; 6183 } 6184 6185 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6186 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6187 // We have a mismatch between instruction sets (say arm vs arm64) warn about 6188 // this but there's not much we can do. 6189 String errorMessage = "Instruction set mismatch, " 6190 + ((requirer == null) ? "[caller]" : requirer) 6191 + " requires " + requiredInstructionSet + " whereas " + ps 6192 + " requires " + instructionSet; 6193 Slog.w(TAG, errorMessage); 6194 } 6195 6196 if (requiredInstructionSet == null) { 6197 requiredInstructionSet = instructionSet; 6198 requirer = ps; 6199 } 6200 } 6201 } 6202 6203 if (requiredInstructionSet != null) { 6204 String adjustedAbi; 6205 if (requirer != null) { 6206 // requirer != null implies that either scannedPackage was null or that scannedPackage 6207 // did not require an ABI, in which case we have to adjust scannedPackage to match 6208 // the ABI of the set (which is the same as requirer's ABI) 6209 adjustedAbi = requirer.primaryCpuAbiString; 6210 if (scannedPackage != null) { 6211 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6212 } 6213 } else { 6214 // requirer == null implies that we're updating all ABIs in the set to 6215 // match scannedPackage. 6216 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6217 } 6218 6219 for (PackageSetting ps : packagesForUser) { 6220 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6221 if (ps.primaryCpuAbiString != null) { 6222 continue; 6223 } 6224 6225 ps.primaryCpuAbiString = adjustedAbi; 6226 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6227 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6228 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6229 6230 if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt, 6231 deferDexOpt, true) == DEX_OPT_FAILED) { 6232 ps.primaryCpuAbiString = null; 6233 ps.pkg.applicationInfo.primaryCpuAbi = null; 6234 return; 6235 } else { 6236 mInstaller.rmdex(ps.codePathString, 6237 getDexCodeInstructionSet(getPreferredInstructionSet())); 6238 } 6239 } 6240 } 6241 } 6242 } 6243 } 6244 6245 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6246 synchronized (mPackages) { 6247 mResolverReplaced = true; 6248 // Set up information for custom user intent resolution activity. 6249 mResolveActivity.applicationInfo = pkg.applicationInfo; 6250 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6251 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6252 mResolveActivity.processName = null; 6253 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6254 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6255 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6256 mResolveActivity.theme = 0; 6257 mResolveActivity.exported = true; 6258 mResolveActivity.enabled = true; 6259 mResolveInfo.activityInfo = mResolveActivity; 6260 mResolveInfo.priority = 0; 6261 mResolveInfo.preferredOrder = 0; 6262 mResolveInfo.match = 0; 6263 mResolveComponentName = mCustomResolverComponentName; 6264 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6265 mResolveComponentName); 6266 } 6267 } 6268 6269 private static String calculateBundledApkRoot(final String codePathString) { 6270 final File codePath = new File(codePathString); 6271 final File codeRoot; 6272 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6273 codeRoot = Environment.getRootDirectory(); 6274 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6275 codeRoot = Environment.getOemDirectory(); 6276 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6277 codeRoot = Environment.getVendorDirectory(); 6278 } else { 6279 // Unrecognized code path; take its top real segment as the apk root: 6280 // e.g. /something/app/blah.apk => /something 6281 try { 6282 File f = codePath.getCanonicalFile(); 6283 File parent = f.getParentFile(); // non-null because codePath is a file 6284 File tmp; 6285 while ((tmp = parent.getParentFile()) != null) { 6286 f = parent; 6287 parent = tmp; 6288 } 6289 codeRoot = f; 6290 Slog.w(TAG, "Unrecognized code path " 6291 + codePath + " - using " + codeRoot); 6292 } catch (IOException e) { 6293 // Can't canonicalize the code path -- shenanigans? 6294 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6295 return Environment.getRootDirectory().getPath(); 6296 } 6297 } 6298 return codeRoot.getPath(); 6299 } 6300 6301 /** 6302 * Derive and set the location of native libraries for the given package, 6303 * which varies depending on where and how the package was installed. 6304 */ 6305 private void setNativeLibraryPaths(PackageParser.Package pkg) { 6306 final ApplicationInfo info = pkg.applicationInfo; 6307 final String codePath = pkg.codePath; 6308 final File codeFile = new File(codePath); 6309 final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info); 6310 final boolean asecApp = isForwardLocked(info) || isExternal(info); 6311 6312 info.nativeLibraryRootDir = null; 6313 info.nativeLibraryRootRequiresIsa = false; 6314 info.nativeLibraryDir = null; 6315 info.secondaryNativeLibraryDir = null; 6316 6317 if (isApkFile(codeFile)) { 6318 // Monolithic install 6319 if (bundledApp) { 6320 // If "/system/lib64/apkname" exists, assume that is the per-package 6321 // native library directory to use; otherwise use "/system/lib/apkname". 6322 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 6323 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 6324 getPrimaryInstructionSet(info)); 6325 6326 // This is a bundled system app so choose the path based on the ABI. 6327 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 6328 // is just the default path. 6329 final String apkName = deriveCodePathName(codePath); 6330 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 6331 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 6332 apkName).getAbsolutePath(); 6333 6334 if (info.secondaryCpuAbi != null) { 6335 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 6336 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 6337 secondaryLibDir, apkName).getAbsolutePath(); 6338 } 6339 } else if (asecApp) { 6340 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 6341 .getAbsolutePath(); 6342 } else { 6343 final String apkName = deriveCodePathName(codePath); 6344 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 6345 .getAbsolutePath(); 6346 } 6347 6348 info.nativeLibraryRootRequiresIsa = false; 6349 info.nativeLibraryDir = info.nativeLibraryRootDir; 6350 } else { 6351 // Cluster install 6352 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 6353 info.nativeLibraryRootRequiresIsa = true; 6354 6355 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 6356 getPrimaryInstructionSet(info)).getAbsolutePath(); 6357 6358 if (info.secondaryCpuAbi != null) { 6359 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 6360 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 6361 } 6362 } 6363 } 6364 6365 /** 6366 * Calculate the abis and roots for a bundled app. These can uniquely 6367 * be determined from the contents of the system partition, i.e whether 6368 * it contains 64 or 32 bit shared libraries etc. We do not validate any 6369 * of this information, and instead assume that the system was built 6370 * sensibly. 6371 */ 6372 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 6373 PackageSetting pkgSetting) { 6374 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 6375 6376 // If "/system/lib64/apkname" exists, assume that is the per-package 6377 // native library directory to use; otherwise use "/system/lib/apkname". 6378 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 6379 setBundledAppAbi(pkg, apkRoot, apkName); 6380 // pkgSetting might be null during rescan following uninstall of updates 6381 // to a bundled app, so accommodate that possibility. The settings in 6382 // that case will be established later from the parsed package. 6383 // 6384 // If the settings aren't null, sync them up with what we've just derived. 6385 // note that apkRoot isn't stored in the package settings. 6386 if (pkgSetting != null) { 6387 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6388 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6389 } 6390 } 6391 6392 /** 6393 * Deduces the ABI of a bundled app and sets the relevant fields on the 6394 * parsed pkg object. 6395 * 6396 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 6397 * under which system libraries are installed. 6398 * @param apkName the name of the installed package. 6399 */ 6400 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 6401 final File codeFile = new File(pkg.codePath); 6402 6403 final boolean has64BitLibs; 6404 final boolean has32BitLibs; 6405 if (isApkFile(codeFile)) { 6406 // Monolithic install 6407 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 6408 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 6409 } else { 6410 // Cluster install 6411 final File rootDir = new File(codeFile, LIB_DIR_NAME); 6412 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 6413 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 6414 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 6415 has64BitLibs = (new File(rootDir, isa)).exists(); 6416 } else { 6417 has64BitLibs = false; 6418 } 6419 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 6420 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 6421 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 6422 has32BitLibs = (new File(rootDir, isa)).exists(); 6423 } else { 6424 has32BitLibs = false; 6425 } 6426 } 6427 6428 if (has64BitLibs && !has32BitLibs) { 6429 // The package has 64 bit libs, but not 32 bit libs. Its primary 6430 // ABI should be 64 bit. We can safely assume here that the bundled 6431 // native libraries correspond to the most preferred ABI in the list. 6432 6433 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6434 pkg.applicationInfo.secondaryCpuAbi = null; 6435 } else if (has32BitLibs && !has64BitLibs) { 6436 // The package has 32 bit libs but not 64 bit libs. Its primary 6437 // ABI should be 32 bit. 6438 6439 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6440 pkg.applicationInfo.secondaryCpuAbi = null; 6441 } else if (has32BitLibs && has64BitLibs) { 6442 // The application has both 64 and 32 bit bundled libraries. We check 6443 // here that the app declares multiArch support, and warn if it doesn't. 6444 // 6445 // We will be lenient here and record both ABIs. The primary will be the 6446 // ABI that's higher on the list, i.e, a device that's configured to prefer 6447 // 64 bit apps will see a 64 bit primary ABI, 6448 6449 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 6450 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 6451 } 6452 6453 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 6454 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6455 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6456 } else { 6457 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6458 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6459 } 6460 } else { 6461 pkg.applicationInfo.primaryCpuAbi = null; 6462 pkg.applicationInfo.secondaryCpuAbi = null; 6463 } 6464 } 6465 6466 private void killApplication(String pkgName, int appId, String reason) { 6467 // Request the ActivityManager to kill the process(only for existing packages) 6468 // so that we do not end up in a confused state while the user is still using the older 6469 // version of the application while the new one gets installed. 6470 IActivityManager am = ActivityManagerNative.getDefault(); 6471 if (am != null) { 6472 try { 6473 am.killApplicationWithAppId(pkgName, appId, reason); 6474 } catch (RemoteException e) { 6475 } 6476 } 6477 } 6478 6479 void removePackageLI(PackageSetting ps, boolean chatty) { 6480 if (DEBUG_INSTALL) { 6481 if (chatty) 6482 Log.d(TAG, "Removing package " + ps.name); 6483 } 6484 6485 // writer 6486 synchronized (mPackages) { 6487 mPackages.remove(ps.name); 6488 if (ps.codePathString != null) { 6489 mAppDirs.remove(ps.codePathString); 6490 } 6491 6492 final PackageParser.Package pkg = ps.pkg; 6493 if (pkg != null) { 6494 cleanPackageDataStructuresLILPw(pkg, chatty); 6495 } 6496 } 6497 } 6498 6499 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 6500 if (DEBUG_INSTALL) { 6501 if (chatty) 6502 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 6503 } 6504 6505 // writer 6506 synchronized (mPackages) { 6507 mPackages.remove(pkg.applicationInfo.packageName); 6508 if (pkg.codePath != null) { 6509 mAppDirs.remove(pkg.codePath); 6510 } 6511 cleanPackageDataStructuresLILPw(pkg, chatty); 6512 } 6513 } 6514 6515 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 6516 int N = pkg.providers.size(); 6517 StringBuilder r = null; 6518 int i; 6519 for (i=0; i<N; i++) { 6520 PackageParser.Provider p = pkg.providers.get(i); 6521 mProviders.removeProvider(p); 6522 if (p.info.authority == null) { 6523 6524 /* There was another ContentProvider with this authority when 6525 * this app was installed so this authority is null, 6526 * Ignore it as we don't have to unregister the provider. 6527 */ 6528 continue; 6529 } 6530 String names[] = p.info.authority.split(";"); 6531 for (int j = 0; j < names.length; j++) { 6532 if (mProvidersByAuthority.get(names[j]) == p) { 6533 mProvidersByAuthority.remove(names[j]); 6534 if (DEBUG_REMOVE) { 6535 if (chatty) 6536 Log.d(TAG, "Unregistered content provider: " + names[j] 6537 + ", className = " + p.info.name + ", isSyncable = " 6538 + p.info.isSyncable); 6539 } 6540 } 6541 } 6542 if (DEBUG_REMOVE && chatty) { 6543 if (r == null) { 6544 r = new StringBuilder(256); 6545 } else { 6546 r.append(' '); 6547 } 6548 r.append(p.info.name); 6549 } 6550 } 6551 if (r != null) { 6552 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 6553 } 6554 6555 N = pkg.services.size(); 6556 r = null; 6557 for (i=0; i<N; i++) { 6558 PackageParser.Service s = pkg.services.get(i); 6559 mServices.removeService(s); 6560 if (chatty) { 6561 if (r == null) { 6562 r = new StringBuilder(256); 6563 } else { 6564 r.append(' '); 6565 } 6566 r.append(s.info.name); 6567 } 6568 } 6569 if (r != null) { 6570 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 6571 } 6572 6573 N = pkg.receivers.size(); 6574 r = null; 6575 for (i=0; i<N; i++) { 6576 PackageParser.Activity a = pkg.receivers.get(i); 6577 mReceivers.removeActivity(a, "receiver"); 6578 if (DEBUG_REMOVE && chatty) { 6579 if (r == null) { 6580 r = new StringBuilder(256); 6581 } else { 6582 r.append(' '); 6583 } 6584 r.append(a.info.name); 6585 } 6586 } 6587 if (r != null) { 6588 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 6589 } 6590 6591 N = pkg.activities.size(); 6592 r = null; 6593 for (i=0; i<N; i++) { 6594 PackageParser.Activity a = pkg.activities.get(i); 6595 mActivities.removeActivity(a, "activity"); 6596 if (DEBUG_REMOVE && chatty) { 6597 if (r == null) { 6598 r = new StringBuilder(256); 6599 } else { 6600 r.append(' '); 6601 } 6602 r.append(a.info.name); 6603 } 6604 } 6605 if (r != null) { 6606 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 6607 } 6608 6609 N = pkg.permissions.size(); 6610 r = null; 6611 for (i=0; i<N; i++) { 6612 PackageParser.Permission p = pkg.permissions.get(i); 6613 BasePermission bp = mSettings.mPermissions.get(p.info.name); 6614 if (bp == null) { 6615 bp = mSettings.mPermissionTrees.get(p.info.name); 6616 } 6617 if (bp != null && bp.perm == p) { 6618 bp.perm = null; 6619 if (DEBUG_REMOVE && chatty) { 6620 if (r == null) { 6621 r = new StringBuilder(256); 6622 } else { 6623 r.append(' '); 6624 } 6625 r.append(p.info.name); 6626 } 6627 } 6628 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6629 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 6630 if (appOpPerms != null) { 6631 appOpPerms.remove(pkg.packageName); 6632 } 6633 } 6634 } 6635 if (r != null) { 6636 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6637 } 6638 6639 N = pkg.requestedPermissions.size(); 6640 r = null; 6641 for (i=0; i<N; i++) { 6642 String perm = pkg.requestedPermissions.get(i); 6643 BasePermission bp = mSettings.mPermissions.get(perm); 6644 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6645 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 6646 if (appOpPerms != null) { 6647 appOpPerms.remove(pkg.packageName); 6648 if (appOpPerms.isEmpty()) { 6649 mAppOpPermissionPackages.remove(perm); 6650 } 6651 } 6652 } 6653 } 6654 if (r != null) { 6655 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6656 } 6657 6658 N = pkg.instrumentation.size(); 6659 r = null; 6660 for (i=0; i<N; i++) { 6661 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6662 mInstrumentation.remove(a.getComponentName()); 6663 if (DEBUG_REMOVE && chatty) { 6664 if (r == null) { 6665 r = new StringBuilder(256); 6666 } else { 6667 r.append(' '); 6668 } 6669 r.append(a.info.name); 6670 } 6671 } 6672 if (r != null) { 6673 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 6674 } 6675 6676 r = null; 6677 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6678 // Only system apps can hold shared libraries. 6679 if (pkg.libraryNames != null) { 6680 for (i=0; i<pkg.libraryNames.size(); i++) { 6681 String name = pkg.libraryNames.get(i); 6682 SharedLibraryEntry cur = mSharedLibraries.get(name); 6683 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 6684 mSharedLibraries.remove(name); 6685 if (DEBUG_REMOVE && chatty) { 6686 if (r == null) { 6687 r = new StringBuilder(256); 6688 } else { 6689 r.append(' '); 6690 } 6691 r.append(name); 6692 } 6693 } 6694 } 6695 } 6696 } 6697 if (r != null) { 6698 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 6699 } 6700 } 6701 6702 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 6703 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 6704 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 6705 return true; 6706 } 6707 } 6708 return false; 6709 } 6710 6711 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 6712 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 6713 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 6714 6715 private void updatePermissionsLPw(String changingPkg, 6716 PackageParser.Package pkgInfo, int flags) { 6717 // Make sure there are no dangling permission trees. 6718 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 6719 while (it.hasNext()) { 6720 final BasePermission bp = it.next(); 6721 if (bp.packageSetting == null) { 6722 // We may not yet have parsed the package, so just see if 6723 // we still know about its settings. 6724 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6725 } 6726 if (bp.packageSetting == null) { 6727 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 6728 + " from package " + bp.sourcePackage); 6729 it.remove(); 6730 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6731 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6732 Slog.i(TAG, "Removing old permission tree: " + bp.name 6733 + " from package " + bp.sourcePackage); 6734 flags |= UPDATE_PERMISSIONS_ALL; 6735 it.remove(); 6736 } 6737 } 6738 } 6739 6740 // Make sure all dynamic permissions have been assigned to a package, 6741 // and make sure there are no dangling permissions. 6742 it = mSettings.mPermissions.values().iterator(); 6743 while (it.hasNext()) { 6744 final BasePermission bp = it.next(); 6745 if (bp.type == BasePermission.TYPE_DYNAMIC) { 6746 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 6747 + bp.name + " pkg=" + bp.sourcePackage 6748 + " info=" + bp.pendingInfo); 6749 if (bp.packageSetting == null && bp.pendingInfo != null) { 6750 final BasePermission tree = findPermissionTreeLP(bp.name); 6751 if (tree != null && tree.perm != null) { 6752 bp.packageSetting = tree.packageSetting; 6753 bp.perm = new PackageParser.Permission(tree.perm.owner, 6754 new PermissionInfo(bp.pendingInfo)); 6755 bp.perm.info.packageName = tree.perm.info.packageName; 6756 bp.perm.info.name = bp.name; 6757 bp.uid = tree.uid; 6758 } 6759 } 6760 } 6761 if (bp.packageSetting == null) { 6762 // We may not yet have parsed the package, so just see if 6763 // we still know about its settings. 6764 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6765 } 6766 if (bp.packageSetting == null) { 6767 Slog.w(TAG, "Removing dangling permission: " + bp.name 6768 + " from package " + bp.sourcePackage); 6769 it.remove(); 6770 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6771 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6772 Slog.i(TAG, "Removing old permission: " + bp.name 6773 + " from package " + bp.sourcePackage); 6774 flags |= UPDATE_PERMISSIONS_ALL; 6775 it.remove(); 6776 } 6777 } 6778 } 6779 6780 // Now update the permissions for all packages, in particular 6781 // replace the granted permissions of the system packages. 6782 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 6783 for (PackageParser.Package pkg : mPackages.values()) { 6784 if (pkg != pkgInfo) { 6785 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0); 6786 } 6787 } 6788 } 6789 6790 if (pkgInfo != null) { 6791 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0); 6792 } 6793 } 6794 6795 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) { 6796 final PackageSetting ps = (PackageSetting) pkg.mExtras; 6797 if (ps == null) { 6798 return; 6799 } 6800 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 6801 HashSet<String> origPermissions = gp.grantedPermissions; 6802 boolean changedPermission = false; 6803 6804 if (replace) { 6805 ps.permissionsFixed = false; 6806 if (gp == ps) { 6807 origPermissions = new HashSet<String>(gp.grantedPermissions); 6808 gp.grantedPermissions.clear(); 6809 gp.gids = mGlobalGids; 6810 } 6811 } 6812 6813 if (gp.gids == null) { 6814 gp.gids = mGlobalGids; 6815 } 6816 6817 final int N = pkg.requestedPermissions.size(); 6818 for (int i=0; i<N; i++) { 6819 final String name = pkg.requestedPermissions.get(i); 6820 final boolean required = pkg.requestedPermissionsRequired.get(i); 6821 final BasePermission bp = mSettings.mPermissions.get(name); 6822 if (DEBUG_INSTALL) { 6823 if (gp != ps) { 6824 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 6825 } 6826 } 6827 6828 if (bp == null || bp.packageSetting == null) { 6829 Slog.w(TAG, "Unknown permission " + name 6830 + " in package " + pkg.packageName); 6831 continue; 6832 } 6833 6834 final String perm = bp.name; 6835 boolean allowed; 6836 boolean allowedSig = false; 6837 if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6838 // Keep track of app op permissions. 6839 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 6840 if (pkgs == null) { 6841 pkgs = new ArraySet<>(); 6842 mAppOpPermissionPackages.put(bp.name, pkgs); 6843 } 6844 pkgs.add(pkg.packageName); 6845 } 6846 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 6847 if (level == PermissionInfo.PROTECTION_NORMAL 6848 || level == PermissionInfo.PROTECTION_DANGEROUS) { 6849 // We grant a normal or dangerous permission if any of the following 6850 // are true: 6851 // 1) The permission is required 6852 // 2) The permission is optional, but was granted in the past 6853 // 3) The permission is optional, but was requested by an 6854 // app in /system (not /data) 6855 // 6856 // Otherwise, reject the permission. 6857 allowed = (required || origPermissions.contains(perm) 6858 || (isSystemApp(ps) && !isUpdatedSystemApp(ps))); 6859 } else if (bp.packageSetting == null) { 6860 // This permission is invalid; skip it. 6861 allowed = false; 6862 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 6863 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions); 6864 if (allowed) { 6865 allowedSig = true; 6866 } 6867 } else { 6868 allowed = false; 6869 } 6870 if (DEBUG_INSTALL) { 6871 if (gp != ps) { 6872 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 6873 } 6874 } 6875 if (allowed) { 6876 if (!isSystemApp(ps) && ps.permissionsFixed) { 6877 // If this is an existing, non-system package, then 6878 // we can't add any new permissions to it. 6879 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 6880 // Except... if this is a permission that was added 6881 // to the platform (note: need to only do this when 6882 // updating the platform). 6883 allowed = isNewPlatformPermissionForPackage(perm, pkg); 6884 } 6885 } 6886 if (allowed) { 6887 if (!gp.grantedPermissions.contains(perm)) { 6888 changedPermission = true; 6889 gp.grantedPermissions.add(perm); 6890 gp.gids = appendInts(gp.gids, bp.gids); 6891 } else if (!ps.haveGids) { 6892 gp.gids = appendInts(gp.gids, bp.gids); 6893 } 6894 } else { 6895 Slog.w(TAG, "Not granting permission " + perm 6896 + " to package " + pkg.packageName 6897 + " because it was previously installed without"); 6898 } 6899 } else { 6900 if (gp.grantedPermissions.remove(perm)) { 6901 changedPermission = true; 6902 gp.gids = removeInts(gp.gids, bp.gids); 6903 Slog.i(TAG, "Un-granting permission " + perm 6904 + " from package " + pkg.packageName 6905 + " (protectionLevel=" + bp.protectionLevel 6906 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6907 + ")"); 6908 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 6909 // Don't print warning for app op permissions, since it is fine for them 6910 // not to be granted, there is a UI for the user to decide. 6911 Slog.w(TAG, "Not granting permission " + perm 6912 + " to package " + pkg.packageName 6913 + " (protectionLevel=" + bp.protectionLevel 6914 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6915 + ")"); 6916 } 6917 } 6918 } 6919 6920 if ((changedPermission || replace) && !ps.permissionsFixed && 6921 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 6922 // This is the first that we have heard about this package, so the 6923 // permissions we have now selected are fixed until explicitly 6924 // changed. 6925 ps.permissionsFixed = true; 6926 } 6927 ps.haveGids = true; 6928 } 6929 6930 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 6931 boolean allowed = false; 6932 final int NP = PackageParser.NEW_PERMISSIONS.length; 6933 for (int ip=0; ip<NP; ip++) { 6934 final PackageParser.NewPermissionInfo npi 6935 = PackageParser.NEW_PERMISSIONS[ip]; 6936 if (npi.name.equals(perm) 6937 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 6938 allowed = true; 6939 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 6940 + pkg.packageName); 6941 break; 6942 } 6943 } 6944 return allowed; 6945 } 6946 6947 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 6948 BasePermission bp, HashSet<String> origPermissions) { 6949 boolean allowed; 6950 allowed = (compareSignatures( 6951 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 6952 == PackageManager.SIGNATURE_MATCH) 6953 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 6954 == PackageManager.SIGNATURE_MATCH); 6955 if (!allowed && (bp.protectionLevel 6956 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 6957 if (isSystemApp(pkg)) { 6958 // For updated system applications, a system permission 6959 // is granted only if it had been defined by the original application. 6960 if (isUpdatedSystemApp(pkg)) { 6961 final PackageSetting sysPs = mSettings 6962 .getDisabledSystemPkgLPr(pkg.packageName); 6963 final GrantedPermissions origGp = sysPs.sharedUser != null 6964 ? sysPs.sharedUser : sysPs; 6965 6966 if (origGp.grantedPermissions.contains(perm)) { 6967 // If the original was granted this permission, we take 6968 // that grant decision as read and propagate it to the 6969 // update. 6970 allowed = true; 6971 } else { 6972 // The system apk may have been updated with an older 6973 // version of the one on the data partition, but which 6974 // granted a new system permission that it didn't have 6975 // before. In this case we do want to allow the app to 6976 // now get the new permission if the ancestral apk is 6977 // privileged to get it. 6978 if (sysPs.pkg != null && sysPs.isPrivileged()) { 6979 for (int j=0; 6980 j<sysPs.pkg.requestedPermissions.size(); j++) { 6981 if (perm.equals( 6982 sysPs.pkg.requestedPermissions.get(j))) { 6983 allowed = true; 6984 break; 6985 } 6986 } 6987 } 6988 } 6989 } else { 6990 allowed = isPrivilegedApp(pkg); 6991 } 6992 } 6993 } 6994 if (!allowed && (bp.protectionLevel 6995 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 6996 // For development permissions, a development permission 6997 // is granted only if it was already granted. 6998 allowed = origPermissions.contains(perm); 6999 } 7000 return allowed; 7001 } 7002 7003 final class ActivityIntentResolver 7004 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 7005 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7006 boolean defaultOnly, int userId) { 7007 if (!sUserManager.exists(userId)) return null; 7008 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7009 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7010 } 7011 7012 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7013 int userId) { 7014 if (!sUserManager.exists(userId)) return null; 7015 mFlags = flags; 7016 return super.queryIntent(intent, resolvedType, 7017 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7018 } 7019 7020 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7021 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 7022 if (!sUserManager.exists(userId)) return null; 7023 if (packageActivities == null) { 7024 return null; 7025 } 7026 mFlags = flags; 7027 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7028 final int N = packageActivities.size(); 7029 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 7030 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 7031 7032 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 7033 for (int i = 0; i < N; ++i) { 7034 intentFilters = packageActivities.get(i).intents; 7035 if (intentFilters != null && intentFilters.size() > 0) { 7036 PackageParser.ActivityIntentInfo[] array = 7037 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 7038 intentFilters.toArray(array); 7039 listCut.add(array); 7040 } 7041 } 7042 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7043 } 7044 7045 public final void addActivity(PackageParser.Activity a, String type) { 7046 final boolean systemApp = isSystemApp(a.info.applicationInfo); 7047 mActivities.put(a.getComponentName(), a); 7048 if (DEBUG_SHOW_INFO) 7049 Log.v( 7050 TAG, " " + type + " " + 7051 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 7052 if (DEBUG_SHOW_INFO) 7053 Log.v(TAG, " Class=" + a.info.name); 7054 final int NI = a.intents.size(); 7055 for (int j=0; j<NI; j++) { 7056 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7057 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 7058 intent.setPriority(0); 7059 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 7060 + a.className + " with priority > 0, forcing to 0"); 7061 } 7062 if (DEBUG_SHOW_INFO) { 7063 Log.v(TAG, " IntentFilter:"); 7064 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7065 } 7066 if (!intent.debugCheck()) { 7067 Log.w(TAG, "==> For Activity " + a.info.name); 7068 } 7069 addFilter(intent); 7070 } 7071 } 7072 7073 public final void removeActivity(PackageParser.Activity a, String type) { 7074 mActivities.remove(a.getComponentName()); 7075 if (DEBUG_SHOW_INFO) { 7076 Log.v(TAG, " " + type + " " 7077 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 7078 : a.info.name) + ":"); 7079 Log.v(TAG, " Class=" + a.info.name); 7080 } 7081 final int NI = a.intents.size(); 7082 for (int j=0; j<NI; j++) { 7083 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7084 if (DEBUG_SHOW_INFO) { 7085 Log.v(TAG, " IntentFilter:"); 7086 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7087 } 7088 removeFilter(intent); 7089 } 7090 } 7091 7092 @Override 7093 protected boolean allowFilterResult( 7094 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 7095 ActivityInfo filterAi = filter.activity.info; 7096 for (int i=dest.size()-1; i>=0; i--) { 7097 ActivityInfo destAi = dest.get(i).activityInfo; 7098 if (destAi.name == filterAi.name 7099 && destAi.packageName == filterAi.packageName) { 7100 return false; 7101 } 7102 } 7103 return true; 7104 } 7105 7106 @Override 7107 protected ActivityIntentInfo[] newArray(int size) { 7108 return new ActivityIntentInfo[size]; 7109 } 7110 7111 @Override 7112 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 7113 if (!sUserManager.exists(userId)) return true; 7114 PackageParser.Package p = filter.activity.owner; 7115 if (p != null) { 7116 PackageSetting ps = (PackageSetting)p.mExtras; 7117 if (ps != null) { 7118 // System apps are never considered stopped for purposes of 7119 // filtering, because there may be no way for the user to 7120 // actually re-launch them. 7121 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 7122 && ps.getStopped(userId); 7123 } 7124 } 7125 return false; 7126 } 7127 7128 @Override 7129 protected boolean isPackageForFilter(String packageName, 7130 PackageParser.ActivityIntentInfo info) { 7131 return packageName.equals(info.activity.owner.packageName); 7132 } 7133 7134 @Override 7135 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7136 int match, int userId) { 7137 if (!sUserManager.exists(userId)) return null; 7138 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7139 return null; 7140 } 7141 final PackageParser.Activity activity = info.activity; 7142 if (mSafeMode && (activity.info.applicationInfo.flags 7143 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7144 return null; 7145 } 7146 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7147 if (ps == null) { 7148 return null; 7149 } 7150 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7151 ps.readUserState(userId), userId); 7152 if (ai == null) { 7153 return null; 7154 } 7155 final ResolveInfo res = new ResolveInfo(); 7156 res.activityInfo = ai; 7157 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7158 res.filter = info; 7159 } 7160 res.priority = info.getPriority(); 7161 res.preferredOrder = activity.owner.mPreferredOrder; 7162 //System.out.println("Result: " + res.activityInfo.className + 7163 // " = " + res.priority); 7164 res.match = match; 7165 res.isDefault = info.hasDefault; 7166 res.labelRes = info.labelRes; 7167 res.nonLocalizedLabel = info.nonLocalizedLabel; 7168 if (userNeedsBadging(userId)) { 7169 res.noResourceId = true; 7170 } else { 7171 res.icon = info.icon; 7172 } 7173 res.system = isSystemApp(res.activityInfo.applicationInfo); 7174 return res; 7175 } 7176 7177 @Override 7178 protected void sortResults(List<ResolveInfo> results) { 7179 Collections.sort(results, mResolvePrioritySorter); 7180 } 7181 7182 @Override 7183 protected void dumpFilter(PrintWriter out, String prefix, 7184 PackageParser.ActivityIntentInfo filter) { 7185 out.print(prefix); out.print( 7186 Integer.toHexString(System.identityHashCode(filter.activity))); 7187 out.print(' '); 7188 filter.activity.printComponentShortName(out); 7189 out.print(" filter "); 7190 out.println(Integer.toHexString(System.identityHashCode(filter))); 7191 } 7192 7193// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7194// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7195// final List<ResolveInfo> retList = Lists.newArrayList(); 7196// while (i.hasNext()) { 7197// final ResolveInfo resolveInfo = i.next(); 7198// if (isEnabledLP(resolveInfo.activityInfo)) { 7199// retList.add(resolveInfo); 7200// } 7201// } 7202// return retList; 7203// } 7204 7205 // Keys are String (activity class name), values are Activity. 7206 private final HashMap<ComponentName, PackageParser.Activity> mActivities 7207 = new HashMap<ComponentName, PackageParser.Activity>(); 7208 private int mFlags; 7209 } 7210 7211 private final class ServiceIntentResolver 7212 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 7213 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7214 boolean defaultOnly, int userId) { 7215 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7216 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7217 } 7218 7219 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7220 int userId) { 7221 if (!sUserManager.exists(userId)) return null; 7222 mFlags = flags; 7223 return super.queryIntent(intent, resolvedType, 7224 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7225 } 7226 7227 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7228 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 7229 if (!sUserManager.exists(userId)) return null; 7230 if (packageServices == null) { 7231 return null; 7232 } 7233 mFlags = flags; 7234 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7235 final int N = packageServices.size(); 7236 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 7237 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 7238 7239 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 7240 for (int i = 0; i < N; ++i) { 7241 intentFilters = packageServices.get(i).intents; 7242 if (intentFilters != null && intentFilters.size() > 0) { 7243 PackageParser.ServiceIntentInfo[] array = 7244 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 7245 intentFilters.toArray(array); 7246 listCut.add(array); 7247 } 7248 } 7249 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7250 } 7251 7252 public final void addService(PackageParser.Service s) { 7253 mServices.put(s.getComponentName(), s); 7254 if (DEBUG_SHOW_INFO) { 7255 Log.v(TAG, " " 7256 + (s.info.nonLocalizedLabel != null 7257 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7258 Log.v(TAG, " Class=" + s.info.name); 7259 } 7260 final int NI = s.intents.size(); 7261 int j; 7262 for (j=0; j<NI; j++) { 7263 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7264 if (DEBUG_SHOW_INFO) { 7265 Log.v(TAG, " IntentFilter:"); 7266 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7267 } 7268 if (!intent.debugCheck()) { 7269 Log.w(TAG, "==> For Service " + s.info.name); 7270 } 7271 addFilter(intent); 7272 } 7273 } 7274 7275 public final void removeService(PackageParser.Service s) { 7276 mServices.remove(s.getComponentName()); 7277 if (DEBUG_SHOW_INFO) { 7278 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 7279 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7280 Log.v(TAG, " Class=" + s.info.name); 7281 } 7282 final int NI = s.intents.size(); 7283 int j; 7284 for (j=0; j<NI; j++) { 7285 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7286 if (DEBUG_SHOW_INFO) { 7287 Log.v(TAG, " IntentFilter:"); 7288 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7289 } 7290 removeFilter(intent); 7291 } 7292 } 7293 7294 @Override 7295 protected boolean allowFilterResult( 7296 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 7297 ServiceInfo filterSi = filter.service.info; 7298 for (int i=dest.size()-1; i>=0; i--) { 7299 ServiceInfo destAi = dest.get(i).serviceInfo; 7300 if (destAi.name == filterSi.name 7301 && destAi.packageName == filterSi.packageName) { 7302 return false; 7303 } 7304 } 7305 return true; 7306 } 7307 7308 @Override 7309 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 7310 return new PackageParser.ServiceIntentInfo[size]; 7311 } 7312 7313 @Override 7314 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 7315 if (!sUserManager.exists(userId)) return true; 7316 PackageParser.Package p = filter.service.owner; 7317 if (p != null) { 7318 PackageSetting ps = (PackageSetting)p.mExtras; 7319 if (ps != null) { 7320 // System apps are never considered stopped for purposes of 7321 // filtering, because there may be no way for the user to 7322 // actually re-launch them. 7323 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7324 && ps.getStopped(userId); 7325 } 7326 } 7327 return false; 7328 } 7329 7330 @Override 7331 protected boolean isPackageForFilter(String packageName, 7332 PackageParser.ServiceIntentInfo info) { 7333 return packageName.equals(info.service.owner.packageName); 7334 } 7335 7336 @Override 7337 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 7338 int match, int userId) { 7339 if (!sUserManager.exists(userId)) return null; 7340 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 7341 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 7342 return null; 7343 } 7344 final PackageParser.Service service = info.service; 7345 if (mSafeMode && (service.info.applicationInfo.flags 7346 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7347 return null; 7348 } 7349 PackageSetting ps = (PackageSetting) service.owner.mExtras; 7350 if (ps == null) { 7351 return null; 7352 } 7353 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 7354 ps.readUserState(userId), userId); 7355 if (si == null) { 7356 return null; 7357 } 7358 final ResolveInfo res = new ResolveInfo(); 7359 res.serviceInfo = si; 7360 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7361 res.filter = filter; 7362 } 7363 res.priority = info.getPriority(); 7364 res.preferredOrder = service.owner.mPreferredOrder; 7365 //System.out.println("Result: " + res.activityInfo.className + 7366 // " = " + res.priority); 7367 res.match = match; 7368 res.isDefault = info.hasDefault; 7369 res.labelRes = info.labelRes; 7370 res.nonLocalizedLabel = info.nonLocalizedLabel; 7371 res.icon = info.icon; 7372 res.system = isSystemApp(res.serviceInfo.applicationInfo); 7373 return res; 7374 } 7375 7376 @Override 7377 protected void sortResults(List<ResolveInfo> results) { 7378 Collections.sort(results, mResolvePrioritySorter); 7379 } 7380 7381 @Override 7382 protected void dumpFilter(PrintWriter out, String prefix, 7383 PackageParser.ServiceIntentInfo filter) { 7384 out.print(prefix); out.print( 7385 Integer.toHexString(System.identityHashCode(filter.service))); 7386 out.print(' '); 7387 filter.service.printComponentShortName(out); 7388 out.print(" filter "); 7389 out.println(Integer.toHexString(System.identityHashCode(filter))); 7390 } 7391 7392// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7393// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7394// final List<ResolveInfo> retList = Lists.newArrayList(); 7395// while (i.hasNext()) { 7396// final ResolveInfo resolveInfo = (ResolveInfo) i; 7397// if (isEnabledLP(resolveInfo.serviceInfo)) { 7398// retList.add(resolveInfo); 7399// } 7400// } 7401// return retList; 7402// } 7403 7404 // Keys are String (activity class name), values are Activity. 7405 private final HashMap<ComponentName, PackageParser.Service> mServices 7406 = new HashMap<ComponentName, PackageParser.Service>(); 7407 private int mFlags; 7408 }; 7409 7410 private final class ProviderIntentResolver 7411 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 7412 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7413 boolean defaultOnly, int userId) { 7414 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7415 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7416 } 7417 7418 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7419 int userId) { 7420 if (!sUserManager.exists(userId)) 7421 return null; 7422 mFlags = flags; 7423 return super.queryIntent(intent, resolvedType, 7424 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7425 } 7426 7427 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7428 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 7429 if (!sUserManager.exists(userId)) 7430 return null; 7431 if (packageProviders == null) { 7432 return null; 7433 } 7434 mFlags = flags; 7435 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 7436 final int N = packageProviders.size(); 7437 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 7438 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 7439 7440 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 7441 for (int i = 0; i < N; ++i) { 7442 intentFilters = packageProviders.get(i).intents; 7443 if (intentFilters != null && intentFilters.size() > 0) { 7444 PackageParser.ProviderIntentInfo[] array = 7445 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 7446 intentFilters.toArray(array); 7447 listCut.add(array); 7448 } 7449 } 7450 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7451 } 7452 7453 public final void addProvider(PackageParser.Provider p) { 7454 if (mProviders.containsKey(p.getComponentName())) { 7455 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 7456 return; 7457 } 7458 7459 mProviders.put(p.getComponentName(), p); 7460 if (DEBUG_SHOW_INFO) { 7461 Log.v(TAG, " " 7462 + (p.info.nonLocalizedLabel != null 7463 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7464 Log.v(TAG, " Class=" + p.info.name); 7465 } 7466 final int NI = p.intents.size(); 7467 int j; 7468 for (j = 0; j < NI; j++) { 7469 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7470 if (DEBUG_SHOW_INFO) { 7471 Log.v(TAG, " IntentFilter:"); 7472 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7473 } 7474 if (!intent.debugCheck()) { 7475 Log.w(TAG, "==> For Provider " + p.info.name); 7476 } 7477 addFilter(intent); 7478 } 7479 } 7480 7481 public final void removeProvider(PackageParser.Provider p) { 7482 mProviders.remove(p.getComponentName()); 7483 if (DEBUG_SHOW_INFO) { 7484 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 7485 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7486 Log.v(TAG, " Class=" + p.info.name); 7487 } 7488 final int NI = p.intents.size(); 7489 int j; 7490 for (j = 0; j < NI; j++) { 7491 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7492 if (DEBUG_SHOW_INFO) { 7493 Log.v(TAG, " IntentFilter:"); 7494 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7495 } 7496 removeFilter(intent); 7497 } 7498 } 7499 7500 @Override 7501 protected boolean allowFilterResult( 7502 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 7503 ProviderInfo filterPi = filter.provider.info; 7504 for (int i = dest.size() - 1; i >= 0; i--) { 7505 ProviderInfo destPi = dest.get(i).providerInfo; 7506 if (destPi.name == filterPi.name 7507 && destPi.packageName == filterPi.packageName) { 7508 return false; 7509 } 7510 } 7511 return true; 7512 } 7513 7514 @Override 7515 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 7516 return new PackageParser.ProviderIntentInfo[size]; 7517 } 7518 7519 @Override 7520 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 7521 if (!sUserManager.exists(userId)) 7522 return true; 7523 PackageParser.Package p = filter.provider.owner; 7524 if (p != null) { 7525 PackageSetting ps = (PackageSetting) p.mExtras; 7526 if (ps != null) { 7527 // System apps are never considered stopped for purposes of 7528 // filtering, because there may be no way for the user to 7529 // actually re-launch them. 7530 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7531 && ps.getStopped(userId); 7532 } 7533 } 7534 return false; 7535 } 7536 7537 @Override 7538 protected boolean isPackageForFilter(String packageName, 7539 PackageParser.ProviderIntentInfo info) { 7540 return packageName.equals(info.provider.owner.packageName); 7541 } 7542 7543 @Override 7544 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 7545 int match, int userId) { 7546 if (!sUserManager.exists(userId)) 7547 return null; 7548 final PackageParser.ProviderIntentInfo info = filter; 7549 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 7550 return null; 7551 } 7552 final PackageParser.Provider provider = info.provider; 7553 if (mSafeMode && (provider.info.applicationInfo.flags 7554 & ApplicationInfo.FLAG_SYSTEM) == 0) { 7555 return null; 7556 } 7557 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 7558 if (ps == null) { 7559 return null; 7560 } 7561 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 7562 ps.readUserState(userId), userId); 7563 if (pi == null) { 7564 return null; 7565 } 7566 final ResolveInfo res = new ResolveInfo(); 7567 res.providerInfo = pi; 7568 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 7569 res.filter = filter; 7570 } 7571 res.priority = info.getPriority(); 7572 res.preferredOrder = provider.owner.mPreferredOrder; 7573 res.match = match; 7574 res.isDefault = info.hasDefault; 7575 res.labelRes = info.labelRes; 7576 res.nonLocalizedLabel = info.nonLocalizedLabel; 7577 res.icon = info.icon; 7578 res.system = isSystemApp(res.providerInfo.applicationInfo); 7579 return res; 7580 } 7581 7582 @Override 7583 protected void sortResults(List<ResolveInfo> results) { 7584 Collections.sort(results, mResolvePrioritySorter); 7585 } 7586 7587 @Override 7588 protected void dumpFilter(PrintWriter out, String prefix, 7589 PackageParser.ProviderIntentInfo filter) { 7590 out.print(prefix); 7591 out.print( 7592 Integer.toHexString(System.identityHashCode(filter.provider))); 7593 out.print(' '); 7594 filter.provider.printComponentShortName(out); 7595 out.print(" filter "); 7596 out.println(Integer.toHexString(System.identityHashCode(filter))); 7597 } 7598 7599 private final HashMap<ComponentName, PackageParser.Provider> mProviders 7600 = new HashMap<ComponentName, PackageParser.Provider>(); 7601 private int mFlags; 7602 }; 7603 7604 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 7605 new Comparator<ResolveInfo>() { 7606 public int compare(ResolveInfo r1, ResolveInfo r2) { 7607 int v1 = r1.priority; 7608 int v2 = r2.priority; 7609 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 7610 if (v1 != v2) { 7611 return (v1 > v2) ? -1 : 1; 7612 } 7613 v1 = r1.preferredOrder; 7614 v2 = r2.preferredOrder; 7615 if (v1 != v2) { 7616 return (v1 > v2) ? -1 : 1; 7617 } 7618 if (r1.isDefault != r2.isDefault) { 7619 return r1.isDefault ? -1 : 1; 7620 } 7621 v1 = r1.match; 7622 v2 = r2.match; 7623 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 7624 if (v1 != v2) { 7625 return (v1 > v2) ? -1 : 1; 7626 } 7627 if (r1.system != r2.system) { 7628 return r1.system ? -1 : 1; 7629 } 7630 return 0; 7631 } 7632 }; 7633 7634 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 7635 new Comparator<ProviderInfo>() { 7636 public int compare(ProviderInfo p1, ProviderInfo p2) { 7637 final int v1 = p1.initOrder; 7638 final int v2 = p2.initOrder; 7639 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 7640 } 7641 }; 7642 7643 static final void sendPackageBroadcast(String action, String pkg, 7644 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 7645 int[] userIds) { 7646 IActivityManager am = ActivityManagerNative.getDefault(); 7647 if (am != null) { 7648 try { 7649 if (userIds == null) { 7650 userIds = am.getRunningUserIds(); 7651 } 7652 for (int id : userIds) { 7653 final Intent intent = new Intent(action, 7654 pkg != null ? Uri.fromParts("package", pkg, null) : null); 7655 if (extras != null) { 7656 intent.putExtras(extras); 7657 } 7658 if (targetPkg != null) { 7659 intent.setPackage(targetPkg); 7660 } 7661 // Modify the UID when posting to other users 7662 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 7663 if (uid > 0 && UserHandle.getUserId(uid) != id) { 7664 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 7665 intent.putExtra(Intent.EXTRA_UID, uid); 7666 } 7667 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 7668 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 7669 if (DEBUG_BROADCASTS) { 7670 RuntimeException here = new RuntimeException("here"); 7671 here.fillInStackTrace(); 7672 Slog.d(TAG, "Sending to user " + id + ": " 7673 + intent.toShortString(false, true, false, false) 7674 + " " + intent.getExtras(), here); 7675 } 7676 am.broadcastIntent(null, intent, null, finishedReceiver, 7677 0, null, null, null, android.app.AppOpsManager.OP_NONE, 7678 finishedReceiver != null, false, id); 7679 } 7680 } catch (RemoteException ex) { 7681 } 7682 } 7683 } 7684 7685 /** 7686 * Check if the external storage media is available. This is true if there 7687 * is a mounted external storage medium or if the external storage is 7688 * emulated. 7689 */ 7690 private boolean isExternalMediaAvailable() { 7691 return mMediaMounted || Environment.isExternalStorageEmulated(); 7692 } 7693 7694 @Override 7695 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 7696 // writer 7697 synchronized (mPackages) { 7698 if (!isExternalMediaAvailable()) { 7699 // If the external storage is no longer mounted at this point, 7700 // the caller may not have been able to delete all of this 7701 // packages files and can not delete any more. Bail. 7702 return null; 7703 } 7704 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 7705 if (lastPackage != null) { 7706 pkgs.remove(lastPackage); 7707 } 7708 if (pkgs.size() > 0) { 7709 return pkgs.get(0); 7710 } 7711 } 7712 return null; 7713 } 7714 7715 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 7716 if (false) { 7717 RuntimeException here = new RuntimeException("here"); 7718 here.fillInStackTrace(); 7719 Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId 7720 + " andCode=" + andCode, here); 7721 } 7722 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, 7723 userId, andCode ? 1 : 0, packageName)); 7724 } 7725 7726 void startCleaningPackages() { 7727 // reader 7728 synchronized (mPackages) { 7729 if (!isExternalMediaAvailable()) { 7730 return; 7731 } 7732 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 7733 return; 7734 } 7735 } 7736 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 7737 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 7738 IActivityManager am = ActivityManagerNative.getDefault(); 7739 if (am != null) { 7740 try { 7741 am.startService(null, intent, null, UserHandle.USER_OWNER); 7742 } catch (RemoteException e) { 7743 } 7744 } 7745 } 7746 7747 @Override 7748 public void installPackage(String originPath, IPackageInstallObserver2 observer, int flags, 7749 String installerPackageName, VerificationParams verificationParams, 7750 String packageAbiOverride) { 7751 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7752 null); 7753 7754 final File originFile = new File(originPath); 7755 final int uid = Binder.getCallingUid(); 7756 if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) { 7757 try { 7758 if (observer != null) { 7759 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 7760 } 7761 } catch (RemoteException re) { 7762 } 7763 return; 7764 } 7765 7766 UserHandle user; 7767 if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) { 7768 user = UserHandle.ALL; 7769 } else { 7770 user = new UserHandle(UserHandle.getUserId(uid)); 7771 } 7772 7773 final int filteredFlags; 7774 if (uid == Process.SHELL_UID || uid == 0) { 7775 if (DEBUG_INSTALL) { 7776 Slog.v(TAG, "Install from ADB"); 7777 } 7778 filteredFlags = flags | PackageManager.INSTALL_FROM_ADB; 7779 } else { 7780 filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB; 7781 } 7782 7783 verificationParams.setInstallerUid(uid); 7784 7785 final Message msg = mHandler.obtainMessage(INIT_COPY); 7786 final OriginInfo origin = new OriginInfo(originFile, null, false); 7787 msg.obj = new InstallParams(origin, observer, filteredFlags, 7788 installerPackageName, verificationParams, user, packageAbiOverride); 7789 mHandler.sendMessage(msg); 7790 } 7791 7792 void installStage(String packageName, File stagedDir, String stagedCid, 7793 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 7794 String installerPackageName, int installerUid, UserHandle user) { 7795 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 7796 params.referrerUri, installerUid, null); 7797 7798 final Message msg = mHandler.obtainMessage(INIT_COPY); 7799 final OriginInfo origin = new OriginInfo(stagedDir, stagedCid, true); 7800 msg.obj = new InstallParams(origin, observer, params.installFlags, 7801 installerPackageName, verifParams, user, params.abiOverride); 7802 mHandler.sendMessage(msg); 7803 } 7804 7805 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 7806 Bundle extras = new Bundle(1); 7807 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 7808 7809 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 7810 packageName, extras, null, null, new int[] {userId}); 7811 try { 7812 IActivityManager am = ActivityManagerNative.getDefault(); 7813 final boolean isSystem = 7814 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 7815 if (isSystem && am.isUserRunning(userId, false)) { 7816 // The just-installed/enabled app is bundled on the system, so presumed 7817 // to be able to run automatically without needing an explicit launch. 7818 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 7819 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 7820 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 7821 .setPackage(packageName); 7822 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 7823 android.app.AppOpsManager.OP_NONE, false, false, userId); 7824 } 7825 } catch (RemoteException e) { 7826 // shouldn't happen 7827 Slog.w(TAG, "Unable to bootstrap installed package", e); 7828 } 7829 } 7830 7831 @Override 7832 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 7833 int userId) { 7834 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7835 PackageSetting pkgSetting; 7836 final int uid = Binder.getCallingUid(); 7837 if (UserHandle.getUserId(uid) != userId) { 7838 mContext.enforceCallingOrSelfPermission( 7839 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 7840 "setApplicationHiddenSetting for user " + userId); 7841 } 7842 7843 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 7844 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 7845 return false; 7846 } 7847 7848 long callingId = Binder.clearCallingIdentity(); 7849 try { 7850 boolean sendAdded = false; 7851 boolean sendRemoved = false; 7852 // writer 7853 synchronized (mPackages) { 7854 pkgSetting = mSettings.mPackages.get(packageName); 7855 if (pkgSetting == null) { 7856 return false; 7857 } 7858 if (pkgSetting.getHidden(userId) != hidden) { 7859 pkgSetting.setHidden(hidden, userId); 7860 mSettings.writePackageRestrictionsLPr(userId); 7861 if (hidden) { 7862 sendRemoved = true; 7863 } else { 7864 sendAdded = true; 7865 } 7866 } 7867 } 7868 if (sendAdded) { 7869 sendPackageAddedForUser(packageName, pkgSetting, userId); 7870 return true; 7871 } 7872 if (sendRemoved) { 7873 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 7874 "hiding pkg"); 7875 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 7876 } 7877 } finally { 7878 Binder.restoreCallingIdentity(callingId); 7879 } 7880 return false; 7881 } 7882 7883 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 7884 int userId) { 7885 final PackageRemovedInfo info = new PackageRemovedInfo(); 7886 info.removedPackage = packageName; 7887 info.removedUsers = new int[] {userId}; 7888 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 7889 info.sendBroadcast(false, false, false); 7890 } 7891 7892 /** 7893 * Returns true if application is not found or there was an error. Otherwise it returns 7894 * the hidden state of the package for the given user. 7895 */ 7896 @Override 7897 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 7898 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7899 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 7900 "getApplicationHidden for user " + userId); 7901 PackageSetting pkgSetting; 7902 long callingId = Binder.clearCallingIdentity(); 7903 try { 7904 // writer 7905 synchronized (mPackages) { 7906 pkgSetting = mSettings.mPackages.get(packageName); 7907 if (pkgSetting == null) { 7908 return true; 7909 } 7910 return pkgSetting.getHidden(userId); 7911 } 7912 } finally { 7913 Binder.restoreCallingIdentity(callingId); 7914 } 7915 } 7916 7917 /** 7918 * @hide 7919 */ 7920 @Override 7921 public int installExistingPackageAsUser(String packageName, int userId) { 7922 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7923 null); 7924 PackageSetting pkgSetting; 7925 final int uid = Binder.getCallingUid(); 7926 enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId); 7927 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 7928 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 7929 } 7930 7931 long callingId = Binder.clearCallingIdentity(); 7932 try { 7933 boolean sendAdded = false; 7934 Bundle extras = new Bundle(1); 7935 7936 // writer 7937 synchronized (mPackages) { 7938 pkgSetting = mSettings.mPackages.get(packageName); 7939 if (pkgSetting == null) { 7940 return PackageManager.INSTALL_FAILED_INVALID_URI; 7941 } 7942 if (!pkgSetting.getInstalled(userId)) { 7943 pkgSetting.setInstalled(true, userId); 7944 pkgSetting.setHidden(false, userId); 7945 mSettings.writePackageRestrictionsLPr(userId); 7946 sendAdded = true; 7947 } 7948 } 7949 7950 if (sendAdded) { 7951 sendPackageAddedForUser(packageName, pkgSetting, userId); 7952 } 7953 } finally { 7954 Binder.restoreCallingIdentity(callingId); 7955 } 7956 7957 return PackageManager.INSTALL_SUCCEEDED; 7958 } 7959 7960 boolean isUserRestricted(int userId, String restrictionKey) { 7961 Bundle restrictions = sUserManager.getUserRestrictions(userId); 7962 if (restrictions.getBoolean(restrictionKey, false)) { 7963 Log.w(TAG, "User is restricted: " + restrictionKey); 7964 return true; 7965 } 7966 return false; 7967 } 7968 7969 @Override 7970 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 7971 mContext.enforceCallingOrSelfPermission( 7972 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7973 "Only package verification agents can verify applications"); 7974 7975 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7976 final PackageVerificationResponse response = new PackageVerificationResponse( 7977 verificationCode, Binder.getCallingUid()); 7978 msg.arg1 = id; 7979 msg.obj = response; 7980 mHandler.sendMessage(msg); 7981 } 7982 7983 @Override 7984 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 7985 long millisecondsToDelay) { 7986 mContext.enforceCallingOrSelfPermission( 7987 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7988 "Only package verification agents can extend verification timeouts"); 7989 7990 final PackageVerificationState state = mPendingVerification.get(id); 7991 final PackageVerificationResponse response = new PackageVerificationResponse( 7992 verificationCodeAtTimeout, Binder.getCallingUid()); 7993 7994 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 7995 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 7996 } 7997 if (millisecondsToDelay < 0) { 7998 millisecondsToDelay = 0; 7999 } 8000 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 8001 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 8002 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 8003 } 8004 8005 if ((state != null) && !state.timeoutExtended()) { 8006 state.extendTimeout(); 8007 8008 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8009 msg.arg1 = id; 8010 msg.obj = response; 8011 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 8012 } 8013 } 8014 8015 private void broadcastPackageVerified(int verificationId, Uri packageUri, 8016 int verificationCode, UserHandle user) { 8017 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 8018 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 8019 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8020 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8021 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 8022 8023 mContext.sendBroadcastAsUser(intent, user, 8024 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 8025 } 8026 8027 private ComponentName matchComponentForVerifier(String packageName, 8028 List<ResolveInfo> receivers) { 8029 ActivityInfo targetReceiver = null; 8030 8031 final int NR = receivers.size(); 8032 for (int i = 0; i < NR; i++) { 8033 final ResolveInfo info = receivers.get(i); 8034 if (info.activityInfo == null) { 8035 continue; 8036 } 8037 8038 if (packageName.equals(info.activityInfo.packageName)) { 8039 targetReceiver = info.activityInfo; 8040 break; 8041 } 8042 } 8043 8044 if (targetReceiver == null) { 8045 return null; 8046 } 8047 8048 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8049 } 8050 8051 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8052 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8053 if (pkgInfo.verifiers.length == 0) { 8054 return null; 8055 } 8056 8057 final int N = pkgInfo.verifiers.length; 8058 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8059 for (int i = 0; i < N; i++) { 8060 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8061 8062 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8063 receivers); 8064 if (comp == null) { 8065 continue; 8066 } 8067 8068 final int verifierUid = getUidForVerifier(verifierInfo); 8069 if (verifierUid == -1) { 8070 continue; 8071 } 8072 8073 if (DEBUG_VERIFY) { 8074 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8075 + " with the correct signature"); 8076 } 8077 sufficientVerifiers.add(comp); 8078 verificationState.addSufficientVerifier(verifierUid); 8079 } 8080 8081 return sufficientVerifiers; 8082 } 8083 8084 private int getUidForVerifier(VerifierInfo verifierInfo) { 8085 synchronized (mPackages) { 8086 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8087 if (pkg == null) { 8088 return -1; 8089 } else if (pkg.mSignatures.length != 1) { 8090 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8091 + " has more than one signature; ignoring"); 8092 return -1; 8093 } 8094 8095 /* 8096 * If the public key of the package's signature does not match 8097 * our expected public key, then this is a different package and 8098 * we should skip. 8099 */ 8100 8101 final byte[] expectedPublicKey; 8102 try { 8103 final Signature verifierSig = pkg.mSignatures[0]; 8104 final PublicKey publicKey = verifierSig.getPublicKey(); 8105 expectedPublicKey = publicKey.getEncoded(); 8106 } catch (CertificateException e) { 8107 return -1; 8108 } 8109 8110 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8111 8112 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8113 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8114 + " does not have the expected public key; ignoring"); 8115 return -1; 8116 } 8117 8118 return pkg.applicationInfo.uid; 8119 } 8120 } 8121 8122 @Override 8123 public void finishPackageInstall(int token) { 8124 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8125 8126 if (DEBUG_INSTALL) { 8127 Slog.v(TAG, "BM finishing package install for " + token); 8128 } 8129 8130 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8131 mHandler.sendMessage(msg); 8132 } 8133 8134 /** 8135 * Get the verification agent timeout. 8136 * 8137 * @return verification timeout in milliseconds 8138 */ 8139 private long getVerificationTimeout() { 8140 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8141 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8142 DEFAULT_VERIFICATION_TIMEOUT); 8143 } 8144 8145 /** 8146 * Get the default verification agent response code. 8147 * 8148 * @return default verification response code 8149 */ 8150 private int getDefaultVerificationResponse() { 8151 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8152 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8153 DEFAULT_VERIFICATION_RESPONSE); 8154 } 8155 8156 /** 8157 * Check whether or not package verification has been enabled. 8158 * 8159 * @return true if verification should be performed 8160 */ 8161 private boolean isVerificationEnabled(int userId, int flags) { 8162 if (!DEFAULT_VERIFY_ENABLE) { 8163 return false; 8164 } 8165 8166 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 8167 8168 // Check if installing from ADB 8169 if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) { 8170 // Do not run verification in a test harness environment 8171 if (ActivityManager.isRunningInTestHarness()) { 8172 return false; 8173 } 8174 if (ensureVerifyAppsEnabled) { 8175 return true; 8176 } 8177 // Check if the developer does not want package verification for ADB installs 8178 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8179 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8180 return false; 8181 } 8182 } 8183 8184 if (ensureVerifyAppsEnabled) { 8185 return true; 8186 } 8187 8188 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8189 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8190 } 8191 8192 /** 8193 * Get the "allow unknown sources" setting. 8194 * 8195 * @return the current "allow unknown sources" setting 8196 */ 8197 private int getUnknownSourcesSettings() { 8198 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8199 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 8200 -1); 8201 } 8202 8203 @Override 8204 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 8205 final int uid = Binder.getCallingUid(); 8206 // writer 8207 synchronized (mPackages) { 8208 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 8209 if (targetPackageSetting == null) { 8210 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 8211 } 8212 8213 PackageSetting installerPackageSetting; 8214 if (installerPackageName != null) { 8215 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 8216 if (installerPackageSetting == null) { 8217 throw new IllegalArgumentException("Unknown installer package: " 8218 + installerPackageName); 8219 } 8220 } else { 8221 installerPackageSetting = null; 8222 } 8223 8224 Signature[] callerSignature; 8225 Object obj = mSettings.getUserIdLPr(uid); 8226 if (obj != null) { 8227 if (obj instanceof SharedUserSetting) { 8228 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 8229 } else if (obj instanceof PackageSetting) { 8230 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 8231 } else { 8232 throw new SecurityException("Bad object " + obj + " for uid " + uid); 8233 } 8234 } else { 8235 throw new SecurityException("Unknown calling uid " + uid); 8236 } 8237 8238 // Verify: can't set installerPackageName to a package that is 8239 // not signed with the same cert as the caller. 8240 if (installerPackageSetting != null) { 8241 if (compareSignatures(callerSignature, 8242 installerPackageSetting.signatures.mSignatures) 8243 != PackageManager.SIGNATURE_MATCH) { 8244 throw new SecurityException( 8245 "Caller does not have same cert as new installer package " 8246 + installerPackageName); 8247 } 8248 } 8249 8250 // Verify: if target already has an installer package, it must 8251 // be signed with the same cert as the caller. 8252 if (targetPackageSetting.installerPackageName != null) { 8253 PackageSetting setting = mSettings.mPackages.get( 8254 targetPackageSetting.installerPackageName); 8255 // If the currently set package isn't valid, then it's always 8256 // okay to change it. 8257 if (setting != null) { 8258 if (compareSignatures(callerSignature, 8259 setting.signatures.mSignatures) 8260 != PackageManager.SIGNATURE_MATCH) { 8261 throw new SecurityException( 8262 "Caller does not have same cert as old installer package " 8263 + targetPackageSetting.installerPackageName); 8264 } 8265 } 8266 } 8267 8268 // Okay! 8269 targetPackageSetting.installerPackageName = installerPackageName; 8270 scheduleWriteSettingsLocked(); 8271 } 8272 } 8273 8274 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 8275 // Queue up an async operation since the package installation may take a little while. 8276 mHandler.post(new Runnable() { 8277 public void run() { 8278 mHandler.removeCallbacks(this); 8279 // Result object to be returned 8280 PackageInstalledInfo res = new PackageInstalledInfo(); 8281 res.returnCode = currentStatus; 8282 res.uid = -1; 8283 res.pkg = null; 8284 res.removedInfo = new PackageRemovedInfo(); 8285 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 8286 args.doPreInstall(res.returnCode); 8287 synchronized (mInstallLock) { 8288 installPackageLI(args, true, res); 8289 } 8290 args.doPostInstall(res.returnCode, res.uid); 8291 } 8292 8293 // A restore should be performed at this point if (a) the install 8294 // succeeded, (b) the operation is not an update, and (c) the new 8295 // package has not opted out of backup participation. 8296 final boolean update = res.removedInfo.removedPackage != null; 8297 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 8298 boolean doRestore = !update 8299 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 8300 8301 // Set up the post-install work request bookkeeping. This will be used 8302 // and cleaned up by the post-install event handling regardless of whether 8303 // there's a restore pass performed. Token values are >= 1. 8304 int token; 8305 if (mNextInstallToken < 0) mNextInstallToken = 1; 8306 token = mNextInstallToken++; 8307 8308 PostInstallData data = new PostInstallData(args, res); 8309 mRunningInstalls.put(token, data); 8310 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 8311 8312 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 8313 // Pass responsibility to the Backup Manager. It will perform a 8314 // restore if appropriate, then pass responsibility back to the 8315 // Package Manager to run the post-install observer callbacks 8316 // and broadcasts. 8317 IBackupManager bm = IBackupManager.Stub.asInterface( 8318 ServiceManager.getService(Context.BACKUP_SERVICE)); 8319 if (bm != null) { 8320 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 8321 + " to BM for possible restore"); 8322 try { 8323 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 8324 } catch (RemoteException e) { 8325 // can't happen; the backup manager is local 8326 } catch (Exception e) { 8327 Slog.e(TAG, "Exception trying to enqueue restore", e); 8328 doRestore = false; 8329 } 8330 } else { 8331 Slog.e(TAG, "Backup Manager not found!"); 8332 doRestore = false; 8333 } 8334 } 8335 8336 if (!doRestore) { 8337 // No restore possible, or the Backup Manager was mysteriously not 8338 // available -- just fire the post-install work request directly. 8339 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 8340 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8341 mHandler.sendMessage(msg); 8342 } 8343 } 8344 }); 8345 } 8346 8347 private abstract class HandlerParams { 8348 private static final int MAX_RETRIES = 4; 8349 8350 /** 8351 * Number of times startCopy() has been attempted and had a non-fatal 8352 * error. 8353 */ 8354 private int mRetries = 0; 8355 8356 /** User handle for the user requesting the information or installation. */ 8357 private final UserHandle mUser; 8358 8359 HandlerParams(UserHandle user) { 8360 mUser = user; 8361 } 8362 8363 UserHandle getUser() { 8364 return mUser; 8365 } 8366 8367 final boolean startCopy() { 8368 boolean res; 8369 try { 8370 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 8371 8372 if (++mRetries > MAX_RETRIES) { 8373 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 8374 mHandler.sendEmptyMessage(MCS_GIVE_UP); 8375 handleServiceError(); 8376 return false; 8377 } else { 8378 handleStartCopy(); 8379 res = true; 8380 } 8381 } catch (RemoteException e) { 8382 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 8383 mHandler.sendEmptyMessage(MCS_RECONNECT); 8384 res = false; 8385 } 8386 handleReturnCode(); 8387 return res; 8388 } 8389 8390 final void serviceError() { 8391 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 8392 handleServiceError(); 8393 handleReturnCode(); 8394 } 8395 8396 abstract void handleStartCopy() throws RemoteException; 8397 abstract void handleServiceError(); 8398 abstract void handleReturnCode(); 8399 } 8400 8401 class MeasureParams extends HandlerParams { 8402 private final PackageStats mStats; 8403 private boolean mSuccess; 8404 8405 private final IPackageStatsObserver mObserver; 8406 8407 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 8408 super(new UserHandle(stats.userHandle)); 8409 mObserver = observer; 8410 mStats = stats; 8411 } 8412 8413 @Override 8414 public String toString() { 8415 return "MeasureParams{" 8416 + Integer.toHexString(System.identityHashCode(this)) 8417 + " " + mStats.packageName + "}"; 8418 } 8419 8420 @Override 8421 void handleStartCopy() throws RemoteException { 8422 synchronized (mInstallLock) { 8423 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 8424 } 8425 8426 if (mSuccess) { 8427 final boolean mounted; 8428 if (Environment.isExternalStorageEmulated()) { 8429 mounted = true; 8430 } else { 8431 final String status = Environment.getExternalStorageState(); 8432 mounted = (Environment.MEDIA_MOUNTED.equals(status) 8433 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 8434 } 8435 8436 if (mounted) { 8437 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 8438 8439 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 8440 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 8441 8442 mStats.externalDataSize = calculateDirectorySize(mContainerService, 8443 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 8444 8445 // Always subtract cache size, since it's a subdirectory 8446 mStats.externalDataSize -= mStats.externalCacheSize; 8447 8448 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 8449 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 8450 8451 mStats.externalObbSize = calculateDirectorySize(mContainerService, 8452 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 8453 } 8454 } 8455 } 8456 8457 @Override 8458 void handleReturnCode() { 8459 if (mObserver != null) { 8460 try { 8461 mObserver.onGetStatsCompleted(mStats, mSuccess); 8462 } catch (RemoteException e) { 8463 Slog.i(TAG, "Observer no longer exists."); 8464 } 8465 } 8466 } 8467 8468 @Override 8469 void handleServiceError() { 8470 Slog.e(TAG, "Could not measure application " + mStats.packageName 8471 + " external storage"); 8472 } 8473 } 8474 8475 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 8476 throws RemoteException { 8477 long result = 0; 8478 for (File path : paths) { 8479 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 8480 } 8481 return result; 8482 } 8483 8484 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 8485 for (File path : paths) { 8486 try { 8487 mcs.clearDirectory(path.getAbsolutePath()); 8488 } catch (RemoteException e) { 8489 } 8490 } 8491 } 8492 8493 static class OriginInfo { 8494 /** 8495 * Location where install is coming from, before it has been 8496 * copied/renamed into place. This could be a single monolithic APK 8497 * file, or a cluster directory. This location may be untrusted. 8498 */ 8499 final File file; 8500 final String cid; 8501 8502 /** 8503 * Flag indicating that {@link #file} or {@link #cid} has already been 8504 * staged, meaning downstream users don't need to defensively copy the 8505 * contents. 8506 */ 8507 final boolean staged; 8508 8509 final String resolvedPath; 8510 final File resolvedFile; 8511 8512 public OriginInfo(File file, String cid, boolean staged) { 8513 this.file = file; 8514 this.cid = cid; 8515 this.staged = staged; 8516 8517 if (cid != null) { 8518 resolvedPath = PackageHelper.getSdDir(cid); 8519 resolvedFile = new File(resolvedPath); 8520 } else if (file != null) { 8521 resolvedPath = file.getAbsolutePath(); 8522 resolvedFile = file; 8523 } else { 8524 resolvedPath = null; 8525 resolvedFile = null; 8526 } 8527 } 8528 } 8529 8530 class InstallParams extends HandlerParams { 8531 final OriginInfo origin; 8532 final IPackageInstallObserver2 observer; 8533 int flags; 8534 final String installerPackageName; 8535 final VerificationParams verificationParams; 8536 private InstallArgs mArgs; 8537 private int mRet; 8538 final String packageAbiOverride; 8539 8540 InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int flags, 8541 String installerPackageName, VerificationParams verificationParams, UserHandle user, 8542 String packageAbiOverride) { 8543 super(user); 8544 this.origin = origin; 8545 this.observer = observer; 8546 this.flags = flags; 8547 this.installerPackageName = installerPackageName; 8548 this.verificationParams = verificationParams; 8549 this.packageAbiOverride = packageAbiOverride; 8550 } 8551 8552 @Override 8553 public String toString() { 8554 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 8555 + " file=" + origin.file + " cid=" + origin.cid + "}"; 8556 } 8557 8558 public ManifestDigest getManifestDigest() { 8559 if (verificationParams == null) { 8560 return null; 8561 } 8562 return verificationParams.getManifestDigest(); 8563 } 8564 8565 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) { 8566 String packageName = pkgLite.packageName; 8567 int installLocation = pkgLite.installLocation; 8568 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8569 // reader 8570 synchronized (mPackages) { 8571 PackageParser.Package pkg = mPackages.get(packageName); 8572 if (pkg != null) { 8573 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 8574 // Check for downgrading. 8575 if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 8576 if (pkgLite.versionCode < pkg.mVersionCode) { 8577 Slog.w(TAG, "Can't install update of " + packageName 8578 + " update version " + pkgLite.versionCode 8579 + " is older than installed version " 8580 + pkg.mVersionCode); 8581 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 8582 } 8583 } 8584 // Check for updated system application. 8585 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8586 if (onSd) { 8587 Slog.w(TAG, "Cannot install update to system app on sdcard"); 8588 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 8589 } 8590 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8591 } else { 8592 if (onSd) { 8593 // Install flag overrides everything. 8594 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8595 } 8596 // If current upgrade specifies particular preference 8597 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 8598 // Application explicitly specified internal. 8599 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8600 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 8601 // App explictly prefers external. Let policy decide 8602 } else { 8603 // Prefer previous location 8604 if (isExternal(pkg)) { 8605 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8606 } 8607 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8608 } 8609 } 8610 } else { 8611 // Invalid install. Return error code 8612 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 8613 } 8614 } 8615 } 8616 // All the special cases have been taken care of. 8617 // Return result based on recommended install location. 8618 if (onSd) { 8619 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8620 } 8621 return pkgLite.recommendedInstallLocation; 8622 } 8623 8624 /* 8625 * Invoke remote method to get package information and install 8626 * location values. Override install location based on default 8627 * policy if needed and then create install arguments based 8628 * on the install location. 8629 */ 8630 public void handleStartCopy() throws RemoteException { 8631 int ret = PackageManager.INSTALL_SUCCEEDED; 8632 8633 // If we're already staged, we've firmly committed to an install location 8634 if (origin.staged) { 8635 if (origin.file != null) { 8636 flags |= PackageManager.INSTALL_INTERNAL; 8637 flags &= ~PackageManager.INSTALL_EXTERNAL; 8638 } else if (origin.cid != null) { 8639 flags |= PackageManager.INSTALL_EXTERNAL; 8640 flags &= ~PackageManager.INSTALL_INTERNAL; 8641 } else { 8642 throw new IllegalStateException("Invalid stage location"); 8643 } 8644 } 8645 8646 final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8647 final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0; 8648 8649 PackageInfoLite pkgLite = null; 8650 8651 if (onInt && onSd) { 8652 // Check if both bits are set. 8653 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 8654 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8655 } else { 8656 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, flags, 8657 packageAbiOverride); 8658 8659 /* 8660 * If we have too little free space, try to free cache 8661 * before giving up. 8662 */ 8663 if (!origin.staged && pkgLite.recommendedInstallLocation 8664 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8665 // TODO: focus freeing disk space on the target device 8666 final StorageManager storage = StorageManager.from(mContext); 8667 final long lowThreshold = storage.getStorageLowBytes( 8668 Environment.getDataDirectory()); 8669 8670 final long sizeBytes = mContainerService.calculateInstalledSize( 8671 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 8672 8673 if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) { 8674 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 8675 flags, packageAbiOverride); 8676 } 8677 8678 /* 8679 * The cache free must have deleted the file we 8680 * downloaded to install. 8681 * 8682 * TODO: fix the "freeCache" call to not delete 8683 * the file we care about. 8684 */ 8685 if (pkgLite.recommendedInstallLocation 8686 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8687 pkgLite.recommendedInstallLocation 8688 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 8689 } 8690 } 8691 } 8692 8693 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8694 int loc = pkgLite.recommendedInstallLocation; 8695 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 8696 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8697 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 8698 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 8699 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8700 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8701 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 8702 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 8703 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8704 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 8705 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 8706 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 8707 } else { 8708 // Override with defaults if needed. 8709 loc = installLocationPolicy(pkgLite, flags); 8710 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 8711 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 8712 } else if (!onSd && !onInt) { 8713 // Override install location with flags 8714 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 8715 // Set the flag to install on external media. 8716 flags |= PackageManager.INSTALL_EXTERNAL; 8717 flags &= ~PackageManager.INSTALL_INTERNAL; 8718 } else { 8719 // Make sure the flag for installing on external 8720 // media is unset 8721 flags |= PackageManager.INSTALL_INTERNAL; 8722 flags &= ~PackageManager.INSTALL_EXTERNAL; 8723 } 8724 } 8725 } 8726 } 8727 8728 final InstallArgs args = createInstallArgs(this); 8729 mArgs = args; 8730 8731 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8732 /* 8733 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 8734 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 8735 */ 8736 int userIdentifier = getUser().getIdentifier(); 8737 if (userIdentifier == UserHandle.USER_ALL 8738 && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) { 8739 userIdentifier = UserHandle.USER_OWNER; 8740 } 8741 8742 /* 8743 * Determine if we have any installed package verifiers. If we 8744 * do, then we'll defer to them to verify the packages. 8745 */ 8746 final int requiredUid = mRequiredVerifierPackage == null ? -1 8747 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 8748 if (requiredUid != -1 && isVerificationEnabled(userIdentifier, flags)) { 8749 final Intent verification = new Intent( 8750 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 8751 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 8752 PACKAGE_MIME_TYPE); 8753 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8754 8755 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 8756 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 8757 0 /* TODO: Which userId? */); 8758 8759 if (DEBUG_VERIFY) { 8760 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 8761 + verification.toString() + " with " + pkgLite.verifiers.length 8762 + " optional verifiers"); 8763 } 8764 8765 final int verificationId = mPendingVerificationToken++; 8766 8767 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8768 8769 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 8770 installerPackageName); 8771 8772 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags); 8773 8774 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 8775 pkgLite.packageName); 8776 8777 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 8778 pkgLite.versionCode); 8779 8780 if (verificationParams != null) { 8781 if (verificationParams.getVerificationURI() != null) { 8782 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 8783 verificationParams.getVerificationURI()); 8784 } 8785 if (verificationParams.getOriginatingURI() != null) { 8786 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 8787 verificationParams.getOriginatingURI()); 8788 } 8789 if (verificationParams.getReferrer() != null) { 8790 verification.putExtra(Intent.EXTRA_REFERRER, 8791 verificationParams.getReferrer()); 8792 } 8793 if (verificationParams.getOriginatingUid() >= 0) { 8794 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 8795 verificationParams.getOriginatingUid()); 8796 } 8797 if (verificationParams.getInstallerUid() >= 0) { 8798 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 8799 verificationParams.getInstallerUid()); 8800 } 8801 } 8802 8803 final PackageVerificationState verificationState = new PackageVerificationState( 8804 requiredUid, args); 8805 8806 mPendingVerification.append(verificationId, verificationState); 8807 8808 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 8809 receivers, verificationState); 8810 8811 /* 8812 * If any sufficient verifiers were listed in the package 8813 * manifest, attempt to ask them. 8814 */ 8815 if (sufficientVerifiers != null) { 8816 final int N = sufficientVerifiers.size(); 8817 if (N == 0) { 8818 Slog.i(TAG, "Additional verifiers required, but none installed."); 8819 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 8820 } else { 8821 for (int i = 0; i < N; i++) { 8822 final ComponentName verifierComponent = sufficientVerifiers.get(i); 8823 8824 final Intent sufficientIntent = new Intent(verification); 8825 sufficientIntent.setComponent(verifierComponent); 8826 8827 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 8828 } 8829 } 8830 } 8831 8832 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 8833 mRequiredVerifierPackage, receivers); 8834 if (ret == PackageManager.INSTALL_SUCCEEDED 8835 && mRequiredVerifierPackage != null) { 8836 /* 8837 * Send the intent to the required verification agent, 8838 * but only start the verification timeout after the 8839 * target BroadcastReceivers have run. 8840 */ 8841 verification.setComponent(requiredVerifierComponent); 8842 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 8843 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8844 new BroadcastReceiver() { 8845 @Override 8846 public void onReceive(Context context, Intent intent) { 8847 final Message msg = mHandler 8848 .obtainMessage(CHECK_PENDING_VERIFICATION); 8849 msg.arg1 = verificationId; 8850 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 8851 } 8852 }, null, 0, null, null); 8853 8854 /* 8855 * We don't want the copy to proceed until verification 8856 * succeeds, so null out this field. 8857 */ 8858 mArgs = null; 8859 } 8860 } else { 8861 /* 8862 * No package verification is enabled, so immediately start 8863 * the remote call to initiate copy using temporary file. 8864 */ 8865 ret = args.copyApk(mContainerService, true); 8866 } 8867 } 8868 8869 mRet = ret; 8870 } 8871 8872 @Override 8873 void handleReturnCode() { 8874 // If mArgs is null, then MCS couldn't be reached. When it 8875 // reconnects, it will try again to install. At that point, this 8876 // will succeed. 8877 if (mArgs != null) { 8878 processPendingInstall(mArgs, mRet); 8879 } 8880 } 8881 8882 @Override 8883 void handleServiceError() { 8884 mArgs = createInstallArgs(this); 8885 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8886 } 8887 8888 public boolean isForwardLocked() { 8889 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8890 } 8891 } 8892 8893 /* 8894 * Utility class used in movePackage api. 8895 * srcArgs and targetArgs are not set for invalid flags and make 8896 * sure to do null checks when invoking methods on them. 8897 * We probably want to return ErrorPrams for both failed installs 8898 * and moves. 8899 */ 8900 class MoveParams extends HandlerParams { 8901 final IPackageMoveObserver observer; 8902 final int flags; 8903 final String packageName; 8904 final InstallArgs srcArgs; 8905 final InstallArgs targetArgs; 8906 int uid; 8907 int mRet; 8908 8909 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags, 8910 String packageName, String[] instructionSets, int uid, UserHandle user) { 8911 super(user); 8912 this.srcArgs = srcArgs; 8913 this.observer = observer; 8914 this.flags = flags; 8915 this.packageName = packageName; 8916 this.uid = uid; 8917 if (srcArgs != null) { 8918 final String codePath = srcArgs.getCodePath(); 8919 targetArgs = createInstallArgsForMoveTarget(codePath, flags, packageName, 8920 instructionSets); 8921 } else { 8922 targetArgs = null; 8923 } 8924 } 8925 8926 @Override 8927 public String toString() { 8928 return "MoveParams{" 8929 + Integer.toHexString(System.identityHashCode(this)) 8930 + " " + packageName + "}"; 8931 } 8932 8933 public void handleStartCopy() throws RemoteException { 8934 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8935 // Check for storage space on target medium 8936 if (!targetArgs.checkFreeStorage(mContainerService)) { 8937 Log.w(TAG, "Insufficient storage to install"); 8938 return; 8939 } 8940 8941 mRet = srcArgs.doPreCopy(); 8942 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8943 return; 8944 } 8945 8946 mRet = targetArgs.copyApk(mContainerService, false); 8947 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8948 srcArgs.doPostCopy(uid); 8949 return; 8950 } 8951 8952 mRet = srcArgs.doPostCopy(uid); 8953 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8954 return; 8955 } 8956 8957 mRet = targetArgs.doPreInstall(mRet); 8958 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8959 return; 8960 } 8961 8962 if (DEBUG_SD_INSTALL) { 8963 StringBuilder builder = new StringBuilder(); 8964 if (srcArgs != null) { 8965 builder.append("src: "); 8966 builder.append(srcArgs.getCodePath()); 8967 } 8968 if (targetArgs != null) { 8969 builder.append(" target : "); 8970 builder.append(targetArgs.getCodePath()); 8971 } 8972 Log.i(TAG, builder.toString()); 8973 } 8974 } 8975 8976 @Override 8977 void handleReturnCode() { 8978 targetArgs.doPostInstall(mRet, uid); 8979 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 8980 if (mRet == PackageManager.INSTALL_SUCCEEDED) { 8981 currentStatus = PackageManager.MOVE_SUCCEEDED; 8982 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){ 8983 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 8984 } 8985 processPendingMove(this, currentStatus); 8986 } 8987 8988 @Override 8989 void handleServiceError() { 8990 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8991 } 8992 } 8993 8994 /** 8995 * Used during creation of InstallArgs 8996 * 8997 * @param flags package installation flags 8998 * @return true if should be installed on external storage 8999 */ 9000 private static boolean installOnSd(int flags) { 9001 if ((flags & PackageManager.INSTALL_INTERNAL) != 0) { 9002 return false; 9003 } 9004 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) { 9005 return true; 9006 } 9007 return false; 9008 } 9009 9010 /** 9011 * Used during creation of InstallArgs 9012 * 9013 * @param flags package installation flags 9014 * @return true if should be installed as forward locked 9015 */ 9016 private static boolean installForwardLocked(int flags) { 9017 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9018 } 9019 9020 private InstallArgs createInstallArgs(InstallParams params) { 9021 if (installOnSd(params.flags) || params.isForwardLocked()) { 9022 return new AsecInstallArgs(params); 9023 } else { 9024 return new FileInstallArgs(params); 9025 } 9026 } 9027 9028 /** 9029 * Create args that describe an existing installed package. Typically used 9030 * when cleaning up old installs, or used as a move source. 9031 */ 9032 private InstallArgs createInstallArgsForExisting(int flags, String codePath, 9033 String resourcePath, String nativeLibraryRoot, String[] instructionSets) { 9034 final boolean isInAsec; 9035 if (installOnSd(flags)) { 9036 /* Apps on SD card are always in ASEC containers. */ 9037 isInAsec = true; 9038 } else if (installForwardLocked(flags) 9039 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 9040 /* 9041 * Forward-locked apps are only in ASEC containers if they're the 9042 * new style 9043 */ 9044 isInAsec = true; 9045 } else { 9046 isInAsec = false; 9047 } 9048 9049 if (isInAsec) { 9050 return new AsecInstallArgs(codePath, instructionSets, 9051 installOnSd(flags), installForwardLocked(flags)); 9052 } else { 9053 return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot, 9054 instructionSets); 9055 } 9056 } 9057 9058 private InstallArgs createInstallArgsForMoveTarget(String codePath, int flags, String pkgName, 9059 String[] instructionSets) { 9060 final File codeFile = new File(codePath); 9061 if (installOnSd(flags) || installForwardLocked(flags)) { 9062 String cid = getNextCodePath(codePath, pkgName, "/" 9063 + AsecInstallArgs.RES_FILE_NAME); 9064 return new AsecInstallArgs(codeFile, cid, instructionSets, installOnSd(flags), 9065 installForwardLocked(flags)); 9066 } else { 9067 return new FileInstallArgs(codeFile, instructionSets); 9068 } 9069 } 9070 9071 static abstract class InstallArgs { 9072 /** @see InstallParams#origin */ 9073 final OriginInfo origin; 9074 9075 final IPackageInstallObserver2 observer; 9076 // Always refers to PackageManager flags only 9077 final int flags; 9078 final String installerPackageName; 9079 final ManifestDigest manifestDigest; 9080 final UserHandle user; 9081 final String abiOverride; 9082 9083 // The list of instruction sets supported by this app. This is currently 9084 // only used during the rmdex() phase to clean up resources. We can get rid of this 9085 // if we move dex files under the common app path. 9086 /* nullable */ String[] instructionSets; 9087 9088 InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int flags, 9089 String installerPackageName, ManifestDigest manifestDigest, UserHandle user, 9090 String[] instructionSets, String abiOverride) { 9091 this.origin = origin; 9092 this.flags = flags; 9093 this.observer = observer; 9094 this.installerPackageName = installerPackageName; 9095 this.manifestDigest = manifestDigest; 9096 this.user = user; 9097 this.instructionSets = instructionSets; 9098 this.abiOverride = abiOverride; 9099 } 9100 9101 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 9102 abstract int doPreInstall(int status); 9103 9104 /** 9105 * Rename package into final resting place. All paths on the given 9106 * scanned package should be updated to reflect the rename. 9107 */ 9108 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 9109 abstract int doPostInstall(int status, int uid); 9110 9111 /** @see PackageSettingBase#codePathString */ 9112 abstract String getCodePath(); 9113 /** @see PackageSettingBase#resourcePathString */ 9114 abstract String getResourcePath(); 9115 abstract String getLegacyNativeLibraryPath(); 9116 9117 // Need installer lock especially for dex file removal. 9118 abstract void cleanUpResourcesLI(); 9119 abstract boolean doPostDeleteLI(boolean delete); 9120 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9121 9122 /** 9123 * Called before the source arguments are copied. This is used mostly 9124 * for MoveParams when it needs to read the source file to put it in the 9125 * destination. 9126 */ 9127 int doPreCopy() { 9128 return PackageManager.INSTALL_SUCCEEDED; 9129 } 9130 9131 /** 9132 * Called after the source arguments are copied. This is used mostly for 9133 * MoveParams when it needs to read the source file to put it in the 9134 * destination. 9135 * 9136 * @return 9137 */ 9138 int doPostCopy(int uid) { 9139 return PackageManager.INSTALL_SUCCEEDED; 9140 } 9141 9142 protected boolean isFwdLocked() { 9143 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9144 } 9145 9146 UserHandle getUser() { 9147 return user; 9148 } 9149 } 9150 9151 /** 9152 * Logic to handle installation of non-ASEC applications, including copying 9153 * and renaming logic. 9154 */ 9155 class FileInstallArgs extends InstallArgs { 9156 private File codeFile; 9157 private File resourceFile; 9158 private File legacyNativeLibraryPath; 9159 9160 // Example topology: 9161 // /data/app/com.example/base.apk 9162 // /data/app/com.example/split_foo.apk 9163 // /data/app/com.example/lib/arm/libfoo.so 9164 // /data/app/com.example/lib/arm64/libfoo.so 9165 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 9166 9167 /** New install */ 9168 FileInstallArgs(InstallParams params) { 9169 super(params.origin, params.observer, params.flags, 9170 params.installerPackageName, params.getManifestDigest(), params.getUser(), 9171 null /* instruction sets */, params.packageAbiOverride); 9172 if (isFwdLocked()) { 9173 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 9174 } 9175 } 9176 9177 /** Existing install */ 9178 FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath, 9179 String[] instructionSets) { 9180 super(new OriginInfo(null, null, false), null, 0, null, null, null, instructionSets, null); 9181 this.codeFile = (codePath != null) ? new File(codePath) : null; 9182 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 9183 this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ? 9184 new File(legacyNativeLibraryPath) : null; 9185 } 9186 9187 /** New install from existing */ 9188 FileInstallArgs(File originFile, String[] instructionSets) { 9189 super(new OriginInfo(originFile, null, false), null, 0, null, null, null, instructionSets, null); 9190 } 9191 9192 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9193 final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(), 9194 isFwdLocked(), abiOverride); 9195 9196 final StorageManager storage = StorageManager.from(mContext); 9197 return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory())); 9198 } 9199 9200 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9201 if (origin.staged) { 9202 Slog.d(TAG, origin.file + " already staged; skipping copy"); 9203 codeFile = origin.file; 9204 resourceFile = origin.file; 9205 return PackageManager.INSTALL_SUCCEEDED; 9206 } 9207 9208 try { 9209 final File tempDir = mInstallerService.allocateInternalStageDirLegacy(); 9210 codeFile = tempDir; 9211 resourceFile = tempDir; 9212 } catch (IOException e) { 9213 Slog.w(TAG, "Failed to create copy file: " + e); 9214 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9215 } 9216 9217 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 9218 @Override 9219 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 9220 if (!FileUtils.isValidExtFilename(name)) { 9221 throw new IllegalArgumentException("Invalid filename: " + name); 9222 } 9223 try { 9224 final File file = new File(codeFile, name); 9225 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 9226 O_RDWR | O_CREAT, 0644); 9227 Os.chmod(file.getAbsolutePath(), 0644); 9228 return new ParcelFileDescriptor(fd); 9229 } catch (ErrnoException e) { 9230 throw new RemoteException("Failed to open: " + e.getMessage()); 9231 } 9232 } 9233 }; 9234 9235 int ret = PackageManager.INSTALL_SUCCEEDED; 9236 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 9237 if (ret != PackageManager.INSTALL_SUCCEEDED) { 9238 Slog.e(TAG, "Failed to copy package"); 9239 return ret; 9240 } 9241 9242 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 9243 NativeLibraryHelper.Handle handle = null; 9244 try { 9245 handle = NativeLibraryHelper.Handle.create(codeFile); 9246 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 9247 abiOverride); 9248 } catch (IOException e) { 9249 Slog.e(TAG, "Copying native libraries failed", e); 9250 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9251 } finally { 9252 IoUtils.closeQuietly(handle); 9253 } 9254 9255 return ret; 9256 } 9257 9258 int doPreInstall(int status) { 9259 if (status != PackageManager.INSTALL_SUCCEEDED) { 9260 cleanUp(); 9261 } 9262 return status; 9263 } 9264 9265 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9266 if (status != PackageManager.INSTALL_SUCCEEDED) { 9267 cleanUp(); 9268 return false; 9269 } else { 9270 final File beforeCodeFile = codeFile; 9271 final File afterCodeFile = getNextCodePath(pkg.packageName); 9272 9273 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 9274 try { 9275 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 9276 } catch (ErrnoException e) { 9277 Slog.d(TAG, "Failed to rename", e); 9278 return false; 9279 } 9280 9281 if (!SELinux.restoreconRecursive(afterCodeFile)) { 9282 Slog.d(TAG, "Failed to restorecon"); 9283 return false; 9284 } 9285 9286 // Reflect the rename internally 9287 codeFile = afterCodeFile; 9288 resourceFile = afterCodeFile; 9289 9290 // Reflect the rename in scanned details 9291 pkg.codePath = afterCodeFile.getAbsolutePath(); 9292 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9293 pkg.baseCodePath); 9294 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9295 pkg.splitCodePaths); 9296 9297 // Reflect the rename in app info 9298 pkg.applicationInfo.setCodePath(pkg.codePath); 9299 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9300 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9301 pkg.applicationInfo.setResourcePath(pkg.codePath); 9302 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9303 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9304 9305 return true; 9306 } 9307 } 9308 9309 int doPostInstall(int status, int uid) { 9310 if (status != PackageManager.INSTALL_SUCCEEDED) { 9311 cleanUp(); 9312 } 9313 return status; 9314 } 9315 9316 @Override 9317 String getCodePath() { 9318 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 9319 } 9320 9321 @Override 9322 String getResourcePath() { 9323 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 9324 } 9325 9326 @Override 9327 String getLegacyNativeLibraryPath() { 9328 return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null; 9329 } 9330 9331 private boolean cleanUp() { 9332 if (codeFile == null || !codeFile.exists()) { 9333 return false; 9334 } 9335 9336 if (codeFile.isDirectory()) { 9337 FileUtils.deleteContents(codeFile); 9338 } 9339 codeFile.delete(); 9340 9341 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 9342 resourceFile.delete(); 9343 } 9344 9345 if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) { 9346 if (!FileUtils.deleteContents(legacyNativeLibraryPath)) { 9347 Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath); 9348 } 9349 legacyNativeLibraryPath.delete(); 9350 } 9351 9352 return true; 9353 } 9354 9355 void cleanUpResourcesLI() { 9356 // Try enumerating all code paths before deleting 9357 List<String> allCodePaths = Collections.EMPTY_LIST; 9358 if (codeFile != null && codeFile.exists()) { 9359 try { 9360 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9361 allCodePaths = pkg.getAllCodePaths(); 9362 } catch (PackageParserException e) { 9363 // Ignored; we tried our best 9364 } 9365 } 9366 9367 cleanUp(); 9368 9369 if (!allCodePaths.isEmpty()) { 9370 if (instructionSets == null) { 9371 throw new IllegalStateException("instructionSet == null"); 9372 } 9373 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9374 for (String codePath : allCodePaths) { 9375 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9376 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9377 if (retCode < 0) { 9378 Slog.w(TAG, "Couldn't remove dex file for package: " 9379 + " at location " + codePath + ", retcode=" + retCode); 9380 // we don't consider this to be a failure of the core package deletion 9381 } 9382 } 9383 } 9384 } 9385 } 9386 9387 boolean doPostDeleteLI(boolean delete) { 9388 // XXX err, shouldn't we respect the delete flag? 9389 cleanUpResourcesLI(); 9390 return true; 9391 } 9392 } 9393 9394 private boolean isAsecExternal(String cid) { 9395 final String asecPath = PackageHelper.getSdFilesystem(cid); 9396 return !asecPath.startsWith(mAsecInternalPath); 9397 } 9398 9399 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 9400 PackageManagerException { 9401 if (copyRet < 0) { 9402 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 9403 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 9404 throw new PackageManagerException(copyRet, message); 9405 } 9406 } 9407 } 9408 9409 /** 9410 * Extract the MountService "container ID" from the full code path of an 9411 * .apk. 9412 */ 9413 static String cidFromCodePath(String fullCodePath) { 9414 int eidx = fullCodePath.lastIndexOf("/"); 9415 String subStr1 = fullCodePath.substring(0, eidx); 9416 int sidx = subStr1.lastIndexOf("/"); 9417 return subStr1.substring(sidx+1, eidx); 9418 } 9419 9420 /** 9421 * Logic to handle installation of ASEC applications, including copying and 9422 * renaming logic. 9423 */ 9424 class AsecInstallArgs extends InstallArgs { 9425 static final String RES_FILE_NAME = "pkg.apk"; 9426 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 9427 9428 String cid; 9429 String packagePath; 9430 String resourcePath; 9431 String legacyNativeLibraryDir; 9432 9433 /** New install */ 9434 AsecInstallArgs(InstallParams params) { 9435 super(params.origin, params.observer, params.flags, 9436 params.installerPackageName, params.getManifestDigest(), 9437 params.getUser(), null /* instruction sets */, 9438 params.packageAbiOverride); 9439 } 9440 9441 /** Existing install */ 9442 AsecInstallArgs(String fullCodePath, String[] instructionSets, 9443 boolean isExternal, boolean isForwardLocked) { 9444 super(new OriginInfo(null, null, false), null, (isExternal ? INSTALL_EXTERNAL : 0) 9445 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9446 instructionSets, null); 9447 // Hackily pretend we're still looking at a full code path 9448 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 9449 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 9450 } 9451 9452 // Extract cid from fullCodePath 9453 int eidx = fullCodePath.lastIndexOf("/"); 9454 String subStr1 = fullCodePath.substring(0, eidx); 9455 int sidx = subStr1.lastIndexOf("/"); 9456 cid = subStr1.substring(sidx+1, eidx); 9457 setMountPath(subStr1); 9458 } 9459 9460 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 9461 super(new OriginInfo(null, null, false), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 9462 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9463 instructionSets, null); 9464 this.cid = cid; 9465 setMountPath(PackageHelper.getSdDir(cid)); 9466 } 9467 9468 /** New install from existing */ 9469 AsecInstallArgs(File originPackageFile, String cid, String[] instructionSets, 9470 boolean isExternal, boolean isForwardLocked) { 9471 super(new OriginInfo(originPackageFile, null, false), null, (isExternal ? INSTALL_EXTERNAL : 0) 9472 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9473 instructionSets, null); 9474 this.cid = cid; 9475 } 9476 9477 void createCopyFile() { 9478 cid = mInstallerService.allocateExternalStageCidLegacy(); 9479 } 9480 9481 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9482 final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(), 9483 abiOverride); 9484 9485 final File target; 9486 if (isExternal()) { 9487 target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory(); 9488 } else { 9489 target = Environment.getDataDirectory(); 9490 } 9491 9492 final StorageManager storage = StorageManager.from(mContext); 9493 return (sizeBytes <= storage.getStorageBytesUntilLow(target)); 9494 } 9495 9496 private final boolean isExternal() { 9497 return (flags & PackageManager.INSTALL_EXTERNAL) != 0; 9498 } 9499 9500 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9501 if (origin.staged) { 9502 Slog.d(TAG, origin.cid + " already staged; skipping copy"); 9503 cid = origin.cid; 9504 setMountPath(PackageHelper.getSdDir(cid)); 9505 return PackageManager.INSTALL_SUCCEEDED; 9506 } 9507 9508 if (temp) { 9509 createCopyFile(); 9510 } else { 9511 /* 9512 * Pre-emptively destroy the container since it's destroyed if 9513 * copying fails due to it existing anyway. 9514 */ 9515 PackageHelper.destroySdDir(cid); 9516 } 9517 9518 final String newMountPath = imcs.copyPackageToContainer( 9519 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(), 9520 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 9521 9522 if (newMountPath != null) { 9523 setMountPath(newMountPath); 9524 return PackageManager.INSTALL_SUCCEEDED; 9525 } else { 9526 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9527 } 9528 } 9529 9530 @Override 9531 String getCodePath() { 9532 return packagePath; 9533 } 9534 9535 @Override 9536 String getResourcePath() { 9537 return resourcePath; 9538 } 9539 9540 @Override 9541 String getLegacyNativeLibraryPath() { 9542 return legacyNativeLibraryDir; 9543 } 9544 9545 int doPreInstall(int status) { 9546 if (status != PackageManager.INSTALL_SUCCEEDED) { 9547 // Destroy container 9548 PackageHelper.destroySdDir(cid); 9549 } else { 9550 boolean mounted = PackageHelper.isContainerMounted(cid); 9551 if (!mounted) { 9552 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 9553 Process.SYSTEM_UID); 9554 if (newMountPath != null) { 9555 setMountPath(newMountPath); 9556 } else { 9557 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9558 } 9559 } 9560 } 9561 return status; 9562 } 9563 9564 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9565 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 9566 String newMountPath = null; 9567 if (PackageHelper.isContainerMounted(cid)) { 9568 // Unmount the container 9569 if (!PackageHelper.unMountSdDir(cid)) { 9570 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9571 return false; 9572 } 9573 } 9574 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9575 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9576 " which might be stale. Will try to clean up."); 9577 // Clean up the stale container and proceed to recreate. 9578 if (!PackageHelper.destroySdDir(newCacheId)) { 9579 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9580 return false; 9581 } 9582 // Successfully cleaned up stale container. Try to rename again. 9583 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9584 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9585 + " inspite of cleaning it up."); 9586 return false; 9587 } 9588 } 9589 if (!PackageHelper.isContainerMounted(newCacheId)) { 9590 Slog.w(TAG, "Mounting container " + newCacheId); 9591 newMountPath = PackageHelper.mountSdDir(newCacheId, 9592 getEncryptKey(), Process.SYSTEM_UID); 9593 } else { 9594 newMountPath = PackageHelper.getSdDir(newCacheId); 9595 } 9596 if (newMountPath == null) { 9597 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9598 return false; 9599 } 9600 Log.i(TAG, "Succesfully renamed " + cid + 9601 " to " + newCacheId + 9602 " at new path: " + newMountPath); 9603 cid = newCacheId; 9604 9605 final File beforeCodeFile = new File(packagePath); 9606 setMountPath(newMountPath); 9607 final File afterCodeFile = new File(packagePath); 9608 9609 // Reflect the rename in scanned details 9610 pkg.codePath = afterCodeFile.getAbsolutePath(); 9611 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9612 pkg.baseCodePath); 9613 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9614 pkg.splitCodePaths); 9615 9616 // Reflect the rename in app info 9617 pkg.applicationInfo.setCodePath(pkg.codePath); 9618 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9619 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9620 pkg.applicationInfo.setResourcePath(pkg.codePath); 9621 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9622 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9623 9624 return true; 9625 } 9626 9627 private void setMountPath(String mountPath) { 9628 final File mountFile = new File(mountPath); 9629 9630 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 9631 if (monolithicFile.exists()) { 9632 packagePath = monolithicFile.getAbsolutePath(); 9633 if (isFwdLocked()) { 9634 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 9635 } else { 9636 resourcePath = packagePath; 9637 } 9638 } else { 9639 packagePath = mountFile.getAbsolutePath(); 9640 resourcePath = packagePath; 9641 } 9642 9643 legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath(); 9644 } 9645 9646 int doPostInstall(int status, int uid) { 9647 if (status != PackageManager.INSTALL_SUCCEEDED) { 9648 cleanUp(); 9649 } else { 9650 final int groupOwner; 9651 final String protectedFile; 9652 if (isFwdLocked()) { 9653 groupOwner = UserHandle.getSharedAppGid(uid); 9654 protectedFile = RES_FILE_NAME; 9655 } else { 9656 groupOwner = -1; 9657 protectedFile = null; 9658 } 9659 9660 if (uid < Process.FIRST_APPLICATION_UID 9661 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9662 Slog.e(TAG, "Failed to finalize " + cid); 9663 PackageHelper.destroySdDir(cid); 9664 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9665 } 9666 9667 boolean mounted = PackageHelper.isContainerMounted(cid); 9668 if (!mounted) { 9669 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9670 } 9671 } 9672 return status; 9673 } 9674 9675 private void cleanUp() { 9676 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9677 9678 // Destroy secure container 9679 PackageHelper.destroySdDir(cid); 9680 } 9681 9682 private List<String> getAllCodePaths() { 9683 final File codeFile = new File(getCodePath()); 9684 if (codeFile != null && codeFile.exists()) { 9685 try { 9686 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9687 return pkg.getAllCodePaths(); 9688 } catch (PackageParserException e) { 9689 // Ignored; we tried our best 9690 } 9691 } 9692 return Collections.EMPTY_LIST; 9693 } 9694 9695 void cleanUpResourcesLI() { 9696 // Enumerate all code paths before deleting 9697 cleanUpResourcesLI(getAllCodePaths()); 9698 } 9699 9700 private void cleanUpResourcesLI(List<String> allCodePaths) { 9701 cleanUp(); 9702 9703 if (!allCodePaths.isEmpty()) { 9704 if (instructionSets == null) { 9705 throw new IllegalStateException("instructionSet == null"); 9706 } 9707 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9708 for (String codePath : allCodePaths) { 9709 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9710 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9711 if (retCode < 0) { 9712 Slog.w(TAG, "Couldn't remove dex file for package: " 9713 + " at location " + codePath + ", retcode=" + retCode); 9714 // we don't consider this to be a failure of the core package deletion 9715 } 9716 } 9717 } 9718 } 9719 } 9720 9721 boolean matchContainer(String app) { 9722 if (cid.startsWith(app)) { 9723 return true; 9724 } 9725 return false; 9726 } 9727 9728 String getPackageName() { 9729 return getAsecPackageName(cid); 9730 } 9731 9732 boolean doPostDeleteLI(boolean delete) { 9733 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 9734 final List<String> allCodePaths = getAllCodePaths(); 9735 boolean mounted = PackageHelper.isContainerMounted(cid); 9736 if (mounted) { 9737 // Unmount first 9738 if (PackageHelper.unMountSdDir(cid)) { 9739 mounted = false; 9740 } 9741 } 9742 if (!mounted && delete) { 9743 cleanUpResourcesLI(allCodePaths); 9744 } 9745 return !mounted; 9746 } 9747 9748 @Override 9749 int doPreCopy() { 9750 if (isFwdLocked()) { 9751 if (!PackageHelper.fixSdPermissions(cid, 9752 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 9753 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9754 } 9755 } 9756 9757 return PackageManager.INSTALL_SUCCEEDED; 9758 } 9759 9760 @Override 9761 int doPostCopy(int uid) { 9762 if (isFwdLocked()) { 9763 if (uid < Process.FIRST_APPLICATION_UID 9764 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 9765 RES_FILE_NAME)) { 9766 Slog.e(TAG, "Failed to finalize " + cid); 9767 PackageHelper.destroySdDir(cid); 9768 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9769 } 9770 } 9771 9772 return PackageManager.INSTALL_SUCCEEDED; 9773 } 9774 } 9775 9776 static String getAsecPackageName(String packageCid) { 9777 int idx = packageCid.lastIndexOf("-"); 9778 if (idx == -1) { 9779 return packageCid; 9780 } 9781 return packageCid.substring(0, idx); 9782 } 9783 9784 // Utility method used to create code paths based on package name and available index. 9785 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 9786 String idxStr = ""; 9787 int idx = 1; 9788 // Fall back to default value of idx=1 if prefix is not 9789 // part of oldCodePath 9790 if (oldCodePath != null) { 9791 String subStr = oldCodePath; 9792 // Drop the suffix right away 9793 if (suffix != null && subStr.endsWith(suffix)) { 9794 subStr = subStr.substring(0, subStr.length() - suffix.length()); 9795 } 9796 // If oldCodePath already contains prefix find out the 9797 // ending index to either increment or decrement. 9798 int sidx = subStr.lastIndexOf(prefix); 9799 if (sidx != -1) { 9800 subStr = subStr.substring(sidx + prefix.length()); 9801 if (subStr != null) { 9802 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 9803 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 9804 } 9805 try { 9806 idx = Integer.parseInt(subStr); 9807 if (idx <= 1) { 9808 idx++; 9809 } else { 9810 idx--; 9811 } 9812 } catch(NumberFormatException e) { 9813 } 9814 } 9815 } 9816 } 9817 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 9818 return prefix + idxStr; 9819 } 9820 9821 private File getNextCodePath(String packageName) { 9822 int suffix = 1; 9823 File result; 9824 do { 9825 result = new File(mAppInstallDir, packageName + "-" + suffix); 9826 suffix++; 9827 } while (result.exists()); 9828 return result; 9829 } 9830 9831 // Utility method used to ignore ADD/REMOVE events 9832 // by directory observer. 9833 private static boolean ignoreCodePath(String fullPathStr) { 9834 String apkName = deriveCodePathName(fullPathStr); 9835 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 9836 if (idx != -1 && ((idx+1) < apkName.length())) { 9837 // Make sure the package ends with a numeral 9838 String version = apkName.substring(idx+1); 9839 try { 9840 Integer.parseInt(version); 9841 return true; 9842 } catch (NumberFormatException e) {} 9843 } 9844 return false; 9845 } 9846 9847 // Utility method that returns the relative package path with respect 9848 // to the installation directory. Like say for /data/data/com.test-1.apk 9849 // string com.test-1 is returned. 9850 static String deriveCodePathName(String codePath) { 9851 if (codePath == null) { 9852 return null; 9853 } 9854 final File codeFile = new File(codePath); 9855 final String name = codeFile.getName(); 9856 if (codeFile.isDirectory()) { 9857 return name; 9858 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 9859 final int lastDot = name.lastIndexOf('.'); 9860 return name.substring(0, lastDot); 9861 } else { 9862 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 9863 return null; 9864 } 9865 } 9866 9867 class PackageInstalledInfo { 9868 String name; 9869 int uid; 9870 // The set of users that originally had this package installed. 9871 int[] origUsers; 9872 // The set of users that now have this package installed. 9873 int[] newUsers; 9874 PackageParser.Package pkg; 9875 int returnCode; 9876 String returnMsg; 9877 PackageRemovedInfo removedInfo; 9878 9879 public void setError(int code, String msg) { 9880 returnCode = code; 9881 returnMsg = msg; 9882 Slog.w(TAG, msg); 9883 } 9884 9885 public void setError(String msg, PackageParserException e) { 9886 returnCode = e.error; 9887 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9888 Slog.w(TAG, msg, e); 9889 } 9890 9891 public void setError(String msg, PackageManagerException e) { 9892 returnCode = e.error; 9893 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9894 Slog.w(TAG, msg, e); 9895 } 9896 9897 // In some error cases we want to convey more info back to the observer 9898 String origPackage; 9899 String origPermission; 9900 } 9901 9902 /* 9903 * Install a non-existing package. 9904 */ 9905 private void installNewPackageLI(PackageParser.Package pkg, 9906 int parseFlags, int scanMode, UserHandle user, 9907 String installerPackageName, PackageInstalledInfo res) { 9908 // Remember this for later, in case we need to rollback this install 9909 String pkgName = pkg.packageName; 9910 9911 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 9912 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 9913 synchronized(mPackages) { 9914 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 9915 // A package with the same name is already installed, though 9916 // it has been renamed to an older name. The package we 9917 // are trying to install should be installed as an update to 9918 // the existing one, but that has not been requested, so bail. 9919 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9920 + " without first uninstalling package running as " 9921 + mSettings.mRenamedPackages.get(pkgName)); 9922 return; 9923 } 9924 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.codePath)) { 9925 // Don't allow installation over an existing package with the same name. 9926 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9927 + " without first uninstalling."); 9928 return; 9929 } 9930 } 9931 9932 try { 9933 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode, 9934 System.currentTimeMillis(), user); 9935 9936 updateSettingsLI(newPackage, installerPackageName, null, null, res); 9937 // delete the partially installed application. the data directory will have to be 9938 // restored if it was already existing 9939 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9940 // remove package from internal structures. Note that we want deletePackageX to 9941 // delete the package data and cache directories that it created in 9942 // scanPackageLocked, unless those directories existed before we even tried to 9943 // install. 9944 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 9945 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 9946 res.removedInfo, true); 9947 } 9948 9949 } catch (PackageManagerException e) { 9950 res.setError("Package couldn't be installed in " + pkg.codePath, e); 9951 } 9952 } 9953 9954 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 9955 // Upgrade keysets are being used. Determine if new package has a superset of the 9956 // required keys. 9957 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 9958 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9959 for (int i = 0; i < upgradeKeySets.length; i++) { 9960 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 9961 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 9962 return true; 9963 } 9964 } 9965 return false; 9966 } 9967 9968 private void replacePackageLI(PackageParser.Package pkg, 9969 int parseFlags, int scanMode, UserHandle user, 9970 String installerPackageName, PackageInstalledInfo res) { 9971 PackageParser.Package oldPackage; 9972 String pkgName = pkg.packageName; 9973 int[] allUsers; 9974 boolean[] perUserInstalled; 9975 9976 // First find the old package info and check signatures 9977 synchronized(mPackages) { 9978 oldPackage = mPackages.get(pkgName); 9979 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 9980 PackageSetting ps = mSettings.mPackages.get(pkgName); 9981 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 9982 // default to original signature matching 9983 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 9984 != PackageManager.SIGNATURE_MATCH) { 9985 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9986 "New package has a different signature: " + pkgName); 9987 return; 9988 } 9989 } else { 9990 if(!checkUpgradeKeySetLP(ps, pkg)) { 9991 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9992 "New package not signed by keys specified by upgrade-keysets: " 9993 + pkgName); 9994 return; 9995 } 9996 } 9997 9998 // In case of rollback, remember per-user/profile install state 9999 allUsers = sUserManager.getUserIds(); 10000 perUserInstalled = new boolean[allUsers.length]; 10001 for (int i = 0; i < allUsers.length; i++) { 10002 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10003 } 10004 } 10005 10006 boolean sysPkg = (isSystemApp(oldPackage)); 10007 if (sysPkg) { 10008 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 10009 user, allUsers, perUserInstalled, installerPackageName, res); 10010 } else { 10011 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 10012 user, allUsers, perUserInstalled, installerPackageName, res); 10013 } 10014 } 10015 10016 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 10017 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 10018 int[] allUsers, boolean[] perUserInstalled, 10019 String installerPackageName, PackageInstalledInfo res) { 10020 String pkgName = deletedPackage.packageName; 10021 boolean deletedPkg = true; 10022 boolean updatedSettings = false; 10023 10024 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 10025 + deletedPackage); 10026 long origUpdateTime; 10027 if (pkg.mExtras != null) { 10028 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 10029 } else { 10030 origUpdateTime = 0; 10031 } 10032 10033 // First delete the existing package while retaining the data directory 10034 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 10035 res.removedInfo, true)) { 10036 // If the existing package wasn't successfully deleted 10037 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 10038 deletedPkg = false; 10039 } else { 10040 // Successfully deleted the old package. Now proceed with re-installation 10041 deleteCodeCacheDirsLI(pkgName); 10042 try { 10043 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 10044 scanMode | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 10045 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10046 updatedSettings = true; 10047 } catch (PackageManagerException e) { 10048 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10049 } 10050 } 10051 10052 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10053 // remove package from internal structures. Note that we want deletePackageX to 10054 // delete the package data and cache directories that it created in 10055 // scanPackageLocked, unless those directories existed before we even tried to 10056 // install. 10057 if(updatedSettings) { 10058 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 10059 deletePackageLI( 10060 pkgName, null, true, allUsers, perUserInstalled, 10061 PackageManager.DELETE_KEEP_DATA, 10062 res.removedInfo, true); 10063 } 10064 // Since we failed to install the new package we need to restore the old 10065 // package that we deleted. 10066 if (deletedPkg) { 10067 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 10068 File restoreFile = new File(deletedPackage.codePath); 10069 // Parse old package 10070 boolean oldOnSd = isExternal(deletedPackage); 10071 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 10072 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) | 10073 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 10074 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE 10075 | SCAN_UPDATE_TIME; 10076 try { 10077 scanPackageLI(restoreFile, oldParseFlags, oldScanMode, origUpdateTime, null); 10078 } catch (PackageManagerException e) { 10079 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 10080 + e.getMessage()); 10081 return; 10082 } 10083 // Restore of old package succeeded. Update permissions. 10084 // writer 10085 synchronized (mPackages) { 10086 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 10087 UPDATE_PERMISSIONS_ALL); 10088 // can downgrade to reader 10089 mSettings.writeLPr(); 10090 } 10091 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 10092 } 10093 } 10094 } 10095 10096 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 10097 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 10098 int[] allUsers, boolean[] perUserInstalled, 10099 String installerPackageName, PackageInstalledInfo res) { 10100 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 10101 + ", old=" + deletedPackage); 10102 boolean updatedSettings = false; 10103 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING | 10104 PackageParser.PARSE_IS_SYSTEM; 10105 if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) { 10106 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10107 } 10108 String packageName = deletedPackage.packageName; 10109 if (packageName == null) { 10110 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10111 "Attempt to delete null packageName."); 10112 return; 10113 } 10114 PackageParser.Package oldPkg; 10115 PackageSetting oldPkgSetting; 10116 // reader 10117 synchronized (mPackages) { 10118 oldPkg = mPackages.get(packageName); 10119 oldPkgSetting = mSettings.mPackages.get(packageName); 10120 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 10121 (oldPkgSetting == null)) { 10122 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10123 "Couldn't find package:" + packageName + " information"); 10124 return; 10125 } 10126 } 10127 10128 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 10129 10130 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10131 res.removedInfo.removedPackage = packageName; 10132 // Remove existing system package 10133 removePackageLI(oldPkgSetting, true); 10134 // writer 10135 synchronized (mPackages) { 10136 if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) { 10137 // We didn't need to disable the .apk as a current system package, 10138 // which means we are replacing another update that is already 10139 // installed. We need to make sure to delete the older one's .apk. 10140 res.removedInfo.args = createInstallArgsForExisting(0, 10141 deletedPackage.applicationInfo.getCodePath(), 10142 deletedPackage.applicationInfo.getResourcePath(), 10143 deletedPackage.applicationInfo.nativeLibraryRootDir, 10144 getAppDexInstructionSets(deletedPackage.applicationInfo)); 10145 } else { 10146 res.removedInfo.args = null; 10147 } 10148 } 10149 10150 // Successfully disabled the old package. Now proceed with re-installation 10151 deleteCodeCacheDirsLI(packageName); 10152 10153 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10154 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10155 10156 PackageParser.Package newPackage = null; 10157 try { 10158 newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user); 10159 if (newPackage.mExtras != null) { 10160 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 10161 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10162 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10163 10164 // is the update attempting to change shared user? that isn't going to work... 10165 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10166 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 10167 "Forbidding shared user change from " + oldPkgSetting.sharedUser 10168 + " to " + newPkgSetting.sharedUser); 10169 updatedSettings = true; 10170 } 10171 } 10172 10173 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10174 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10175 updatedSettings = true; 10176 } 10177 10178 } catch (PackageManagerException e) { 10179 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10180 } 10181 10182 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10183 // Re installation failed. Restore old information 10184 // Remove new pkg information 10185 if (newPackage != null) { 10186 removeInstalledPackageLI(newPackage, true); 10187 } 10188 // Add back the old system package 10189 try { 10190 scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user); 10191 } catch (PackageManagerException e) { 10192 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 10193 } 10194 // Restore the old system information in Settings 10195 synchronized(mPackages) { 10196 if (updatedSettings) { 10197 mSettings.enableSystemPackageLPw(packageName); 10198 mSettings.setInstallerPackageName(packageName, 10199 oldPkgSetting.installerPackageName); 10200 } 10201 mSettings.writeLPr(); 10202 } 10203 } 10204 } 10205 10206 // Utility method used to move dex files during install. 10207 private int moveDexFilesLI(String oldCodePath, PackageParser.Package newPackage) { 10208 // TODO: extend to move split APK dex files 10209 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) { 10210 final String[] instructionSets = getAppDexInstructionSets(newPackage.applicationInfo); 10211 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10212 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10213 int retCode = mInstaller.movedex(oldCodePath, newPackage.baseCodePath, 10214 dexCodeInstructionSet); 10215 if (retCode != 0) { 10216 /* 10217 * Programs may be lazily run through dexopt, so the 10218 * source may not exist. However, something seems to 10219 * have gone wrong, so note that dexopt needs to be 10220 * run again and remove the source file. In addition, 10221 * remove the target to make sure there isn't a stale 10222 * file from a previous version of the package. 10223 */ 10224 newPackage.mDexOptPerformed.clear(); 10225 mInstaller.rmdex(oldCodePath, dexCodeInstructionSet); 10226 mInstaller.rmdex(newPackage.baseCodePath, dexCodeInstructionSet); 10227 } 10228 } 10229 } 10230 return PackageManager.INSTALL_SUCCEEDED; 10231 } 10232 10233 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10234 int[] allUsers, boolean[] perUserInstalled, 10235 PackageInstalledInfo res) { 10236 String pkgName = newPackage.packageName; 10237 synchronized (mPackages) { 10238 //write settings. the installStatus will be incomplete at this stage. 10239 //note that the new package setting would have already been 10240 //added to mPackages. It hasn't been persisted yet. 10241 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10242 mSettings.writeLPr(); 10243 } 10244 10245 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10246 10247 synchronized (mPackages) { 10248 updatePermissionsLPw(newPackage.packageName, newPackage, 10249 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10250 ? UPDATE_PERMISSIONS_ALL : 0)); 10251 // For system-bundled packages, we assume that installing an upgraded version 10252 // of the package implies that the user actually wants to run that new code, 10253 // so we enable the package. 10254 if (isSystemApp(newPackage)) { 10255 // NB: implicit assumption that system package upgrades apply to all users 10256 if (DEBUG_INSTALL) { 10257 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10258 } 10259 PackageSetting ps = mSettings.mPackages.get(pkgName); 10260 if (ps != null) { 10261 if (res.origUsers != null) { 10262 for (int userHandle : res.origUsers) { 10263 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10264 userHandle, installerPackageName); 10265 } 10266 } 10267 // Also convey the prior install/uninstall state 10268 if (allUsers != null && perUserInstalled != null) { 10269 for (int i = 0; i < allUsers.length; i++) { 10270 if (DEBUG_INSTALL) { 10271 Slog.d(TAG, " user " + allUsers[i] 10272 + " => " + perUserInstalled[i]); 10273 } 10274 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10275 } 10276 // these install state changes will be persisted in the 10277 // upcoming call to mSettings.writeLPr(). 10278 } 10279 } 10280 } 10281 res.name = pkgName; 10282 res.uid = newPackage.applicationInfo.uid; 10283 res.pkg = newPackage; 10284 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10285 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10286 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10287 //to update install status 10288 mSettings.writeLPr(); 10289 } 10290 } 10291 10292 private void installPackageLI(InstallArgs args, boolean newInstall, PackageInstalledInfo res) { 10293 int pFlags = args.flags; 10294 String installerPackageName = args.installerPackageName; 10295 File tmpPackageFile = new File(args.getCodePath()); 10296 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10297 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0); 10298 boolean replace = false; 10299 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE 10300 | (newInstall ? SCAN_NEW_INSTALL : 0); 10301 // Result object to be returned 10302 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10303 10304 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10305 // Retrieve PackageSettings and parse package 10306 int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10307 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10308 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 10309 PackageParser pp = new PackageParser(); 10310 pp.setSeparateProcesses(mSeparateProcesses); 10311 pp.setDisplayMetrics(mMetrics); 10312 10313 final PackageParser.Package pkg; 10314 try { 10315 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 10316 } catch (PackageParserException e) { 10317 res.setError("Failed parse during installPackageLI", e); 10318 return; 10319 } 10320 10321 // Mark that we have an install time CPU ABI override. 10322 pkg.cpuAbiOverride = args.abiOverride; 10323 10324 String pkgName = res.name = pkg.packageName; 10325 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 10326 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) { 10327 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 10328 return; 10329 } 10330 } 10331 10332 try { 10333 pp.collectCertificates(pkg, parseFlags); 10334 pp.collectManifestDigest(pkg); 10335 } catch (PackageParserException e) { 10336 res.setError("Failed collect during installPackageLI", e); 10337 return; 10338 } 10339 10340 /* If the installer passed in a manifest digest, compare it now. */ 10341 if (args.manifestDigest != null) { 10342 if (DEBUG_INSTALL) { 10343 final String parsedManifest = pkg.manifestDigest == null ? "null" 10344 : pkg.manifestDigest.toString(); 10345 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 10346 + parsedManifest); 10347 } 10348 10349 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 10350 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 10351 return; 10352 } 10353 } else if (DEBUG_INSTALL) { 10354 final String parsedManifest = pkg.manifestDigest == null 10355 ? "null" : pkg.manifestDigest.toString(); 10356 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 10357 } 10358 10359 // Get rid of all references to package scan path via parser. 10360 pp = null; 10361 String oldCodePath = null; 10362 boolean systemApp = false; 10363 synchronized (mPackages) { 10364 // Check whether the newly-scanned package wants to define an already-defined perm 10365 int N = pkg.permissions.size(); 10366 for (int i = N-1; i >= 0; i--) { 10367 PackageParser.Permission perm = pkg.permissions.get(i); 10368 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 10369 if (bp != null) { 10370 // If the defining package is signed with our cert, it's okay. This 10371 // also includes the "updating the same package" case, of course. 10372 if (compareSignatures(bp.packageSetting.signatures.mSignatures, 10373 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 10374 // If the owning package is the system itself, we log but allow 10375 // install to proceed; we fail the install on all other permission 10376 // redefinitions. 10377 if (!bp.sourcePackage.equals("android")) { 10378 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 10379 + pkg.packageName + " attempting to redeclare permission " 10380 + perm.info.name + " already owned by " + bp.sourcePackage); 10381 res.origPermission = perm.info.name; 10382 res.origPackage = bp.sourcePackage; 10383 return; 10384 } else { 10385 Slog.w(TAG, "Package " + pkg.packageName 10386 + " attempting to redeclare system permission " 10387 + perm.info.name + "; ignoring new declaration"); 10388 pkg.permissions.remove(i); 10389 } 10390 } 10391 } 10392 } 10393 10394 // Check if installing already existing package 10395 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10396 String oldName = mSettings.mRenamedPackages.get(pkgName); 10397 if (pkg.mOriginalPackages != null 10398 && pkg.mOriginalPackages.contains(oldName) 10399 && mPackages.containsKey(oldName)) { 10400 // This package is derived from an original package, 10401 // and this device has been updating from that original 10402 // name. We must continue using the original name, so 10403 // rename the new package here. 10404 pkg.setPackageName(oldName); 10405 pkgName = pkg.packageName; 10406 replace = true; 10407 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 10408 + oldName + " pkgName=" + pkgName); 10409 } else if (mPackages.containsKey(pkgName)) { 10410 // This package, under its official name, already exists 10411 // on the device; we should replace it. 10412 replace = true; 10413 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 10414 } 10415 } 10416 PackageSetting ps = mSettings.mPackages.get(pkgName); 10417 if (ps != null) { 10418 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 10419 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 10420 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 10421 systemApp = (ps.pkg.applicationInfo.flags & 10422 ApplicationInfo.FLAG_SYSTEM) != 0; 10423 } 10424 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10425 } 10426 } 10427 10428 if (systemApp && onSd) { 10429 // Disable updates to system apps on sdcard 10430 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 10431 "Cannot install updates to system apps on sdcard"); 10432 return; 10433 } 10434 10435 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 10436 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 10437 return; 10438 } 10439 10440 if (replace) { 10441 replacePackageLI(pkg, parseFlags, scanMode, args.user, 10442 installerPackageName, res); 10443 } else { 10444 installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user, 10445 installerPackageName, res); 10446 } 10447 synchronized (mPackages) { 10448 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10449 if (ps != null) { 10450 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10451 } 10452 } 10453 } 10454 10455 private static boolean isForwardLocked(PackageParser.Package pkg) { 10456 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10457 } 10458 10459 private static boolean isForwardLocked(ApplicationInfo info) { 10460 return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10461 } 10462 10463 private boolean isForwardLocked(PackageSetting ps) { 10464 return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10465 } 10466 10467 private static boolean isMultiArch(PackageSetting ps) { 10468 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10469 } 10470 10471 private static boolean isMultiArch(ApplicationInfo info) { 10472 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10473 } 10474 10475 private static boolean isExternal(PackageParser.Package pkg) { 10476 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10477 } 10478 10479 private static boolean isExternal(PackageSetting ps) { 10480 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10481 } 10482 10483 private static boolean isExternal(ApplicationInfo info) { 10484 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10485 } 10486 10487 private static boolean isSystemApp(PackageParser.Package pkg) { 10488 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10489 } 10490 10491 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 10492 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0; 10493 } 10494 10495 private static boolean isSystemApp(ApplicationInfo info) { 10496 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10497 } 10498 10499 private static boolean isSystemApp(PackageSetting ps) { 10500 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 10501 } 10502 10503 private static boolean isUpdatedSystemApp(PackageSetting ps) { 10504 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10505 } 10506 10507 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 10508 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10509 } 10510 10511 private static boolean isUpdatedSystemApp(ApplicationInfo info) { 10512 return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10513 } 10514 10515 private int packageFlagsToInstallFlags(PackageSetting ps) { 10516 int installFlags = 0; 10517 if (isExternal(ps)) { 10518 installFlags |= PackageManager.INSTALL_EXTERNAL; 10519 } 10520 if (isForwardLocked(ps)) { 10521 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 10522 } 10523 return installFlags; 10524 } 10525 10526 private void deleteTempPackageFiles() { 10527 final FilenameFilter filter = new FilenameFilter() { 10528 public boolean accept(File dir, String name) { 10529 return name.startsWith("vmdl") && name.endsWith(".tmp"); 10530 } 10531 }; 10532 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 10533 file.delete(); 10534 } 10535 } 10536 10537 @Override 10538 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 10539 int flags) { 10540 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 10541 flags); 10542 } 10543 10544 @Override 10545 public void deletePackage(final String packageName, 10546 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 10547 mContext.enforceCallingOrSelfPermission( 10548 android.Manifest.permission.DELETE_PACKAGES, null); 10549 final int uid = Binder.getCallingUid(); 10550 if (UserHandle.getUserId(uid) != userId) { 10551 mContext.enforceCallingPermission( 10552 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 10553 "deletePackage for user " + userId); 10554 } 10555 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 10556 try { 10557 observer.onPackageDeleted(packageName, 10558 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 10559 } catch (RemoteException re) { 10560 } 10561 return; 10562 } 10563 10564 boolean uninstallBlocked = false; 10565 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 10566 int[] users = sUserManager.getUserIds(); 10567 for (int i = 0; i < users.length; ++i) { 10568 if (getBlockUninstallForUser(packageName, users[i])) { 10569 uninstallBlocked = true; 10570 break; 10571 } 10572 } 10573 } else { 10574 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 10575 } 10576 if (uninstallBlocked) { 10577 try { 10578 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 10579 null); 10580 } catch (RemoteException re) { 10581 } 10582 return; 10583 } 10584 10585 if (DEBUG_REMOVE) { 10586 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 10587 } 10588 // Queue up an async operation since the package deletion may take a little while. 10589 mHandler.post(new Runnable() { 10590 public void run() { 10591 mHandler.removeCallbacks(this); 10592 final int returnCode = deletePackageX(packageName, userId, flags); 10593 if (observer != null) { 10594 try { 10595 observer.onPackageDeleted(packageName, returnCode, null); 10596 } catch (RemoteException e) { 10597 Log.i(TAG, "Observer no longer exists."); 10598 } //end catch 10599 } //end if 10600 } //end run 10601 }); 10602 } 10603 10604 private boolean isPackageDeviceAdmin(String packageName, int userId) { 10605 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 10606 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 10607 try { 10608 if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId) 10609 || dpm.isDeviceOwner(packageName))) { 10610 return true; 10611 } 10612 } catch (RemoteException e) { 10613 } 10614 return false; 10615 } 10616 10617 /** 10618 * This method is an internal method that could be get invoked either 10619 * to delete an installed package or to clean up a failed installation. 10620 * After deleting an installed package, a broadcast is sent to notify any 10621 * listeners that the package has been installed. For cleaning up a failed 10622 * installation, the broadcast is not necessary since the package's 10623 * installation wouldn't have sent the initial broadcast either 10624 * The key steps in deleting a package are 10625 * deleting the package information in internal structures like mPackages, 10626 * deleting the packages base directories through installd 10627 * updating mSettings to reflect current status 10628 * persisting settings for later use 10629 * sending a broadcast if necessary 10630 */ 10631 private int deletePackageX(String packageName, int userId, int flags) { 10632 final PackageRemovedInfo info = new PackageRemovedInfo(); 10633 final boolean res; 10634 10635 if (isPackageDeviceAdmin(packageName, userId)) { 10636 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 10637 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 10638 } 10639 10640 boolean removedForAllUsers = false; 10641 boolean systemUpdate = false; 10642 10643 // for the uninstall-updates case and restricted profiles, remember the per- 10644 // userhandle installed state 10645 int[] allUsers; 10646 boolean[] perUserInstalled; 10647 synchronized (mPackages) { 10648 PackageSetting ps = mSettings.mPackages.get(packageName); 10649 allUsers = sUserManager.getUserIds(); 10650 perUserInstalled = new boolean[allUsers.length]; 10651 for (int i = 0; i < allUsers.length; i++) { 10652 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10653 } 10654 } 10655 10656 synchronized (mInstallLock) { 10657 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 10658 res = deletePackageLI(packageName, 10659 (flags & PackageManager.DELETE_ALL_USERS) != 0 10660 ? UserHandle.ALL : new UserHandle(userId), 10661 true, allUsers, perUserInstalled, 10662 flags | REMOVE_CHATTY, info, true); 10663 systemUpdate = info.isRemovedPackageSystemUpdate; 10664 if (res && !systemUpdate && mPackages.get(packageName) == null) { 10665 removedForAllUsers = true; 10666 } 10667 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 10668 + " removedForAllUsers=" + removedForAllUsers); 10669 } 10670 10671 if (res) { 10672 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 10673 10674 // If the removed package was a system update, the old system package 10675 // was re-enabled; we need to broadcast this information 10676 if (systemUpdate) { 10677 Bundle extras = new Bundle(1); 10678 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 10679 ? info.removedAppId : info.uid); 10680 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10681 10682 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 10683 extras, null, null, null); 10684 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 10685 extras, null, null, null); 10686 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 10687 null, packageName, null, null); 10688 } 10689 } 10690 // Force a gc here. 10691 Runtime.getRuntime().gc(); 10692 // Delete the resources here after sending the broadcast to let 10693 // other processes clean up before deleting resources. 10694 if (info.args != null) { 10695 synchronized (mInstallLock) { 10696 info.args.doPostDeleteLI(true); 10697 } 10698 } 10699 10700 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10701 } 10702 10703 static class PackageRemovedInfo { 10704 String removedPackage; 10705 int uid = -1; 10706 int removedAppId = -1; 10707 int[] removedUsers = null; 10708 boolean isRemovedPackageSystemUpdate = false; 10709 // Clean up resources deleted packages. 10710 InstallArgs args = null; 10711 10712 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 10713 Bundle extras = new Bundle(1); 10714 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 10715 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 10716 if (replacing) { 10717 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10718 } 10719 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 10720 if (removedPackage != null) { 10721 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 10722 extras, null, null, removedUsers); 10723 if (fullRemove && !replacing) { 10724 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 10725 extras, null, null, removedUsers); 10726 } 10727 } 10728 if (removedAppId >= 0) { 10729 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 10730 removedUsers); 10731 } 10732 } 10733 } 10734 10735 /* 10736 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 10737 * flag is not set, the data directory is removed as well. 10738 * make sure this flag is set for partially installed apps. If not its meaningless to 10739 * delete a partially installed application. 10740 */ 10741 private void removePackageDataLI(PackageSetting ps, 10742 int[] allUserHandles, boolean[] perUserInstalled, 10743 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 10744 String packageName = ps.name; 10745 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 10746 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 10747 // Retrieve object to delete permissions for shared user later on 10748 final PackageSetting deletedPs; 10749 // reader 10750 synchronized (mPackages) { 10751 deletedPs = mSettings.mPackages.get(packageName); 10752 if (outInfo != null) { 10753 outInfo.removedPackage = packageName; 10754 outInfo.removedUsers = deletedPs != null 10755 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 10756 : null; 10757 } 10758 } 10759 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10760 removeDataDirsLI(packageName); 10761 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 10762 } 10763 // writer 10764 synchronized (mPackages) { 10765 if (deletedPs != null) { 10766 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10767 if (outInfo != null) { 10768 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 10769 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 10770 } 10771 if (deletedPs != null) { 10772 updatePermissionsLPw(deletedPs.name, null, 0); 10773 if (deletedPs.sharedUser != null) { 10774 // remove permissions associated with package 10775 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 10776 } 10777 } 10778 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 10779 } 10780 // make sure to preserve per-user disabled state if this removal was just 10781 // a downgrade of a system app to the factory package 10782 if (allUserHandles != null && perUserInstalled != null) { 10783 if (DEBUG_REMOVE) { 10784 Slog.d(TAG, "Propagating install state across downgrade"); 10785 } 10786 for (int i = 0; i < allUserHandles.length; i++) { 10787 if (DEBUG_REMOVE) { 10788 Slog.d(TAG, " user " + allUserHandles[i] 10789 + " => " + perUserInstalled[i]); 10790 } 10791 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10792 } 10793 } 10794 } 10795 // can downgrade to reader 10796 if (writeSettings) { 10797 // Save settings now 10798 mSettings.writeLPr(); 10799 } 10800 } 10801 if (outInfo != null) { 10802 // A user ID was deleted here. Go through all users and remove it 10803 // from KeyStore. 10804 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 10805 } 10806 } 10807 10808 static boolean locationIsPrivileged(File path) { 10809 try { 10810 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 10811 .getCanonicalPath(); 10812 return path.getCanonicalPath().startsWith(privilegedAppDir); 10813 } catch (IOException e) { 10814 Slog.e(TAG, "Unable to access code path " + path); 10815 } 10816 return false; 10817 } 10818 10819 /* 10820 * Tries to delete system package. 10821 */ 10822 private boolean deleteSystemPackageLI(PackageSetting newPs, 10823 int[] allUserHandles, boolean[] perUserInstalled, 10824 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 10825 final boolean applyUserRestrictions 10826 = (allUserHandles != null) && (perUserInstalled != null); 10827 PackageSetting disabledPs = null; 10828 // Confirm if the system package has been updated 10829 // An updated system app can be deleted. This will also have to restore 10830 // the system pkg from system partition 10831 // reader 10832 synchronized (mPackages) { 10833 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 10834 } 10835 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 10836 + " disabledPs=" + disabledPs); 10837 if (disabledPs == null) { 10838 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 10839 return false; 10840 } else if (DEBUG_REMOVE) { 10841 Slog.d(TAG, "Deleting system pkg from data partition"); 10842 } 10843 if (DEBUG_REMOVE) { 10844 if (applyUserRestrictions) { 10845 Slog.d(TAG, "Remembering install states:"); 10846 for (int i = 0; i < allUserHandles.length; i++) { 10847 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 10848 } 10849 } 10850 } 10851 // Delete the updated package 10852 outInfo.isRemovedPackageSystemUpdate = true; 10853 if (disabledPs.versionCode < newPs.versionCode) { 10854 // Delete data for downgrades 10855 flags &= ~PackageManager.DELETE_KEEP_DATA; 10856 } else { 10857 // Preserve data by setting flag 10858 flags |= PackageManager.DELETE_KEEP_DATA; 10859 } 10860 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 10861 allUserHandles, perUserInstalled, outInfo, writeSettings); 10862 if (!ret) { 10863 return false; 10864 } 10865 // writer 10866 synchronized (mPackages) { 10867 // Reinstate the old system package 10868 mSettings.enableSystemPackageLPw(newPs.name); 10869 // Remove any native libraries from the upgraded package. 10870 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 10871 } 10872 // Install the system package 10873 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 10874 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 10875 if (locationIsPrivileged(disabledPs.codePath)) { 10876 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10877 } 10878 10879 final PackageParser.Package newPkg; 10880 try { 10881 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, null); 10882 } catch (PackageManagerException e) { 10883 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 10884 return false; 10885 } 10886 10887 // writer 10888 synchronized (mPackages) { 10889 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 10890 updatePermissionsLPw(newPkg.packageName, newPkg, 10891 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 10892 if (applyUserRestrictions) { 10893 if (DEBUG_REMOVE) { 10894 Slog.d(TAG, "Propagating install state across reinstall"); 10895 } 10896 for (int i = 0; i < allUserHandles.length; i++) { 10897 if (DEBUG_REMOVE) { 10898 Slog.d(TAG, " user " + allUserHandles[i] 10899 + " => " + perUserInstalled[i]); 10900 } 10901 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10902 } 10903 // Regardless of writeSettings we need to ensure that this restriction 10904 // state propagation is persisted 10905 mSettings.writeAllUsersPackageRestrictionsLPr(); 10906 } 10907 // can downgrade to reader here 10908 if (writeSettings) { 10909 mSettings.writeLPr(); 10910 } 10911 } 10912 return true; 10913 } 10914 10915 private boolean deleteInstalledPackageLI(PackageSetting ps, 10916 boolean deleteCodeAndResources, int flags, 10917 int[] allUserHandles, boolean[] perUserInstalled, 10918 PackageRemovedInfo outInfo, boolean writeSettings) { 10919 if (outInfo != null) { 10920 outInfo.uid = ps.appId; 10921 } 10922 10923 // Delete package data from internal structures and also remove data if flag is set 10924 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 10925 10926 // Delete application code and resources 10927 if (deleteCodeAndResources && (outInfo != null)) { 10928 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 10929 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 10930 getAppDexInstructionSets(ps)); 10931 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 10932 } 10933 return true; 10934 } 10935 10936 @Override 10937 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 10938 int userId) { 10939 mContext.enforceCallingOrSelfPermission( 10940 android.Manifest.permission.DELETE_PACKAGES, null); 10941 synchronized (mPackages) { 10942 PackageSetting ps = mSettings.mPackages.get(packageName); 10943 if (ps == null) { 10944 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 10945 return false; 10946 } 10947 if (!ps.getInstalled(userId)) { 10948 // Can't block uninstall for an app that is not installed or enabled. 10949 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 10950 return false; 10951 } 10952 ps.setBlockUninstall(blockUninstall, userId); 10953 mSettings.writePackageRestrictionsLPr(userId); 10954 } 10955 return true; 10956 } 10957 10958 @Override 10959 public boolean getBlockUninstallForUser(String packageName, int userId) { 10960 synchronized (mPackages) { 10961 PackageSetting ps = mSettings.mPackages.get(packageName); 10962 if (ps == null) { 10963 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 10964 return false; 10965 } 10966 return ps.getBlockUninstall(userId); 10967 } 10968 } 10969 10970 /* 10971 * This method handles package deletion in general 10972 */ 10973 private boolean deletePackageLI(String packageName, UserHandle user, 10974 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 10975 int flags, PackageRemovedInfo outInfo, 10976 boolean writeSettings) { 10977 if (packageName == null) { 10978 Slog.w(TAG, "Attempt to delete null packageName."); 10979 return false; 10980 } 10981 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 10982 PackageSetting ps; 10983 boolean dataOnly = false; 10984 int removeUser = -1; 10985 int appId = -1; 10986 synchronized (mPackages) { 10987 ps = mSettings.mPackages.get(packageName); 10988 if (ps == null) { 10989 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 10990 return false; 10991 } 10992 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 10993 && user.getIdentifier() != UserHandle.USER_ALL) { 10994 // The caller is asking that the package only be deleted for a single 10995 // user. To do this, we just mark its uninstalled state and delete 10996 // its data. If this is a system app, we only allow this to happen if 10997 // they have set the special DELETE_SYSTEM_APP which requests different 10998 // semantics than normal for uninstalling system apps. 10999 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 11000 ps.setUserState(user.getIdentifier(), 11001 COMPONENT_ENABLED_STATE_DEFAULT, 11002 false, //installed 11003 true, //stopped 11004 true, //notLaunched 11005 false, //hidden 11006 null, null, null, 11007 false // blockUninstall 11008 ); 11009 if (!isSystemApp(ps)) { 11010 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 11011 // Other user still have this package installed, so all 11012 // we need to do is clear this user's data and save that 11013 // it is uninstalled. 11014 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 11015 removeUser = user.getIdentifier(); 11016 appId = ps.appId; 11017 mSettings.writePackageRestrictionsLPr(removeUser); 11018 } else { 11019 // We need to set it back to 'installed' so the uninstall 11020 // broadcasts will be sent correctly. 11021 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 11022 ps.setInstalled(true, user.getIdentifier()); 11023 } 11024 } else { 11025 // This is a system app, so we assume that the 11026 // other users still have this package installed, so all 11027 // we need to do is clear this user's data and save that 11028 // it is uninstalled. 11029 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 11030 removeUser = user.getIdentifier(); 11031 appId = ps.appId; 11032 mSettings.writePackageRestrictionsLPr(removeUser); 11033 } 11034 } 11035 } 11036 11037 if (removeUser >= 0) { 11038 // From above, we determined that we are deleting this only 11039 // for a single user. Continue the work here. 11040 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 11041 if (outInfo != null) { 11042 outInfo.removedPackage = packageName; 11043 outInfo.removedAppId = appId; 11044 outInfo.removedUsers = new int[] {removeUser}; 11045 } 11046 mInstaller.clearUserData(packageName, removeUser); 11047 removeKeystoreDataIfNeeded(removeUser, appId); 11048 schedulePackageCleaning(packageName, removeUser, false); 11049 return true; 11050 } 11051 11052 if (dataOnly) { 11053 // Delete application data first 11054 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 11055 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 11056 return true; 11057 } 11058 11059 boolean ret = false; 11060 if (isSystemApp(ps)) { 11061 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 11062 // When an updated system application is deleted we delete the existing resources as well and 11063 // fall back to existing code in system partition 11064 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 11065 flags, outInfo, writeSettings); 11066 } else { 11067 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 11068 // Kill application pre-emptively especially for apps on sd. 11069 killApplication(packageName, ps.appId, "uninstall pkg"); 11070 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 11071 allUserHandles, perUserInstalled, 11072 outInfo, writeSettings); 11073 } 11074 11075 return ret; 11076 } 11077 11078 private final class ClearStorageConnection implements ServiceConnection { 11079 IMediaContainerService mContainerService; 11080 11081 @Override 11082 public void onServiceConnected(ComponentName name, IBinder service) { 11083 synchronized (this) { 11084 mContainerService = IMediaContainerService.Stub.asInterface(service); 11085 notifyAll(); 11086 } 11087 } 11088 11089 @Override 11090 public void onServiceDisconnected(ComponentName name) { 11091 } 11092 } 11093 11094 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 11095 final boolean mounted; 11096 if (Environment.isExternalStorageEmulated()) { 11097 mounted = true; 11098 } else { 11099 final String status = Environment.getExternalStorageState(); 11100 11101 mounted = status.equals(Environment.MEDIA_MOUNTED) 11102 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 11103 } 11104 11105 if (!mounted) { 11106 return; 11107 } 11108 11109 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 11110 int[] users; 11111 if (userId == UserHandle.USER_ALL) { 11112 users = sUserManager.getUserIds(); 11113 } else { 11114 users = new int[] { userId }; 11115 } 11116 final ClearStorageConnection conn = new ClearStorageConnection(); 11117 if (mContext.bindServiceAsUser( 11118 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 11119 try { 11120 for (int curUser : users) { 11121 long timeout = SystemClock.uptimeMillis() + 5000; 11122 synchronized (conn) { 11123 long now = SystemClock.uptimeMillis(); 11124 while (conn.mContainerService == null && now < timeout) { 11125 try { 11126 conn.wait(timeout - now); 11127 } catch (InterruptedException e) { 11128 } 11129 } 11130 } 11131 if (conn.mContainerService == null) { 11132 return; 11133 } 11134 11135 final UserEnvironment userEnv = new UserEnvironment(curUser); 11136 clearDirectory(conn.mContainerService, 11137 userEnv.buildExternalStorageAppCacheDirs(packageName)); 11138 if (allData) { 11139 clearDirectory(conn.mContainerService, 11140 userEnv.buildExternalStorageAppDataDirs(packageName)); 11141 clearDirectory(conn.mContainerService, 11142 userEnv.buildExternalStorageAppMediaDirs(packageName)); 11143 } 11144 } 11145 } finally { 11146 mContext.unbindService(conn); 11147 } 11148 } 11149 } 11150 11151 @Override 11152 public void clearApplicationUserData(final String packageName, 11153 final IPackageDataObserver observer, final int userId) { 11154 mContext.enforceCallingOrSelfPermission( 11155 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 11156 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data"); 11157 // Queue up an async operation since the package deletion may take a little while. 11158 mHandler.post(new Runnable() { 11159 public void run() { 11160 mHandler.removeCallbacks(this); 11161 final boolean succeeded; 11162 synchronized (mInstallLock) { 11163 succeeded = clearApplicationUserDataLI(packageName, userId); 11164 } 11165 clearExternalStorageDataSync(packageName, userId, true); 11166 if (succeeded) { 11167 // invoke DeviceStorageMonitor's update method to clear any notifications 11168 DeviceStorageMonitorInternal 11169 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 11170 if (dsm != null) { 11171 dsm.checkMemory(); 11172 } 11173 } 11174 if(observer != null) { 11175 try { 11176 observer.onRemoveCompleted(packageName, succeeded); 11177 } catch (RemoteException e) { 11178 Log.i(TAG, "Observer no longer exists."); 11179 } 11180 } //end if observer 11181 } //end run 11182 }); 11183 } 11184 11185 private boolean clearApplicationUserDataLI(String packageName, int userId) { 11186 if (packageName == null) { 11187 Slog.w(TAG, "Attempt to delete null packageName."); 11188 return false; 11189 } 11190 PackageParser.Package p; 11191 boolean dataOnly = false; 11192 final int appId; 11193 synchronized (mPackages) { 11194 p = mPackages.get(packageName); 11195 if (p == null) { 11196 dataOnly = true; 11197 PackageSetting ps = mSettings.mPackages.get(packageName); 11198 if ((ps == null) || (ps.pkg == null)) { 11199 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11200 return false; 11201 } 11202 p = ps.pkg; 11203 } 11204 if (!dataOnly) { 11205 // need to check this only for fully installed applications 11206 if (p == null) { 11207 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11208 return false; 11209 } 11210 final ApplicationInfo applicationInfo = p.applicationInfo; 11211 if (applicationInfo == null) { 11212 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11213 return false; 11214 } 11215 } 11216 if (p != null && p.applicationInfo != null) { 11217 appId = p.applicationInfo.uid; 11218 } else { 11219 appId = -1; 11220 } 11221 } 11222 int retCode = mInstaller.clearUserData(packageName, userId); 11223 if (retCode < 0) { 11224 Slog.w(TAG, "Couldn't remove cache files for package: " 11225 + packageName); 11226 return false; 11227 } 11228 removeKeystoreDataIfNeeded(userId, appId); 11229 return true; 11230 } 11231 11232 /** 11233 * Remove entries from the keystore daemon. Will only remove it if the 11234 * {@code appId} is valid. 11235 */ 11236 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 11237 if (appId < 0) { 11238 return; 11239 } 11240 11241 final KeyStore keyStore = KeyStore.getInstance(); 11242 if (keyStore != null) { 11243 if (userId == UserHandle.USER_ALL) { 11244 for (final int individual : sUserManager.getUserIds()) { 11245 keyStore.clearUid(UserHandle.getUid(individual, appId)); 11246 } 11247 } else { 11248 keyStore.clearUid(UserHandle.getUid(userId, appId)); 11249 } 11250 } else { 11251 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 11252 } 11253 } 11254 11255 @Override 11256 public void deleteApplicationCacheFiles(final String packageName, 11257 final IPackageDataObserver observer) { 11258 mContext.enforceCallingOrSelfPermission( 11259 android.Manifest.permission.DELETE_CACHE_FILES, null); 11260 // Queue up an async operation since the package deletion may take a little while. 11261 final int userId = UserHandle.getCallingUserId(); 11262 mHandler.post(new Runnable() { 11263 public void run() { 11264 mHandler.removeCallbacks(this); 11265 final boolean succeded; 11266 synchronized (mInstallLock) { 11267 succeded = deleteApplicationCacheFilesLI(packageName, userId); 11268 } 11269 clearExternalStorageDataSync(packageName, userId, false); 11270 if(observer != null) { 11271 try { 11272 observer.onRemoveCompleted(packageName, succeded); 11273 } catch (RemoteException e) { 11274 Log.i(TAG, "Observer no longer exists."); 11275 } 11276 } //end if observer 11277 } //end run 11278 }); 11279 } 11280 11281 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 11282 if (packageName == null) { 11283 Slog.w(TAG, "Attempt to delete null packageName."); 11284 return false; 11285 } 11286 PackageParser.Package p; 11287 synchronized (mPackages) { 11288 p = mPackages.get(packageName); 11289 } 11290 if (p == null) { 11291 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11292 return false; 11293 } 11294 final ApplicationInfo applicationInfo = p.applicationInfo; 11295 if (applicationInfo == null) { 11296 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11297 return false; 11298 } 11299 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 11300 if (retCode < 0) { 11301 Slog.w(TAG, "Couldn't remove cache files for package: " 11302 + packageName + " u" + userId); 11303 return false; 11304 } 11305 return true; 11306 } 11307 11308 @Override 11309 public void getPackageSizeInfo(final String packageName, int userHandle, 11310 final IPackageStatsObserver observer) { 11311 mContext.enforceCallingOrSelfPermission( 11312 android.Manifest.permission.GET_PACKAGE_SIZE, null); 11313 if (packageName == null) { 11314 throw new IllegalArgumentException("Attempt to get size of null packageName"); 11315 } 11316 11317 PackageStats stats = new PackageStats(packageName, userHandle); 11318 11319 /* 11320 * Queue up an async operation since the package measurement may take a 11321 * little while. 11322 */ 11323 Message msg = mHandler.obtainMessage(INIT_COPY); 11324 msg.obj = new MeasureParams(stats, observer); 11325 mHandler.sendMessage(msg); 11326 } 11327 11328 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 11329 PackageStats pStats) { 11330 if (packageName == null) { 11331 Slog.w(TAG, "Attempt to get size of null packageName."); 11332 return false; 11333 } 11334 PackageParser.Package p; 11335 boolean dataOnly = false; 11336 String libDirRoot = null; 11337 String asecPath = null; 11338 PackageSetting ps = null; 11339 synchronized (mPackages) { 11340 p = mPackages.get(packageName); 11341 ps = mSettings.mPackages.get(packageName); 11342 if(p == null) { 11343 dataOnly = true; 11344 if((ps == null) || (ps.pkg == null)) { 11345 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11346 return false; 11347 } 11348 p = ps.pkg; 11349 } 11350 if (ps != null) { 11351 libDirRoot = ps.legacyNativeLibraryPathString; 11352 } 11353 if (p != null && (isExternal(p) || isForwardLocked(p))) { 11354 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 11355 if (secureContainerId != null) { 11356 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 11357 } 11358 } 11359 } 11360 String publicSrcDir = null; 11361 if(!dataOnly) { 11362 final ApplicationInfo applicationInfo = p.applicationInfo; 11363 if (applicationInfo == null) { 11364 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11365 return false; 11366 } 11367 if (isForwardLocked(p)) { 11368 publicSrcDir = applicationInfo.getBaseResourcePath(); 11369 } 11370 } 11371 // TODO: extend to measure size of split APKs 11372 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 11373 // not just the first level. 11374 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 11375 // just the primary. 11376 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 11377 int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot, 11378 publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 11379 if (res < 0) { 11380 return false; 11381 } 11382 11383 // Fix-up for forward-locked applications in ASEC containers. 11384 if (!isExternal(p)) { 11385 pStats.codeSize += pStats.externalCodeSize; 11386 pStats.externalCodeSize = 0L; 11387 } 11388 11389 return true; 11390 } 11391 11392 11393 @Override 11394 public void addPackageToPreferred(String packageName) { 11395 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 11396 } 11397 11398 @Override 11399 public void removePackageFromPreferred(String packageName) { 11400 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 11401 } 11402 11403 @Override 11404 public List<PackageInfo> getPreferredPackages(int flags) { 11405 return new ArrayList<PackageInfo>(); 11406 } 11407 11408 private int getUidTargetSdkVersionLockedLPr(int uid) { 11409 Object obj = mSettings.getUserIdLPr(uid); 11410 if (obj instanceof SharedUserSetting) { 11411 final SharedUserSetting sus = (SharedUserSetting) obj; 11412 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 11413 final Iterator<PackageSetting> it = sus.packages.iterator(); 11414 while (it.hasNext()) { 11415 final PackageSetting ps = it.next(); 11416 if (ps.pkg != null) { 11417 int v = ps.pkg.applicationInfo.targetSdkVersion; 11418 if (v < vers) vers = v; 11419 } 11420 } 11421 return vers; 11422 } else if (obj instanceof PackageSetting) { 11423 final PackageSetting ps = (PackageSetting) obj; 11424 if (ps.pkg != null) { 11425 return ps.pkg.applicationInfo.targetSdkVersion; 11426 } 11427 } 11428 return Build.VERSION_CODES.CUR_DEVELOPMENT; 11429 } 11430 11431 @Override 11432 public void addPreferredActivity(IntentFilter filter, int match, 11433 ComponentName[] set, ComponentName activity, int userId) { 11434 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11435 "Adding preferred"); 11436 } 11437 11438 private void addPreferredActivityInternal(IntentFilter filter, int match, 11439 ComponentName[] set, ComponentName activity, boolean always, int userId, 11440 String opname) { 11441 // writer 11442 int callingUid = Binder.getCallingUid(); 11443 enforceCrossUserPermission(callingUid, userId, true, "add preferred activity"); 11444 if (filter.countActions() == 0) { 11445 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11446 return; 11447 } 11448 synchronized (mPackages) { 11449 if (mContext.checkCallingOrSelfPermission( 11450 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11451 != PackageManager.PERMISSION_GRANTED) { 11452 if (getUidTargetSdkVersionLockedLPr(callingUid) 11453 < Build.VERSION_CODES.FROYO) { 11454 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 11455 + callingUid); 11456 return; 11457 } 11458 mContext.enforceCallingOrSelfPermission( 11459 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11460 } 11461 11462 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 11463 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 11464 + userId + ":"); 11465 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11466 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 11467 mSettings.writePackageRestrictionsLPr(userId); 11468 } 11469 } 11470 11471 @Override 11472 public void replacePreferredActivity(IntentFilter filter, int match, 11473 ComponentName[] set, ComponentName activity, int userId) { 11474 if (filter.countActions() != 1) { 11475 throw new IllegalArgumentException( 11476 "replacePreferredActivity expects filter to have only 1 action."); 11477 } 11478 if (filter.countDataAuthorities() != 0 11479 || filter.countDataPaths() != 0 11480 || filter.countDataSchemes() > 1 11481 || filter.countDataTypes() != 0) { 11482 throw new IllegalArgumentException( 11483 "replacePreferredActivity expects filter to have no data authorities, " + 11484 "paths, or types; and at most one scheme."); 11485 } 11486 11487 final int callingUid = Binder.getCallingUid(); 11488 enforceCrossUserPermission(callingUid, userId, true, "replace preferred activity"); 11489 synchronized (mPackages) { 11490 if (mContext.checkCallingOrSelfPermission( 11491 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11492 != PackageManager.PERMISSION_GRANTED) { 11493 if (getUidTargetSdkVersionLockedLPr(callingUid) 11494 < Build.VERSION_CODES.FROYO) { 11495 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 11496 + Binder.getCallingUid()); 11497 return; 11498 } 11499 mContext.enforceCallingOrSelfPermission( 11500 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11501 } 11502 11503 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11504 if (pir != null) { 11505 // Get all of the existing entries that exactly match this filter. 11506 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 11507 if (existing != null && existing.size() == 1) { 11508 PreferredActivity cur = existing.get(0); 11509 if (DEBUG_PREFERRED) { 11510 Slog.i(TAG, "Checking replace of preferred:"); 11511 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11512 if (!cur.mPref.mAlways) { 11513 Slog.i(TAG, " -- CUR; not mAlways!"); 11514 } else { 11515 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 11516 Slog.i(TAG, " -- CUR: mSet=" 11517 + Arrays.toString(cur.mPref.mSetComponents)); 11518 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 11519 Slog.i(TAG, " -- NEW: mMatch=" 11520 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 11521 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 11522 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 11523 } 11524 } 11525 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 11526 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 11527 && cur.mPref.sameSet(set)) { 11528 if (DEBUG_PREFERRED) { 11529 Slog.i(TAG, "Replacing with same preferred activity " 11530 + cur.mPref.mShortComponent + " for user " 11531 + userId + ":"); 11532 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11533 } else { 11534 Slog.i(TAG, "Replacing with same preferred activity " 11535 + cur.mPref.mShortComponent + " for user " 11536 + userId); 11537 } 11538 return; 11539 } 11540 } 11541 11542 if (existing != null) { 11543 if (DEBUG_PREFERRED) { 11544 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 11545 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11546 } 11547 for (int i = 0; i < existing.size(); i++) { 11548 PreferredActivity pa = existing.get(i); 11549 if (DEBUG_PREFERRED) { 11550 Slog.i(TAG, "Removing existing preferred activity " 11551 + pa.mPref.mComponent + ":"); 11552 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 11553 } 11554 pir.removeFilter(pa); 11555 } 11556 } 11557 } 11558 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11559 "Replacing preferred"); 11560 } 11561 } 11562 11563 @Override 11564 public void clearPackagePreferredActivities(String packageName) { 11565 final int uid = Binder.getCallingUid(); 11566 // writer 11567 synchronized (mPackages) { 11568 PackageParser.Package pkg = mPackages.get(packageName); 11569 if (pkg == null || pkg.applicationInfo.uid != uid) { 11570 if (mContext.checkCallingOrSelfPermission( 11571 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11572 != PackageManager.PERMISSION_GRANTED) { 11573 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11574 < Build.VERSION_CODES.FROYO) { 11575 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 11576 + Binder.getCallingUid()); 11577 return; 11578 } 11579 mContext.enforceCallingOrSelfPermission( 11580 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11581 } 11582 } 11583 11584 int user = UserHandle.getCallingUserId(); 11585 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 11586 mSettings.writePackageRestrictionsLPr(user); 11587 scheduleWriteSettingsLocked(); 11588 } 11589 } 11590 } 11591 11592 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 11593 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 11594 ArrayList<PreferredActivity> removed = null; 11595 boolean changed = false; 11596 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11597 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 11598 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11599 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 11600 continue; 11601 } 11602 Iterator<PreferredActivity> it = pir.filterIterator(); 11603 while (it.hasNext()) { 11604 PreferredActivity pa = it.next(); 11605 // Mark entry for removal only if it matches the package name 11606 // and the entry is of type "always". 11607 if (packageName == null || 11608 (pa.mPref.mComponent.getPackageName().equals(packageName) 11609 && pa.mPref.mAlways)) { 11610 if (removed == null) { 11611 removed = new ArrayList<PreferredActivity>(); 11612 } 11613 removed.add(pa); 11614 } 11615 } 11616 if (removed != null) { 11617 for (int j=0; j<removed.size(); j++) { 11618 PreferredActivity pa = removed.get(j); 11619 pir.removeFilter(pa); 11620 } 11621 changed = true; 11622 } 11623 } 11624 return changed; 11625 } 11626 11627 @Override 11628 public void resetPreferredActivities(int userId) { 11629 mContext.enforceCallingOrSelfPermission( 11630 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11631 // writer 11632 synchronized (mPackages) { 11633 int user = UserHandle.getCallingUserId(); 11634 clearPackagePreferredActivitiesLPw(null, user); 11635 mSettings.readDefaultPreferredAppsLPw(this, user); 11636 mSettings.writePackageRestrictionsLPr(user); 11637 scheduleWriteSettingsLocked(); 11638 } 11639 } 11640 11641 @Override 11642 public int getPreferredActivities(List<IntentFilter> outFilters, 11643 List<ComponentName> outActivities, String packageName) { 11644 11645 int num = 0; 11646 final int userId = UserHandle.getCallingUserId(); 11647 // reader 11648 synchronized (mPackages) { 11649 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11650 if (pir != null) { 11651 final Iterator<PreferredActivity> it = pir.filterIterator(); 11652 while (it.hasNext()) { 11653 final PreferredActivity pa = it.next(); 11654 if (packageName == null 11655 || (pa.mPref.mComponent.getPackageName().equals(packageName) 11656 && pa.mPref.mAlways)) { 11657 if (outFilters != null) { 11658 outFilters.add(new IntentFilter(pa)); 11659 } 11660 if (outActivities != null) { 11661 outActivities.add(pa.mPref.mComponent); 11662 } 11663 } 11664 } 11665 } 11666 } 11667 11668 return num; 11669 } 11670 11671 @Override 11672 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 11673 int userId) { 11674 int callingUid = Binder.getCallingUid(); 11675 if (callingUid != Process.SYSTEM_UID) { 11676 throw new SecurityException( 11677 "addPersistentPreferredActivity can only be run by the system"); 11678 } 11679 if (filter.countActions() == 0) { 11680 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11681 return; 11682 } 11683 synchronized (mPackages) { 11684 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 11685 " :"); 11686 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11687 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 11688 new PersistentPreferredActivity(filter, activity)); 11689 mSettings.writePackageRestrictionsLPr(userId); 11690 } 11691 } 11692 11693 @Override 11694 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 11695 int callingUid = Binder.getCallingUid(); 11696 if (callingUid != Process.SYSTEM_UID) { 11697 throw new SecurityException( 11698 "clearPackagePersistentPreferredActivities can only be run by the system"); 11699 } 11700 ArrayList<PersistentPreferredActivity> removed = null; 11701 boolean changed = false; 11702 synchronized (mPackages) { 11703 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 11704 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 11705 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 11706 .valueAt(i); 11707 if (userId != thisUserId) { 11708 continue; 11709 } 11710 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 11711 while (it.hasNext()) { 11712 PersistentPreferredActivity ppa = it.next(); 11713 // Mark entry for removal only if it matches the package name. 11714 if (ppa.mComponent.getPackageName().equals(packageName)) { 11715 if (removed == null) { 11716 removed = new ArrayList<PersistentPreferredActivity>(); 11717 } 11718 removed.add(ppa); 11719 } 11720 } 11721 if (removed != null) { 11722 for (int j=0; j<removed.size(); j++) { 11723 PersistentPreferredActivity ppa = removed.get(j); 11724 ppir.removeFilter(ppa); 11725 } 11726 changed = true; 11727 } 11728 } 11729 11730 if (changed) { 11731 mSettings.writePackageRestrictionsLPr(userId); 11732 } 11733 } 11734 } 11735 11736 @Override 11737 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 11738 int ownerUserId, int sourceUserId, int targetUserId, int flags) { 11739 mContext.enforceCallingOrSelfPermission( 11740 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11741 int callingUid = Binder.getCallingUid(); 11742 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11743 if (intentFilter.countActions() == 0) { 11744 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 11745 return; 11746 } 11747 synchronized (mPackages) { 11748 CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter, 11749 ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags); 11750 mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter); 11751 mSettings.writePackageRestrictionsLPr(sourceUserId); 11752 } 11753 } 11754 11755 @Override 11756 public void addCrossProfileIntentsForPackage(String packageName, 11757 int sourceUserId, int targetUserId) { 11758 mContext.enforceCallingOrSelfPermission( 11759 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11760 mSettings.addCrossProfilePackage(packageName, sourceUserId, targetUserId); 11761 mSettings.writePackageRestrictionsLPr(sourceUserId); 11762 } 11763 11764 @Override 11765 public void removeCrossProfileIntentsForPackage(String packageName, 11766 int sourceUserId, int targetUserId) { 11767 mContext.enforceCallingOrSelfPermission( 11768 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11769 mSettings.removeCrossProfilePackage(packageName, sourceUserId, targetUserId); 11770 mSettings.writePackageRestrictionsLPr(sourceUserId); 11771 } 11772 11773 @Override 11774 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage, 11775 int ownerUserId) { 11776 mContext.enforceCallingOrSelfPermission( 11777 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11778 int callingUid = Binder.getCallingUid(); 11779 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11780 int callingUserId = UserHandle.getUserId(callingUid); 11781 synchronized (mPackages) { 11782 CrossProfileIntentResolver resolver = 11783 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11784 HashSet<CrossProfileIntentFilter> set = 11785 new HashSet<CrossProfileIntentFilter>(resolver.filterSet()); 11786 for (CrossProfileIntentFilter filter : set) { 11787 if (filter.getOwnerPackage().equals(ownerPackage) 11788 && filter.getOwnerUserId() == callingUserId) { 11789 resolver.removeFilter(filter); 11790 } 11791 } 11792 mSettings.writePackageRestrictionsLPr(sourceUserId); 11793 } 11794 } 11795 11796 // Enforcing that callingUid is owning pkg on userId 11797 private void enforceOwnerRights(String pkg, int userId, int callingUid) { 11798 // The system owns everything. 11799 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 11800 return; 11801 } 11802 int callingUserId = UserHandle.getUserId(callingUid); 11803 if (callingUserId != userId) { 11804 throw new SecurityException("calling uid " + callingUid 11805 + " pretends to own " + pkg + " on user " + userId + " but belongs to user " 11806 + callingUserId); 11807 } 11808 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 11809 if (pi == null) { 11810 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 11811 + callingUserId); 11812 } 11813 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 11814 throw new SecurityException("Calling uid " + callingUid 11815 + " does not own package " + pkg); 11816 } 11817 } 11818 11819 @Override 11820 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 11821 Intent intent = new Intent(Intent.ACTION_MAIN); 11822 intent.addCategory(Intent.CATEGORY_HOME); 11823 11824 final int callingUserId = UserHandle.getCallingUserId(); 11825 List<ResolveInfo> list = queryIntentActivities(intent, null, 11826 PackageManager.GET_META_DATA, callingUserId); 11827 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 11828 true, false, false, callingUserId); 11829 11830 allHomeCandidates.clear(); 11831 if (list != null) { 11832 for (ResolveInfo ri : list) { 11833 allHomeCandidates.add(ri); 11834 } 11835 } 11836 return (preferred == null || preferred.activityInfo == null) 11837 ? null 11838 : new ComponentName(preferred.activityInfo.packageName, 11839 preferred.activityInfo.name); 11840 } 11841 11842 /** 11843 * Check if calling UID is the current home app. This handles both the case 11844 * where the user has selected a specific home app, and where there is only 11845 * one home app. 11846 */ 11847 public boolean checkCallerIsHomeApp() { 11848 final Intent intent = new Intent(Intent.ACTION_MAIN); 11849 intent.addCategory(Intent.CATEGORY_HOME); 11850 11851 final int callingUid = Binder.getCallingUid(); 11852 final int callingUserId = UserHandle.getCallingUserId(); 11853 final List<ResolveInfo> allHomes = queryIntentActivities(intent, null, 0, callingUserId); 11854 final ResolveInfo preferredHome = findPreferredActivity(intent, null, 0, allHomes, 0, true, 11855 false, false, callingUserId); 11856 11857 if (preferredHome != null) { 11858 if (callingUid == preferredHome.activityInfo.applicationInfo.uid) { 11859 return true; 11860 } 11861 } else { 11862 for (ResolveInfo info : allHomes) { 11863 if (callingUid == info.activityInfo.applicationInfo.uid) { 11864 return true; 11865 } 11866 } 11867 } 11868 11869 return false; 11870 } 11871 11872 /** 11873 * Enforce that calling UID is the current home app. This handles both the 11874 * case where the user has selected a specific home app, and where there is 11875 * only one home app. 11876 */ 11877 public void enforceCallerIsHomeApp() { 11878 if (!checkCallerIsHomeApp()) { 11879 throw new SecurityException("Caller is not currently selected home app"); 11880 } 11881 } 11882 11883 @Override 11884 public void setApplicationEnabledSetting(String appPackageName, 11885 int newState, int flags, int userId, String callingPackage) { 11886 if (!sUserManager.exists(userId)) return; 11887 if (callingPackage == null) { 11888 callingPackage = Integer.toString(Binder.getCallingUid()); 11889 } 11890 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 11891 } 11892 11893 @Override 11894 public void setComponentEnabledSetting(ComponentName componentName, 11895 int newState, int flags, int userId) { 11896 if (!sUserManager.exists(userId)) return; 11897 setEnabledSetting(componentName.getPackageName(), 11898 componentName.getClassName(), newState, flags, userId, null); 11899 } 11900 11901 private void setEnabledSetting(final String packageName, String className, int newState, 11902 final int flags, int userId, String callingPackage) { 11903 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 11904 || newState == COMPONENT_ENABLED_STATE_ENABLED 11905 || newState == COMPONENT_ENABLED_STATE_DISABLED 11906 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 11907 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 11908 throw new IllegalArgumentException("Invalid new component state: " 11909 + newState); 11910 } 11911 PackageSetting pkgSetting; 11912 final int uid = Binder.getCallingUid(); 11913 final int permission = mContext.checkCallingOrSelfPermission( 11914 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11915 enforceCrossUserPermission(uid, userId, false, "set enabled"); 11916 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11917 boolean sendNow = false; 11918 boolean isApp = (className == null); 11919 String componentName = isApp ? packageName : className; 11920 int packageUid = -1; 11921 ArrayList<String> components; 11922 11923 // writer 11924 synchronized (mPackages) { 11925 pkgSetting = mSettings.mPackages.get(packageName); 11926 if (pkgSetting == null) { 11927 if (className == null) { 11928 throw new IllegalArgumentException( 11929 "Unknown package: " + packageName); 11930 } 11931 throw new IllegalArgumentException( 11932 "Unknown component: " + packageName 11933 + "/" + className); 11934 } 11935 // Allow root and verify that userId is not being specified by a different user 11936 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 11937 throw new SecurityException( 11938 "Permission Denial: attempt to change component state from pid=" 11939 + Binder.getCallingPid() 11940 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 11941 } 11942 if (className == null) { 11943 // We're dealing with an application/package level state change 11944 if (pkgSetting.getEnabled(userId) == newState) { 11945 // Nothing to do 11946 return; 11947 } 11948 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 11949 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 11950 // Don't care about who enables an app. 11951 callingPackage = null; 11952 } 11953 pkgSetting.setEnabled(newState, userId, callingPackage); 11954 // pkgSetting.pkg.mSetEnabled = newState; 11955 } else { 11956 // We're dealing with a component level state change 11957 // First, verify that this is a valid class name. 11958 PackageParser.Package pkg = pkgSetting.pkg; 11959 if (pkg == null || !pkg.hasComponentClassName(className)) { 11960 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 11961 throw new IllegalArgumentException("Component class " + className 11962 + " does not exist in " + packageName); 11963 } else { 11964 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 11965 + className + " does not exist in " + packageName); 11966 } 11967 } 11968 switch (newState) { 11969 case COMPONENT_ENABLED_STATE_ENABLED: 11970 if (!pkgSetting.enableComponentLPw(className, userId)) { 11971 return; 11972 } 11973 break; 11974 case COMPONENT_ENABLED_STATE_DISABLED: 11975 if (!pkgSetting.disableComponentLPw(className, userId)) { 11976 return; 11977 } 11978 break; 11979 case COMPONENT_ENABLED_STATE_DEFAULT: 11980 if (!pkgSetting.restoreComponentLPw(className, userId)) { 11981 return; 11982 } 11983 break; 11984 default: 11985 Slog.e(TAG, "Invalid new component state: " + newState); 11986 return; 11987 } 11988 } 11989 mSettings.writePackageRestrictionsLPr(userId); 11990 components = mPendingBroadcasts.get(userId, packageName); 11991 final boolean newPackage = components == null; 11992 if (newPackage) { 11993 components = new ArrayList<String>(); 11994 } 11995 if (!components.contains(componentName)) { 11996 components.add(componentName); 11997 } 11998 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 11999 sendNow = true; 12000 // Purge entry from pending broadcast list if another one exists already 12001 // since we are sending one right away. 12002 mPendingBroadcasts.remove(userId, packageName); 12003 } else { 12004 if (newPackage) { 12005 mPendingBroadcasts.put(userId, packageName, components); 12006 } 12007 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 12008 // Schedule a message 12009 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 12010 } 12011 } 12012 } 12013 12014 long callingId = Binder.clearCallingIdentity(); 12015 try { 12016 if (sendNow) { 12017 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 12018 sendPackageChangedBroadcast(packageName, 12019 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 12020 } 12021 } finally { 12022 Binder.restoreCallingIdentity(callingId); 12023 } 12024 } 12025 12026 private void sendPackageChangedBroadcast(String packageName, 12027 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 12028 if (DEBUG_INSTALL) 12029 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 12030 + componentNames); 12031 Bundle extras = new Bundle(4); 12032 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 12033 String nameList[] = new String[componentNames.size()]; 12034 componentNames.toArray(nameList); 12035 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 12036 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 12037 extras.putInt(Intent.EXTRA_UID, packageUid); 12038 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 12039 new int[] {UserHandle.getUserId(packageUid)}); 12040 } 12041 12042 @Override 12043 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 12044 if (!sUserManager.exists(userId)) return; 12045 final int uid = Binder.getCallingUid(); 12046 final int permission = mContext.checkCallingOrSelfPermission( 12047 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 12048 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 12049 enforceCrossUserPermission(uid, userId, true, "stop package"); 12050 // writer 12051 synchronized (mPackages) { 12052 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 12053 uid, userId)) { 12054 scheduleWritePackageRestrictionsLocked(userId); 12055 } 12056 } 12057 } 12058 12059 @Override 12060 public String getInstallerPackageName(String packageName) { 12061 // reader 12062 synchronized (mPackages) { 12063 return mSettings.getInstallerPackageNameLPr(packageName); 12064 } 12065 } 12066 12067 @Override 12068 public int getApplicationEnabledSetting(String packageName, int userId) { 12069 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12070 int uid = Binder.getCallingUid(); 12071 enforceCrossUserPermission(uid, userId, false, "get enabled"); 12072 // reader 12073 synchronized (mPackages) { 12074 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 12075 } 12076 } 12077 12078 @Override 12079 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 12080 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12081 int uid = Binder.getCallingUid(); 12082 enforceCrossUserPermission(uid, userId, false, "get component enabled"); 12083 // reader 12084 synchronized (mPackages) { 12085 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 12086 } 12087 } 12088 12089 @Override 12090 public void enterSafeMode() { 12091 enforceSystemOrRoot("Only the system can request entering safe mode"); 12092 12093 if (!mSystemReady) { 12094 mSafeMode = true; 12095 } 12096 } 12097 12098 @Override 12099 public void systemReady() { 12100 mSystemReady = true; 12101 12102 // Read the compatibilty setting when the system is ready. 12103 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 12104 mContext.getContentResolver(), 12105 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 12106 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 12107 if (DEBUG_SETTINGS) { 12108 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 12109 } 12110 12111 synchronized (mPackages) { 12112 // Verify that all of the preferred activity components actually 12113 // exist. It is possible for applications to be updated and at 12114 // that point remove a previously declared activity component that 12115 // had been set as a preferred activity. We try to clean this up 12116 // the next time we encounter that preferred activity, but it is 12117 // possible for the user flow to never be able to return to that 12118 // situation so here we do a sanity check to make sure we haven't 12119 // left any junk around. 12120 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 12121 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12122 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12123 removed.clear(); 12124 for (PreferredActivity pa : pir.filterSet()) { 12125 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 12126 removed.add(pa); 12127 } 12128 } 12129 if (removed.size() > 0) { 12130 for (int r=0; r<removed.size(); r++) { 12131 PreferredActivity pa = removed.get(r); 12132 Slog.w(TAG, "Removing dangling preferred activity: " 12133 + pa.mPref.mComponent); 12134 pir.removeFilter(pa); 12135 } 12136 mSettings.writePackageRestrictionsLPr( 12137 mSettings.mPreferredActivities.keyAt(i)); 12138 } 12139 } 12140 } 12141 sUserManager.systemReady(); 12142 } 12143 12144 @Override 12145 public boolean isSafeMode() { 12146 return mSafeMode; 12147 } 12148 12149 @Override 12150 public boolean hasSystemUidErrors() { 12151 return mHasSystemUidErrors; 12152 } 12153 12154 static String arrayToString(int[] array) { 12155 StringBuffer buf = new StringBuffer(128); 12156 buf.append('['); 12157 if (array != null) { 12158 for (int i=0; i<array.length; i++) { 12159 if (i > 0) buf.append(", "); 12160 buf.append(array[i]); 12161 } 12162 } 12163 buf.append(']'); 12164 return buf.toString(); 12165 } 12166 12167 static class DumpState { 12168 public static final int DUMP_LIBS = 1 << 0; 12169 public static final int DUMP_FEATURES = 1 << 1; 12170 public static final int DUMP_RESOLVERS = 1 << 2; 12171 public static final int DUMP_PERMISSIONS = 1 << 3; 12172 public static final int DUMP_PACKAGES = 1 << 4; 12173 public static final int DUMP_SHARED_USERS = 1 << 5; 12174 public static final int DUMP_MESSAGES = 1 << 6; 12175 public static final int DUMP_PROVIDERS = 1 << 7; 12176 public static final int DUMP_VERIFIERS = 1 << 8; 12177 public static final int DUMP_PREFERRED = 1 << 9; 12178 public static final int DUMP_PREFERRED_XML = 1 << 10; 12179 public static final int DUMP_KEYSETS = 1 << 11; 12180 public static final int DUMP_VERSION = 1 << 12; 12181 public static final int DUMP_INSTALLS = 1 << 13; 12182 12183 public static final int OPTION_SHOW_FILTERS = 1 << 0; 12184 12185 private int mTypes; 12186 12187 private int mOptions; 12188 12189 private boolean mTitlePrinted; 12190 12191 private SharedUserSetting mSharedUser; 12192 12193 public boolean isDumping(int type) { 12194 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 12195 return true; 12196 } 12197 12198 return (mTypes & type) != 0; 12199 } 12200 12201 public void setDump(int type) { 12202 mTypes |= type; 12203 } 12204 12205 public boolean isOptionEnabled(int option) { 12206 return (mOptions & option) != 0; 12207 } 12208 12209 public void setOptionEnabled(int option) { 12210 mOptions |= option; 12211 } 12212 12213 public boolean onTitlePrinted() { 12214 final boolean printed = mTitlePrinted; 12215 mTitlePrinted = true; 12216 return printed; 12217 } 12218 12219 public boolean getTitlePrinted() { 12220 return mTitlePrinted; 12221 } 12222 12223 public void setTitlePrinted(boolean enabled) { 12224 mTitlePrinted = enabled; 12225 } 12226 12227 public SharedUserSetting getSharedUser() { 12228 return mSharedUser; 12229 } 12230 12231 public void setSharedUser(SharedUserSetting user) { 12232 mSharedUser = user; 12233 } 12234 } 12235 12236 @Override 12237 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 12238 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 12239 != PackageManager.PERMISSION_GRANTED) { 12240 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 12241 + Binder.getCallingPid() 12242 + ", uid=" + Binder.getCallingUid() 12243 + " without permission " 12244 + android.Manifest.permission.DUMP); 12245 return; 12246 } 12247 12248 DumpState dumpState = new DumpState(); 12249 boolean fullPreferred = false; 12250 boolean checkin = false; 12251 12252 String packageName = null; 12253 12254 int opti = 0; 12255 while (opti < args.length) { 12256 String opt = args[opti]; 12257 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 12258 break; 12259 } 12260 opti++; 12261 if ("-a".equals(opt)) { 12262 // Right now we only know how to print all. 12263 } else if ("-h".equals(opt)) { 12264 pw.println("Package manager dump options:"); 12265 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 12266 pw.println(" --checkin: dump for a checkin"); 12267 pw.println(" -f: print details of intent filters"); 12268 pw.println(" -h: print this help"); 12269 pw.println(" cmd may be one of:"); 12270 pw.println(" l[ibraries]: list known shared libraries"); 12271 pw.println(" f[ibraries]: list device features"); 12272 pw.println(" k[eysets]: print known keysets"); 12273 pw.println(" r[esolvers]: dump intent resolvers"); 12274 pw.println(" perm[issions]: dump permissions"); 12275 pw.println(" pref[erred]: print preferred package settings"); 12276 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 12277 pw.println(" prov[iders]: dump content providers"); 12278 pw.println(" p[ackages]: dump installed packages"); 12279 pw.println(" s[hared-users]: dump shared user IDs"); 12280 pw.println(" m[essages]: print collected runtime messages"); 12281 pw.println(" v[erifiers]: print package verifier info"); 12282 pw.println(" version: print database version info"); 12283 pw.println(" write: write current settings now"); 12284 pw.println(" <package.name>: info about given package"); 12285 pw.println(" installs: details about install sessions"); 12286 return; 12287 } else if ("--checkin".equals(opt)) { 12288 checkin = true; 12289 } else if ("-f".equals(opt)) { 12290 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12291 } else { 12292 pw.println("Unknown argument: " + opt + "; use -h for help"); 12293 } 12294 } 12295 12296 // Is the caller requesting to dump a particular piece of data? 12297 if (opti < args.length) { 12298 String cmd = args[opti]; 12299 opti++; 12300 // Is this a package name? 12301 if ("android".equals(cmd) || cmd.contains(".")) { 12302 packageName = cmd; 12303 // When dumping a single package, we always dump all of its 12304 // filter information since the amount of data will be reasonable. 12305 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12306 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 12307 dumpState.setDump(DumpState.DUMP_LIBS); 12308 } else if ("f".equals(cmd) || "features".equals(cmd)) { 12309 dumpState.setDump(DumpState.DUMP_FEATURES); 12310 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 12311 dumpState.setDump(DumpState.DUMP_RESOLVERS); 12312 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 12313 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 12314 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 12315 dumpState.setDump(DumpState.DUMP_PREFERRED); 12316 } else if ("preferred-xml".equals(cmd)) { 12317 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 12318 if (opti < args.length && "--full".equals(args[opti])) { 12319 fullPreferred = true; 12320 opti++; 12321 } 12322 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 12323 dumpState.setDump(DumpState.DUMP_PACKAGES); 12324 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 12325 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 12326 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 12327 dumpState.setDump(DumpState.DUMP_PROVIDERS); 12328 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 12329 dumpState.setDump(DumpState.DUMP_MESSAGES); 12330 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 12331 dumpState.setDump(DumpState.DUMP_VERIFIERS); 12332 } else if ("version".equals(cmd)) { 12333 dumpState.setDump(DumpState.DUMP_VERSION); 12334 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 12335 dumpState.setDump(DumpState.DUMP_KEYSETS); 12336 } else if ("write".equals(cmd)) { 12337 synchronized (mPackages) { 12338 mSettings.writeLPr(); 12339 pw.println("Settings written."); 12340 return; 12341 } 12342 } else if ("installs".equals(cmd)) { 12343 dumpState.setDump(DumpState.DUMP_INSTALLS); 12344 } 12345 } 12346 12347 if (checkin) { 12348 pw.println("vers,1"); 12349 } 12350 12351 // reader 12352 synchronized (mPackages) { 12353 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 12354 if (!checkin) { 12355 if (dumpState.onTitlePrinted()) 12356 pw.println(); 12357 pw.println("Database versions:"); 12358 pw.print(" SDK Version:"); 12359 pw.print(" internal="); 12360 pw.print(mSettings.mInternalSdkPlatform); 12361 pw.print(" external="); 12362 pw.println(mSettings.mExternalSdkPlatform); 12363 pw.print(" DB Version:"); 12364 pw.print(" internal="); 12365 pw.print(mSettings.mInternalDatabaseVersion); 12366 pw.print(" external="); 12367 pw.println(mSettings.mExternalDatabaseVersion); 12368 } 12369 } 12370 12371 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 12372 if (!checkin) { 12373 if (dumpState.onTitlePrinted()) 12374 pw.println(); 12375 pw.println("Verifiers:"); 12376 pw.print(" Required: "); 12377 pw.print(mRequiredVerifierPackage); 12378 pw.print(" (uid="); 12379 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 12380 pw.println(")"); 12381 } else if (mRequiredVerifierPackage != null) { 12382 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 12383 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 12384 } 12385 } 12386 12387 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 12388 boolean printedHeader = false; 12389 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 12390 while (it.hasNext()) { 12391 String name = it.next(); 12392 SharedLibraryEntry ent = mSharedLibraries.get(name); 12393 if (!checkin) { 12394 if (!printedHeader) { 12395 if (dumpState.onTitlePrinted()) 12396 pw.println(); 12397 pw.println("Libraries:"); 12398 printedHeader = true; 12399 } 12400 pw.print(" "); 12401 } else { 12402 pw.print("lib,"); 12403 } 12404 pw.print(name); 12405 if (!checkin) { 12406 pw.print(" -> "); 12407 } 12408 if (ent.path != null) { 12409 if (!checkin) { 12410 pw.print("(jar) "); 12411 pw.print(ent.path); 12412 } else { 12413 pw.print(",jar,"); 12414 pw.print(ent.path); 12415 } 12416 } else { 12417 if (!checkin) { 12418 pw.print("(apk) "); 12419 pw.print(ent.apk); 12420 } else { 12421 pw.print(",apk,"); 12422 pw.print(ent.apk); 12423 } 12424 } 12425 pw.println(); 12426 } 12427 } 12428 12429 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 12430 if (dumpState.onTitlePrinted()) 12431 pw.println(); 12432 if (!checkin) { 12433 pw.println("Features:"); 12434 } 12435 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 12436 while (it.hasNext()) { 12437 String name = it.next(); 12438 if (!checkin) { 12439 pw.print(" "); 12440 } else { 12441 pw.print("feat,"); 12442 } 12443 pw.println(name); 12444 } 12445 } 12446 12447 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 12448 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 12449 : "Activity Resolver Table:", " ", packageName, 12450 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12451 dumpState.setTitlePrinted(true); 12452 } 12453 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 12454 : "Receiver Resolver Table:", " ", packageName, 12455 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12456 dumpState.setTitlePrinted(true); 12457 } 12458 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 12459 : "Service Resolver Table:", " ", packageName, 12460 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12461 dumpState.setTitlePrinted(true); 12462 } 12463 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 12464 : "Provider Resolver Table:", " ", packageName, 12465 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12466 dumpState.setTitlePrinted(true); 12467 } 12468 } 12469 12470 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 12471 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12472 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12473 int user = mSettings.mPreferredActivities.keyAt(i); 12474 if (pir.dump(pw, 12475 dumpState.getTitlePrinted() 12476 ? "\nPreferred Activities User " + user + ":" 12477 : "Preferred Activities User " + user + ":", " ", 12478 packageName, true)) { 12479 dumpState.setTitlePrinted(true); 12480 } 12481 } 12482 } 12483 12484 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 12485 pw.flush(); 12486 FileOutputStream fout = new FileOutputStream(fd); 12487 BufferedOutputStream str = new BufferedOutputStream(fout); 12488 XmlSerializer serializer = new FastXmlSerializer(); 12489 try { 12490 serializer.setOutput(str, "utf-8"); 12491 serializer.startDocument(null, true); 12492 serializer.setFeature( 12493 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 12494 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 12495 serializer.endDocument(); 12496 serializer.flush(); 12497 } catch (IllegalArgumentException e) { 12498 pw.println("Failed writing: " + e); 12499 } catch (IllegalStateException e) { 12500 pw.println("Failed writing: " + e); 12501 } catch (IOException e) { 12502 pw.println("Failed writing: " + e); 12503 } 12504 } 12505 12506 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 12507 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 12508 if (packageName == null) { 12509 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 12510 if (iperm == 0) { 12511 if (dumpState.onTitlePrinted()) 12512 pw.println(); 12513 pw.println("AppOp Permissions:"); 12514 } 12515 pw.print(" AppOp Permission "); 12516 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 12517 pw.println(":"); 12518 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 12519 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 12520 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 12521 } 12522 } 12523 } 12524 } 12525 12526 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 12527 boolean printedSomething = false; 12528 for (PackageParser.Provider p : mProviders.mProviders.values()) { 12529 if (packageName != null && !packageName.equals(p.info.packageName)) { 12530 continue; 12531 } 12532 if (!printedSomething) { 12533 if (dumpState.onTitlePrinted()) 12534 pw.println(); 12535 pw.println("Registered ContentProviders:"); 12536 printedSomething = true; 12537 } 12538 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 12539 pw.print(" "); pw.println(p.toString()); 12540 } 12541 printedSomething = false; 12542 for (Map.Entry<String, PackageParser.Provider> entry : 12543 mProvidersByAuthority.entrySet()) { 12544 PackageParser.Provider p = entry.getValue(); 12545 if (packageName != null && !packageName.equals(p.info.packageName)) { 12546 continue; 12547 } 12548 if (!printedSomething) { 12549 if (dumpState.onTitlePrinted()) 12550 pw.println(); 12551 pw.println("ContentProvider Authorities:"); 12552 printedSomething = true; 12553 } 12554 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 12555 pw.print(" "); pw.println(p.toString()); 12556 if (p.info != null && p.info.applicationInfo != null) { 12557 final String appInfo = p.info.applicationInfo.toString(); 12558 pw.print(" applicationInfo="); pw.println(appInfo); 12559 } 12560 } 12561 } 12562 12563 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 12564 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 12565 } 12566 12567 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 12568 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 12569 } 12570 12571 if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 12572 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState); 12573 } 12574 12575 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS)) { 12576 if (dumpState.onTitlePrinted()) pw.println(); 12577 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 12578 } 12579 12580 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 12581 if (dumpState.onTitlePrinted()) pw.println(); 12582 mSettings.dumpReadMessagesLPr(pw, dumpState); 12583 12584 pw.println(); 12585 pw.println("Package warning messages:"); 12586 final File fname = getSettingsProblemFile(); 12587 FileInputStream in = null; 12588 try { 12589 in = new FileInputStream(fname); 12590 final int avail = in.available(); 12591 final byte[] data = new byte[avail]; 12592 in.read(data); 12593 pw.print(new String(data)); 12594 } catch (FileNotFoundException e) { 12595 } catch (IOException e) { 12596 } finally { 12597 if (in != null) { 12598 try { 12599 in.close(); 12600 } catch (IOException e) { 12601 } 12602 } 12603 } 12604 } 12605 } 12606 } 12607 12608 // ------- apps on sdcard specific code ------- 12609 static final boolean DEBUG_SD_INSTALL = false; 12610 12611 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 12612 12613 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 12614 12615 private boolean mMediaMounted = false; 12616 12617 static String getEncryptKey() { 12618 try { 12619 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 12620 SD_ENCRYPTION_KEYSTORE_NAME); 12621 if (sdEncKey == null) { 12622 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 12623 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 12624 if (sdEncKey == null) { 12625 Slog.e(TAG, "Failed to create encryption keys"); 12626 return null; 12627 } 12628 } 12629 return sdEncKey; 12630 } catch (NoSuchAlgorithmException nsae) { 12631 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 12632 return null; 12633 } catch (IOException ioe) { 12634 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 12635 return null; 12636 } 12637 } 12638 12639 /* 12640 * Update media status on PackageManager. 12641 */ 12642 @Override 12643 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 12644 int callingUid = Binder.getCallingUid(); 12645 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 12646 throw new SecurityException("Media status can only be updated by the system"); 12647 } 12648 // reader; this apparently protects mMediaMounted, but should probably 12649 // be a different lock in that case. 12650 synchronized (mPackages) { 12651 Log.i(TAG, "Updating external media status from " 12652 + (mMediaMounted ? "mounted" : "unmounted") + " to " 12653 + (mediaStatus ? "mounted" : "unmounted")); 12654 if (DEBUG_SD_INSTALL) 12655 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 12656 + ", mMediaMounted=" + mMediaMounted); 12657 if (mediaStatus == mMediaMounted) { 12658 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 12659 : 0, -1); 12660 mHandler.sendMessage(msg); 12661 return; 12662 } 12663 mMediaMounted = mediaStatus; 12664 } 12665 // Queue up an async operation since the package installation may take a 12666 // little while. 12667 mHandler.post(new Runnable() { 12668 public void run() { 12669 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 12670 } 12671 }); 12672 } 12673 12674 /** 12675 * Called by MountService when the initial ASECs to scan are available. 12676 * Should block until all the ASEC containers are finished being scanned. 12677 */ 12678 public void scanAvailableAsecs() { 12679 updateExternalMediaStatusInner(true, false, false); 12680 if (mShouldRestoreconData) { 12681 SELinuxMMAC.setRestoreconDone(); 12682 mShouldRestoreconData = false; 12683 } 12684 } 12685 12686 /* 12687 * Collect information of applications on external media, map them against 12688 * existing containers and update information based on current mount status. 12689 * Please note that we always have to report status if reportStatus has been 12690 * set to true especially when unloading packages. 12691 */ 12692 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 12693 boolean externalStorage) { 12694 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 12695 int[] uidArr = EmptyArray.INT; 12696 12697 final String[] list = PackageHelper.getSecureContainerList(); 12698 if (ArrayUtils.isEmpty(list)) { 12699 Log.i(TAG, "No secure containers found"); 12700 } else { 12701 // Process list of secure containers and categorize them 12702 // as active or stale based on their package internal state. 12703 12704 // reader 12705 synchronized (mPackages) { 12706 for (String cid : list) { 12707 // Leave stages untouched for now; installer service owns them 12708 if (PackageInstallerService.isStageName(cid)) continue; 12709 12710 if (DEBUG_SD_INSTALL) 12711 Log.i(TAG, "Processing container " + cid); 12712 String pkgName = getAsecPackageName(cid); 12713 if (pkgName == null) { 12714 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 12715 continue; 12716 } 12717 if (DEBUG_SD_INSTALL) 12718 Log.i(TAG, "Looking for pkg : " + pkgName); 12719 12720 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12721 if (ps == null) { 12722 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 12723 continue; 12724 } 12725 12726 /* 12727 * Skip packages that are not external if we're unmounting 12728 * external storage. 12729 */ 12730 if (externalStorage && !isMounted && !isExternal(ps)) { 12731 continue; 12732 } 12733 12734 final AsecInstallArgs args = new AsecInstallArgs(cid, 12735 getAppDexInstructionSets(ps), isForwardLocked(ps)); 12736 // The package status is changed only if the code path 12737 // matches between settings and the container id. 12738 if (ps.codePathString != null 12739 && ps.codePathString.startsWith(args.getCodePath())) { 12740 if (DEBUG_SD_INSTALL) { 12741 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 12742 + " at code path: " + ps.codePathString); 12743 } 12744 12745 // We do have a valid package installed on sdcard 12746 processCids.put(args, ps.codePathString); 12747 final int uid = ps.appId; 12748 if (uid != -1) { 12749 uidArr = ArrayUtils.appendInt(uidArr, uid); 12750 } 12751 } else { 12752 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 12753 + ps.codePathString); 12754 } 12755 } 12756 } 12757 12758 Arrays.sort(uidArr); 12759 } 12760 12761 // Process packages with valid entries. 12762 if (isMounted) { 12763 if (DEBUG_SD_INSTALL) 12764 Log.i(TAG, "Loading packages"); 12765 loadMediaPackages(processCids, uidArr); 12766 startCleaningPackages(); 12767 mInstallerService.onSecureContainersAvailable(); 12768 } else { 12769 if (DEBUG_SD_INSTALL) 12770 Log.i(TAG, "Unloading packages"); 12771 unloadMediaPackages(processCids, uidArr, reportStatus); 12772 } 12773 } 12774 12775 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 12776 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 12777 int size = pkgList.size(); 12778 if (size > 0) { 12779 // Send broadcasts here 12780 Bundle extras = new Bundle(); 12781 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 12782 .toArray(new String[size])); 12783 if (uidArr != null) { 12784 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 12785 } 12786 if (replacing) { 12787 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 12788 } 12789 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 12790 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 12791 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 12792 } 12793 } 12794 12795 /* 12796 * Look at potentially valid container ids from processCids If package 12797 * information doesn't match the one on record or package scanning fails, 12798 * the cid is added to list of removeCids. We currently don't delete stale 12799 * containers. 12800 */ 12801 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 12802 ArrayList<String> pkgList = new ArrayList<String>(); 12803 Set<AsecInstallArgs> keys = processCids.keySet(); 12804 12805 for (AsecInstallArgs args : keys) { 12806 String codePath = processCids.get(args); 12807 if (DEBUG_SD_INSTALL) 12808 Log.i(TAG, "Loading container : " + args.cid); 12809 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12810 try { 12811 // Make sure there are no container errors first. 12812 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 12813 Slog.e(TAG, "Failed to mount cid : " + args.cid 12814 + " when installing from sdcard"); 12815 continue; 12816 } 12817 // Check code path here. 12818 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 12819 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 12820 + " does not match one in settings " + codePath); 12821 continue; 12822 } 12823 // Parse package 12824 int parseFlags = mDefParseFlags; 12825 if (args.isExternal()) { 12826 parseFlags |= PackageParser.PARSE_ON_SDCARD; 12827 } 12828 if (args.isFwdLocked()) { 12829 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 12830 } 12831 12832 synchronized (mInstallLock) { 12833 PackageParser.Package pkg = null; 12834 try { 12835 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 12836 } catch (PackageManagerException e) { 12837 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 12838 } 12839 // Scan the package 12840 if (pkg != null) { 12841 /* 12842 * TODO why is the lock being held? doPostInstall is 12843 * called in other places without the lock. This needs 12844 * to be straightened out. 12845 */ 12846 // writer 12847 synchronized (mPackages) { 12848 retCode = PackageManager.INSTALL_SUCCEEDED; 12849 pkgList.add(pkg.packageName); 12850 // Post process args 12851 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 12852 pkg.applicationInfo.uid); 12853 } 12854 } else { 12855 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 12856 } 12857 } 12858 12859 } finally { 12860 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 12861 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 12862 } 12863 } 12864 } 12865 // writer 12866 synchronized (mPackages) { 12867 // If the platform SDK has changed since the last time we booted, 12868 // we need to re-grant app permission to catch any new ones that 12869 // appear. This is really a hack, and means that apps can in some 12870 // cases get permissions that the user didn't initially explicitly 12871 // allow... it would be nice to have some better way to handle 12872 // this situation. 12873 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 12874 if (regrantPermissions) 12875 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 12876 + mSdkVersion + "; regranting permissions for external storage"); 12877 mSettings.mExternalSdkPlatform = mSdkVersion; 12878 12879 // Make sure group IDs have been assigned, and any permission 12880 // changes in other apps are accounted for 12881 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 12882 | (regrantPermissions 12883 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 12884 : 0)); 12885 12886 mSettings.updateExternalDatabaseVersion(); 12887 12888 // can downgrade to reader 12889 // Persist settings 12890 mSettings.writeLPr(); 12891 } 12892 // Send a broadcast to let everyone know we are done processing 12893 if (pkgList.size() > 0) { 12894 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12895 } 12896 } 12897 12898 /* 12899 * Utility method to unload a list of specified containers 12900 */ 12901 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 12902 // Just unmount all valid containers. 12903 for (AsecInstallArgs arg : cidArgs) { 12904 synchronized (mInstallLock) { 12905 arg.doPostDeleteLI(false); 12906 } 12907 } 12908 } 12909 12910 /* 12911 * Unload packages mounted on external media. This involves deleting package 12912 * data from internal structures, sending broadcasts about diabled packages, 12913 * gc'ing to free up references, unmounting all secure containers 12914 * corresponding to packages on external media, and posting a 12915 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 12916 * that we always have to post this message if status has been requested no 12917 * matter what. 12918 */ 12919 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 12920 final boolean reportStatus) { 12921 if (DEBUG_SD_INSTALL) 12922 Log.i(TAG, "unloading media packages"); 12923 ArrayList<String> pkgList = new ArrayList<String>(); 12924 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 12925 final Set<AsecInstallArgs> keys = processCids.keySet(); 12926 for (AsecInstallArgs args : keys) { 12927 String pkgName = args.getPackageName(); 12928 if (DEBUG_SD_INSTALL) 12929 Log.i(TAG, "Trying to unload pkg : " + pkgName); 12930 // Delete package internally 12931 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 12932 synchronized (mInstallLock) { 12933 boolean res = deletePackageLI(pkgName, null, false, null, null, 12934 PackageManager.DELETE_KEEP_DATA, outInfo, false); 12935 if (res) { 12936 pkgList.add(pkgName); 12937 } else { 12938 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 12939 failedList.add(args); 12940 } 12941 } 12942 } 12943 12944 // reader 12945 synchronized (mPackages) { 12946 // We didn't update the settings after removing each package; 12947 // write them now for all packages. 12948 mSettings.writeLPr(); 12949 } 12950 12951 // We have to absolutely send UPDATED_MEDIA_STATUS only 12952 // after confirming that all the receivers processed the ordered 12953 // broadcast when packages get disabled, force a gc to clean things up. 12954 // and unload all the containers. 12955 if (pkgList.size() > 0) { 12956 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 12957 new IIntentReceiver.Stub() { 12958 public void performReceive(Intent intent, int resultCode, String data, 12959 Bundle extras, boolean ordered, boolean sticky, 12960 int sendingUser) throws RemoteException { 12961 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 12962 reportStatus ? 1 : 0, 1, keys); 12963 mHandler.sendMessage(msg); 12964 } 12965 }); 12966 } else { 12967 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 12968 keys); 12969 mHandler.sendMessage(msg); 12970 } 12971 } 12972 12973 /** Binder call */ 12974 @Override 12975 public void movePackage(final String packageName, final IPackageMoveObserver observer, 12976 final int flags) { 12977 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 12978 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 12979 int returnCode = PackageManager.MOVE_SUCCEEDED; 12980 int currFlags = 0; 12981 int newFlags = 0; 12982 // reader 12983 synchronized (mPackages) { 12984 PackageParser.Package pkg = mPackages.get(packageName); 12985 if (pkg == null) { 12986 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12987 } else { 12988 // Disable moving fwd locked apps and system packages 12989 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 12990 Slog.w(TAG, "Cannot move system application"); 12991 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 12992 } else if (pkg.mOperationPending) { 12993 Slog.w(TAG, "Attempt to move package which has pending operations"); 12994 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 12995 } else { 12996 // Find install location first 12997 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 12998 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 12999 Slog.w(TAG, "Ambigous flags specified for move location."); 13000 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 13001 } else { 13002 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL 13003 : PackageManager.INSTALL_INTERNAL; 13004 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL 13005 : PackageManager.INSTALL_INTERNAL; 13006 13007 if (newFlags == currFlags) { 13008 Slog.w(TAG, "No move required. Trying to move to same location"); 13009 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 13010 } else { 13011 if (isForwardLocked(pkg)) { 13012 currFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13013 newFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13014 } 13015 } 13016 } 13017 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13018 pkg.mOperationPending = true; 13019 } 13020 } 13021 } 13022 13023 /* 13024 * TODO this next block probably shouldn't be inside the lock. We 13025 * can't guarantee these won't change after this is fired off 13026 * anyway. 13027 */ 13028 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 13029 processPendingMove(new MoveParams(null, observer, 0, packageName, null, -1, user), 13030 returnCode); 13031 } else { 13032 Message msg = mHandler.obtainMessage(INIT_COPY); 13033 final String[] instructionSets = getAppDexInstructionSets(pkg.applicationInfo); 13034 final boolean multiArch = isMultiArch(pkg.applicationInfo); 13035 InstallArgs srcArgs = createInstallArgsForExisting(currFlags, 13036 pkg.applicationInfo.getCodePath(), pkg.applicationInfo.getResourcePath(), 13037 pkg.applicationInfo.nativeLibraryRootDir, instructionSets); 13038 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName, 13039 instructionSets, pkg.applicationInfo.uid, user); 13040 msg.obj = mp; 13041 mHandler.sendMessage(msg); 13042 } 13043 } 13044 } 13045 13046 private void processPendingMove(final MoveParams mp, final int currentStatus) { 13047 // Queue up an async operation since the package deletion may take a 13048 // little while. 13049 mHandler.post(new Runnable() { 13050 public void run() { 13051 // TODO fix this; this does nothing. 13052 mHandler.removeCallbacks(this); 13053 int returnCode = currentStatus; 13054 if (currentStatus == PackageManager.MOVE_SUCCEEDED) { 13055 int uidArr[] = null; 13056 ArrayList<String> pkgList = null; 13057 synchronized (mPackages) { 13058 PackageParser.Package pkg = mPackages.get(mp.packageName); 13059 if (pkg == null) { 13060 Slog.w(TAG, " Package " + mp.packageName 13061 + " doesn't exist. Aborting move"); 13062 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 13063 } else if (!mp.srcArgs.getCodePath().equals( 13064 pkg.applicationInfo.getCodePath())) { 13065 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " 13066 + mp.srcArgs.getCodePath() + " to " 13067 + pkg.applicationInfo.getCodePath() 13068 + " Aborting move and returning error"); 13069 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 13070 } else { 13071 uidArr = new int[] { 13072 pkg.applicationInfo.uid 13073 }; 13074 pkgList = new ArrayList<String>(); 13075 pkgList.add(mp.packageName); 13076 } 13077 } 13078 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13079 // Send resources unavailable broadcast 13080 sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null); 13081 // Update package code and resource paths 13082 synchronized (mInstallLock) { 13083 synchronized (mPackages) { 13084 PackageParser.Package pkg = mPackages.get(mp.packageName); 13085 // Recheck for package again. 13086 if (pkg == null) { 13087 Slog.w(TAG, " Package " + mp.packageName 13088 + " doesn't exist. Aborting move"); 13089 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 13090 } else if (!mp.srcArgs.getCodePath().equals( 13091 pkg.applicationInfo.getCodePath())) { 13092 Slog.w(TAG, "Package " + mp.packageName 13093 + " code path changed from " + mp.srcArgs.getCodePath() 13094 + " to " + pkg.applicationInfo.getCodePath() 13095 + " Aborting move and returning error"); 13096 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 13097 } else { 13098 final String oldCodePath = pkg.codePath; 13099 final String newCodePath = mp.targetArgs.getCodePath(); 13100 final String newResPath = mp.targetArgs.getResourcePath(); 13101 // TODO: This assumes the new style of installation. 13102 // should we look at legacyNativeLibraryPath ? 13103 final String newNativeRoot = new File(pkg.codePath, LIB_DIR_NAME).getAbsolutePath(); 13104 final File newNativeDir = new File(newNativeRoot); 13105 13106 if (!isForwardLocked(pkg) && !isExternal(pkg)) { 13107 // TODO(multiArch): Fix this so that it looks at the existing 13108 // recorded CPU abis from the package. There's no need for a separate 13109 // round of ABI scanning here. 13110 NativeLibraryHelper.Handle handle = null; 13111 try { 13112 handle = NativeLibraryHelper.Handle.create( 13113 new File(newCodePath)); 13114 final int abi = NativeLibraryHelper.findSupportedAbi( 13115 handle, Build.SUPPORTED_ABIS); 13116 if (abi >= 0) { 13117 NativeLibraryHelper.copyNativeBinaries(handle, 13118 newNativeDir, Build.SUPPORTED_ABIS[abi]); 13119 } 13120 } catch (IOException ioe) { 13121 Slog.w(TAG, "Unable to extract native libs for package :" 13122 + mp.packageName, ioe); 13123 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 13124 } finally { 13125 IoUtils.closeQuietly(handle); 13126 } 13127 } 13128 13129 final int[] users = sUserManager.getUserIds(); 13130 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13131 for (int user : users) { 13132 // TODO(multiArch): Fix this so that it links to the 13133 // correct directory. We're currently pointing to root. but we 13134 // must point to the arch specific subdirectory (if applicable). 13135 // 13136 // TODO(multiArch): Bogus reference to nativeLibraryDir. 13137 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, 13138 newNativeRoot, user) < 0) { 13139 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 13140 } 13141 } 13142 } 13143 13144 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13145 pkg.codePath = newCodePath; 13146 pkg.baseCodePath = newCodePath; 13147 // Move dex files around 13148 if (moveDexFilesLI(oldCodePath, pkg) != PackageManager.INSTALL_SUCCEEDED) { 13149 // Moving of dex files failed. Set 13150 // error code and abort move. 13151 pkg.codePath = oldCodePath; 13152 pkg.baseCodePath = oldCodePath; 13153 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 13154 } 13155 } 13156 13157 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13158 pkg.applicationInfo.setCodePath(newCodePath); 13159 pkg.applicationInfo.setBaseCodePath(newCodePath); 13160 pkg.applicationInfo.setSplitCodePaths(null); 13161 pkg.applicationInfo.setResourcePath(newResPath); 13162 pkg.applicationInfo.setBaseResourcePath(newResPath); 13163 pkg.applicationInfo.setSplitResourcePaths(null); 13164 13165 PackageSetting ps = (PackageSetting) pkg.mExtras; 13166 ps.codePath = new File(pkg.applicationInfo.getCodePath()); 13167 ps.codePathString = ps.codePath.getPath(); 13168 ps.resourcePath = new File(pkg.applicationInfo.getResourcePath()); 13169 ps.resourcePathString = ps.resourcePath.getPath(); 13170 13171 // Note that we don't have to recalculate the primary and secondary 13172 // CPU ABIs because they must already have been calculated during the 13173 // initial install of the app. 13174 ps.legacyNativeLibraryPathString = null; 13175 13176 // Set the application info flag 13177 // correctly. 13178 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) { 13179 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE; 13180 } else { 13181 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE; 13182 } 13183 ps.setFlags(pkg.applicationInfo.flags); 13184 mAppDirs.remove(oldCodePath); 13185 mAppDirs.put(newCodePath, pkg); 13186 // Persist settings 13187 mSettings.writeLPr(); 13188 } 13189 } 13190 } 13191 } 13192 // Send resources available broadcast 13193 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 13194 } 13195 } 13196 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 13197 // Clean up failed installation 13198 if (mp.targetArgs != null) { 13199 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR, 13200 -1); 13201 } 13202 } else { 13203 // Force a gc to clear things up. 13204 Runtime.getRuntime().gc(); 13205 // Delete older code 13206 synchronized (mInstallLock) { 13207 mp.srcArgs.doPostDeleteLI(true); 13208 } 13209 } 13210 13211 // Allow more operations on this file if we didn't fail because 13212 // an operation was already pending for this package. 13213 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) { 13214 synchronized (mPackages) { 13215 PackageParser.Package pkg = mPackages.get(mp.packageName); 13216 if (pkg != null) { 13217 pkg.mOperationPending = false; 13218 } 13219 } 13220 } 13221 13222 IPackageMoveObserver observer = mp.observer; 13223 if (observer != null) { 13224 try { 13225 observer.packageMoved(mp.packageName, returnCode); 13226 } catch (RemoteException e) { 13227 Log.i(TAG, "Observer no longer exists."); 13228 } 13229 } 13230 } 13231 }); 13232 } 13233 13234 @Override 13235 public boolean setInstallLocation(int loc) { 13236 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 13237 null); 13238 if (getInstallLocation() == loc) { 13239 return true; 13240 } 13241 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 13242 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 13243 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 13244 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 13245 return true; 13246 } 13247 return false; 13248 } 13249 13250 @Override 13251 public int getInstallLocation() { 13252 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13253 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 13254 PackageHelper.APP_INSTALL_AUTO); 13255 } 13256 13257 /** Called by UserManagerService */ 13258 void cleanUpUserLILPw(int userHandle) { 13259 mDirtyUsers.remove(userHandle); 13260 mSettings.removeUserLPw(userHandle); 13261 mPendingBroadcasts.remove(userHandle); 13262 if (mInstaller != null) { 13263 // Technically, we shouldn't be doing this with the package lock 13264 // held. However, this is very rare, and there is already so much 13265 // other disk I/O going on, that we'll let it slide for now. 13266 mInstaller.removeUserDataDirs(userHandle); 13267 } 13268 mUserNeedsBadging.delete(userHandle); 13269 } 13270 13271 /** Called by UserManagerService */ 13272 void createNewUserLILPw(int userHandle, File path) { 13273 if (mInstaller != null) { 13274 mInstaller.createUserConfig(userHandle); 13275 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 13276 } 13277 } 13278 13279 @Override 13280 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 13281 mContext.enforceCallingOrSelfPermission( 13282 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13283 "Only package verification agents can read the verifier device identity"); 13284 13285 synchronized (mPackages) { 13286 return mSettings.getVerifierDeviceIdentityLPw(); 13287 } 13288 } 13289 13290 @Override 13291 public void setPermissionEnforced(String permission, boolean enforced) { 13292 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 13293 if (READ_EXTERNAL_STORAGE.equals(permission)) { 13294 synchronized (mPackages) { 13295 if (mSettings.mReadExternalStorageEnforced == null 13296 || mSettings.mReadExternalStorageEnforced != enforced) { 13297 mSettings.mReadExternalStorageEnforced = enforced; 13298 mSettings.writeLPr(); 13299 } 13300 } 13301 // kill any non-foreground processes so we restart them and 13302 // grant/revoke the GID. 13303 final IActivityManager am = ActivityManagerNative.getDefault(); 13304 if (am != null) { 13305 final long token = Binder.clearCallingIdentity(); 13306 try { 13307 am.killProcessesBelowForeground("setPermissionEnforcement"); 13308 } catch (RemoteException e) { 13309 } finally { 13310 Binder.restoreCallingIdentity(token); 13311 } 13312 } 13313 } else { 13314 throw new IllegalArgumentException("No selective enforcement for " + permission); 13315 } 13316 } 13317 13318 @Override 13319 @Deprecated 13320 public boolean isPermissionEnforced(String permission) { 13321 return true; 13322 } 13323 13324 @Override 13325 public boolean isStorageLow() { 13326 final long token = Binder.clearCallingIdentity(); 13327 try { 13328 final DeviceStorageMonitorInternal 13329 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13330 if (dsm != null) { 13331 return dsm.isMemoryLow(); 13332 } else { 13333 return false; 13334 } 13335 } finally { 13336 Binder.restoreCallingIdentity(token); 13337 } 13338 } 13339 13340 @Override 13341 public IPackageInstaller getPackageInstaller() { 13342 return mInstallerService; 13343 } 13344 13345 private boolean userNeedsBadging(int userId) { 13346 int index = mUserNeedsBadging.indexOfKey(userId); 13347 if (index < 0) { 13348 final UserInfo userInfo; 13349 final long token = Binder.clearCallingIdentity(); 13350 try { 13351 userInfo = sUserManager.getUserInfo(userId); 13352 } finally { 13353 Binder.restoreCallingIdentity(token); 13354 } 13355 final boolean b; 13356 if (userInfo != null && userInfo.isManagedProfile()) { 13357 b = true; 13358 } else { 13359 b = false; 13360 } 13361 mUserNeedsBadging.put(userId, b); 13362 return b; 13363 } 13364 return mUserNeedsBadging.valueAt(index); 13365 } 13366 13367 @Override 13368 public KeySetHandle getKeySetByAlias(String packageName, String alias) { 13369 if (packageName == null || alias == null) { 13370 return null; 13371 } 13372 synchronized(mPackages) { 13373 final PackageParser.Package pkg = mPackages.get(packageName); 13374 if (pkg == null) { 13375 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13376 throw new IllegalArgumentException("Unknown package: " + packageName); 13377 } 13378 if (pkg.applicationInfo.uid != Binder.getCallingUid() 13379 && Process.SYSTEM_UID != Binder.getCallingUid()) { 13380 throw new SecurityException("May not access KeySets defined by" 13381 + " aliases in other applications."); 13382 } 13383 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13384 return ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias); 13385 } 13386 } 13387 13388 @Override 13389 public KeySetHandle getSigningKeySet(String packageName) { 13390 if (packageName == null) { 13391 return null; 13392 } 13393 synchronized(mPackages) { 13394 final PackageParser.Package pkg = mPackages.get(packageName); 13395 if (pkg == null) { 13396 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13397 throw new IllegalArgumentException("Unknown package: " + packageName); 13398 } 13399 if (pkg.applicationInfo.uid != Binder.getCallingUid() 13400 && Process.SYSTEM_UID != Binder.getCallingUid()) { 13401 throw new SecurityException("May not access signing KeySet of other apps."); 13402 } 13403 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13404 return ksms.getSigningKeySetByPackageNameLPr(packageName); 13405 } 13406 } 13407 13408 @Override 13409 public boolean isPackageSignedByKeySet(String packageName, IBinder ks) { 13410 if (packageName == null || ks == null) { 13411 return false; 13412 } 13413 synchronized(mPackages) { 13414 final PackageParser.Package pkg = mPackages.get(packageName); 13415 if (pkg == null) { 13416 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13417 throw new IllegalArgumentException("Unknown package: " + packageName); 13418 } 13419 if (ks instanceof KeySetHandle) { 13420 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13421 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ks); 13422 } 13423 return false; 13424 } 13425 } 13426 13427 @Override 13428 public boolean isPackageSignedByKeySetExactly(String packageName, IBinder ks) { 13429 if (packageName == null || ks == null) { 13430 return false; 13431 } 13432 synchronized(mPackages) { 13433 final PackageParser.Package pkg = mPackages.get(packageName); 13434 if (pkg == null) { 13435 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13436 throw new IllegalArgumentException("Unknown package: " + packageName); 13437 } 13438 if (ks instanceof KeySetHandle) { 13439 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13440 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ks); 13441 } 13442 return false; 13443 } 13444 } 13445} 13446