PackageManagerService.java revision bb7b7bea19223c1eba74f525c7fe87ca3911813b
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.util.ArrayUtils.appendInt; 54import static com.android.internal.util.ArrayUtils.removeInt; 55 56import android.util.ArrayMap; 57 58import com.android.internal.R; 59import com.android.internal.app.IMediaContainerService; 60import com.android.internal.app.ResolverActivity; 61import com.android.internal.content.NativeLibraryHelper; 62import com.android.internal.content.PackageHelper; 63import com.android.internal.os.IParcelFileDescriptorFactory; 64import com.android.internal.util.ArrayUtils; 65import com.android.internal.util.FastPrintWriter; 66import com.android.internal.util.FastXmlSerializer; 67import com.android.internal.util.IndentingPrintWriter; 68import com.android.server.EventLogTags; 69import com.android.server.IntentResolver; 70import com.android.server.LocalServices; 71import com.android.server.ServiceThread; 72import com.android.server.SystemConfig; 73import com.android.server.Watchdog; 74import com.android.server.pm.Settings.DatabaseVersion; 75import com.android.server.storage.DeviceStorageMonitorInternal; 76 77import org.xmlpull.v1.XmlSerializer; 78 79import android.app.ActivityManager; 80import android.app.ActivityManagerNative; 81import android.app.IActivityManager; 82import android.app.admin.IDevicePolicyManager; 83import android.app.backup.IBackupManager; 84import android.content.BroadcastReceiver; 85import android.content.ComponentName; 86import android.content.Context; 87import android.content.IIntentReceiver; 88import android.content.Intent; 89import android.content.IntentFilter; 90import android.content.IntentSender; 91import android.content.IntentSender.SendIntentException; 92import android.content.ServiceConnection; 93import android.content.pm.ActivityInfo; 94import android.content.pm.ApplicationInfo; 95import android.content.pm.FeatureInfo; 96import android.content.pm.IPackageDataObserver; 97import android.content.pm.IPackageDeleteObserver; 98import android.content.pm.IPackageDeleteObserver2; 99import android.content.pm.IPackageInstallObserver2; 100import android.content.pm.IPackageInstaller; 101import android.content.pm.IPackageManager; 102import android.content.pm.IPackageMoveObserver; 103import android.content.pm.IPackageStatsObserver; 104import android.content.pm.InstrumentationInfo; 105import android.content.pm.ManifestDigest; 106import android.content.pm.PackageCleanItem; 107import android.content.pm.PackageInfo; 108import android.content.pm.PackageInfoLite; 109import android.content.pm.PackageInstaller; 110import android.content.pm.PackageManager; 111import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 112import android.content.pm.PackageParser.ActivityIntentInfo; 113import android.content.pm.PackageParser.PackageLite; 114import android.content.pm.PackageParser.PackageParserException; 115import android.content.pm.PackageParser; 116import android.content.pm.PackageStats; 117import android.content.pm.PackageUserState; 118import android.content.pm.ParceledListSlice; 119import android.content.pm.PermissionGroupInfo; 120import android.content.pm.PermissionInfo; 121import android.content.pm.ProviderInfo; 122import android.content.pm.ResolveInfo; 123import android.content.pm.ServiceInfo; 124import android.content.pm.Signature; 125import android.content.pm.UserInfo; 126import android.content.pm.VerificationParams; 127import android.content.pm.VerifierDeviceIdentity; 128import android.content.pm.VerifierInfo; 129import android.content.res.Resources; 130import android.hardware.display.DisplayManager; 131import android.net.Uri; 132import android.os.Binder; 133import android.os.Build; 134import android.os.Bundle; 135import android.os.Environment; 136import android.os.Environment.UserEnvironment; 137import android.os.storage.StorageManager; 138import android.os.FileUtils; 139import android.os.Handler; 140import android.os.IBinder; 141import android.os.Looper; 142import android.os.Message; 143import android.os.Parcel; 144import android.os.ParcelFileDescriptor; 145import android.os.Process; 146import android.os.RemoteException; 147import android.os.SELinux; 148import android.os.ServiceManager; 149import android.os.SystemClock; 150import android.os.SystemProperties; 151import android.os.UserHandle; 152import android.os.UserManager; 153import android.security.KeyStore; 154import android.security.SystemKeyStore; 155import android.system.ErrnoException; 156import android.system.Os; 157import android.system.StructStat; 158import android.text.TextUtils; 159import android.util.ArraySet; 160import android.util.AtomicFile; 161import android.util.DisplayMetrics; 162import android.util.EventLog; 163import android.util.ExceptionUtils; 164import android.util.Log; 165import android.util.LogPrinter; 166import android.util.PrintStreamPrinter; 167import android.util.Slog; 168import android.util.SparseArray; 169import android.util.SparseBooleanArray; 170import android.view.Display; 171 172import java.io.BufferedInputStream; 173import java.io.BufferedOutputStream; 174import java.io.File; 175import java.io.FileDescriptor; 176import java.io.FileInputStream; 177import java.io.FileNotFoundException; 178import java.io.FileOutputStream; 179import java.io.FilenameFilter; 180import java.io.IOException; 181import java.io.InputStream; 182import java.io.PrintWriter; 183import java.nio.charset.StandardCharsets; 184import java.security.NoSuchAlgorithmException; 185import java.security.PublicKey; 186import java.security.cert.CertificateEncodingException; 187import java.security.cert.CertificateException; 188import java.text.SimpleDateFormat; 189import java.util.ArrayList; 190import java.util.Arrays; 191import java.util.Collection; 192import java.util.Collections; 193import java.util.Comparator; 194import java.util.Date; 195import java.util.HashMap; 196import java.util.HashSet; 197import java.util.Iterator; 198import java.util.List; 199import java.util.Map; 200import java.util.Set; 201import java.util.concurrent.atomic.AtomicBoolean; 202import java.util.concurrent.atomic.AtomicLong; 203 204import dalvik.system.DexFile; 205import dalvik.system.StaleDexCacheError; 206import dalvik.system.VMRuntime; 207 208import libcore.io.IoUtils; 209import libcore.util.EmptyArray; 210 211/** 212 * Keep track of all those .apks everywhere. 213 * 214 * This is very central to the platform's security; please run the unit 215 * tests whenever making modifications here: 216 * 217mmm frameworks/base/tests/AndroidTests 218adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 219adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 220 * 221 * {@hide} 222 */ 223public class PackageManagerService extends IPackageManager.Stub { 224 static final String TAG = "PackageManager"; 225 static final boolean DEBUG_SETTINGS = false; 226 static final boolean DEBUG_PREFERRED = false; 227 static final boolean DEBUG_UPGRADE = false; 228 private static final boolean DEBUG_INSTALL = false; 229 private static final boolean DEBUG_REMOVE = false; 230 private static final boolean DEBUG_BROADCASTS = false; 231 private static final boolean DEBUG_SHOW_INFO = false; 232 private static final boolean DEBUG_PACKAGE_INFO = false; 233 private static final boolean DEBUG_INTENT_MATCHING = false; 234 private static final boolean DEBUG_PACKAGE_SCANNING = false; 235 private static final boolean DEBUG_VERIFY = false; 236 private static final boolean DEBUG_DEXOPT = false; 237 private static final boolean DEBUG_ABI_SELECTION = false; 238 239 private static final int RADIO_UID = Process.PHONE_UID; 240 private static final int LOG_UID = Process.LOG_UID; 241 private static final int NFC_UID = Process.NFC_UID; 242 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 243 private static final int SHELL_UID = Process.SHELL_UID; 244 245 // Cap the size of permission trees that 3rd party apps can define 246 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 247 248 // Suffix used during package installation when copying/moving 249 // package apks to install directory. 250 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 251 252 static final int SCAN_MONITOR = 1<<0; 253 static final int SCAN_NO_DEX = 1<<1; 254 static final int SCAN_FORCE_DEX = 1<<2; 255 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 256 static final int SCAN_NEW_INSTALL = 1<<4; 257 static final int SCAN_NO_PATHS = 1<<5; 258 static final int SCAN_UPDATE_TIME = 1<<6; 259 static final int SCAN_DEFER_DEX = 1<<7; 260 static final int SCAN_BOOTING = 1<<8; 261 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 262 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 263 264 static final int REMOVE_CHATTY = 1<<16; 265 266 /** 267 * Timeout (in milliseconds) after which the watchdog should declare that 268 * our handler thread is wedged. The usual default for such things is one 269 * minute but we sometimes do very lengthy I/O operations on this thread, 270 * such as installing multi-gigabyte applications, so ours needs to be longer. 271 */ 272 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 273 274 /** 275 * Whether verification is enabled by default. 276 */ 277 private static final boolean DEFAULT_VERIFY_ENABLE = true; 278 279 /** 280 * The default maximum time to wait for the verification agent to return in 281 * milliseconds. 282 */ 283 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 284 285 /** 286 * The default response for package verification timeout. 287 * 288 * This can be either PackageManager.VERIFICATION_ALLOW or 289 * PackageManager.VERIFICATION_REJECT. 290 */ 291 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 292 293 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 294 295 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 296 DEFAULT_CONTAINER_PACKAGE, 297 "com.android.defcontainer.DefaultContainerService"); 298 299 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 300 301 private static final String LIB_DIR_NAME = "lib"; 302 private static final String LIB64_DIR_NAME = "lib64"; 303 304 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 305 306 private static String sPreferredInstructionSet; 307 308 final ServiceThread mHandlerThread; 309 310 private static final String IDMAP_PREFIX = "/data/resource-cache/"; 311 private static final String IDMAP_SUFFIX = "@idmap"; 312 313 final PackageHandler mHandler; 314 315 final int mSdkVersion = Build.VERSION.SDK_INT; 316 317 final Context mContext; 318 final boolean mFactoryTest; 319 final boolean mOnlyCore; 320 final DisplayMetrics mMetrics; 321 final int mDefParseFlags; 322 final String[] mSeparateProcesses; 323 324 // This is where all application persistent data goes. 325 final File mAppDataDir; 326 327 // This is where all application persistent data goes for secondary users. 328 final File mUserAppDataDir; 329 330 /** The location for ASEC container files on internal storage. */ 331 final String mAsecInternalPath; 332 333 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 334 // LOCK HELD. Can be called with mInstallLock held. 335 final Installer mInstaller; 336 337 /** Directory where installed third-party apps stored */ 338 final File mAppInstallDir; 339 340 /** 341 * Directory to which applications installed internally have their 342 * 32 bit native libraries copied. 343 */ 344 private File mAppLib32InstallDir; 345 346 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 347 // apps. 348 final File mDrmAppPrivateInstallDir; 349 350 // ---------------------------------------------------------------- 351 352 // Lock for state used when installing and doing other long running 353 // operations. Methods that must be called with this lock held have 354 // the suffix "LI". 355 final Object mInstallLock = new Object(); 356 357 // These are the directories in the 3rd party applications installed dir 358 // that we have currently loaded packages from. Keys are the application's 359 // installed zip file (absolute codePath), and values are Package. 360 final HashMap<String, PackageParser.Package> mAppDirs = 361 new HashMap<String, PackageParser.Package>(); 362 363 // ---------------------------------------------------------------- 364 365 // Keys are String (package name), values are Package. This also serves 366 // as the lock for the global state. Methods that must be called with 367 // this lock held have the prefix "LP". 368 final HashMap<String, PackageParser.Package> mPackages = 369 new HashMap<String, PackageParser.Package>(); 370 371 // Tracks available target package names -> overlay package paths. 372 final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays = 373 new HashMap<String, HashMap<String, PackageParser.Package>>(); 374 375 final Settings mSettings; 376 boolean mRestoredSettings; 377 378 // System configuration read by SystemConfig. 379 final int[] mGlobalGids; 380 final SparseArray<HashSet<String>> mSystemPermissions; 381 final HashMap<String, FeatureInfo> mAvailableFeatures; 382 383 // If mac_permissions.xml was found for seinfo labeling. 384 boolean mFoundPolicyFile; 385 386 // If a recursive restorecon of /data/data/<pkg> is needed. 387 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 388 389 public static final class SharedLibraryEntry { 390 public final String path; 391 public final String apk; 392 393 SharedLibraryEntry(String _path, String _apk) { 394 path = _path; 395 apk = _apk; 396 } 397 } 398 399 // Currently known shared libraries. 400 final HashMap<String, SharedLibraryEntry> mSharedLibraries = 401 new HashMap<String, SharedLibraryEntry>(); 402 403 // All available activities, for your resolving pleasure. 404 final ActivityIntentResolver mActivities = 405 new ActivityIntentResolver(); 406 407 // All available receivers, for your resolving pleasure. 408 final ActivityIntentResolver mReceivers = 409 new ActivityIntentResolver(); 410 411 // All available services, for your resolving pleasure. 412 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 413 414 // All available providers, for your resolving pleasure. 415 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 416 417 // Mapping from provider base names (first directory in content URI codePath) 418 // to the provider information. 419 final HashMap<String, PackageParser.Provider> mProvidersByAuthority = 420 new HashMap<String, PackageParser.Provider>(); 421 422 // Mapping from instrumentation class names to info about them. 423 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 424 new HashMap<ComponentName, PackageParser.Instrumentation>(); 425 426 // Mapping from permission names to info about them. 427 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups = 428 new HashMap<String, PackageParser.PermissionGroup>(); 429 430 // Packages whose data we have transfered into another package, thus 431 // should no longer exist. 432 final HashSet<String> mTransferedPackages = new HashSet<String>(); 433 434 // Broadcast actions that are only available to the system. 435 final HashSet<String> mProtectedBroadcasts = new HashSet<String>(); 436 437 /** List of packages waiting for verification. */ 438 final SparseArray<PackageVerificationState> mPendingVerification 439 = new SparseArray<PackageVerificationState>(); 440 441 /** Set of packages associated with each app op permission. */ 442 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 443 444 final PackageInstallerService mInstallerService; 445 446 HashSet<PackageParser.Package> mDeferredDexOpt = null; 447 448 // Cache of users who need badging. 449 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 450 451 /** Token for keys in mPendingVerification. */ 452 private int mPendingVerificationToken = 0; 453 454 boolean mSystemReady; 455 boolean mSafeMode; 456 boolean mHasSystemUidErrors; 457 458 ApplicationInfo mAndroidApplication; 459 final ActivityInfo mResolveActivity = new ActivityInfo(); 460 final ResolveInfo mResolveInfo = new ResolveInfo(); 461 ComponentName mResolveComponentName; 462 PackageParser.Package mPlatformPackage; 463 ComponentName mCustomResolverComponentName; 464 465 boolean mResolverReplaced = false; 466 467 // Set of pending broadcasts for aggregating enable/disable of components. 468 static class PendingPackageBroadcasts { 469 // for each user id, a map of <package name -> components within that package> 470 final SparseArray<HashMap<String, ArrayList<String>>> mUidMap; 471 472 public PendingPackageBroadcasts() { 473 mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2); 474 } 475 476 public ArrayList<String> get(int userId, String packageName) { 477 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 478 return packages.get(packageName); 479 } 480 481 public void put(int userId, String packageName, ArrayList<String> components) { 482 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 483 packages.put(packageName, components); 484 } 485 486 public void remove(int userId, String packageName) { 487 HashMap<String, ArrayList<String>> packages = mUidMap.get(userId); 488 if (packages != null) { 489 packages.remove(packageName); 490 } 491 } 492 493 public void remove(int userId) { 494 mUidMap.remove(userId); 495 } 496 497 public int userIdCount() { 498 return mUidMap.size(); 499 } 500 501 public int userIdAt(int n) { 502 return mUidMap.keyAt(n); 503 } 504 505 public HashMap<String, ArrayList<String>> packagesForUserId(int userId) { 506 return mUidMap.get(userId); 507 } 508 509 public int size() { 510 // total number of pending broadcast entries across all userIds 511 int num = 0; 512 for (int i = 0; i< mUidMap.size(); i++) { 513 num += mUidMap.valueAt(i).size(); 514 } 515 return num; 516 } 517 518 public void clear() { 519 mUidMap.clear(); 520 } 521 522 private HashMap<String, ArrayList<String>> getOrAllocate(int userId) { 523 HashMap<String, ArrayList<String>> map = mUidMap.get(userId); 524 if (map == null) { 525 map = new HashMap<String, ArrayList<String>>(); 526 mUidMap.put(userId, map); 527 } 528 return map; 529 } 530 } 531 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 532 533 // Service Connection to remote media container service to copy 534 // package uri's from external media onto secure containers 535 // or internal storage. 536 private IMediaContainerService mContainerService = null; 537 538 static final int SEND_PENDING_BROADCAST = 1; 539 static final int MCS_BOUND = 3; 540 static final int END_COPY = 4; 541 static final int INIT_COPY = 5; 542 static final int MCS_UNBIND = 6; 543 static final int START_CLEANING_PACKAGE = 7; 544 static final int FIND_INSTALL_LOC = 8; 545 static final int POST_INSTALL = 9; 546 static final int MCS_RECONNECT = 10; 547 static final int MCS_GIVE_UP = 11; 548 static final int UPDATED_MEDIA_STATUS = 12; 549 static final int WRITE_SETTINGS = 13; 550 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 551 static final int PACKAGE_VERIFIED = 15; 552 static final int CHECK_PENDING_VERIFICATION = 16; 553 554 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 555 556 // Delay time in millisecs 557 static final int BROADCAST_DELAY = 10 * 1000; 558 559 static UserManagerService sUserManager; 560 561 // Stores a list of users whose package restrictions file needs to be updated 562 private HashSet<Integer> mDirtyUsers = new HashSet<Integer>(); 563 564 final private DefaultContainerConnection mDefContainerConn = 565 new DefaultContainerConnection(); 566 class DefaultContainerConnection implements ServiceConnection { 567 public void onServiceConnected(ComponentName name, IBinder service) { 568 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 569 IMediaContainerService imcs = 570 IMediaContainerService.Stub.asInterface(service); 571 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 572 } 573 574 public void onServiceDisconnected(ComponentName name) { 575 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 576 } 577 }; 578 579 // Recordkeeping of restore-after-install operations that are currently in flight 580 // between the Package Manager and the Backup Manager 581 class PostInstallData { 582 public InstallArgs args; 583 public PackageInstalledInfo res; 584 585 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 586 args = _a; 587 res = _r; 588 } 589 }; 590 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 591 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 592 593 private final String mRequiredVerifierPackage; 594 595 private final PackageUsage mPackageUsage = new PackageUsage(); 596 597 private class PackageUsage { 598 private static final int WRITE_INTERVAL 599 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 600 601 private final Object mFileLock = new Object(); 602 private final AtomicLong mLastWritten = new AtomicLong(0); 603 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 604 605 private boolean mIsHistoricalPackageUsageAvailable = true; 606 607 boolean isHistoricalPackageUsageAvailable() { 608 return mIsHistoricalPackageUsageAvailable; 609 } 610 611 void write(boolean force) { 612 if (force) { 613 writeInternal(); 614 return; 615 } 616 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 617 && !DEBUG_DEXOPT) { 618 return; 619 } 620 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 621 new Thread("PackageUsage_DiskWriter") { 622 @Override 623 public void run() { 624 try { 625 writeInternal(); 626 } finally { 627 mBackgroundWriteRunning.set(false); 628 } 629 } 630 }.start(); 631 } 632 } 633 634 private void writeInternal() { 635 synchronized (mPackages) { 636 synchronized (mFileLock) { 637 AtomicFile file = getFile(); 638 FileOutputStream f = null; 639 try { 640 f = file.startWrite(); 641 BufferedOutputStream out = new BufferedOutputStream(f); 642 FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID); 643 StringBuilder sb = new StringBuilder(); 644 for (PackageParser.Package pkg : mPackages.values()) { 645 if (pkg.mLastPackageUsageTimeInMills == 0) { 646 continue; 647 } 648 sb.setLength(0); 649 sb.append(pkg.packageName); 650 sb.append(' '); 651 sb.append((long)pkg.mLastPackageUsageTimeInMills); 652 sb.append('\n'); 653 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 654 } 655 out.flush(); 656 file.finishWrite(f); 657 } catch (IOException e) { 658 if (f != null) { 659 file.failWrite(f); 660 } 661 Log.e(TAG, "Failed to write package usage times", e); 662 } 663 } 664 } 665 mLastWritten.set(SystemClock.elapsedRealtime()); 666 } 667 668 void readLP() { 669 synchronized (mFileLock) { 670 AtomicFile file = getFile(); 671 BufferedInputStream in = null; 672 try { 673 in = new BufferedInputStream(file.openRead()); 674 StringBuffer sb = new StringBuffer(); 675 while (true) { 676 String packageName = readToken(in, sb, ' '); 677 if (packageName == null) { 678 break; 679 } 680 String timeInMillisString = readToken(in, sb, '\n'); 681 if (timeInMillisString == null) { 682 throw new IOException("Failed to find last usage time for package " 683 + packageName); 684 } 685 PackageParser.Package pkg = mPackages.get(packageName); 686 if (pkg == null) { 687 continue; 688 } 689 long timeInMillis; 690 try { 691 timeInMillis = Long.parseLong(timeInMillisString.toString()); 692 } catch (NumberFormatException e) { 693 throw new IOException("Failed to parse " + timeInMillisString 694 + " as a long.", e); 695 } 696 pkg.mLastPackageUsageTimeInMills = timeInMillis; 697 } 698 } catch (FileNotFoundException expected) { 699 mIsHistoricalPackageUsageAvailable = false; 700 } catch (IOException e) { 701 Log.w(TAG, "Failed to read package usage times", e); 702 } finally { 703 IoUtils.closeQuietly(in); 704 } 705 } 706 mLastWritten.set(SystemClock.elapsedRealtime()); 707 } 708 709 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 710 throws IOException { 711 sb.setLength(0); 712 while (true) { 713 int ch = in.read(); 714 if (ch == -1) { 715 if (sb.length() == 0) { 716 return null; 717 } 718 throw new IOException("Unexpected EOF"); 719 } 720 if (ch == endOfToken) { 721 return sb.toString(); 722 } 723 sb.append((char)ch); 724 } 725 } 726 727 private AtomicFile getFile() { 728 File dataDir = Environment.getDataDirectory(); 729 File systemDir = new File(dataDir, "system"); 730 File fname = new File(systemDir, "package-usage.list"); 731 return new AtomicFile(fname); 732 } 733 } 734 735 class PackageHandler extends Handler { 736 private boolean mBound = false; 737 final ArrayList<HandlerParams> mPendingInstalls = 738 new ArrayList<HandlerParams>(); 739 740 private boolean connectToService() { 741 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 742 " DefaultContainerService"); 743 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 744 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 745 if (mContext.bindServiceAsUser(service, mDefContainerConn, 746 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 747 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 748 mBound = true; 749 return true; 750 } 751 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 752 return false; 753 } 754 755 private void disconnectService() { 756 mContainerService = null; 757 mBound = false; 758 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 759 mContext.unbindService(mDefContainerConn); 760 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 761 } 762 763 PackageHandler(Looper looper) { 764 super(looper); 765 } 766 767 public void handleMessage(Message msg) { 768 try { 769 doHandleMessage(msg); 770 } finally { 771 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 772 } 773 } 774 775 void doHandleMessage(Message msg) { 776 switch (msg.what) { 777 case INIT_COPY: { 778 HandlerParams params = (HandlerParams) msg.obj; 779 int idx = mPendingInstalls.size(); 780 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 781 // If a bind was already initiated we dont really 782 // need to do anything. The pending install 783 // will be processed later on. 784 if (!mBound) { 785 // If this is the only one pending we might 786 // have to bind to the service again. 787 if (!connectToService()) { 788 Slog.e(TAG, "Failed to bind to media container service"); 789 params.serviceError(); 790 return; 791 } else { 792 // Once we bind to the service, the first 793 // pending request will be processed. 794 mPendingInstalls.add(idx, params); 795 } 796 } else { 797 mPendingInstalls.add(idx, params); 798 // Already bound to the service. Just make 799 // sure we trigger off processing the first request. 800 if (idx == 0) { 801 mHandler.sendEmptyMessage(MCS_BOUND); 802 } 803 } 804 break; 805 } 806 case MCS_BOUND: { 807 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 808 if (msg.obj != null) { 809 mContainerService = (IMediaContainerService) msg.obj; 810 } 811 if (mContainerService == null) { 812 // Something seriously wrong. Bail out 813 Slog.e(TAG, "Cannot bind to media container service"); 814 for (HandlerParams params : mPendingInstalls) { 815 // Indicate service bind error 816 params.serviceError(); 817 } 818 mPendingInstalls.clear(); 819 } else if (mPendingInstalls.size() > 0) { 820 HandlerParams params = mPendingInstalls.get(0); 821 if (params != null) { 822 if (params.startCopy()) { 823 // We are done... look for more work or to 824 // go idle. 825 if (DEBUG_SD_INSTALL) Log.i(TAG, 826 "Checking for more work or unbind..."); 827 // Delete pending install 828 if (mPendingInstalls.size() > 0) { 829 mPendingInstalls.remove(0); 830 } 831 if (mPendingInstalls.size() == 0) { 832 if (mBound) { 833 if (DEBUG_SD_INSTALL) Log.i(TAG, 834 "Posting delayed MCS_UNBIND"); 835 removeMessages(MCS_UNBIND); 836 Message ubmsg = obtainMessage(MCS_UNBIND); 837 // Unbind after a little delay, to avoid 838 // continual thrashing. 839 sendMessageDelayed(ubmsg, 10000); 840 } 841 } else { 842 // There are more pending requests in queue. 843 // Just post MCS_BOUND message to trigger processing 844 // of next pending install. 845 if (DEBUG_SD_INSTALL) Log.i(TAG, 846 "Posting MCS_BOUND for next work"); 847 mHandler.sendEmptyMessage(MCS_BOUND); 848 } 849 } 850 } 851 } else { 852 // Should never happen ideally. 853 Slog.w(TAG, "Empty queue"); 854 } 855 break; 856 } 857 case MCS_RECONNECT: { 858 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 859 if (mPendingInstalls.size() > 0) { 860 if (mBound) { 861 disconnectService(); 862 } 863 if (!connectToService()) { 864 Slog.e(TAG, "Failed to bind to media container service"); 865 for (HandlerParams params : mPendingInstalls) { 866 // Indicate service bind error 867 params.serviceError(); 868 } 869 mPendingInstalls.clear(); 870 } 871 } 872 break; 873 } 874 case MCS_UNBIND: { 875 // If there is no actual work left, then time to unbind. 876 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 877 878 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 879 if (mBound) { 880 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 881 882 disconnectService(); 883 } 884 } else if (mPendingInstalls.size() > 0) { 885 // There are more pending requests in queue. 886 // Just post MCS_BOUND message to trigger processing 887 // of next pending install. 888 mHandler.sendEmptyMessage(MCS_BOUND); 889 } 890 891 break; 892 } 893 case MCS_GIVE_UP: { 894 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 895 mPendingInstalls.remove(0); 896 break; 897 } 898 case SEND_PENDING_BROADCAST: { 899 String packages[]; 900 ArrayList<String> components[]; 901 int size = 0; 902 int uids[]; 903 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 904 synchronized (mPackages) { 905 if (mPendingBroadcasts == null) { 906 return; 907 } 908 size = mPendingBroadcasts.size(); 909 if (size <= 0) { 910 // Nothing to be done. Just return 911 return; 912 } 913 packages = new String[size]; 914 components = new ArrayList[size]; 915 uids = new int[size]; 916 int i = 0; // filling out the above arrays 917 918 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 919 int packageUserId = mPendingBroadcasts.userIdAt(n); 920 Iterator<Map.Entry<String, ArrayList<String>>> it 921 = mPendingBroadcasts.packagesForUserId(packageUserId) 922 .entrySet().iterator(); 923 while (it.hasNext() && i < size) { 924 Map.Entry<String, ArrayList<String>> ent = it.next(); 925 packages[i] = ent.getKey(); 926 components[i] = ent.getValue(); 927 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 928 uids[i] = (ps != null) 929 ? UserHandle.getUid(packageUserId, ps.appId) 930 : -1; 931 i++; 932 } 933 } 934 size = i; 935 mPendingBroadcasts.clear(); 936 } 937 // Send broadcasts 938 for (int i = 0; i < size; i++) { 939 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 940 } 941 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 942 break; 943 } 944 case START_CLEANING_PACKAGE: { 945 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 946 final String packageName = (String)msg.obj; 947 final int userId = msg.arg1; 948 final boolean andCode = msg.arg2 != 0; 949 synchronized (mPackages) { 950 if (userId == UserHandle.USER_ALL) { 951 int[] users = sUserManager.getUserIds(); 952 for (int user : users) { 953 mSettings.addPackageToCleanLPw( 954 new PackageCleanItem(user, packageName, andCode)); 955 } 956 } else { 957 mSettings.addPackageToCleanLPw( 958 new PackageCleanItem(userId, packageName, andCode)); 959 } 960 } 961 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 962 startCleaningPackages(); 963 } break; 964 case POST_INSTALL: { 965 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 966 PostInstallData data = mRunningInstalls.get(msg.arg1); 967 mRunningInstalls.delete(msg.arg1); 968 boolean deleteOld = false; 969 970 if (data != null) { 971 InstallArgs args = data.args; 972 PackageInstalledInfo res = data.res; 973 974 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 975 res.removedInfo.sendBroadcast(false, true, false); 976 Bundle extras = new Bundle(1); 977 extras.putInt(Intent.EXTRA_UID, res.uid); 978 // Determine the set of users who are adding this 979 // package for the first time vs. those who are seeing 980 // an update. 981 int[] firstUsers; 982 int[] updateUsers = new int[0]; 983 if (res.origUsers == null || res.origUsers.length == 0) { 984 firstUsers = res.newUsers; 985 } else { 986 firstUsers = new int[0]; 987 for (int i=0; i<res.newUsers.length; i++) { 988 int user = res.newUsers[i]; 989 boolean isNew = true; 990 for (int j=0; j<res.origUsers.length; j++) { 991 if (res.origUsers[j] == user) { 992 isNew = false; 993 break; 994 } 995 } 996 if (isNew) { 997 int[] newFirst = new int[firstUsers.length+1]; 998 System.arraycopy(firstUsers, 0, newFirst, 0, 999 firstUsers.length); 1000 newFirst[firstUsers.length] = user; 1001 firstUsers = newFirst; 1002 } else { 1003 int[] newUpdate = new int[updateUsers.length+1]; 1004 System.arraycopy(updateUsers, 0, newUpdate, 0, 1005 updateUsers.length); 1006 newUpdate[updateUsers.length] = user; 1007 updateUsers = newUpdate; 1008 } 1009 } 1010 } 1011 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1012 res.pkg.applicationInfo.packageName, 1013 extras, null, null, firstUsers); 1014 final boolean update = res.removedInfo.removedPackage != null; 1015 if (update) { 1016 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1017 } 1018 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1019 res.pkg.applicationInfo.packageName, 1020 extras, null, null, updateUsers); 1021 if (update) { 1022 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1023 res.pkg.applicationInfo.packageName, 1024 extras, null, null, updateUsers); 1025 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1026 null, null, 1027 res.pkg.applicationInfo.packageName, null, updateUsers); 1028 1029 // treat asec-hosted packages like removable media on upgrade 1030 if (isForwardLocked(res.pkg) || isExternal(res.pkg)) { 1031 if (DEBUG_INSTALL) { 1032 Slog.i(TAG, "upgrading pkg " + res.pkg 1033 + " is ASEC-hosted -> AVAILABLE"); 1034 } 1035 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1036 ArrayList<String> pkgList = new ArrayList<String>(1); 1037 pkgList.add(res.pkg.applicationInfo.packageName); 1038 sendResourcesChangedBroadcast(true, true, 1039 pkgList,uidArray, null); 1040 } 1041 } 1042 if (res.removedInfo.args != null) { 1043 // Remove the replaced package's older resources safely now 1044 deleteOld = true; 1045 } 1046 1047 // Log current value of "unknown sources" setting 1048 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1049 getUnknownSourcesSettings()); 1050 } 1051 // Force a gc to clear up things 1052 Runtime.getRuntime().gc(); 1053 // We delete after a gc for applications on sdcard. 1054 if (deleteOld) { 1055 synchronized (mInstallLock) { 1056 res.removedInfo.args.doPostDeleteLI(true); 1057 } 1058 } 1059 if (args.observer != null) { 1060 try { 1061 Bundle extras = extrasForInstallResult(res); 1062 args.observer.onPackageInstalled(res.name, res.returnCode, 1063 res.returnMsg, extras); 1064 } catch (RemoteException e) { 1065 Slog.i(TAG, "Observer no longer exists."); 1066 } 1067 } 1068 } else { 1069 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1070 } 1071 } break; 1072 case UPDATED_MEDIA_STATUS: { 1073 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1074 boolean reportStatus = msg.arg1 == 1; 1075 boolean doGc = msg.arg2 == 1; 1076 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1077 if (doGc) { 1078 // Force a gc to clear up stale containers. 1079 Runtime.getRuntime().gc(); 1080 } 1081 if (msg.obj != null) { 1082 @SuppressWarnings("unchecked") 1083 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1084 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1085 // Unload containers 1086 unloadAllContainers(args); 1087 } 1088 if (reportStatus) { 1089 try { 1090 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1091 PackageHelper.getMountService().finishMediaUpdate(); 1092 } catch (RemoteException e) { 1093 Log.e(TAG, "MountService not running?"); 1094 } 1095 } 1096 } break; 1097 case WRITE_SETTINGS: { 1098 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1099 synchronized (mPackages) { 1100 removeMessages(WRITE_SETTINGS); 1101 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1102 mSettings.writeLPr(); 1103 mDirtyUsers.clear(); 1104 } 1105 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1106 } break; 1107 case WRITE_PACKAGE_RESTRICTIONS: { 1108 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1109 synchronized (mPackages) { 1110 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1111 for (int userId : mDirtyUsers) { 1112 mSettings.writePackageRestrictionsLPr(userId); 1113 } 1114 mDirtyUsers.clear(); 1115 } 1116 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1117 } break; 1118 case CHECK_PENDING_VERIFICATION: { 1119 final int verificationId = msg.arg1; 1120 final PackageVerificationState state = mPendingVerification.get(verificationId); 1121 1122 if ((state != null) && !state.timeoutExtended()) { 1123 final InstallArgs args = state.getInstallArgs(); 1124 final Uri originUri = Uri.fromFile(args.originFile); 1125 1126 Slog.i(TAG, "Verification timed out for " + originUri); 1127 mPendingVerification.remove(verificationId); 1128 1129 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1130 1131 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1132 Slog.i(TAG, "Continuing with installation of " + originUri); 1133 state.setVerifierResponse(Binder.getCallingUid(), 1134 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1135 broadcastPackageVerified(verificationId, originUri, 1136 PackageManager.VERIFICATION_ALLOW, 1137 state.getInstallArgs().getUser()); 1138 try { 1139 ret = args.copyApk(mContainerService, true); 1140 } catch (RemoteException e) { 1141 Slog.e(TAG, "Could not contact the ContainerService"); 1142 } 1143 } else { 1144 broadcastPackageVerified(verificationId, originUri, 1145 PackageManager.VERIFICATION_REJECT, 1146 state.getInstallArgs().getUser()); 1147 } 1148 1149 processPendingInstall(args, ret); 1150 mHandler.sendEmptyMessage(MCS_UNBIND); 1151 } 1152 break; 1153 } 1154 case PACKAGE_VERIFIED: { 1155 final int verificationId = msg.arg1; 1156 1157 final PackageVerificationState state = mPendingVerification.get(verificationId); 1158 if (state == null) { 1159 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1160 break; 1161 } 1162 1163 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1164 1165 state.setVerifierResponse(response.callerUid, response.code); 1166 1167 if (state.isVerificationComplete()) { 1168 mPendingVerification.remove(verificationId); 1169 1170 final InstallArgs args = state.getInstallArgs(); 1171 final Uri originUri = Uri.fromFile(args.originFile); 1172 1173 int ret; 1174 if (state.isInstallAllowed()) { 1175 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1176 broadcastPackageVerified(verificationId, originUri, 1177 response.code, state.getInstallArgs().getUser()); 1178 try { 1179 ret = args.copyApk(mContainerService, true); 1180 } catch (RemoteException e) { 1181 Slog.e(TAG, "Could not contact the ContainerService"); 1182 } 1183 } else { 1184 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1185 } 1186 1187 processPendingInstall(args, ret); 1188 1189 mHandler.sendEmptyMessage(MCS_UNBIND); 1190 } 1191 1192 break; 1193 } 1194 } 1195 } 1196 } 1197 1198 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1199 Bundle extras = null; 1200 switch (res.returnCode) { 1201 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1202 extras = new Bundle(); 1203 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1204 res.origPermission); 1205 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1206 res.origPackage); 1207 break; 1208 } 1209 } 1210 return extras; 1211 } 1212 1213 void scheduleWriteSettingsLocked() { 1214 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1215 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1216 } 1217 } 1218 1219 void scheduleWritePackageRestrictionsLocked(int userId) { 1220 if (!sUserManager.exists(userId)) return; 1221 mDirtyUsers.add(userId); 1222 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1223 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1224 } 1225 } 1226 1227 public static final PackageManagerService main(Context context, Installer installer, 1228 boolean factoryTest, boolean onlyCore) { 1229 PackageManagerService m = new PackageManagerService(context, installer, 1230 factoryTest, onlyCore); 1231 ServiceManager.addService("package", m); 1232 return m; 1233 } 1234 1235 static String[] splitString(String str, char sep) { 1236 int count = 1; 1237 int i = 0; 1238 while ((i=str.indexOf(sep, i)) >= 0) { 1239 count++; 1240 i++; 1241 } 1242 1243 String[] res = new String[count]; 1244 i=0; 1245 count = 0; 1246 int lastI=0; 1247 while ((i=str.indexOf(sep, i)) >= 0) { 1248 res[count] = str.substring(lastI, i); 1249 count++; 1250 i++; 1251 lastI = i; 1252 } 1253 res[count] = str.substring(lastI, str.length()); 1254 return res; 1255 } 1256 1257 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1258 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1259 Context.DISPLAY_SERVICE); 1260 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1261 } 1262 1263 public PackageManagerService(Context context, Installer installer, 1264 boolean factoryTest, boolean onlyCore) { 1265 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1266 SystemClock.uptimeMillis()); 1267 1268 if (mSdkVersion <= 0) { 1269 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1270 } 1271 1272 mContext = context; 1273 mFactoryTest = factoryTest; 1274 mOnlyCore = onlyCore; 1275 mMetrics = new DisplayMetrics(); 1276 mSettings = new Settings(context); 1277 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1278 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1279 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1280 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1281 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1282 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1283 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1284 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1285 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1286 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1287 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1288 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1289 1290 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1291 if (separateProcesses != null && separateProcesses.length() > 0) { 1292 if ("*".equals(separateProcesses)) { 1293 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1294 mSeparateProcesses = null; 1295 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1296 } else { 1297 mDefParseFlags = 0; 1298 mSeparateProcesses = separateProcesses.split(","); 1299 Slog.w(TAG, "Running with debug.separate_processes: " 1300 + separateProcesses); 1301 } 1302 } else { 1303 mDefParseFlags = 0; 1304 mSeparateProcesses = null; 1305 } 1306 1307 mInstaller = installer; 1308 1309 getDefaultDisplayMetrics(context, mMetrics); 1310 1311 SystemConfig systemConfig = SystemConfig.getInstance(); 1312 mGlobalGids = systemConfig.getGlobalGids(); 1313 mSystemPermissions = systemConfig.getSystemPermissions(); 1314 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1315 1316 synchronized (mInstallLock) { 1317 // writer 1318 synchronized (mPackages) { 1319 mHandlerThread = new ServiceThread(TAG, 1320 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1321 mHandlerThread.start(); 1322 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1323 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1324 1325 File dataDir = Environment.getDataDirectory(); 1326 mAppDataDir = new File(dataDir, "data"); 1327 mAppInstallDir = new File(dataDir, "app"); 1328 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1329 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1330 mUserAppDataDir = new File(dataDir, "user"); 1331 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1332 1333 sUserManager = new UserManagerService(context, this, 1334 mInstallLock, mPackages); 1335 1336 // Propagate permission configuration in to package manager. 1337 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1338 = systemConfig.getPermissions(); 1339 for (int i=0; i<permConfig.size(); i++) { 1340 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1341 BasePermission bp = mSettings.mPermissions.get(perm.name); 1342 if (bp == null) { 1343 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1344 mSettings.mPermissions.put(perm.name, bp); 1345 } 1346 if (perm.gids != null) { 1347 bp.gids = appendInts(bp.gids, perm.gids); 1348 } 1349 } 1350 1351 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1352 for (int i=0; i<libConfig.size(); i++) { 1353 mSharedLibraries.put(libConfig.keyAt(i), 1354 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1355 } 1356 1357 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1358 1359 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1360 mSdkVersion, mOnlyCore); 1361 1362 String customResolverActivity = Resources.getSystem().getString( 1363 R.string.config_customResolverActivity); 1364 if (TextUtils.isEmpty(customResolverActivity)) { 1365 customResolverActivity = null; 1366 } else { 1367 mCustomResolverComponentName = ComponentName.unflattenFromString( 1368 customResolverActivity); 1369 } 1370 1371 long startTime = SystemClock.uptimeMillis(); 1372 1373 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1374 startTime); 1375 1376 // Set flag to monitor and not change apk file paths when 1377 // scanning install directories. 1378 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1379 1380 final HashSet<String> alreadyDexOpted = new HashSet<String>(); 1381 1382 /** 1383 * Add everything in the in the boot class path to the 1384 * list of process files because dexopt will have been run 1385 * if necessary during zygote startup. 1386 */ 1387 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1388 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1389 1390 if (bootClassPath != null) { 1391 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1392 for (String element : bootClassPathElements) { 1393 alreadyDexOpted.add(element); 1394 } 1395 } else { 1396 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1397 } 1398 1399 if (systemServerClassPath != null) { 1400 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1401 for (String element : systemServerClassPathElements) { 1402 alreadyDexOpted.add(element); 1403 } 1404 } else { 1405 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1406 } 1407 1408 boolean didDexOptLibraryOrTool = false; 1409 1410 final List<String> allInstructionSets = getAllInstructionSets(); 1411 final String[] dexCodeInstructionSets = 1412 getDexCodeInstructionSets(allInstructionSets.toArray(new String[allInstructionSets.size()])); 1413 1414 /** 1415 * Ensure all external libraries have had dexopt run on them. 1416 */ 1417 if (mSharedLibraries.size() > 0) { 1418 // NOTE: For now, we're compiling these system "shared libraries" 1419 // (and framework jars) into all available architectures. It's possible 1420 // to compile them only when we come across an app that uses them (there's 1421 // already logic for that in scanPackageLI) but that adds some complexity. 1422 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1423 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1424 final String lib = libEntry.path; 1425 if (lib == null) { 1426 continue; 1427 } 1428 1429 try { 1430 byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null, 1431 dexCodeInstructionSet, 1432 false); 1433 if (dexoptRequired != DexFile.UP_TO_DATE) { 1434 alreadyDexOpted.add(lib); 1435 1436 // The list of "shared libraries" we have at this point is 1437 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1438 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1439 } else { 1440 mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1441 } 1442 didDexOptLibraryOrTool = true; 1443 } 1444 } catch (FileNotFoundException e) { 1445 Slog.w(TAG, "Library not found: " + lib); 1446 } catch (IOException e) { 1447 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1448 + e.getMessage()); 1449 } 1450 } 1451 } 1452 } 1453 1454 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1455 1456 // Gross hack for now: we know this file doesn't contain any 1457 // code, so don't dexopt it to avoid the resulting log spew. 1458 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1459 1460 // Gross hack for now: we know this file is only part of 1461 // the boot class path for art, so don't dexopt it to 1462 // avoid the resulting log spew. 1463 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1464 1465 /** 1466 * And there are a number of commands implemented in Java, which 1467 * we currently need to do the dexopt on so that they can be 1468 * run from a non-root shell. 1469 */ 1470 String[] frameworkFiles = frameworkDir.list(); 1471 if (frameworkFiles != null) { 1472 // TODO: We could compile these only for the most preferred ABI. We should 1473 // first double check that the dex files for these commands are not referenced 1474 // by other system apps. 1475 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1476 for (int i=0; i<frameworkFiles.length; i++) { 1477 File libPath = new File(frameworkDir, frameworkFiles[i]); 1478 String path = libPath.getPath(); 1479 // Skip the file if we already did it. 1480 if (alreadyDexOpted.contains(path)) { 1481 continue; 1482 } 1483 // Skip the file if it is not a type we want to dexopt. 1484 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1485 continue; 1486 } 1487 try { 1488 byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null, 1489 dexCodeInstructionSet, 1490 false); 1491 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1492 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1493 didDexOptLibraryOrTool = true; 1494 } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) { 1495 mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1496 didDexOptLibraryOrTool = true; 1497 } 1498 } catch (FileNotFoundException e) { 1499 Slog.w(TAG, "Jar not found: " + path); 1500 } catch (IOException e) { 1501 Slog.w(TAG, "Exception reading jar: " + path, e); 1502 } 1503 } 1504 } 1505 } 1506 1507 if (didDexOptLibraryOrTool) { 1508 // If we dexopted a library or tool, then something on the system has 1509 // changed. Consider this significant, and wipe away all other 1510 // existing dexopt files to ensure we don't leave any dangling around. 1511 // 1512 // TODO: This should be revisited because it isn't as good an indicator 1513 // as it used to be. It used to include the boot classpath but at some point 1514 // DexFile.isDexOptNeeded started returning false for the boot 1515 // class path files in all cases. It is very possible in a 1516 // small maintenance release update that the library and tool 1517 // jars may be unchanged but APK could be removed resulting in 1518 // unused dalvik-cache files. 1519 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1520 mInstaller.pruneDexCache(dexCodeInstructionSet); 1521 } 1522 1523 // Additionally, delete all dex files from the root directory 1524 // since there shouldn't be any there anyway, unless we're upgrading 1525 // from an older OS version or a build that contained the "old" style 1526 // flat scheme. 1527 mInstaller.pruneDexCache("."); 1528 } 1529 1530 // Collect vendor overlay packages. 1531 // (Do this before scanning any apps.) 1532 // For security and version matching reason, only consider 1533 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1534 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1535 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1536 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode | SCAN_TRUSTED_OVERLAY, 0); 1537 1538 // Find base frameworks (resource packages without code). 1539 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1540 | PackageParser.PARSE_IS_SYSTEM_DIR 1541 | PackageParser.PARSE_IS_PRIVILEGED, 1542 scanMode | SCAN_NO_DEX, 0); 1543 1544 // Collected privileged system packages. 1545 File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1546 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1547 | PackageParser.PARSE_IS_SYSTEM_DIR 1548 | PackageParser.PARSE_IS_PRIVILEGED, scanMode, 0); 1549 1550 // Collect ordinary system packages. 1551 File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1552 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1553 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1554 1555 // Collect all vendor packages. 1556 File vendorAppDir = new File("/vendor/app"); 1557 try { 1558 vendorAppDir = vendorAppDir.getCanonicalFile(); 1559 } catch (IOException e) { 1560 // failed to look up canonical path, continue with original one 1561 } 1562 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1563 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1564 1565 // Collect all OEM packages. 1566 File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1567 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1568 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1569 1570 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1571 mInstaller.moveFiles(); 1572 1573 // Prune any system packages that no longer exist. 1574 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1575 if (!mOnlyCore) { 1576 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1577 while (psit.hasNext()) { 1578 PackageSetting ps = psit.next(); 1579 1580 /* 1581 * If this is not a system app, it can't be a 1582 * disable system app. 1583 */ 1584 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1585 continue; 1586 } 1587 1588 /* 1589 * If the package is scanned, it's not erased. 1590 */ 1591 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1592 if (scannedPkg != null) { 1593 /* 1594 * If the system app is both scanned and in the 1595 * disabled packages list, then it must have been 1596 * added via OTA. Remove it from the currently 1597 * scanned package so the previously user-installed 1598 * application can be scanned. 1599 */ 1600 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1601 Slog.i(TAG, "Expecting better updatd system app for " + ps.name 1602 + "; removing system app"); 1603 removePackageLI(ps, true); 1604 } 1605 1606 continue; 1607 } 1608 1609 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1610 psit.remove(); 1611 String msg = "System package " + ps.name 1612 + " no longer exists; wiping its data"; 1613 reportSettingsProblem(Log.WARN, msg); 1614 removeDataDirsLI(ps.name); 1615 } else { 1616 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1617 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1618 possiblyDeletedUpdatedSystemApps.add(ps.name); 1619 } 1620 } 1621 } 1622 } 1623 1624 //look for any incomplete package installations 1625 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1626 //clean up list 1627 for(int i = 0; i < deletePkgsList.size(); i++) { 1628 //clean up here 1629 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1630 } 1631 //delete tmp files 1632 deleteTempPackageFiles(); 1633 1634 // Remove any shared userIDs that have no associated packages 1635 mSettings.pruneSharedUsersLPw(); 1636 1637 if (!mOnlyCore) { 1638 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 1639 SystemClock.uptimeMillis()); 1640 scanDirLI(mAppInstallDir, 0, scanMode, 0); 1641 1642 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 1643 scanMode, 0); 1644 1645 /** 1646 * Remove disable package settings for any updated system 1647 * apps that were removed via an OTA. If they're not a 1648 * previously-updated app, remove them completely. 1649 * Otherwise, just revoke their system-level permissions. 1650 */ 1651 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 1652 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 1653 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 1654 1655 String msg; 1656 if (deletedPkg == null) { 1657 msg = "Updated system package " + deletedAppName 1658 + " no longer exists; wiping its data"; 1659 removeDataDirsLI(deletedAppName); 1660 } else { 1661 msg = "Updated system app + " + deletedAppName 1662 + " no longer present; removing system privileges for " 1663 + deletedAppName; 1664 1665 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 1666 1667 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 1668 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 1669 } 1670 reportSettingsProblem(Log.WARN, msg); 1671 } 1672 } 1673 1674 // Now that we know all of the shared libraries, update all clients to have 1675 // the correct library paths. 1676 updateAllSharedLibrariesLPw(); 1677 1678 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 1679 // NOTE: We ignore potential failures here during a system scan (like 1680 // the rest of the commands above) because there's precious little we 1681 // can do about it. A settings error is reported, though. 1682 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 1683 false /* force dexopt */, false /* defer dexopt */); 1684 } 1685 1686 // Now that we know all the packages we are keeping, 1687 // read and update their last usage times. 1688 mPackageUsage.readLP(); 1689 1690 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 1691 SystemClock.uptimeMillis()); 1692 Slog.i(TAG, "Time to scan packages: " 1693 + ((SystemClock.uptimeMillis()-startTime)/1000f) 1694 + " seconds"); 1695 1696 // If the platform SDK has changed since the last time we booted, 1697 // we need to re-grant app permission to catch any new ones that 1698 // appear. This is really a hack, and means that apps can in some 1699 // cases get permissions that the user didn't initially explicitly 1700 // allow... it would be nice to have some better way to handle 1701 // this situation. 1702 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 1703 != mSdkVersion; 1704 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 1705 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 1706 + "; regranting permissions for internal storage"); 1707 mSettings.mInternalSdkPlatform = mSdkVersion; 1708 1709 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 1710 | (regrantPermissions 1711 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 1712 : 0)); 1713 1714 // If this is the first boot, and it is a normal boot, then 1715 // we need to initialize the default preferred apps. 1716 if (!mRestoredSettings && !onlyCore) { 1717 mSettings.readDefaultPreferredAppsLPw(this, 0); 1718 } 1719 1720 // If this is first boot after an OTA, and a normal boot, then 1721 // we need to clear code cache directories. 1722 if (!Build.FINGERPRINT.equals(mSettings.mFingerprint) && !onlyCore) { 1723 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 1724 for (String pkgName : mSettings.mPackages.keySet()) { 1725 deleteCodeCacheDirsLI(pkgName); 1726 } 1727 mSettings.mFingerprint = Build.FINGERPRINT; 1728 } 1729 1730 // All the changes are done during package scanning. 1731 mSettings.updateInternalDatabaseVersion(); 1732 1733 // can downgrade to reader 1734 mSettings.writeLPr(); 1735 1736 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 1737 SystemClock.uptimeMillis()); 1738 1739 1740 mRequiredVerifierPackage = getRequiredVerifierLPr(); 1741 } // synchronized (mPackages) 1742 } // synchronized (mInstallLock) 1743 1744 mInstallerService = new PackageInstallerService(context, this, mAppInstallDir); 1745 1746 // Now after opening every single application zip, make sure they 1747 // are all flushed. Not really needed, but keeps things nice and 1748 // tidy. 1749 Runtime.getRuntime().gc(); 1750 } 1751 1752 @Override 1753 public boolean isFirstBoot() { 1754 return !mRestoredSettings; 1755 } 1756 1757 @Override 1758 public boolean isOnlyCoreApps() { 1759 return mOnlyCore; 1760 } 1761 1762 private String getRequiredVerifierLPr() { 1763 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 1764 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 1765 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 1766 1767 String requiredVerifier = null; 1768 1769 final int N = receivers.size(); 1770 for (int i = 0; i < N; i++) { 1771 final ResolveInfo info = receivers.get(i); 1772 1773 if (info.activityInfo == null) { 1774 continue; 1775 } 1776 1777 final String packageName = info.activityInfo.packageName; 1778 1779 final PackageSetting ps = mSettings.mPackages.get(packageName); 1780 if (ps == null) { 1781 continue; 1782 } 1783 1784 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1785 if (!gp.grantedPermissions 1786 .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) { 1787 continue; 1788 } 1789 1790 if (requiredVerifier != null) { 1791 throw new RuntimeException("There can be only one required verifier"); 1792 } 1793 1794 requiredVerifier = packageName; 1795 } 1796 1797 return requiredVerifier; 1798 } 1799 1800 @Override 1801 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 1802 throws RemoteException { 1803 try { 1804 return super.onTransact(code, data, reply, flags); 1805 } catch (RuntimeException e) { 1806 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 1807 Slog.wtf(TAG, "Package Manager Crash", e); 1808 } 1809 throw e; 1810 } 1811 } 1812 1813 void cleanupInstallFailedPackage(PackageSetting ps) { 1814 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name); 1815 removeDataDirsLI(ps.name); 1816 1817 // TODO: try cleaning up codePath directory contents first, since it 1818 // might be a cluster 1819 1820 if (ps.codePath != null) { 1821 if (!ps.codePath.delete()) { 1822 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath); 1823 } 1824 } 1825 if (ps.resourcePath != null) { 1826 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) { 1827 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath); 1828 } 1829 } 1830 mSettings.removePackageLPw(ps.name); 1831 } 1832 1833 static int[] appendInts(int[] cur, int[] add) { 1834 if (add == null) return cur; 1835 if (cur == null) return add; 1836 final int N = add.length; 1837 for (int i=0; i<N; i++) { 1838 cur = appendInt(cur, add[i]); 1839 } 1840 return cur; 1841 } 1842 1843 static int[] removeInts(int[] cur, int[] rem) { 1844 if (rem == null) return cur; 1845 if (cur == null) return cur; 1846 final int N = rem.length; 1847 for (int i=0; i<N; i++) { 1848 cur = removeInt(cur, rem[i]); 1849 } 1850 return cur; 1851 } 1852 1853 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 1854 if (!sUserManager.exists(userId)) return null; 1855 final PackageSetting ps = (PackageSetting) p.mExtras; 1856 if (ps == null) { 1857 return null; 1858 } 1859 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1860 final PackageUserState state = ps.readUserState(userId); 1861 return PackageParser.generatePackageInfo(p, gp.gids, flags, 1862 ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions, 1863 state, userId); 1864 } 1865 1866 @Override 1867 public boolean isPackageAvailable(String packageName, int userId) { 1868 if (!sUserManager.exists(userId)) return false; 1869 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available"); 1870 synchronized (mPackages) { 1871 PackageParser.Package p = mPackages.get(packageName); 1872 if (p != null) { 1873 final PackageSetting ps = (PackageSetting) p.mExtras; 1874 if (ps != null) { 1875 final PackageUserState state = ps.readUserState(userId); 1876 if (state != null) { 1877 return PackageParser.isAvailable(state); 1878 } 1879 } 1880 } 1881 } 1882 return false; 1883 } 1884 1885 @Override 1886 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 1887 if (!sUserManager.exists(userId)) return null; 1888 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info"); 1889 // reader 1890 synchronized (mPackages) { 1891 PackageParser.Package p = mPackages.get(packageName); 1892 if (DEBUG_PACKAGE_INFO) 1893 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 1894 if (p != null) { 1895 return generatePackageInfo(p, flags, userId); 1896 } 1897 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 1898 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 1899 } 1900 } 1901 return null; 1902 } 1903 1904 @Override 1905 public String[] currentToCanonicalPackageNames(String[] names) { 1906 String[] out = new String[names.length]; 1907 // reader 1908 synchronized (mPackages) { 1909 for (int i=names.length-1; i>=0; i--) { 1910 PackageSetting ps = mSettings.mPackages.get(names[i]); 1911 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 1912 } 1913 } 1914 return out; 1915 } 1916 1917 @Override 1918 public String[] canonicalToCurrentPackageNames(String[] names) { 1919 String[] out = new String[names.length]; 1920 // reader 1921 synchronized (mPackages) { 1922 for (int i=names.length-1; i>=0; i--) { 1923 String cur = mSettings.mRenamedPackages.get(names[i]); 1924 out[i] = cur != null ? cur : names[i]; 1925 } 1926 } 1927 return out; 1928 } 1929 1930 @Override 1931 public int getPackageUid(String packageName, int userId) { 1932 if (!sUserManager.exists(userId)) return -1; 1933 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid"); 1934 // reader 1935 synchronized (mPackages) { 1936 PackageParser.Package p = mPackages.get(packageName); 1937 if(p != null) { 1938 return UserHandle.getUid(userId, p.applicationInfo.uid); 1939 } 1940 PackageSetting ps = mSettings.mPackages.get(packageName); 1941 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 1942 return -1; 1943 } 1944 p = ps.pkg; 1945 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 1946 } 1947 } 1948 1949 @Override 1950 public int[] getPackageGids(String packageName) { 1951 // reader 1952 synchronized (mPackages) { 1953 PackageParser.Package p = mPackages.get(packageName); 1954 if (DEBUG_PACKAGE_INFO) 1955 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 1956 if (p != null) { 1957 final PackageSetting ps = (PackageSetting)p.mExtras; 1958 return ps.getGids(); 1959 } 1960 } 1961 // stupid thing to indicate an error. 1962 return new int[0]; 1963 } 1964 1965 static final PermissionInfo generatePermissionInfo( 1966 BasePermission bp, int flags) { 1967 if (bp.perm != null) { 1968 return PackageParser.generatePermissionInfo(bp.perm, flags); 1969 } 1970 PermissionInfo pi = new PermissionInfo(); 1971 pi.name = bp.name; 1972 pi.packageName = bp.sourcePackage; 1973 pi.nonLocalizedLabel = bp.name; 1974 pi.protectionLevel = bp.protectionLevel; 1975 return pi; 1976 } 1977 1978 @Override 1979 public PermissionInfo getPermissionInfo(String name, int flags) { 1980 // reader 1981 synchronized (mPackages) { 1982 final BasePermission p = mSettings.mPermissions.get(name); 1983 if (p != null) { 1984 return generatePermissionInfo(p, flags); 1985 } 1986 return null; 1987 } 1988 } 1989 1990 @Override 1991 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 1992 // reader 1993 synchronized (mPackages) { 1994 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 1995 for (BasePermission p : mSettings.mPermissions.values()) { 1996 if (group == null) { 1997 if (p.perm == null || p.perm.info.group == null) { 1998 out.add(generatePermissionInfo(p, flags)); 1999 } 2000 } else { 2001 if (p.perm != null && group.equals(p.perm.info.group)) { 2002 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2003 } 2004 } 2005 } 2006 2007 if (out.size() > 0) { 2008 return out; 2009 } 2010 return mPermissionGroups.containsKey(group) ? out : null; 2011 } 2012 } 2013 2014 @Override 2015 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2016 // reader 2017 synchronized (mPackages) { 2018 return PackageParser.generatePermissionGroupInfo( 2019 mPermissionGroups.get(name), flags); 2020 } 2021 } 2022 2023 @Override 2024 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2025 // reader 2026 synchronized (mPackages) { 2027 final int N = mPermissionGroups.size(); 2028 ArrayList<PermissionGroupInfo> out 2029 = new ArrayList<PermissionGroupInfo>(N); 2030 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2031 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2032 } 2033 return out; 2034 } 2035 } 2036 2037 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2038 int userId) { 2039 if (!sUserManager.exists(userId)) return null; 2040 PackageSetting ps = mSettings.mPackages.get(packageName); 2041 if (ps != null) { 2042 if (ps.pkg == null) { 2043 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2044 flags, userId); 2045 if (pInfo != null) { 2046 return pInfo.applicationInfo; 2047 } 2048 return null; 2049 } 2050 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2051 ps.readUserState(userId), userId); 2052 } 2053 return null; 2054 } 2055 2056 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2057 int userId) { 2058 if (!sUserManager.exists(userId)) return null; 2059 PackageSetting ps = mSettings.mPackages.get(packageName); 2060 if (ps != null) { 2061 PackageParser.Package pkg = ps.pkg; 2062 if (pkg == null) { 2063 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2064 return null; 2065 } 2066 // Only data remains, so we aren't worried about code paths 2067 pkg = new PackageParser.Package(packageName); 2068 pkg.applicationInfo.packageName = packageName; 2069 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2070 pkg.applicationInfo.dataDir = 2071 getDataPathForPackage(packageName, 0).getPath(); 2072 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2073 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2074 } 2075 return generatePackageInfo(pkg, flags, userId); 2076 } 2077 return null; 2078 } 2079 2080 @Override 2081 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2082 if (!sUserManager.exists(userId)) return null; 2083 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info"); 2084 // writer 2085 synchronized (mPackages) { 2086 PackageParser.Package p = mPackages.get(packageName); 2087 if (DEBUG_PACKAGE_INFO) Log.v( 2088 TAG, "getApplicationInfo " + packageName 2089 + ": " + p); 2090 if (p != null) { 2091 PackageSetting ps = mSettings.mPackages.get(packageName); 2092 if (ps == null) return null; 2093 // Note: isEnabledLP() does not apply here - always return info 2094 return PackageParser.generateApplicationInfo( 2095 p, flags, ps.readUserState(userId), userId); 2096 } 2097 if ("android".equals(packageName)||"system".equals(packageName)) { 2098 return mAndroidApplication; 2099 } 2100 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2101 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2102 } 2103 } 2104 return null; 2105 } 2106 2107 2108 @Override 2109 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2110 mContext.enforceCallingOrSelfPermission( 2111 android.Manifest.permission.CLEAR_APP_CACHE, null); 2112 // Queue up an async operation since clearing cache may take a little while. 2113 mHandler.post(new Runnable() { 2114 public void run() { 2115 mHandler.removeCallbacks(this); 2116 int retCode = -1; 2117 synchronized (mInstallLock) { 2118 retCode = mInstaller.freeCache(freeStorageSize); 2119 if (retCode < 0) { 2120 Slog.w(TAG, "Couldn't clear application caches"); 2121 } 2122 } 2123 if (observer != null) { 2124 try { 2125 observer.onRemoveCompleted(null, (retCode >= 0)); 2126 } catch (RemoteException e) { 2127 Slog.w(TAG, "RemoveException when invoking call back"); 2128 } 2129 } 2130 } 2131 }); 2132 } 2133 2134 @Override 2135 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2136 mContext.enforceCallingOrSelfPermission( 2137 android.Manifest.permission.CLEAR_APP_CACHE, null); 2138 // Queue up an async operation since clearing cache may take a little while. 2139 mHandler.post(new Runnable() { 2140 public void run() { 2141 mHandler.removeCallbacks(this); 2142 int retCode = -1; 2143 synchronized (mInstallLock) { 2144 retCode = mInstaller.freeCache(freeStorageSize); 2145 if (retCode < 0) { 2146 Slog.w(TAG, "Couldn't clear application caches"); 2147 } 2148 } 2149 if(pi != null) { 2150 try { 2151 // Callback via pending intent 2152 int code = (retCode >= 0) ? 1 : 0; 2153 pi.sendIntent(null, code, null, 2154 null, null); 2155 } catch (SendIntentException e1) { 2156 Slog.i(TAG, "Failed to send pending intent"); 2157 } 2158 } 2159 } 2160 }); 2161 } 2162 2163 void freeStorage(long freeStorageSize) throws IOException { 2164 synchronized (mInstallLock) { 2165 if (mInstaller.freeCache(freeStorageSize) < 0) { 2166 throw new IOException("Failed to free enough space"); 2167 } 2168 } 2169 } 2170 2171 @Override 2172 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2173 if (!sUserManager.exists(userId)) return null; 2174 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info"); 2175 synchronized (mPackages) { 2176 PackageParser.Activity a = mActivities.mActivities.get(component); 2177 2178 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2179 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2180 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2181 if (ps == null) return null; 2182 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2183 userId); 2184 } 2185 if (mResolveComponentName.equals(component)) { 2186 return mResolveActivity; 2187 } 2188 } 2189 return null; 2190 } 2191 2192 @Override 2193 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2194 String resolvedType) { 2195 synchronized (mPackages) { 2196 PackageParser.Activity a = mActivities.mActivities.get(component); 2197 if (a == null) { 2198 return false; 2199 } 2200 for (int i=0; i<a.intents.size(); i++) { 2201 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2202 intent.getData(), intent.getCategories(), TAG) >= 0) { 2203 return true; 2204 } 2205 } 2206 return false; 2207 } 2208 } 2209 2210 @Override 2211 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2212 if (!sUserManager.exists(userId)) return null; 2213 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info"); 2214 synchronized (mPackages) { 2215 PackageParser.Activity a = mReceivers.mActivities.get(component); 2216 if (DEBUG_PACKAGE_INFO) Log.v( 2217 TAG, "getReceiverInfo " + component + ": " + a); 2218 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2219 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2220 if (ps == null) return null; 2221 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2222 userId); 2223 } 2224 } 2225 return null; 2226 } 2227 2228 @Override 2229 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2230 if (!sUserManager.exists(userId)) return null; 2231 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info"); 2232 synchronized (mPackages) { 2233 PackageParser.Service s = mServices.mServices.get(component); 2234 if (DEBUG_PACKAGE_INFO) Log.v( 2235 TAG, "getServiceInfo " + component + ": " + s); 2236 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2237 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2238 if (ps == null) return null; 2239 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2240 userId); 2241 } 2242 } 2243 return null; 2244 } 2245 2246 @Override 2247 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2248 if (!sUserManager.exists(userId)) return null; 2249 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info"); 2250 synchronized (mPackages) { 2251 PackageParser.Provider p = mProviders.mProviders.get(component); 2252 if (DEBUG_PACKAGE_INFO) Log.v( 2253 TAG, "getProviderInfo " + component + ": " + p); 2254 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2255 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2256 if (ps == null) return null; 2257 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2258 userId); 2259 } 2260 } 2261 return null; 2262 } 2263 2264 @Override 2265 public String[] getSystemSharedLibraryNames() { 2266 Set<String> libSet; 2267 synchronized (mPackages) { 2268 libSet = mSharedLibraries.keySet(); 2269 int size = libSet.size(); 2270 if (size > 0) { 2271 String[] libs = new String[size]; 2272 libSet.toArray(libs); 2273 return libs; 2274 } 2275 } 2276 return null; 2277 } 2278 2279 @Override 2280 public FeatureInfo[] getSystemAvailableFeatures() { 2281 Collection<FeatureInfo> featSet; 2282 synchronized (mPackages) { 2283 featSet = mAvailableFeatures.values(); 2284 int size = featSet.size(); 2285 if (size > 0) { 2286 FeatureInfo[] features = new FeatureInfo[size+1]; 2287 featSet.toArray(features); 2288 FeatureInfo fi = new FeatureInfo(); 2289 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2290 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2291 features[size] = fi; 2292 return features; 2293 } 2294 } 2295 return null; 2296 } 2297 2298 @Override 2299 public boolean hasSystemFeature(String name) { 2300 synchronized (mPackages) { 2301 return mAvailableFeatures.containsKey(name); 2302 } 2303 } 2304 2305 private void checkValidCaller(int uid, int userId) { 2306 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2307 return; 2308 2309 throw new SecurityException("Caller uid=" + uid 2310 + " is not privileged to communicate with user=" + userId); 2311 } 2312 2313 @Override 2314 public int checkPermission(String permName, String pkgName) { 2315 synchronized (mPackages) { 2316 PackageParser.Package p = mPackages.get(pkgName); 2317 if (p != null && p.mExtras != null) { 2318 PackageSetting ps = (PackageSetting)p.mExtras; 2319 if (ps.sharedUser != null) { 2320 if (ps.sharedUser.grantedPermissions.contains(permName)) { 2321 return PackageManager.PERMISSION_GRANTED; 2322 } 2323 } else if (ps.grantedPermissions.contains(permName)) { 2324 return PackageManager.PERMISSION_GRANTED; 2325 } 2326 } 2327 } 2328 return PackageManager.PERMISSION_DENIED; 2329 } 2330 2331 @Override 2332 public int checkUidPermission(String permName, int uid) { 2333 synchronized (mPackages) { 2334 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2335 if (obj != null) { 2336 GrantedPermissions gp = (GrantedPermissions)obj; 2337 if (gp.grantedPermissions.contains(permName)) { 2338 return PackageManager.PERMISSION_GRANTED; 2339 } 2340 } else { 2341 HashSet<String> perms = mSystemPermissions.get(uid); 2342 if (perms != null && perms.contains(permName)) { 2343 return PackageManager.PERMISSION_GRANTED; 2344 } 2345 } 2346 } 2347 return PackageManager.PERMISSION_DENIED; 2348 } 2349 2350 /** 2351 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2352 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2353 * @param message the message to log on security exception 2354 */ 2355 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2356 String message) { 2357 if (userId < 0) { 2358 throw new IllegalArgumentException("Invalid userId " + userId); 2359 } 2360 if (userId == UserHandle.getUserId(callingUid)) return; 2361 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2362 if (requireFullPermission) { 2363 mContext.enforceCallingOrSelfPermission( 2364 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2365 } else { 2366 try { 2367 mContext.enforceCallingOrSelfPermission( 2368 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2369 } catch (SecurityException se) { 2370 mContext.enforceCallingOrSelfPermission( 2371 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2372 } 2373 } 2374 } 2375 } 2376 2377 private BasePermission findPermissionTreeLP(String permName) { 2378 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2379 if (permName.startsWith(bp.name) && 2380 permName.length() > bp.name.length() && 2381 permName.charAt(bp.name.length()) == '.') { 2382 return bp; 2383 } 2384 } 2385 return null; 2386 } 2387 2388 private BasePermission checkPermissionTreeLP(String permName) { 2389 if (permName != null) { 2390 BasePermission bp = findPermissionTreeLP(permName); 2391 if (bp != null) { 2392 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2393 return bp; 2394 } 2395 throw new SecurityException("Calling uid " 2396 + Binder.getCallingUid() 2397 + " is not allowed to add to permission tree " 2398 + bp.name + " owned by uid " + bp.uid); 2399 } 2400 } 2401 throw new SecurityException("No permission tree found for " + permName); 2402 } 2403 2404 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2405 if (s1 == null) { 2406 return s2 == null; 2407 } 2408 if (s2 == null) { 2409 return false; 2410 } 2411 if (s1.getClass() != s2.getClass()) { 2412 return false; 2413 } 2414 return s1.equals(s2); 2415 } 2416 2417 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2418 if (pi1.icon != pi2.icon) return false; 2419 if (pi1.logo != pi2.logo) return false; 2420 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2421 if (!compareStrings(pi1.name, pi2.name)) return false; 2422 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2423 // We'll take care of setting this one. 2424 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2425 // These are not currently stored in settings. 2426 //if (!compareStrings(pi1.group, pi2.group)) return false; 2427 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2428 //if (pi1.labelRes != pi2.labelRes) return false; 2429 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2430 return true; 2431 } 2432 2433 int permissionInfoFootprint(PermissionInfo info) { 2434 int size = info.name.length(); 2435 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2436 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2437 return size; 2438 } 2439 2440 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2441 int size = 0; 2442 for (BasePermission perm : mSettings.mPermissions.values()) { 2443 if (perm.uid == tree.uid) { 2444 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2445 } 2446 } 2447 return size; 2448 } 2449 2450 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2451 // We calculate the max size of permissions defined by this uid and throw 2452 // if that plus the size of 'info' would exceed our stated maximum. 2453 if (tree.uid != Process.SYSTEM_UID) { 2454 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2455 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2456 throw new SecurityException("Permission tree size cap exceeded"); 2457 } 2458 } 2459 } 2460 2461 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2462 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2463 throw new SecurityException("Label must be specified in permission"); 2464 } 2465 BasePermission tree = checkPermissionTreeLP(info.name); 2466 BasePermission bp = mSettings.mPermissions.get(info.name); 2467 boolean added = bp == null; 2468 boolean changed = true; 2469 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2470 if (added) { 2471 enforcePermissionCapLocked(info, tree); 2472 bp = new BasePermission(info.name, tree.sourcePackage, 2473 BasePermission.TYPE_DYNAMIC); 2474 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2475 throw new SecurityException( 2476 "Not allowed to modify non-dynamic permission " 2477 + info.name); 2478 } else { 2479 if (bp.protectionLevel == fixedLevel 2480 && bp.perm.owner.equals(tree.perm.owner) 2481 && bp.uid == tree.uid 2482 && comparePermissionInfos(bp.perm.info, info)) { 2483 changed = false; 2484 } 2485 } 2486 bp.protectionLevel = fixedLevel; 2487 info = new PermissionInfo(info); 2488 info.protectionLevel = fixedLevel; 2489 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 2490 bp.perm.info.packageName = tree.perm.info.packageName; 2491 bp.uid = tree.uid; 2492 if (added) { 2493 mSettings.mPermissions.put(info.name, bp); 2494 } 2495 if (changed) { 2496 if (!async) { 2497 mSettings.writeLPr(); 2498 } else { 2499 scheduleWriteSettingsLocked(); 2500 } 2501 } 2502 return added; 2503 } 2504 2505 @Override 2506 public boolean addPermission(PermissionInfo info) { 2507 synchronized (mPackages) { 2508 return addPermissionLocked(info, false); 2509 } 2510 } 2511 2512 @Override 2513 public boolean addPermissionAsync(PermissionInfo info) { 2514 synchronized (mPackages) { 2515 return addPermissionLocked(info, true); 2516 } 2517 } 2518 2519 @Override 2520 public void removePermission(String name) { 2521 synchronized (mPackages) { 2522 checkPermissionTreeLP(name); 2523 BasePermission bp = mSettings.mPermissions.get(name); 2524 if (bp != null) { 2525 if (bp.type != BasePermission.TYPE_DYNAMIC) { 2526 throw new SecurityException( 2527 "Not allowed to modify non-dynamic permission " 2528 + name); 2529 } 2530 mSettings.mPermissions.remove(name); 2531 mSettings.writeLPr(); 2532 } 2533 } 2534 } 2535 2536 private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) { 2537 int index = pkg.requestedPermissions.indexOf(bp.name); 2538 if (index == -1) { 2539 throw new SecurityException("Package " + pkg.packageName 2540 + " has not requested permission " + bp.name); 2541 } 2542 boolean isNormal = 2543 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2544 == PermissionInfo.PROTECTION_NORMAL); 2545 boolean isDangerous = 2546 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2547 == PermissionInfo.PROTECTION_DANGEROUS); 2548 boolean isDevelopment = 2549 ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0); 2550 2551 if (!isNormal && !isDangerous && !isDevelopment) { 2552 throw new SecurityException("Permission " + bp.name 2553 + " is not a changeable permission type"); 2554 } 2555 2556 if (isNormal || isDangerous) { 2557 if (pkg.requestedPermissionsRequired.get(index)) { 2558 throw new SecurityException("Can't change " + bp.name 2559 + ". It is required by the application"); 2560 } 2561 } 2562 } 2563 2564 @Override 2565 public void grantPermission(String packageName, String permissionName) { 2566 mContext.enforceCallingOrSelfPermission( 2567 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2568 synchronized (mPackages) { 2569 final PackageParser.Package pkg = mPackages.get(packageName); 2570 if (pkg == null) { 2571 throw new IllegalArgumentException("Unknown package: " + packageName); 2572 } 2573 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2574 if (bp == null) { 2575 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2576 } 2577 2578 checkGrantRevokePermissions(pkg, bp); 2579 2580 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2581 if (ps == null) { 2582 return; 2583 } 2584 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2585 if (gp.grantedPermissions.add(permissionName)) { 2586 if (ps.haveGids) { 2587 gp.gids = appendInts(gp.gids, bp.gids); 2588 } 2589 mSettings.writeLPr(); 2590 } 2591 } 2592 } 2593 2594 @Override 2595 public void revokePermission(String packageName, String permissionName) { 2596 int changedAppId = -1; 2597 2598 synchronized (mPackages) { 2599 final PackageParser.Package pkg = mPackages.get(packageName); 2600 if (pkg == null) { 2601 throw new IllegalArgumentException("Unknown package: " + packageName); 2602 } 2603 if (pkg.applicationInfo.uid != Binder.getCallingUid()) { 2604 mContext.enforceCallingOrSelfPermission( 2605 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2606 } 2607 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2608 if (bp == null) { 2609 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2610 } 2611 2612 checkGrantRevokePermissions(pkg, bp); 2613 2614 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2615 if (ps == null) { 2616 return; 2617 } 2618 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2619 if (gp.grantedPermissions.remove(permissionName)) { 2620 gp.grantedPermissions.remove(permissionName); 2621 if (ps.haveGids) { 2622 gp.gids = removeInts(gp.gids, bp.gids); 2623 } 2624 mSettings.writeLPr(); 2625 changedAppId = ps.appId; 2626 } 2627 } 2628 2629 if (changedAppId >= 0) { 2630 // We changed the perm on someone, kill its processes. 2631 IActivityManager am = ActivityManagerNative.getDefault(); 2632 if (am != null) { 2633 final int callingUserId = UserHandle.getCallingUserId(); 2634 final long ident = Binder.clearCallingIdentity(); 2635 try { 2636 //XXX we should only revoke for the calling user's app permissions, 2637 // but for now we impact all users. 2638 //am.killUid(UserHandle.getUid(callingUserId, changedAppId), 2639 // "revoke " + permissionName); 2640 int[] users = sUserManager.getUserIds(); 2641 for (int user : users) { 2642 am.killUid(UserHandle.getUid(user, changedAppId), 2643 "revoke " + permissionName); 2644 } 2645 } catch (RemoteException e) { 2646 } finally { 2647 Binder.restoreCallingIdentity(ident); 2648 } 2649 } 2650 } 2651 } 2652 2653 @Override 2654 public boolean isProtectedBroadcast(String actionName) { 2655 synchronized (mPackages) { 2656 return mProtectedBroadcasts.contains(actionName); 2657 } 2658 } 2659 2660 @Override 2661 public int checkSignatures(String pkg1, String pkg2) { 2662 synchronized (mPackages) { 2663 final PackageParser.Package p1 = mPackages.get(pkg1); 2664 final PackageParser.Package p2 = mPackages.get(pkg2); 2665 if (p1 == null || p1.mExtras == null 2666 || p2 == null || p2.mExtras == null) { 2667 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2668 } 2669 return compareSignatures(p1.mSignatures, p2.mSignatures); 2670 } 2671 } 2672 2673 @Override 2674 public int checkUidSignatures(int uid1, int uid2) { 2675 // Map to base uids. 2676 uid1 = UserHandle.getAppId(uid1); 2677 uid2 = UserHandle.getAppId(uid2); 2678 // reader 2679 synchronized (mPackages) { 2680 Signature[] s1; 2681 Signature[] s2; 2682 Object obj = mSettings.getUserIdLPr(uid1); 2683 if (obj != null) { 2684 if (obj instanceof SharedUserSetting) { 2685 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 2686 } else if (obj instanceof PackageSetting) { 2687 s1 = ((PackageSetting)obj).signatures.mSignatures; 2688 } else { 2689 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2690 } 2691 } else { 2692 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2693 } 2694 obj = mSettings.getUserIdLPr(uid2); 2695 if (obj != null) { 2696 if (obj instanceof SharedUserSetting) { 2697 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 2698 } else if (obj instanceof PackageSetting) { 2699 s2 = ((PackageSetting)obj).signatures.mSignatures; 2700 } else { 2701 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2702 } 2703 } else { 2704 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2705 } 2706 return compareSignatures(s1, s2); 2707 } 2708 } 2709 2710 /** 2711 * Compares two sets of signatures. Returns: 2712 * <br /> 2713 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 2714 * <br /> 2715 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 2716 * <br /> 2717 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 2718 * <br /> 2719 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 2720 * <br /> 2721 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 2722 */ 2723 static int compareSignatures(Signature[] s1, Signature[] s2) { 2724 if (s1 == null) { 2725 return s2 == null 2726 ? PackageManager.SIGNATURE_NEITHER_SIGNED 2727 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 2728 } 2729 2730 if (s2 == null) { 2731 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 2732 } 2733 2734 if (s1.length != s2.length) { 2735 return PackageManager.SIGNATURE_NO_MATCH; 2736 } 2737 2738 // Since both signature sets are of size 1, we can compare without HashSets. 2739 if (s1.length == 1) { 2740 return s1[0].equals(s2[0]) ? 2741 PackageManager.SIGNATURE_MATCH : 2742 PackageManager.SIGNATURE_NO_MATCH; 2743 } 2744 2745 HashSet<Signature> set1 = new HashSet<Signature>(); 2746 for (Signature sig : s1) { 2747 set1.add(sig); 2748 } 2749 HashSet<Signature> set2 = new HashSet<Signature>(); 2750 for (Signature sig : s2) { 2751 set2.add(sig); 2752 } 2753 // Make sure s2 contains all signatures in s1. 2754 if (set1.equals(set2)) { 2755 return PackageManager.SIGNATURE_MATCH; 2756 } 2757 return PackageManager.SIGNATURE_NO_MATCH; 2758 } 2759 2760 /** 2761 * If the database version for this type of package (internal storage or 2762 * external storage) is less than the version where package signatures 2763 * were updated, return true. 2764 */ 2765 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2766 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 2767 DatabaseVersion.SIGNATURE_END_ENTITY)) 2768 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 2769 DatabaseVersion.SIGNATURE_END_ENTITY)); 2770 } 2771 2772 /** 2773 * Used for backward compatibility to make sure any packages with 2774 * certificate chains get upgraded to the new style. {@code existingSigs} 2775 * will be in the old format (since they were stored on disk from before the 2776 * system upgrade) and {@code scannedSigs} will be in the newer format. 2777 */ 2778 private int compareSignaturesCompat(PackageSignatures existingSigs, 2779 PackageParser.Package scannedPkg) { 2780 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 2781 return PackageManager.SIGNATURE_NO_MATCH; 2782 } 2783 2784 HashSet<Signature> existingSet = new HashSet<Signature>(); 2785 for (Signature sig : existingSigs.mSignatures) { 2786 existingSet.add(sig); 2787 } 2788 HashSet<Signature> scannedCompatSet = new HashSet<Signature>(); 2789 for (Signature sig : scannedPkg.mSignatures) { 2790 try { 2791 Signature[] chainSignatures = sig.getChainSignatures(); 2792 for (Signature chainSig : chainSignatures) { 2793 scannedCompatSet.add(chainSig); 2794 } 2795 } catch (CertificateEncodingException e) { 2796 scannedCompatSet.add(sig); 2797 } 2798 } 2799 /* 2800 * Make sure the expanded scanned set contains all signatures in the 2801 * existing one. 2802 */ 2803 if (scannedCompatSet.equals(existingSet)) { 2804 // Migrate the old signatures to the new scheme. 2805 existingSigs.assignSignatures(scannedPkg.mSignatures); 2806 // The new KeySets will be re-added later in the scanning process. 2807 synchronized (mPackages) { 2808 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 2809 } 2810 return PackageManager.SIGNATURE_MATCH; 2811 } 2812 return PackageManager.SIGNATURE_NO_MATCH; 2813 } 2814 2815 @Override 2816 public String[] getPackagesForUid(int uid) { 2817 uid = UserHandle.getAppId(uid); 2818 // reader 2819 synchronized (mPackages) { 2820 Object obj = mSettings.getUserIdLPr(uid); 2821 if (obj instanceof SharedUserSetting) { 2822 final SharedUserSetting sus = (SharedUserSetting) obj; 2823 final int N = sus.packages.size(); 2824 final String[] res = new String[N]; 2825 final Iterator<PackageSetting> it = sus.packages.iterator(); 2826 int i = 0; 2827 while (it.hasNext()) { 2828 res[i++] = it.next().name; 2829 } 2830 return res; 2831 } else if (obj instanceof PackageSetting) { 2832 final PackageSetting ps = (PackageSetting) obj; 2833 return new String[] { ps.name }; 2834 } 2835 } 2836 return null; 2837 } 2838 2839 @Override 2840 public String getNameForUid(int uid) { 2841 // reader 2842 synchronized (mPackages) { 2843 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2844 if (obj instanceof SharedUserSetting) { 2845 final SharedUserSetting sus = (SharedUserSetting) obj; 2846 return sus.name + ":" + sus.userId; 2847 } else if (obj instanceof PackageSetting) { 2848 final PackageSetting ps = (PackageSetting) obj; 2849 return ps.name; 2850 } 2851 } 2852 return null; 2853 } 2854 2855 @Override 2856 public int getUidForSharedUser(String sharedUserName) { 2857 if(sharedUserName == null) { 2858 return -1; 2859 } 2860 // reader 2861 synchronized (mPackages) { 2862 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false); 2863 if (suid == null) { 2864 return -1; 2865 } 2866 return suid.userId; 2867 } 2868 } 2869 2870 @Override 2871 public int getFlagsForUid(int uid) { 2872 synchronized (mPackages) { 2873 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2874 if (obj instanceof SharedUserSetting) { 2875 final SharedUserSetting sus = (SharedUserSetting) obj; 2876 return sus.pkgFlags; 2877 } else if (obj instanceof PackageSetting) { 2878 final PackageSetting ps = (PackageSetting) obj; 2879 return ps.pkgFlags; 2880 } 2881 } 2882 return 0; 2883 } 2884 2885 @Override 2886 public String[] getAppOpPermissionPackages(String permissionName) { 2887 synchronized (mPackages) { 2888 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 2889 if (pkgs == null) { 2890 return null; 2891 } 2892 return pkgs.toArray(new String[pkgs.size()]); 2893 } 2894 } 2895 2896 @Override 2897 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 2898 int flags, int userId) { 2899 if (!sUserManager.exists(userId)) return null; 2900 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent"); 2901 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2902 return chooseBestActivity(intent, resolvedType, flags, query, userId); 2903 } 2904 2905 @Override 2906 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 2907 IntentFilter filter, int match, ComponentName activity) { 2908 final int userId = UserHandle.getCallingUserId(); 2909 if (DEBUG_PREFERRED) { 2910 Log.v(TAG, "setLastChosenActivity intent=" + intent 2911 + " resolvedType=" + resolvedType 2912 + " flags=" + flags 2913 + " filter=" + filter 2914 + " match=" + match 2915 + " activity=" + activity); 2916 filter.dump(new PrintStreamPrinter(System.out), " "); 2917 } 2918 intent.setComponent(null); 2919 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2920 // Find any earlier preferred or last chosen entries and nuke them 2921 findPreferredActivity(intent, resolvedType, 2922 flags, query, 0, false, true, false, userId); 2923 // Add the new activity as the last chosen for this filter 2924 addPreferredActivityInternal(filter, match, null, activity, false, userId, 2925 "Setting last chosen"); 2926 } 2927 2928 @Override 2929 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 2930 final int userId = UserHandle.getCallingUserId(); 2931 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 2932 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2933 return findPreferredActivity(intent, resolvedType, flags, query, 0, 2934 false, false, false, userId); 2935 } 2936 2937 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 2938 int flags, List<ResolveInfo> query, int userId) { 2939 if (query != null) { 2940 final int N = query.size(); 2941 if (N == 1) { 2942 return query.get(0); 2943 } else if (N > 1) { 2944 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 2945 // If there is more than one activity with the same priority, 2946 // then let the user decide between them. 2947 ResolveInfo r0 = query.get(0); 2948 ResolveInfo r1 = query.get(1); 2949 if (DEBUG_INTENT_MATCHING || debug) { 2950 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 2951 + r1.activityInfo.name + "=" + r1.priority); 2952 } 2953 // If the first activity has a higher priority, or a different 2954 // default, then it is always desireable to pick it. 2955 if (r0.priority != r1.priority 2956 || r0.preferredOrder != r1.preferredOrder 2957 || r0.isDefault != r1.isDefault) { 2958 return query.get(0); 2959 } 2960 // If we have saved a preference for a preferred activity for 2961 // this Intent, use that. 2962 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 2963 flags, query, r0.priority, true, false, debug, userId); 2964 if (ri != null) { 2965 return ri; 2966 } 2967 if (userId != 0) { 2968 ri = new ResolveInfo(mResolveInfo); 2969 ri.activityInfo = new ActivityInfo(ri.activityInfo); 2970 ri.activityInfo.applicationInfo = new ApplicationInfo( 2971 ri.activityInfo.applicationInfo); 2972 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 2973 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 2974 return ri; 2975 } 2976 return mResolveInfo; 2977 } 2978 } 2979 return null; 2980 } 2981 2982 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 2983 int flags, List<ResolveInfo> query, boolean debug, int userId) { 2984 final int N = query.size(); 2985 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 2986 .get(userId); 2987 // Get the list of persistent preferred activities that handle the intent 2988 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 2989 List<PersistentPreferredActivity> pprefs = ppir != null 2990 ? ppir.queryIntent(intent, resolvedType, 2991 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 2992 : null; 2993 if (pprefs != null && pprefs.size() > 0) { 2994 final int M = pprefs.size(); 2995 for (int i=0; i<M; i++) { 2996 final PersistentPreferredActivity ppa = pprefs.get(i); 2997 if (DEBUG_PREFERRED || debug) { 2998 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 2999 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3000 + "\n component=" + ppa.mComponent); 3001 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3002 } 3003 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3004 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3005 if (DEBUG_PREFERRED || debug) { 3006 Slog.v(TAG, "Found persistent preferred activity:"); 3007 if (ai != null) { 3008 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3009 } else { 3010 Slog.v(TAG, " null"); 3011 } 3012 } 3013 if (ai == null) { 3014 // This previously registered persistent preferred activity 3015 // component is no longer known. Ignore it and do NOT remove it. 3016 continue; 3017 } 3018 for (int j=0; j<N; j++) { 3019 final ResolveInfo ri = query.get(j); 3020 if (!ri.activityInfo.applicationInfo.packageName 3021 .equals(ai.applicationInfo.packageName)) { 3022 continue; 3023 } 3024 if (!ri.activityInfo.name.equals(ai.name)) { 3025 continue; 3026 } 3027 // Found a persistent preference that can handle the intent. 3028 if (DEBUG_PREFERRED || debug) { 3029 Slog.v(TAG, "Returning persistent preferred activity: " + 3030 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3031 } 3032 return ri; 3033 } 3034 } 3035 } 3036 return null; 3037 } 3038 3039 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3040 List<ResolveInfo> query, int priority, boolean always, 3041 boolean removeMatches, boolean debug, int userId) { 3042 if (!sUserManager.exists(userId)) return null; 3043 // writer 3044 synchronized (mPackages) { 3045 if (intent.getSelector() != null) { 3046 intent = intent.getSelector(); 3047 } 3048 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3049 3050 // Try to find a matching persistent preferred activity. 3051 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3052 debug, userId); 3053 3054 // If a persistent preferred activity matched, use it. 3055 if (pri != null) { 3056 return pri; 3057 } 3058 3059 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3060 // Get the list of preferred activities that handle the intent 3061 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3062 List<PreferredActivity> prefs = pir != null 3063 ? pir.queryIntent(intent, resolvedType, 3064 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3065 : null; 3066 if (prefs != null && prefs.size() > 0) { 3067 // First figure out how good the original match set is. 3068 // We will only allow preferred activities that came 3069 // from the same match quality. 3070 int match = 0; 3071 3072 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3073 3074 final int N = query.size(); 3075 for (int j=0; j<N; j++) { 3076 final ResolveInfo ri = query.get(j); 3077 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3078 + ": 0x" + Integer.toHexString(match)); 3079 if (ri.match > match) { 3080 match = ri.match; 3081 } 3082 } 3083 3084 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3085 + Integer.toHexString(match)); 3086 3087 match &= IntentFilter.MATCH_CATEGORY_MASK; 3088 final int M = prefs.size(); 3089 for (int i=0; i<M; i++) { 3090 final PreferredActivity pa = prefs.get(i); 3091 if (DEBUG_PREFERRED || debug) { 3092 Slog.v(TAG, "Checking PreferredActivity ds=" 3093 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3094 + "\n component=" + pa.mPref.mComponent); 3095 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3096 } 3097 if (pa.mPref.mMatch != match) { 3098 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3099 + Integer.toHexString(pa.mPref.mMatch)); 3100 continue; 3101 } 3102 // If it's not an "always" type preferred activity and that's what we're 3103 // looking for, skip it. 3104 if (always && !pa.mPref.mAlways) { 3105 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3106 continue; 3107 } 3108 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3109 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3110 if (DEBUG_PREFERRED || debug) { 3111 Slog.v(TAG, "Found preferred activity:"); 3112 if (ai != null) { 3113 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3114 } else { 3115 Slog.v(TAG, " null"); 3116 } 3117 } 3118 if (ai == null) { 3119 // This previously registered preferred activity 3120 // component is no longer known. Most likely an update 3121 // to the app was installed and in the new version this 3122 // component no longer exists. Clean it up by removing 3123 // it from the preferred activities list, and skip it. 3124 Slog.w(TAG, "Removing dangling preferred activity: " 3125 + pa.mPref.mComponent); 3126 pir.removeFilter(pa); 3127 continue; 3128 } 3129 for (int j=0; j<N; j++) { 3130 final ResolveInfo ri = query.get(j); 3131 if (!ri.activityInfo.applicationInfo.packageName 3132 .equals(ai.applicationInfo.packageName)) { 3133 continue; 3134 } 3135 if (!ri.activityInfo.name.equals(ai.name)) { 3136 continue; 3137 } 3138 3139 if (removeMatches) { 3140 pir.removeFilter(pa); 3141 if (DEBUG_PREFERRED) { 3142 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3143 } 3144 break; 3145 } 3146 3147 // Okay we found a previously set preferred or last chosen app. 3148 // If the result set is different from when this 3149 // was created, we need to clear it and re-ask the 3150 // user their preference, if we're looking for an "always" type entry. 3151 if (always && !pa.mPref.sameSet(query, priority)) { 3152 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3153 + intent + " type " + resolvedType); 3154 if (DEBUG_PREFERRED) { 3155 Slog.v(TAG, "Removing preferred activity since set changed " 3156 + pa.mPref.mComponent); 3157 } 3158 pir.removeFilter(pa); 3159 // Re-add the filter as a "last chosen" entry (!always) 3160 PreferredActivity lastChosen = new PreferredActivity( 3161 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3162 pir.addFilter(lastChosen); 3163 mSettings.writePackageRestrictionsLPr(userId); 3164 return null; 3165 } 3166 3167 // Yay! Either the set matched or we're looking for the last chosen 3168 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3169 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3170 mSettings.writePackageRestrictionsLPr(userId); 3171 return ri; 3172 } 3173 } 3174 } 3175 mSettings.writePackageRestrictionsLPr(userId); 3176 } 3177 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3178 return null; 3179 } 3180 3181 /* 3182 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3183 */ 3184 @Override 3185 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3186 int targetUserId) { 3187 mContext.enforceCallingOrSelfPermission( 3188 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3189 List<CrossProfileIntentFilter> matches = 3190 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3191 if (matches != null) { 3192 int size = matches.size(); 3193 for (int i = 0; i < size; i++) { 3194 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3195 } 3196 } 3197 ArrayList<String> packageNames = null; 3198 SparseArray<ArrayList<String>> fromSource = 3199 mSettings.mCrossProfilePackageInfo.get(sourceUserId); 3200 if (fromSource != null) { 3201 packageNames = fromSource.get(targetUserId); 3202 if (packageNames != null) { 3203 // We need the package name, so we try to resolve with the loosest flags possible 3204 List<ResolveInfo> resolveInfos = mActivities.queryIntent(intent, resolvedType, 3205 PackageManager.GET_UNINSTALLED_PACKAGES, targetUserId); 3206 int count = resolveInfos.size(); 3207 for (int i = 0; i < count; i++) { 3208 ResolveInfo resolveInfo = resolveInfos.get(i); 3209 if (packageNames.contains(resolveInfo.activityInfo.packageName)) { 3210 return true; 3211 } 3212 } 3213 } 3214 } 3215 return false; 3216 } 3217 3218 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3219 String resolvedType, int userId) { 3220 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3221 if (resolver != null) { 3222 return resolver.queryIntent(intent, resolvedType, false, userId); 3223 } 3224 return null; 3225 } 3226 3227 @Override 3228 public List<ResolveInfo> queryIntentActivities(Intent intent, 3229 String resolvedType, int flags, int userId) { 3230 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3231 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities"); 3232 ComponentName comp = intent.getComponent(); 3233 if (comp == null) { 3234 if (intent.getSelector() != null) { 3235 intent = intent.getSelector(); 3236 comp = intent.getComponent(); 3237 } 3238 } 3239 3240 if (comp != null) { 3241 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3242 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3243 if (ai != null) { 3244 final ResolveInfo ri = new ResolveInfo(); 3245 ri.activityInfo = ai; 3246 list.add(ri); 3247 } 3248 return list; 3249 } 3250 3251 // reader 3252 synchronized (mPackages) { 3253 final String pkgName = intent.getPackage(); 3254 boolean queryCrossProfile = (flags & PackageManager.NO_CROSS_PROFILE) == 0; 3255 if (pkgName == null) { 3256 ResolveInfo resolveInfo = null; 3257 if (queryCrossProfile) { 3258 // Check if the intent needs to be forwarded to another user for this package 3259 ArrayList<ResolveInfo> crossProfileResult = 3260 queryIntentActivitiesCrossProfilePackage( 3261 intent, resolvedType, flags, userId); 3262 if (!crossProfileResult.isEmpty()) { 3263 // Skip the current profile 3264 return crossProfileResult; 3265 } 3266 List<CrossProfileIntentFilter> matchingFilters = 3267 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3268 // Check for results that need to skip the current profile. 3269 resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3270 resolvedType, flags, userId); 3271 if (resolveInfo != null) { 3272 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3273 result.add(resolveInfo); 3274 return result; 3275 } 3276 // Check for cross profile results. 3277 resolveInfo = queryCrossProfileIntents( 3278 matchingFilters, intent, resolvedType, flags, userId); 3279 } 3280 // Check for results in the current profile. 3281 List<ResolveInfo> result = mActivities.queryIntent( 3282 intent, resolvedType, flags, userId); 3283 if (resolveInfo != null) { 3284 result.add(resolveInfo); 3285 Collections.sort(result, mResolvePrioritySorter); 3286 } 3287 return result; 3288 } 3289 final PackageParser.Package pkg = mPackages.get(pkgName); 3290 if (pkg != null) { 3291 if (queryCrossProfile) { 3292 ArrayList<ResolveInfo> crossProfileResult = 3293 queryIntentActivitiesCrossProfilePackage( 3294 intent, resolvedType, flags, userId, pkg, pkgName); 3295 if (!crossProfileResult.isEmpty()) { 3296 // Skip the current profile 3297 return crossProfileResult; 3298 } 3299 } 3300 return mActivities.queryIntentForPackage(intent, resolvedType, flags, 3301 pkg.activities, userId); 3302 } 3303 return new ArrayList<ResolveInfo>(); 3304 } 3305 } 3306 3307 private ResolveInfo querySkipCurrentProfileIntents( 3308 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3309 int flags, int sourceUserId) { 3310 if (matchingFilters != null) { 3311 int size = matchingFilters.size(); 3312 for (int i = 0; i < size; i ++) { 3313 CrossProfileIntentFilter filter = matchingFilters.get(i); 3314 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 3315 // Checking if there are activities in the target user that can handle the 3316 // intent. 3317 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3318 flags, sourceUserId); 3319 if (resolveInfo != null) { 3320 return resolveInfo; 3321 } 3322 } 3323 } 3324 } 3325 return null; 3326 } 3327 3328 private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage( 3329 Intent intent, String resolvedType, int flags, int userId) { 3330 ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>(); 3331 SparseArray<ArrayList<String>> sourceForwardingInfo = 3332 mSettings.mCrossProfilePackageInfo.get(userId); 3333 if (sourceForwardingInfo != null) { 3334 int NI = sourceForwardingInfo.size(); 3335 for (int i = 0; i < NI; i++) { 3336 int targetUserId = sourceForwardingInfo.keyAt(i); 3337 ArrayList<String> packageNames = sourceForwardingInfo.valueAt(i); 3338 List<ResolveInfo> resolveInfos = mActivities.queryIntent( 3339 intent, resolvedType, flags, targetUserId); 3340 int NJ = resolveInfos.size(); 3341 for (int j = 0; j < NJ; j++) { 3342 ResolveInfo resolveInfo = resolveInfos.get(j); 3343 if (packageNames.contains(resolveInfo.activityInfo.packageName)) { 3344 matchingResolveInfos.add(createForwardingResolveInfo( 3345 resolveInfo.filter, userId, targetUserId)); 3346 } 3347 } 3348 } 3349 } 3350 return matchingResolveInfos; 3351 } 3352 3353 private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage( 3354 Intent intent, String resolvedType, int flags, int userId, PackageParser.Package pkg, 3355 String packageName) { 3356 ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>(); 3357 SparseArray<ArrayList<String>> sourceForwardingInfo = 3358 mSettings.mCrossProfilePackageInfo.get(userId); 3359 if (sourceForwardingInfo != null) { 3360 int NI = sourceForwardingInfo.size(); 3361 for (int i = 0; i < NI; i++) { 3362 int targetUserId = sourceForwardingInfo.keyAt(i); 3363 if (sourceForwardingInfo.valueAt(i).contains(packageName)) { 3364 List<ResolveInfo> resolveInfos = mActivities.queryIntentForPackage( 3365 intent, resolvedType, flags, pkg.activities, targetUserId); 3366 int NJ = resolveInfos.size(); 3367 for (int j = 0; j < NJ; j++) { 3368 ResolveInfo resolveInfo = resolveInfos.get(j); 3369 matchingResolveInfos.add(createForwardingResolveInfo( 3370 resolveInfo.filter, userId, targetUserId)); 3371 } 3372 } 3373 } 3374 } 3375 return matchingResolveInfos; 3376 } 3377 3378 // Return matching ResolveInfo if any for skip current profile intent filters. 3379 private ResolveInfo queryCrossProfileIntents( 3380 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3381 int flags, int sourceUserId) { 3382 if (matchingFilters != null) { 3383 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 3384 // match the same intent. For performance reasons, it is better not to 3385 // run queryIntent twice for the same userId 3386 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 3387 int size = matchingFilters.size(); 3388 for (int i = 0; i < size; i++) { 3389 CrossProfileIntentFilter filter = matchingFilters.get(i); 3390 int targetUserId = filter.getTargetUserId(); 3391 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 3392 && !alreadyTriedUserIds.get(targetUserId)) { 3393 // Checking if there are activities in the target user that can handle the 3394 // intent. 3395 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3396 flags, sourceUserId); 3397 if (resolveInfo != null) return resolveInfo; 3398 alreadyTriedUserIds.put(targetUserId, true); 3399 } 3400 } 3401 } 3402 return null; 3403 } 3404 3405 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 3406 String resolvedType, int flags, int sourceUserId) { 3407 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 3408 resolvedType, flags, filter.getTargetUserId()); 3409 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 3410 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 3411 } 3412 return null; 3413 } 3414 3415 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 3416 int sourceUserId, int targetUserId) { 3417 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 3418 String className; 3419 if (targetUserId == UserHandle.USER_OWNER) { 3420 className = FORWARD_INTENT_TO_USER_OWNER; 3421 } else { 3422 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 3423 } 3424 ComponentName forwardingActivityComponentName = new ComponentName( 3425 mAndroidApplication.packageName, className); 3426 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 3427 sourceUserId); 3428 if (targetUserId == UserHandle.USER_OWNER) { 3429 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 3430 forwardingResolveInfo.noResourceId = true; 3431 } 3432 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 3433 forwardingResolveInfo.priority = 0; 3434 forwardingResolveInfo.preferredOrder = 0; 3435 forwardingResolveInfo.match = 0; 3436 forwardingResolveInfo.isDefault = true; 3437 forwardingResolveInfo.filter = filter; 3438 forwardingResolveInfo.targetUserId = targetUserId; 3439 return forwardingResolveInfo; 3440 } 3441 3442 @Override 3443 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 3444 Intent[] specifics, String[] specificTypes, Intent intent, 3445 String resolvedType, int flags, int userId) { 3446 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3447 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 3448 "query intent activity options"); 3449 final String resultsAction = intent.getAction(); 3450 3451 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 3452 | PackageManager.GET_RESOLVED_FILTER, userId); 3453 3454 if (DEBUG_INTENT_MATCHING) { 3455 Log.v(TAG, "Query " + intent + ": " + results); 3456 } 3457 3458 int specificsPos = 0; 3459 int N; 3460 3461 // todo: note that the algorithm used here is O(N^2). This 3462 // isn't a problem in our current environment, but if we start running 3463 // into situations where we have more than 5 or 10 matches then this 3464 // should probably be changed to something smarter... 3465 3466 // First we go through and resolve each of the specific items 3467 // that were supplied, taking care of removing any corresponding 3468 // duplicate items in the generic resolve list. 3469 if (specifics != null) { 3470 for (int i=0; i<specifics.length; i++) { 3471 final Intent sintent = specifics[i]; 3472 if (sintent == null) { 3473 continue; 3474 } 3475 3476 if (DEBUG_INTENT_MATCHING) { 3477 Log.v(TAG, "Specific #" + i + ": " + sintent); 3478 } 3479 3480 String action = sintent.getAction(); 3481 if (resultsAction != null && resultsAction.equals(action)) { 3482 // If this action was explicitly requested, then don't 3483 // remove things that have it. 3484 action = null; 3485 } 3486 3487 ResolveInfo ri = null; 3488 ActivityInfo ai = null; 3489 3490 ComponentName comp = sintent.getComponent(); 3491 if (comp == null) { 3492 ri = resolveIntent( 3493 sintent, 3494 specificTypes != null ? specificTypes[i] : null, 3495 flags, userId); 3496 if (ri == null) { 3497 continue; 3498 } 3499 if (ri == mResolveInfo) { 3500 // ACK! Must do something better with this. 3501 } 3502 ai = ri.activityInfo; 3503 comp = new ComponentName(ai.applicationInfo.packageName, 3504 ai.name); 3505 } else { 3506 ai = getActivityInfo(comp, flags, userId); 3507 if (ai == null) { 3508 continue; 3509 } 3510 } 3511 3512 // Look for any generic query activities that are duplicates 3513 // of this specific one, and remove them from the results. 3514 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 3515 N = results.size(); 3516 int j; 3517 for (j=specificsPos; j<N; j++) { 3518 ResolveInfo sri = results.get(j); 3519 if ((sri.activityInfo.name.equals(comp.getClassName()) 3520 && sri.activityInfo.applicationInfo.packageName.equals( 3521 comp.getPackageName())) 3522 || (action != null && sri.filter.matchAction(action))) { 3523 results.remove(j); 3524 if (DEBUG_INTENT_MATCHING) Log.v( 3525 TAG, "Removing duplicate item from " + j 3526 + " due to specific " + specificsPos); 3527 if (ri == null) { 3528 ri = sri; 3529 } 3530 j--; 3531 N--; 3532 } 3533 } 3534 3535 // Add this specific item to its proper place. 3536 if (ri == null) { 3537 ri = new ResolveInfo(); 3538 ri.activityInfo = ai; 3539 } 3540 results.add(specificsPos, ri); 3541 ri.specificIndex = i; 3542 specificsPos++; 3543 } 3544 } 3545 3546 // Now we go through the remaining generic results and remove any 3547 // duplicate actions that are found here. 3548 N = results.size(); 3549 for (int i=specificsPos; i<N-1; i++) { 3550 final ResolveInfo rii = results.get(i); 3551 if (rii.filter == null) { 3552 continue; 3553 } 3554 3555 // Iterate over all of the actions of this result's intent 3556 // filter... typically this should be just one. 3557 final Iterator<String> it = rii.filter.actionsIterator(); 3558 if (it == null) { 3559 continue; 3560 } 3561 while (it.hasNext()) { 3562 final String action = it.next(); 3563 if (resultsAction != null && resultsAction.equals(action)) { 3564 // If this action was explicitly requested, then don't 3565 // remove things that have it. 3566 continue; 3567 } 3568 for (int j=i+1; j<N; j++) { 3569 final ResolveInfo rij = results.get(j); 3570 if (rij.filter != null && rij.filter.hasAction(action)) { 3571 results.remove(j); 3572 if (DEBUG_INTENT_MATCHING) Log.v( 3573 TAG, "Removing duplicate item from " + j 3574 + " due to action " + action + " at " + i); 3575 j--; 3576 N--; 3577 } 3578 } 3579 } 3580 3581 // If the caller didn't request filter information, drop it now 3582 // so we don't have to marshall/unmarshall it. 3583 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3584 rii.filter = null; 3585 } 3586 } 3587 3588 // Filter out the caller activity if so requested. 3589 if (caller != null) { 3590 N = results.size(); 3591 for (int i=0; i<N; i++) { 3592 ActivityInfo ainfo = results.get(i).activityInfo; 3593 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 3594 && caller.getClassName().equals(ainfo.name)) { 3595 results.remove(i); 3596 break; 3597 } 3598 } 3599 } 3600 3601 // If the caller didn't request filter information, 3602 // drop them now so we don't have to 3603 // marshall/unmarshall it. 3604 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3605 N = results.size(); 3606 for (int i=0; i<N; i++) { 3607 results.get(i).filter = null; 3608 } 3609 } 3610 3611 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 3612 return results; 3613 } 3614 3615 @Override 3616 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 3617 int userId) { 3618 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3619 ComponentName comp = intent.getComponent(); 3620 if (comp == null) { 3621 if (intent.getSelector() != null) { 3622 intent = intent.getSelector(); 3623 comp = intent.getComponent(); 3624 } 3625 } 3626 if (comp != null) { 3627 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3628 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 3629 if (ai != null) { 3630 ResolveInfo ri = new ResolveInfo(); 3631 ri.activityInfo = ai; 3632 list.add(ri); 3633 } 3634 return list; 3635 } 3636 3637 // reader 3638 synchronized (mPackages) { 3639 String pkgName = intent.getPackage(); 3640 if (pkgName == null) { 3641 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 3642 } 3643 final PackageParser.Package pkg = mPackages.get(pkgName); 3644 if (pkg != null) { 3645 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 3646 userId); 3647 } 3648 return null; 3649 } 3650 } 3651 3652 @Override 3653 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 3654 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 3655 if (!sUserManager.exists(userId)) return null; 3656 if (query != null) { 3657 if (query.size() >= 1) { 3658 // If there is more than one service with the same priority, 3659 // just arbitrarily pick the first one. 3660 return query.get(0); 3661 } 3662 } 3663 return null; 3664 } 3665 3666 @Override 3667 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 3668 int userId) { 3669 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3670 ComponentName comp = intent.getComponent(); 3671 if (comp == null) { 3672 if (intent.getSelector() != null) { 3673 intent = intent.getSelector(); 3674 comp = intent.getComponent(); 3675 } 3676 } 3677 if (comp != null) { 3678 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3679 final ServiceInfo si = getServiceInfo(comp, flags, userId); 3680 if (si != null) { 3681 final ResolveInfo ri = new ResolveInfo(); 3682 ri.serviceInfo = si; 3683 list.add(ri); 3684 } 3685 return list; 3686 } 3687 3688 // reader 3689 synchronized (mPackages) { 3690 String pkgName = intent.getPackage(); 3691 if (pkgName == null) { 3692 return mServices.queryIntent(intent, resolvedType, flags, userId); 3693 } 3694 final PackageParser.Package pkg = mPackages.get(pkgName); 3695 if (pkg != null) { 3696 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 3697 userId); 3698 } 3699 return null; 3700 } 3701 } 3702 3703 @Override 3704 public List<ResolveInfo> queryIntentContentProviders( 3705 Intent intent, String resolvedType, int flags, int userId) { 3706 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3707 ComponentName comp = intent.getComponent(); 3708 if (comp == null) { 3709 if (intent.getSelector() != null) { 3710 intent = intent.getSelector(); 3711 comp = intent.getComponent(); 3712 } 3713 } 3714 if (comp != null) { 3715 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3716 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 3717 if (pi != null) { 3718 final ResolveInfo ri = new ResolveInfo(); 3719 ri.providerInfo = pi; 3720 list.add(ri); 3721 } 3722 return list; 3723 } 3724 3725 // reader 3726 synchronized (mPackages) { 3727 String pkgName = intent.getPackage(); 3728 if (pkgName == null) { 3729 return mProviders.queryIntent(intent, resolvedType, flags, userId); 3730 } 3731 final PackageParser.Package pkg = mPackages.get(pkgName); 3732 if (pkg != null) { 3733 return mProviders.queryIntentForPackage( 3734 intent, resolvedType, flags, pkg.providers, userId); 3735 } 3736 return null; 3737 } 3738 } 3739 3740 @Override 3741 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 3742 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3743 3744 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages"); 3745 3746 // writer 3747 synchronized (mPackages) { 3748 ArrayList<PackageInfo> list; 3749 if (listUninstalled) { 3750 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 3751 for (PackageSetting ps : mSettings.mPackages.values()) { 3752 PackageInfo pi; 3753 if (ps.pkg != null) { 3754 pi = generatePackageInfo(ps.pkg, flags, userId); 3755 } else { 3756 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3757 } 3758 if (pi != null) { 3759 list.add(pi); 3760 } 3761 } 3762 } else { 3763 list = new ArrayList<PackageInfo>(mPackages.size()); 3764 for (PackageParser.Package p : mPackages.values()) { 3765 PackageInfo pi = generatePackageInfo(p, flags, userId); 3766 if (pi != null) { 3767 list.add(pi); 3768 } 3769 } 3770 } 3771 3772 return new ParceledListSlice<PackageInfo>(list); 3773 } 3774 } 3775 3776 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 3777 String[] permissions, boolean[] tmp, int flags, int userId) { 3778 int numMatch = 0; 3779 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 3780 for (int i=0; i<permissions.length; i++) { 3781 if (gp.grantedPermissions.contains(permissions[i])) { 3782 tmp[i] = true; 3783 numMatch++; 3784 } else { 3785 tmp[i] = false; 3786 } 3787 } 3788 if (numMatch == 0) { 3789 return; 3790 } 3791 PackageInfo pi; 3792 if (ps.pkg != null) { 3793 pi = generatePackageInfo(ps.pkg, flags, userId); 3794 } else { 3795 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3796 } 3797 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 3798 if (numMatch == permissions.length) { 3799 pi.requestedPermissions = permissions; 3800 } else { 3801 pi.requestedPermissions = new String[numMatch]; 3802 numMatch = 0; 3803 for (int i=0; i<permissions.length; i++) { 3804 if (tmp[i]) { 3805 pi.requestedPermissions[numMatch] = permissions[i]; 3806 numMatch++; 3807 } 3808 } 3809 } 3810 } 3811 list.add(pi); 3812 } 3813 3814 @Override 3815 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 3816 String[] permissions, int flags, int userId) { 3817 if (!sUserManager.exists(userId)) return null; 3818 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3819 3820 // writer 3821 synchronized (mPackages) { 3822 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 3823 boolean[] tmpBools = new boolean[permissions.length]; 3824 if (listUninstalled) { 3825 for (PackageSetting ps : mSettings.mPackages.values()) { 3826 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 3827 } 3828 } else { 3829 for (PackageParser.Package pkg : mPackages.values()) { 3830 PackageSetting ps = (PackageSetting)pkg.mExtras; 3831 if (ps != null) { 3832 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 3833 userId); 3834 } 3835 } 3836 } 3837 3838 return new ParceledListSlice<PackageInfo>(list); 3839 } 3840 } 3841 3842 @Override 3843 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 3844 if (!sUserManager.exists(userId)) return null; 3845 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3846 3847 // writer 3848 synchronized (mPackages) { 3849 ArrayList<ApplicationInfo> list; 3850 if (listUninstalled) { 3851 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 3852 for (PackageSetting ps : mSettings.mPackages.values()) { 3853 ApplicationInfo ai; 3854 if (ps.pkg != null) { 3855 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3856 ps.readUserState(userId), userId); 3857 } else { 3858 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 3859 } 3860 if (ai != null) { 3861 list.add(ai); 3862 } 3863 } 3864 } else { 3865 list = new ArrayList<ApplicationInfo>(mPackages.size()); 3866 for (PackageParser.Package p : mPackages.values()) { 3867 if (p.mExtras != null) { 3868 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3869 ((PackageSetting)p.mExtras).readUserState(userId), userId); 3870 if (ai != null) { 3871 list.add(ai); 3872 } 3873 } 3874 } 3875 } 3876 3877 return new ParceledListSlice<ApplicationInfo>(list); 3878 } 3879 } 3880 3881 public List<ApplicationInfo> getPersistentApplications(int flags) { 3882 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 3883 3884 // reader 3885 synchronized (mPackages) { 3886 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 3887 final int userId = UserHandle.getCallingUserId(); 3888 while (i.hasNext()) { 3889 final PackageParser.Package p = i.next(); 3890 if (p.applicationInfo != null 3891 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 3892 && (!mSafeMode || isSystemApp(p))) { 3893 PackageSetting ps = mSettings.mPackages.get(p.packageName); 3894 if (ps != null) { 3895 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3896 ps.readUserState(userId), userId); 3897 if (ai != null) { 3898 finalList.add(ai); 3899 } 3900 } 3901 } 3902 } 3903 } 3904 3905 return finalList; 3906 } 3907 3908 @Override 3909 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 3910 if (!sUserManager.exists(userId)) return null; 3911 // reader 3912 synchronized (mPackages) { 3913 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 3914 PackageSetting ps = provider != null 3915 ? mSettings.mPackages.get(provider.owner.packageName) 3916 : null; 3917 return ps != null 3918 && mSettings.isEnabledLPr(provider.info, flags, userId) 3919 && (!mSafeMode || (provider.info.applicationInfo.flags 3920 &ApplicationInfo.FLAG_SYSTEM) != 0) 3921 ? PackageParser.generateProviderInfo(provider, flags, 3922 ps.readUserState(userId), userId) 3923 : null; 3924 } 3925 } 3926 3927 /** 3928 * @deprecated 3929 */ 3930 @Deprecated 3931 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 3932 // reader 3933 synchronized (mPackages) { 3934 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 3935 .entrySet().iterator(); 3936 final int userId = UserHandle.getCallingUserId(); 3937 while (i.hasNext()) { 3938 Map.Entry<String, PackageParser.Provider> entry = i.next(); 3939 PackageParser.Provider p = entry.getValue(); 3940 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3941 3942 if (ps != null && p.syncable 3943 && (!mSafeMode || (p.info.applicationInfo.flags 3944 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 3945 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 3946 ps.readUserState(userId), userId); 3947 if (info != null) { 3948 outNames.add(entry.getKey()); 3949 outInfo.add(info); 3950 } 3951 } 3952 } 3953 } 3954 } 3955 3956 @Override 3957 public List<ProviderInfo> queryContentProviders(String processName, 3958 int uid, int flags) { 3959 ArrayList<ProviderInfo> finalList = null; 3960 // reader 3961 synchronized (mPackages) { 3962 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 3963 final int userId = processName != null ? 3964 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 3965 while (i.hasNext()) { 3966 final PackageParser.Provider p = i.next(); 3967 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3968 if (ps != null && p.info.authority != null 3969 && (processName == null 3970 || (p.info.processName.equals(processName) 3971 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 3972 && mSettings.isEnabledLPr(p.info, flags, userId) 3973 && (!mSafeMode 3974 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 3975 if (finalList == null) { 3976 finalList = new ArrayList<ProviderInfo>(3); 3977 } 3978 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 3979 ps.readUserState(userId), userId); 3980 if (info != null) { 3981 finalList.add(info); 3982 } 3983 } 3984 } 3985 } 3986 3987 if (finalList != null) { 3988 Collections.sort(finalList, mProviderInitOrderSorter); 3989 } 3990 3991 return finalList; 3992 } 3993 3994 @Override 3995 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 3996 int flags) { 3997 // reader 3998 synchronized (mPackages) { 3999 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4000 return PackageParser.generateInstrumentationInfo(i, flags); 4001 } 4002 } 4003 4004 @Override 4005 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4006 int flags) { 4007 ArrayList<InstrumentationInfo> finalList = 4008 new ArrayList<InstrumentationInfo>(); 4009 4010 // reader 4011 synchronized (mPackages) { 4012 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4013 while (i.hasNext()) { 4014 final PackageParser.Instrumentation p = i.next(); 4015 if (targetPackage == null 4016 || targetPackage.equals(p.info.targetPackage)) { 4017 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4018 flags); 4019 if (ii != null) { 4020 finalList.add(ii); 4021 } 4022 } 4023 } 4024 } 4025 4026 return finalList; 4027 } 4028 4029 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4030 HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4031 if (overlays == null) { 4032 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4033 return; 4034 } 4035 for (PackageParser.Package opkg : overlays.values()) { 4036 // Not much to do if idmap fails: we already logged the error 4037 // and we certainly don't want to abort installation of pkg simply 4038 // because an overlay didn't fit properly. For these reasons, 4039 // ignore the return value of createIdmapForPackagePairLI. 4040 createIdmapForPackagePairLI(pkg, opkg); 4041 } 4042 } 4043 4044 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4045 PackageParser.Package opkg) { 4046 if (!opkg.mTrustedOverlay) { 4047 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4048 opkg.baseCodePath + ": overlay not trusted"); 4049 return false; 4050 } 4051 HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4052 if (overlaySet == null) { 4053 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4054 opkg.baseCodePath + " but target package has no known overlays"); 4055 return false; 4056 } 4057 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4058 // TODO: generate idmap for split APKs 4059 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4060 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4061 + opkg.baseCodePath); 4062 return false; 4063 } 4064 PackageParser.Package[] overlayArray = 4065 overlaySet.values().toArray(new PackageParser.Package[0]); 4066 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4067 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4068 return p1.mOverlayPriority - p2.mOverlayPriority; 4069 } 4070 }; 4071 Arrays.sort(overlayArray, cmp); 4072 4073 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4074 int i = 0; 4075 for (PackageParser.Package p : overlayArray) { 4076 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4077 } 4078 return true; 4079 } 4080 4081 private void scanDirLI(File dir, int flags, int scanMode, long currentTime) { 4082 final File[] files = dir.listFiles(); 4083 if (ArrayUtils.isEmpty(files)) { 4084 Log.d(TAG, "No files in app dir " + dir); 4085 return; 4086 } 4087 4088 if (DEBUG_PACKAGE_SCANNING) { 4089 Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode 4090 + " flags=0x" + Integer.toHexString(flags)); 4091 } 4092 4093 for (File file : files) { 4094 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 4095 && !PackageInstallerService.isStageName(file.getName()); 4096 if (!isPackage) { 4097 // Ignore entries which are not packages 4098 continue; 4099 } 4100 try { 4101 scanPackageLI(file, flags | PackageParser.PARSE_MUST_BE_APK, 4102 scanMode, currentTime, null); 4103 } catch (PackageManagerException e) { 4104 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4105 4106 // Delete invalid userdata apps 4107 if ((flags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4108 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4109 Slog.w(TAG, "Deleting invalid package at " + file); 4110 if (file.isDirectory()) { 4111 FileUtils.deleteContents(file); 4112 } 4113 file.delete(); 4114 } 4115 } 4116 } 4117 } 4118 4119 private static File getSettingsProblemFile() { 4120 File dataDir = Environment.getDataDirectory(); 4121 File systemDir = new File(dataDir, "system"); 4122 File fname = new File(systemDir, "uiderrors.txt"); 4123 return fname; 4124 } 4125 4126 static void reportSettingsProblem(int priority, String msg) { 4127 try { 4128 File fname = getSettingsProblemFile(); 4129 FileOutputStream out = new FileOutputStream(fname, true); 4130 PrintWriter pw = new FastPrintWriter(out); 4131 SimpleDateFormat formatter = new SimpleDateFormat(); 4132 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4133 pw.println(dateString + ": " + msg); 4134 pw.close(); 4135 FileUtils.setPermissions( 4136 fname.toString(), 4137 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4138 -1, -1); 4139 } catch (java.io.IOException e) { 4140 } 4141 Slog.println(priority, TAG, msg); 4142 } 4143 4144 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 4145 PackageParser.Package pkg, File srcFile, int parseFlags) 4146 throws PackageManagerException { 4147 if (ps != null 4148 && ps.codePath.equals(srcFile) 4149 && ps.timeStamp == srcFile.lastModified() 4150 && !isCompatSignatureUpdateNeeded(pkg)) { 4151 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4152 if (ps.signatures.mSignatures != null 4153 && ps.signatures.mSignatures.length != 0 4154 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4155 // Optimization: reuse the existing cached certificates 4156 // if the package appears to be unchanged. 4157 pkg.mSignatures = ps.signatures.mSignatures; 4158 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4159 synchronized (mPackages) { 4160 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 4161 } 4162 return; 4163 } 4164 4165 Slog.w(TAG, "PackageSetting for " + ps.name 4166 + " is missing signatures. Collecting certs again to recover them."); 4167 } else { 4168 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4169 } 4170 4171 try { 4172 pp.collectCertificates(pkg, parseFlags); 4173 pp.collectManifestDigest(pkg); 4174 } catch (PackageParserException e) { 4175 throw new PackageManagerException(e.error, "Failed to collect certificates for " 4176 + pkg.packageName + ": " + e.getMessage()); 4177 } 4178 } 4179 4180 /* 4181 * Scan a package and return the newly parsed package. 4182 * Returns null in case of errors and the error code is stored in mLastScanError 4183 */ 4184 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanMode, 4185 long currentTime, UserHandle user) throws PackageManagerException { 4186 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4187 parseFlags |= mDefParseFlags; 4188 PackageParser pp = new PackageParser(); 4189 pp.setSeparateProcesses(mSeparateProcesses); 4190 pp.setOnlyCoreApps(mOnlyCore); 4191 pp.setDisplayMetrics(mMetrics); 4192 4193 if ((scanMode & SCAN_TRUSTED_OVERLAY) != 0) { 4194 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4195 } 4196 4197 final PackageParser.Package pkg; 4198 try { 4199 pkg = pp.parsePackage(scanFile, parseFlags); 4200 } catch (PackageParserException e) { 4201 throw new PackageManagerException(e.error, 4202 "Failed to scan " + scanFile + ": " + e.getMessage()); 4203 } 4204 4205 PackageSetting ps = null; 4206 PackageSetting updatedPkg; 4207 // reader 4208 synchronized (mPackages) { 4209 // Look to see if we already know about this package. 4210 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4211 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4212 // This package has been renamed to its original name. Let's 4213 // use that. 4214 ps = mSettings.peekPackageLPr(oldName); 4215 } 4216 // If there was no original package, see one for the real package name. 4217 if (ps == null) { 4218 ps = mSettings.peekPackageLPr(pkg.packageName); 4219 } 4220 // Check to see if this package could be hiding/updating a system 4221 // package. Must look for it either under the original or real 4222 // package name depending on our state. 4223 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4224 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4225 } 4226 boolean updatedPkgBetter = false; 4227 // First check if this is a system package that may involve an update 4228 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4229 if (ps != null && !ps.codePath.equals(scanFile)) { 4230 // The path has changed from what was last scanned... check the 4231 // version of the new path against what we have stored to determine 4232 // what to do. 4233 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4234 if (pkg.mVersionCode < ps.versionCode) { 4235 // The system package has been updated and the code path does not match 4236 // Ignore entry. Skip it. 4237 Log.i(TAG, "Package " + ps.name + " at " + scanFile 4238 + " ignored: updated version " + ps.versionCode 4239 + " better than this " + pkg.mVersionCode); 4240 if (!updatedPkg.codePath.equals(scanFile)) { 4241 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4242 + ps.name + " changing from " + updatedPkg.codePathString 4243 + " to " + scanFile); 4244 updatedPkg.codePath = scanFile; 4245 updatedPkg.codePathString = scanFile.toString(); 4246 // This is the point at which we know that the system-disk APK 4247 // for this package has moved during a reboot (e.g. due to an OTA), 4248 // so we need to reevaluate it for privilege policy. 4249 if (locationIsPrivileged(scanFile)) { 4250 updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED; 4251 } 4252 } 4253 updatedPkg.pkg = pkg; 4254 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 4255 } else { 4256 // The current app on the system partition is better than 4257 // what we have updated to on the data partition; switch 4258 // back to the system partition version. 4259 // At this point, its safely assumed that package installation for 4260 // apps in system partition will go through. If not there won't be a working 4261 // version of the app 4262 // writer 4263 synchronized (mPackages) { 4264 // Just remove the loaded entries from package lists. 4265 mPackages.remove(ps.name); 4266 } 4267 Slog.w(TAG, "Package " + ps.name + " at " + scanFile 4268 + "reverting from " + ps.codePathString 4269 + ": new version " + pkg.mVersionCode 4270 + " better than installed " + ps.versionCode); 4271 4272 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4273 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4274 getAppDexInstructionSets(ps), isMultiArch(ps)); 4275 synchronized (mInstallLock) { 4276 args.cleanUpResourcesLI(); 4277 } 4278 synchronized (mPackages) { 4279 mSettings.enableSystemPackageLPw(ps.name); 4280 } 4281 updatedPkgBetter = true; 4282 } 4283 } 4284 } 4285 4286 if (updatedPkg != null) { 4287 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4288 // initially 4289 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4290 4291 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4292 // flag set initially 4293 if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) { 4294 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4295 } 4296 } 4297 4298 // Verify certificates against what was last scanned 4299 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 4300 4301 /* 4302 * A new system app appeared, but we already had a non-system one of the 4303 * same name installed earlier. 4304 */ 4305 boolean shouldHideSystemApp = false; 4306 if (updatedPkg == null && ps != null 4307 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4308 /* 4309 * Check to make sure the signatures match first. If they don't, 4310 * wipe the installed application and its data. 4311 */ 4312 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4313 != PackageManager.SIGNATURE_MATCH) { 4314 if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!"); 4315 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4316 ps = null; 4317 } else { 4318 /* 4319 * If the newly-added system app is an older version than the 4320 * already installed version, hide it. It will be scanned later 4321 * and re-added like an update. 4322 */ 4323 if (pkg.mVersionCode < ps.versionCode) { 4324 shouldHideSystemApp = true; 4325 } else { 4326 /* 4327 * The newly found system app is a newer version that the 4328 * one previously installed. Simply remove the 4329 * already-installed application and replace it with our own 4330 * while keeping the application data. 4331 */ 4332 Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from " 4333 + ps.codePathString + ": new version " + pkg.mVersionCode 4334 + " better than installed " + ps.versionCode); 4335 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4336 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4337 getAppDexInstructionSets(ps), isMultiArch(ps)); 4338 synchronized (mInstallLock) { 4339 args.cleanUpResourcesLI(); 4340 } 4341 } 4342 } 4343 } 4344 4345 // The apk is forward locked (not public) if its code and resources 4346 // are kept in different files. (except for app in either system or 4347 // vendor path). 4348 // TODO grab this value from PackageSettings 4349 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4350 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4351 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 4352 } 4353 } 4354 4355 // TODO: extend to support forward-locked splits 4356 String resourcePath = null; 4357 String baseResourcePath = null; 4358 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 4359 if (ps != null && ps.resourcePathString != null) { 4360 resourcePath = ps.resourcePathString; 4361 baseResourcePath = ps.resourcePathString; 4362 } else { 4363 // Should not happen at all. Just log an error. 4364 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 4365 } 4366 } else { 4367 resourcePath = pkg.codePath; 4368 baseResourcePath = pkg.baseCodePath; 4369 } 4370 4371 // Set application objects path explicitly. 4372 pkg.applicationInfo.setCodePath(pkg.codePath); 4373 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 4374 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 4375 pkg.applicationInfo.setResourcePath(resourcePath); 4376 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 4377 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 4378 4379 // Note that we invoke the following method only if we are about to unpack an application 4380 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode 4381 | SCAN_UPDATE_SIGNATURE, currentTime, user); 4382 4383 /* 4384 * If the system app should be overridden by a previously installed 4385 * data, hide the system app now and let the /data/app scan pick it up 4386 * again. 4387 */ 4388 if (shouldHideSystemApp) { 4389 synchronized (mPackages) { 4390 /* 4391 * We have to grant systems permissions before we hide, because 4392 * grantPermissions will assume the package update is trying to 4393 * expand its permissions. 4394 */ 4395 grantPermissionsLPw(pkg, true); 4396 mSettings.disableSystemPackageLPw(pkg.packageName); 4397 } 4398 } 4399 4400 return scannedPkg; 4401 } 4402 4403 private static String fixProcessName(String defProcessName, 4404 String processName, int uid) { 4405 if (processName == null) { 4406 return defProcessName; 4407 } 4408 return processName; 4409 } 4410 4411 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 4412 throws PackageManagerException { 4413 if (pkgSetting.signatures.mSignatures != null) { 4414 // Already existing package. Make sure signatures match 4415 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 4416 == PackageManager.SIGNATURE_MATCH; 4417 if (!match) { 4418 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 4419 == PackageManager.SIGNATURE_MATCH; 4420 } 4421 if (!match) { 4422 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 4423 + pkg.packageName + " signatures do not match the " 4424 + "previously installed version; ignoring!"); 4425 } 4426 } 4427 4428 // Check for shared user signatures 4429 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 4430 // Already existing package. Make sure signatures match 4431 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4432 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 4433 if (!match) { 4434 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 4435 == PackageManager.SIGNATURE_MATCH; 4436 } 4437 if (!match) { 4438 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 4439 "Package " + pkg.packageName 4440 + " has no signatures that match those in shared user " 4441 + pkgSetting.sharedUser.name + "; ignoring!"); 4442 } 4443 } 4444 } 4445 4446 /** 4447 * Enforces that only the system UID or root's UID can call a method exposed 4448 * via Binder. 4449 * 4450 * @param message used as message if SecurityException is thrown 4451 * @throws SecurityException if the caller is not system or root 4452 */ 4453 private static final void enforceSystemOrRoot(String message) { 4454 final int uid = Binder.getCallingUid(); 4455 if (uid != Process.SYSTEM_UID && uid != 0) { 4456 throw new SecurityException(message); 4457 } 4458 } 4459 4460 @Override 4461 public void performBootDexOpt() { 4462 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4463 4464 final HashSet<PackageParser.Package> pkgs; 4465 synchronized (mPackages) { 4466 pkgs = mDeferredDexOpt; 4467 mDeferredDexOpt = null; 4468 } 4469 4470 if (pkgs != null) { 4471 // Filter out packages that aren't recently used. 4472 // 4473 // The exception is first boot of a non-eng device, which 4474 // should do a full dexopt. 4475 boolean eng = "eng".equals(SystemProperties.get("ro.build.type")); 4476 if (eng || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 4477 // TODO: add a property to control this? 4478 long dexOptLRUThresholdInMinutes; 4479 if (eng) { 4480 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 4481 } else { 4482 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 4483 } 4484 long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 4485 4486 int total = pkgs.size(); 4487 int skipped = 0; 4488 long now = System.currentTimeMillis(); 4489 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 4490 PackageParser.Package pkg = i.next(); 4491 long then = pkg.mLastPackageUsageTimeInMills; 4492 if (then + dexOptLRUThresholdInMills < now) { 4493 if (DEBUG_DEXOPT) { 4494 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 4495 ((then == 0) ? "never" : new Date(then))); 4496 } 4497 i.remove(); 4498 skipped++; 4499 } 4500 } 4501 if (DEBUG_DEXOPT) { 4502 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 4503 } 4504 } 4505 4506 int i = 0; 4507 for (PackageParser.Package pkg : pkgs) { 4508 i++; 4509 if (DEBUG_DEXOPT) { 4510 Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size() 4511 + ": " + pkg.packageName); 4512 } 4513 if (!isFirstBoot()) { 4514 try { 4515 ActivityManagerNative.getDefault().showBootMessage( 4516 mContext.getResources().getString( 4517 R.string.android_upgrading_apk, 4518 i, pkgs.size()), true); 4519 } catch (RemoteException e) { 4520 } 4521 } 4522 PackageParser.Package p = pkg; 4523 synchronized (mInstallLock) { 4524 performDexOptLI(p, null /* instruction sets */, false /* force dex */, false /* defer */, 4525 true /* include dependencies */); 4526 } 4527 } 4528 } 4529 } 4530 4531 @Override 4532 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 4533 return performDexOpt(packageName, instructionSet, true); 4534 } 4535 4536 private static String getPrimaryInstructionSet(ApplicationInfo info) { 4537 if (info.primaryCpuAbi == null) { 4538 return getPreferredInstructionSet(); 4539 } 4540 4541 return VMRuntime.getInstructionSet(info.primaryCpuAbi); 4542 } 4543 4544 public boolean performDexOpt(String packageName, String instructionSet, boolean updateUsage) { 4545 PackageParser.Package p; 4546 final String targetInstructionSet; 4547 synchronized (mPackages) { 4548 p = mPackages.get(packageName); 4549 if (p == null) { 4550 return false; 4551 } 4552 if (updateUsage) { 4553 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 4554 } 4555 mPackageUsage.write(false); 4556 4557 targetInstructionSet = instructionSet != null ? instructionSet : 4558 getPrimaryInstructionSet(p.applicationInfo); 4559 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 4560 return false; 4561 } 4562 } 4563 4564 synchronized (mInstallLock) { 4565 final String[] instructionSets = new String[] { targetInstructionSet }; 4566 return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */, 4567 true /* include dependencies */) == DEX_OPT_PERFORMED; 4568 } 4569 } 4570 4571 public HashSet<String> getPackagesThatNeedDexOpt() { 4572 HashSet<String> pkgs = null; 4573 synchronized (mPackages) { 4574 for (PackageParser.Package p : mPackages.values()) { 4575 if (DEBUG_DEXOPT) { 4576 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 4577 } 4578 if (!p.mDexOptPerformed.isEmpty()) { 4579 continue; 4580 } 4581 if (pkgs == null) { 4582 pkgs = new HashSet<String>(); 4583 } 4584 pkgs.add(p.packageName); 4585 } 4586 } 4587 return pkgs; 4588 } 4589 4590 public void shutdown() { 4591 mPackageUsage.write(true); 4592 } 4593 4594 private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets, 4595 boolean forceDex, boolean defer, HashSet<String> done) { 4596 for (int i=0; i<libs.size(); i++) { 4597 PackageParser.Package libPkg; 4598 String libName; 4599 synchronized (mPackages) { 4600 libName = libs.get(i); 4601 SharedLibraryEntry lib = mSharedLibraries.get(libName); 4602 if (lib != null && lib.apk != null) { 4603 libPkg = mPackages.get(lib.apk); 4604 } else { 4605 libPkg = null; 4606 } 4607 } 4608 if (libPkg != null && !done.contains(libName)) { 4609 performDexOptLI(libPkg, instructionSets, forceDex, defer, done); 4610 } 4611 } 4612 } 4613 4614 static final int DEX_OPT_SKIPPED = 0; 4615 static final int DEX_OPT_PERFORMED = 1; 4616 static final int DEX_OPT_DEFERRED = 2; 4617 static final int DEX_OPT_FAILED = -1; 4618 4619 private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets, 4620 boolean forceDex, boolean defer, HashSet<String> done) { 4621 final String[] instructionSets = targetInstructionSets != null ? 4622 targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo); 4623 4624 if (done != null) { 4625 done.add(pkg.packageName); 4626 if (pkg.usesLibraries != null) { 4627 performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done); 4628 } 4629 if (pkg.usesOptionalLibraries != null) { 4630 performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done); 4631 } 4632 } 4633 4634 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) { 4635 return DEX_OPT_SKIPPED; 4636 } 4637 4638 final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly(); 4639 boolean performedDexOpt = false; 4640 // There are three basic cases here: 4641 // 1.) we need to dexopt, either because we are forced or it is needed 4642 // 2.) we are defering a needed dexopt 4643 // 3.) we are skipping an unneeded dexopt 4644 final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 4645 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 4646 if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) { 4647 continue; 4648 } 4649 4650 for (String path : paths) { 4651 try { 4652 // This will return DEXOPT_NEEDED if we either cannot find any odex file for this 4653 // patckage or the one we find does not match the image checksum (i.e. it was 4654 // compiled against an old image). It will return PATCHOAT_NEEDED if we can find a 4655 // odex file and it matches the checksum of the image but not its base address, 4656 // meaning we need to move it. 4657 final byte isDexOptNeeded = DexFile.isDexOptNeededInternal(path, 4658 pkg.packageName, dexCodeInstructionSet, defer); 4659 if (forceDex || (!defer && isDexOptNeeded == DexFile.DEXOPT_NEEDED)) { 4660 Log.i(TAG, "Running dexopt on: " + path + " pkg=" 4661 + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet); 4662 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4663 final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg), 4664 pkg.packageName, dexCodeInstructionSet); 4665 4666 if (ret < 0) { 4667 // Don't bother running dexopt again if we failed, it will probably 4668 // just result in an error again. Also, don't bother dexopting for other 4669 // paths & ISAs. 4670 return DEX_OPT_FAILED; 4671 } 4672 4673 performedDexOpt = true; 4674 } else if (!defer && isDexOptNeeded == DexFile.PATCHOAT_NEEDED) { 4675 Log.i(TAG, "Running patchoat on: " + pkg.applicationInfo.packageName); 4676 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4677 final int ret = mInstaller.patchoat(path, sharedGid, !isForwardLocked(pkg), 4678 pkg.packageName, dexCodeInstructionSet); 4679 4680 if (ret < 0) { 4681 // Don't bother running patchoat again if we failed, it will probably 4682 // just result in an error again. Also, don't bother dexopting for other 4683 // paths & ISAs. 4684 return DEX_OPT_FAILED; 4685 } 4686 4687 performedDexOpt = true; 4688 } 4689 4690 // We're deciding to defer a needed dexopt. Don't bother dexopting for other 4691 // paths and instruction sets. We'll deal with them all together when we process 4692 // our list of deferred dexopts. 4693 if (defer && isDexOptNeeded != DexFile.UP_TO_DATE) { 4694 if (mDeferredDexOpt == null) { 4695 mDeferredDexOpt = new HashSet<PackageParser.Package>(); 4696 } 4697 mDeferredDexOpt.add(pkg); 4698 return DEX_OPT_DEFERRED; 4699 } 4700 } catch (FileNotFoundException e) { 4701 Slog.w(TAG, "Apk not found for dexopt: " + path); 4702 return DEX_OPT_FAILED; 4703 } catch (IOException e) { 4704 Slog.w(TAG, "IOException reading apk: " + path, e); 4705 return DEX_OPT_FAILED; 4706 } catch (StaleDexCacheError e) { 4707 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e); 4708 return DEX_OPT_FAILED; 4709 } catch (Exception e) { 4710 Slog.w(TAG, "Exception when doing dexopt : ", e); 4711 return DEX_OPT_FAILED; 4712 } 4713 } 4714 4715 // At this point we haven't failed dexopt and we haven't deferred dexopt. We must 4716 // either have either succeeded dexopt, or have had isDexOptNeededInternal tell us 4717 // it isn't required. We therefore mark that this package doesn't need dexopt unless 4718 // it's forced. performedDexOpt will tell us whether we performed dex-opt or skipped 4719 // it. 4720 pkg.mDexOptPerformed.add(dexCodeInstructionSet); 4721 } 4722 4723 // If we've gotten here, we're sure that no error occurred and that we haven't 4724 // deferred dex-opt. We've either dex-opted one more paths or instruction sets or 4725 // we've skipped all of them because they are up to date. In both cases this 4726 // package doesn't need dexopt any longer. 4727 return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED; 4728 } 4729 4730 private static String[] getAppDexInstructionSets(ApplicationInfo info) { 4731 if (info.primaryCpuAbi != null) { 4732 if (info.secondaryCpuAbi != null) { 4733 return new String[] { 4734 VMRuntime.getInstructionSet(info.primaryCpuAbi), 4735 VMRuntime.getInstructionSet(info.secondaryCpuAbi) }; 4736 } else { 4737 return new String[] { 4738 VMRuntime.getInstructionSet(info.primaryCpuAbi) }; 4739 } 4740 } 4741 4742 return new String[] { getPreferredInstructionSet() }; 4743 } 4744 4745 private static String[] getAppDexInstructionSets(PackageSetting ps) { 4746 if (ps.primaryCpuAbiString != null) { 4747 if (ps.secondaryCpuAbiString != null) { 4748 return new String[] { 4749 VMRuntime.getInstructionSet(ps.primaryCpuAbiString), 4750 VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) }; 4751 } else { 4752 return new String[] { 4753 VMRuntime.getInstructionSet(ps.primaryCpuAbiString) }; 4754 } 4755 } 4756 4757 return new String[] { getPreferredInstructionSet() }; 4758 } 4759 4760 private static String getPreferredInstructionSet() { 4761 if (sPreferredInstructionSet == null) { 4762 sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]); 4763 } 4764 4765 return sPreferredInstructionSet; 4766 } 4767 4768 private static List<String> getAllInstructionSets() { 4769 final String[] allAbis = Build.SUPPORTED_ABIS; 4770 final List<String> allInstructionSets = new ArrayList<String>(allAbis.length); 4771 4772 for (String abi : allAbis) { 4773 final String instructionSet = VMRuntime.getInstructionSet(abi); 4774 if (!allInstructionSets.contains(instructionSet)) { 4775 allInstructionSets.add(instructionSet); 4776 } 4777 } 4778 4779 return allInstructionSets; 4780 } 4781 4782 /** 4783 * Returns the instruction set that should be used to compile dex code. In the presence of 4784 * a native bridge this might be different than the one shared libraries use. 4785 */ 4786 private static String getDexCodeInstructionSet(String sharedLibraryIsa) { 4787 String dexCodeIsa = SystemProperties.get("ro.dalvik.vm.isa." + sharedLibraryIsa); 4788 return (dexCodeIsa.isEmpty() ? sharedLibraryIsa : dexCodeIsa); 4789 } 4790 4791 private static String[] getDexCodeInstructionSets(String[] instructionSets) { 4792 HashSet<String> dexCodeInstructionSets = new HashSet<String>(instructionSets.length); 4793 for (String instructionSet : instructionSets) { 4794 dexCodeInstructionSets.add(getDexCodeInstructionSet(instructionSet)); 4795 } 4796 return dexCodeInstructionSets.toArray(new String[dexCodeInstructionSets.size()]); 4797 } 4798 4799 @Override 4800 public void forceDexOpt(String packageName) { 4801 enforceSystemOrRoot("forceDexOpt"); 4802 4803 PackageParser.Package pkg; 4804 synchronized (mPackages) { 4805 pkg = mPackages.get(packageName); 4806 if (pkg == null) { 4807 throw new IllegalArgumentException("Missing package: " + packageName); 4808 } 4809 } 4810 4811 synchronized (mInstallLock) { 4812 final String[] instructionSets = new String[] { 4813 getPrimaryInstructionSet(pkg.applicationInfo) }; 4814 final int res = performDexOptLI(pkg, instructionSets, true, false, true); 4815 if (res != DEX_OPT_PERFORMED) { 4816 throw new IllegalStateException("Failed to dexopt: " + res); 4817 } 4818 } 4819 } 4820 4821 private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets, 4822 boolean forceDex, boolean defer, boolean inclDependencies) { 4823 HashSet<String> done; 4824 if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) { 4825 done = new HashSet<String>(); 4826 done.add(pkg.packageName); 4827 } else { 4828 done = null; 4829 } 4830 return performDexOptLI(pkg, instructionSets, forceDex, defer, done); 4831 } 4832 4833 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 4834 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 4835 Slog.w(TAG, "Unable to update from " + oldPkg.name 4836 + " to " + newPkg.packageName 4837 + ": old package not in system partition"); 4838 return false; 4839 } else if (mPackages.get(oldPkg.name) != null) { 4840 Slog.w(TAG, "Unable to update from " + oldPkg.name 4841 + " to " + newPkg.packageName 4842 + ": old package still exists"); 4843 return false; 4844 } 4845 return true; 4846 } 4847 4848 File getDataPathForUser(int userId) { 4849 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId); 4850 } 4851 4852 private File getDataPathForPackage(String packageName, int userId) { 4853 /* 4854 * Until we fully support multiple users, return the directory we 4855 * previously would have. The PackageManagerTests will need to be 4856 * revised when this is changed back.. 4857 */ 4858 if (userId == 0) { 4859 return new File(mAppDataDir, packageName); 4860 } else { 4861 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 4862 + File.separator + packageName); 4863 } 4864 } 4865 4866 private int createDataDirsLI(String packageName, int uid, String seinfo) { 4867 int[] users = sUserManager.getUserIds(); 4868 int res = mInstaller.install(packageName, uid, uid, seinfo); 4869 if (res < 0) { 4870 return res; 4871 } 4872 for (int user : users) { 4873 if (user != 0) { 4874 res = mInstaller.createUserData(packageName, 4875 UserHandle.getUid(user, uid), user, seinfo); 4876 if (res < 0) { 4877 return res; 4878 } 4879 } 4880 } 4881 return res; 4882 } 4883 4884 private int removeDataDirsLI(String packageName) { 4885 int[] users = sUserManager.getUserIds(); 4886 int res = 0; 4887 for (int user : users) { 4888 int resInner = mInstaller.remove(packageName, user); 4889 if (resInner < 0) { 4890 res = resInner; 4891 } 4892 } 4893 4894 return res; 4895 } 4896 4897 private int deleteCodeCacheDirsLI(String packageName) { 4898 int[] users = sUserManager.getUserIds(); 4899 int res = 0; 4900 for (int user : users) { 4901 int resInner = mInstaller.deleteCodeCacheFiles(packageName, user); 4902 if (resInner < 0) { 4903 res = resInner; 4904 } 4905 } 4906 return res; 4907 } 4908 4909 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 4910 PackageParser.Package changingLib) { 4911 if (file.path != null) { 4912 usesLibraryFiles.add(file.path); 4913 return; 4914 } 4915 PackageParser.Package p = mPackages.get(file.apk); 4916 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 4917 // If we are doing this while in the middle of updating a library apk, 4918 // then we need to make sure to use that new apk for determining the 4919 // dependencies here. (We haven't yet finished committing the new apk 4920 // to the package manager state.) 4921 if (p == null || p.packageName.equals(changingLib.packageName)) { 4922 p = changingLib; 4923 } 4924 } 4925 if (p != null) { 4926 usesLibraryFiles.addAll(p.getAllCodePaths()); 4927 } 4928 } 4929 4930 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 4931 PackageParser.Package changingLib) throws PackageManagerException { 4932 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 4933 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 4934 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 4935 for (int i=0; i<N; i++) { 4936 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 4937 if (file == null) { 4938 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 4939 "Package " + pkg.packageName + " requires unavailable shared library " 4940 + pkg.usesLibraries.get(i) + "; failing!"); 4941 } 4942 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4943 } 4944 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 4945 for (int i=0; i<N; i++) { 4946 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 4947 if (file == null) { 4948 Slog.w(TAG, "Package " + pkg.packageName 4949 + " desires unavailable shared library " 4950 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 4951 } else { 4952 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4953 } 4954 } 4955 N = usesLibraryFiles.size(); 4956 if (N > 0) { 4957 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 4958 } else { 4959 pkg.usesLibraryFiles = null; 4960 } 4961 } 4962 } 4963 4964 private static boolean hasString(List<String> list, List<String> which) { 4965 if (list == null) { 4966 return false; 4967 } 4968 for (int i=list.size()-1; i>=0; i--) { 4969 for (int j=which.size()-1; j>=0; j--) { 4970 if (which.get(j).equals(list.get(i))) { 4971 return true; 4972 } 4973 } 4974 } 4975 return false; 4976 } 4977 4978 private void updateAllSharedLibrariesLPw() { 4979 for (PackageParser.Package pkg : mPackages.values()) { 4980 try { 4981 updateSharedLibrariesLPw(pkg, null); 4982 } catch (PackageManagerException e) { 4983 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 4984 } 4985 } 4986 } 4987 4988 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 4989 PackageParser.Package changingPkg) { 4990 ArrayList<PackageParser.Package> res = null; 4991 for (PackageParser.Package pkg : mPackages.values()) { 4992 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 4993 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 4994 if (res == null) { 4995 res = new ArrayList<PackageParser.Package>(); 4996 } 4997 res.add(pkg); 4998 try { 4999 updateSharedLibrariesLPw(pkg, changingPkg); 5000 } catch (PackageManagerException e) { 5001 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5002 } 5003 } 5004 } 5005 return res; 5006 } 5007 5008 /** 5009 * Derive the value of the {@code cpuAbiOverride} based on the provided 5010 * value and an optional stored value from the package settings. 5011 */ 5012 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5013 String cpuAbiOverride = null; 5014 5015 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5016 cpuAbiOverride = null; 5017 } else if (abiOverride != null) { 5018 cpuAbiOverride = abiOverride; 5019 } else if (settings != null) { 5020 cpuAbiOverride = settings.cpuAbiOverrideString; 5021 } 5022 5023 return cpuAbiOverride; 5024 } 5025 5026 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5027 int scanMode, long currentTime, UserHandle user) 5028 throws PackageManagerException { 5029 final File scanFile = new File(pkg.codePath); 5030 if (pkg.applicationInfo.getCodePath() == null || 5031 pkg.applicationInfo.getResourcePath() == null) { 5032 // Bail out. The resource and code paths haven't been set. 5033 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5034 "Code and resource paths haven't been set correctly"); 5035 } 5036 5037 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5038 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5039 } 5040 5041 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5042 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED; 5043 } 5044 5045 if (mCustomResolverComponentName != null && 5046 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5047 setUpCustomResolverActivity(pkg); 5048 } 5049 5050 if (pkg.packageName.equals("android")) { 5051 synchronized (mPackages) { 5052 if (mAndroidApplication != null) { 5053 Slog.w(TAG, "*************************************************"); 5054 Slog.w(TAG, "Core android package being redefined. Skipping."); 5055 Slog.w(TAG, " file=" + scanFile); 5056 Slog.w(TAG, "*************************************************"); 5057 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5058 "Core android package being redefined. Skipping."); 5059 } 5060 5061 // Set up information for our fall-back user intent resolution activity. 5062 mPlatformPackage = pkg; 5063 pkg.mVersionCode = mSdkVersion; 5064 mAndroidApplication = pkg.applicationInfo; 5065 5066 if (!mResolverReplaced) { 5067 mResolveActivity.applicationInfo = mAndroidApplication; 5068 mResolveActivity.name = ResolverActivity.class.getName(); 5069 mResolveActivity.packageName = mAndroidApplication.packageName; 5070 mResolveActivity.processName = "system:ui"; 5071 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5072 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5073 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5074 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5075 mResolveActivity.exported = true; 5076 mResolveActivity.enabled = true; 5077 mResolveInfo.activityInfo = mResolveActivity; 5078 mResolveInfo.priority = 0; 5079 mResolveInfo.preferredOrder = 0; 5080 mResolveInfo.match = 0; 5081 mResolveComponentName = new ComponentName( 5082 mAndroidApplication.packageName, mResolveActivity.name); 5083 } 5084 } 5085 } 5086 5087 if (DEBUG_PACKAGE_SCANNING) { 5088 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5089 Log.d(TAG, "Scanning package " + pkg.packageName); 5090 } 5091 5092 if (mPackages.containsKey(pkg.packageName) 5093 || mSharedLibraries.containsKey(pkg.packageName)) { 5094 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5095 "Application package " + pkg.packageName 5096 + " already installed. Skipping duplicate."); 5097 } 5098 5099 // Initialize package source and resource directories 5100 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5101 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5102 5103 SharedUserSetting suid = null; 5104 PackageSetting pkgSetting = null; 5105 5106 if (!isSystemApp(pkg)) { 5107 // Only system apps can use these features. 5108 pkg.mOriginalPackages = null; 5109 pkg.mRealPackage = null; 5110 pkg.mAdoptPermissions = null; 5111 } 5112 5113 // writer 5114 synchronized (mPackages) { 5115 if (pkg.mSharedUserId != null) { 5116 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true); 5117 if (suid == null) { 5118 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5119 "Creating application package " + pkg.packageName 5120 + " for shared user failed"); 5121 } 5122 if (DEBUG_PACKAGE_SCANNING) { 5123 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5124 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5125 + "): packages=" + suid.packages); 5126 } 5127 } 5128 5129 // Check if we are renaming from an original package name. 5130 PackageSetting origPackage = null; 5131 String realName = null; 5132 if (pkg.mOriginalPackages != null) { 5133 // This package may need to be renamed to a previously 5134 // installed name. Let's check on that... 5135 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5136 if (pkg.mOriginalPackages.contains(renamed)) { 5137 // This package had originally been installed as the 5138 // original name, and we have already taken care of 5139 // transitioning to the new one. Just update the new 5140 // one to continue using the old name. 5141 realName = pkg.mRealPackage; 5142 if (!pkg.packageName.equals(renamed)) { 5143 // Callers into this function may have already taken 5144 // care of renaming the package; only do it here if 5145 // it is not already done. 5146 pkg.setPackageName(renamed); 5147 } 5148 5149 } else { 5150 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5151 if ((origPackage = mSettings.peekPackageLPr( 5152 pkg.mOriginalPackages.get(i))) != null) { 5153 // We do have the package already installed under its 5154 // original name... should we use it? 5155 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5156 // New package is not compatible with original. 5157 origPackage = null; 5158 continue; 5159 } else if (origPackage.sharedUser != null) { 5160 // Make sure uid is compatible between packages. 5161 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5162 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5163 + " to " + pkg.packageName + ": old uid " 5164 + origPackage.sharedUser.name 5165 + " differs from " + pkg.mSharedUserId); 5166 origPackage = null; 5167 continue; 5168 } 5169 } else { 5170 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5171 + pkg.packageName + " to old name " + origPackage.name); 5172 } 5173 break; 5174 } 5175 } 5176 } 5177 } 5178 5179 if (mTransferedPackages.contains(pkg.packageName)) { 5180 Slog.w(TAG, "Package " + pkg.packageName 5181 + " was transferred to another, but its .apk remains"); 5182 } 5183 5184 // Just create the setting, don't add it yet. For already existing packages 5185 // the PkgSetting exists already and doesn't have to be created. 5186 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5187 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 5188 pkg.applicationInfo.primaryCpuAbi, 5189 pkg.applicationInfo.secondaryCpuAbi, 5190 pkg.applicationInfo.flags, user, false); 5191 if (pkgSetting == null) { 5192 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5193 "Creating application package " + pkg.packageName + " failed"); 5194 } 5195 5196 if (pkgSetting.origPackage != null) { 5197 // If we are first transitioning from an original package, 5198 // fix up the new package's name now. We need to do this after 5199 // looking up the package under its new name, so getPackageLP 5200 // can take care of fiddling things correctly. 5201 pkg.setPackageName(origPackage.name); 5202 5203 // File a report about this. 5204 String msg = "New package " + pkgSetting.realName 5205 + " renamed to replace old package " + pkgSetting.name; 5206 reportSettingsProblem(Log.WARN, msg); 5207 5208 // Make a note of it. 5209 mTransferedPackages.add(origPackage.name); 5210 5211 // No longer need to retain this. 5212 pkgSetting.origPackage = null; 5213 } 5214 5215 if (realName != null) { 5216 // Make a note of it. 5217 mTransferedPackages.add(pkg.packageName); 5218 } 5219 5220 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5221 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5222 } 5223 5224 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5225 // Check all shared libraries and map to their actual file path. 5226 // We only do this here for apps not on a system dir, because those 5227 // are the only ones that can fail an install due to this. We 5228 // will take care of the system apps by updating all of their 5229 // library paths after the scan is done. 5230 updateSharedLibrariesLPw(pkg, null); 5231 } 5232 5233 if (mFoundPolicyFile) { 5234 SELinuxMMAC.assignSeinfoValue(pkg); 5235 } 5236 5237 pkg.applicationInfo.uid = pkgSetting.appId; 5238 pkg.mExtras = pkgSetting; 5239 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5240 try { 5241 verifySignaturesLP(pkgSetting, pkg); 5242 } catch (PackageManagerException e) { 5243 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5244 throw e; 5245 } 5246 // The signature has changed, but this package is in the system 5247 // image... let's recover! 5248 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5249 // However... if this package is part of a shared user, but it 5250 // doesn't match the signature of the shared user, let's fail. 5251 // What this means is that you can't change the signatures 5252 // associated with an overall shared user, which doesn't seem all 5253 // that unreasonable. 5254 if (pkgSetting.sharedUser != null) { 5255 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5256 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5257 throw new PackageManagerException( 5258 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 5259 "Signature mismatch for shared user : " 5260 + pkgSetting.sharedUser); 5261 } 5262 } 5263 // File a report about this. 5264 String msg = "System package " + pkg.packageName 5265 + " signature changed; retaining data."; 5266 reportSettingsProblem(Log.WARN, msg); 5267 } 5268 } else { 5269 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 5270 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5271 + pkg.packageName + " upgrade keys do not match the " 5272 + "previously installed version"); 5273 } else { 5274 // signatures may have changed as result of upgrade 5275 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5276 } 5277 } 5278 // Verify that this new package doesn't have any content providers 5279 // that conflict with existing packages. Only do this if the 5280 // package isn't already installed, since we don't want to break 5281 // things that are installed. 5282 if ((scanMode&SCAN_NEW_INSTALL) != 0) { 5283 final int N = pkg.providers.size(); 5284 int i; 5285 for (i=0; i<N; i++) { 5286 PackageParser.Provider p = pkg.providers.get(i); 5287 if (p.info.authority != null) { 5288 String names[] = p.info.authority.split(";"); 5289 for (int j = 0; j < names.length; j++) { 5290 if (mProvidersByAuthority.containsKey(names[j])) { 5291 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5292 final String otherPackageName = 5293 ((other != null && other.getComponentName() != null) ? 5294 other.getComponentName().getPackageName() : "?"); 5295 throw new PackageManagerException( 5296 INSTALL_FAILED_CONFLICTING_PROVIDER, 5297 "Can't install because provider name " + names[j] 5298 + " (in package " + pkg.applicationInfo.packageName 5299 + ") is already used by " + otherPackageName); 5300 } 5301 } 5302 } 5303 } 5304 } 5305 5306 if (pkg.mAdoptPermissions != null) { 5307 // This package wants to adopt ownership of permissions from 5308 // another package. 5309 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 5310 final String origName = pkg.mAdoptPermissions.get(i); 5311 final PackageSetting orig = mSettings.peekPackageLPr(origName); 5312 if (orig != null) { 5313 if (verifyPackageUpdateLPr(orig, pkg)) { 5314 Slog.i(TAG, "Adopting permissions from " + origName + " to " 5315 + pkg.packageName); 5316 mSettings.transferPermissionsLPw(origName, pkg.packageName); 5317 } 5318 } 5319 } 5320 } 5321 } 5322 5323 final String pkgName = pkg.packageName; 5324 5325 final long scanFileTime = scanFile.lastModified(); 5326 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0; 5327 pkg.applicationInfo.processName = fixProcessName( 5328 pkg.applicationInfo.packageName, 5329 pkg.applicationInfo.processName, 5330 pkg.applicationInfo.uid); 5331 5332 File dataPath; 5333 if (mPlatformPackage == pkg) { 5334 // The system package is special. 5335 dataPath = new File (Environment.getDataDirectory(), "system"); 5336 pkg.applicationInfo.dataDir = dataPath.getPath(); 5337 5338 } else { 5339 // This is a normal package, need to make its data directory. 5340 dataPath = getDataPathForPackage(pkg.packageName, 0); 5341 5342 boolean uidError = false; 5343 5344 if (dataPath.exists()) { 5345 int currentUid = 0; 5346 try { 5347 StructStat stat = Os.stat(dataPath.getPath()); 5348 currentUid = stat.st_uid; 5349 } catch (ErrnoException e) { 5350 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 5351 } 5352 5353 // If we have mismatched owners for the data path, we have a problem. 5354 if (currentUid != pkg.applicationInfo.uid) { 5355 boolean recovered = false; 5356 if (currentUid == 0) { 5357 // The directory somehow became owned by root. Wow. 5358 // This is probably because the system was stopped while 5359 // installd was in the middle of messing with its libs 5360 // directory. Ask installd to fix that. 5361 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 5362 pkg.applicationInfo.uid); 5363 if (ret >= 0) { 5364 recovered = true; 5365 String msg = "Package " + pkg.packageName 5366 + " unexpectedly changed to uid 0; recovered to " + 5367 + pkg.applicationInfo.uid; 5368 reportSettingsProblem(Log.WARN, msg); 5369 } 5370 } 5371 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5372 || (scanMode&SCAN_BOOTING) != 0)) { 5373 // If this is a system app, we can at least delete its 5374 // current data so the application will still work. 5375 int ret = removeDataDirsLI(pkgName); 5376 if (ret >= 0) { 5377 // TODO: Kill the processes first 5378 // Old data gone! 5379 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5380 ? "System package " : "Third party package "; 5381 String msg = prefix + pkg.packageName 5382 + " has changed from uid: " 5383 + currentUid + " to " 5384 + pkg.applicationInfo.uid + "; old data erased"; 5385 reportSettingsProblem(Log.WARN, msg); 5386 recovered = true; 5387 5388 // And now re-install the app. 5389 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5390 pkg.applicationInfo.seinfo); 5391 if (ret == -1) { 5392 // Ack should not happen! 5393 msg = prefix + pkg.packageName 5394 + " could not have data directory re-created after delete."; 5395 reportSettingsProblem(Log.WARN, msg); 5396 throw new PackageManagerException( 5397 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 5398 } 5399 } 5400 if (!recovered) { 5401 mHasSystemUidErrors = true; 5402 } 5403 } else if (!recovered) { 5404 // If we allow this install to proceed, we will be broken. 5405 // Abort, abort! 5406 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 5407 "scanPackageLI"); 5408 } 5409 if (!recovered) { 5410 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 5411 + pkg.applicationInfo.uid + "/fs_" 5412 + currentUid; 5413 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 5414 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 5415 String msg = "Package " + pkg.packageName 5416 + " has mismatched uid: " 5417 + currentUid + " on disk, " 5418 + pkg.applicationInfo.uid + " in settings"; 5419 // writer 5420 synchronized (mPackages) { 5421 mSettings.mReadMessages.append(msg); 5422 mSettings.mReadMessages.append('\n'); 5423 uidError = true; 5424 if (!pkgSetting.uidError) { 5425 reportSettingsProblem(Log.ERROR, msg); 5426 } 5427 } 5428 } 5429 } 5430 pkg.applicationInfo.dataDir = dataPath.getPath(); 5431 if (mShouldRestoreconData) { 5432 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 5433 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 5434 pkg.applicationInfo.uid); 5435 } 5436 } else { 5437 if (DEBUG_PACKAGE_SCANNING) { 5438 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5439 Log.v(TAG, "Want this data dir: " + dataPath); 5440 } 5441 //invoke installer to do the actual installation 5442 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5443 pkg.applicationInfo.seinfo); 5444 if (ret < 0) { 5445 // Error from installer 5446 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5447 "Unable to create data dirs [errorCode=" + ret + "]"); 5448 } 5449 5450 if (dataPath.exists()) { 5451 pkg.applicationInfo.dataDir = dataPath.getPath(); 5452 } else { 5453 Slog.w(TAG, "Unable to create data directory: " + dataPath); 5454 pkg.applicationInfo.dataDir = null; 5455 } 5456 } 5457 5458 pkgSetting.uidError = uidError; 5459 } 5460 5461 final String path = scanFile.getPath(); 5462 final String codePath = pkg.applicationInfo.getCodePath(); 5463 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 5464 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 5465 setBundledAppAbisAndRoots(pkg, pkgSetting); 5466 5467 // If we haven't found any native libraries for the app, check if it has 5468 // renderscript code. We'll need to force the app to 32 bit if it has 5469 // renderscript bitcode. 5470 if (pkg.applicationInfo.primaryCpuAbi == null 5471 && pkg.applicationInfo.secondaryCpuAbi == null 5472 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5473 NativeLibraryHelper.Handle handle = null; 5474 try { 5475 handle = NativeLibraryHelper.Handle.create(scanFile); 5476 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5477 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 5478 } 5479 } catch (IOException ioe) { 5480 Slog.w(TAG, "Error scanning system app : " + ioe); 5481 } finally { 5482 IoUtils.closeQuietly(handle); 5483 } 5484 } 5485 5486 setNativeLibraryPaths(pkg); 5487 } else { 5488 // TODO: We can probably be smarter about this stuff. For installed apps, 5489 // we can calculate this information at install time once and for all. For 5490 // system apps, we can probably assume that this information doesn't change 5491 // after the first boot scan. As things stand, we do lots of unnecessary work. 5492 5493 // Give ourselves some initial paths; we'll come back for another 5494 // pass once we've determined ABI below. 5495 setNativeLibraryPaths(pkg); 5496 5497 final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg); 5498 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 5499 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 5500 5501 NativeLibraryHelper.Handle handle = null; 5502 try { 5503 handle = NativeLibraryHelper.Handle.create(scanFile); 5504 // TODO(multiArch): This can be null for apps that didn't go through the 5505 // usual installation process. We can calculate it again, like we 5506 // do during install time. 5507 // 5508 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 5509 // unnecessary. 5510 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 5511 5512 // Null out the abis so that they can be recalculated. 5513 pkg.applicationInfo.primaryCpuAbi = null; 5514 pkg.applicationInfo.secondaryCpuAbi = null; 5515 if (isMultiArch(pkg.applicationInfo)) { 5516 // Warn if we've set an abiOverride for multi-lib packages.. 5517 // By definition, we need to copy both 32 and 64 bit libraries for 5518 // such packages. 5519 if (pkg.cpuAbiOverride != null 5520 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 5521 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 5522 } 5523 5524 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 5525 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 5526 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 5527 if (isAsec) { 5528 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 5529 } else { 5530 abi32 = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle, 5531 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 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.copyNativeBinariesIfNeededLI(handle, 5543 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, useIsaSpecificSubdirs); 5544 } 5545 } 5546 5547 maybeThrowExceptionForMultiArchCopy( 5548 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 5549 5550 if (abi64 >= 0) { 5551 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 5552 } 5553 5554 if (abi32 >= 0) { 5555 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 5556 if (abi64 >= 0) { 5557 pkg.applicationInfo.secondaryCpuAbi = abi; 5558 } else { 5559 pkg.applicationInfo.primaryCpuAbi = abi; 5560 } 5561 } 5562 } else { 5563 String[] abiList = (cpuAbiOverride != null) ? 5564 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 5565 5566 // Enable gross and lame hacks for apps that are built with old 5567 // SDK tools. We must scan their APKs for renderscript bitcode and 5568 // not launch them if it's present. Don't bother checking on devices 5569 // that don't have 64 bit support. 5570 boolean needsRenderScriptOverride = false; 5571 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 5572 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5573 abiList = Build.SUPPORTED_32_BIT_ABIS; 5574 needsRenderScriptOverride = true; 5575 } 5576 5577 final int copyRet; 5578 if (isAsec) { 5579 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 5580 } else { 5581 copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle, 5582 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 5583 } 5584 5585 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5586 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5587 "Error unpackaging native libs for app, errorCode=" + copyRet); 5588 } 5589 5590 if (copyRet >= 0) { 5591 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 5592 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 5593 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 5594 } else if (needsRenderScriptOverride) { 5595 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 5596 } 5597 } 5598 } catch (IOException ioe) { 5599 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 5600 } finally { 5601 IoUtils.closeQuietly(handle); 5602 } 5603 5604 // Now that we've calculated the ABIs and determined if it's an internal app, 5605 // we will go ahead and populate the nativeLibraryPath. 5606 setNativeLibraryPaths(pkg); 5607 5608 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 5609 final int[] userIds = sUserManager.getUserIds(); 5610 synchronized (mInstallLock) { 5611 // Create a native library symlink only if we have native libraries 5612 // and if the native libraries are 32 bit libraries. We do not provide 5613 // this symlink for 64 bit libraries. 5614 if (pkg.applicationInfo.primaryCpuAbi != null && 5615 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 5616 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 5617 for (int userId : userIds) { 5618 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 5619 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5620 "Failed linking native library dir (user=" + userId + ")"); 5621 } 5622 } 5623 } 5624 } 5625 } 5626 5627 // This is a special case for the "system" package, where the ABI is 5628 // dictated by the zygote configuration (and init.rc). We should keep track 5629 // of this ABI so that we can deal with "normal" applications that run under 5630 // the same UID correctly. 5631 if (mPlatformPackage == pkg) { 5632 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 5633 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 5634 } 5635 5636 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 5637 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 5638 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 5639 // Copy the derived override back to the parsed package, so that we can 5640 // update the package settings accordingly. 5641 pkg.cpuAbiOverride = cpuAbiOverride; 5642 5643 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 5644 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 5645 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 5646 5647 // Push the derived path down into PackageSettings so we know what to 5648 // clean up at uninstall time. 5649 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 5650 5651 if (DEBUG_ABI_SELECTION) { 5652 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 5653 " primary=" + pkg.applicationInfo.primaryCpuAbi + 5654 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 5655 } 5656 5657 if ((scanMode&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 5658 // We don't do this here during boot because we can do it all 5659 // at once after scanning all existing packages. 5660 // 5661 // We also do this *before* we perform dexopt on this package, so that 5662 // we can avoid redundant dexopts, and also to make sure we've got the 5663 // code and package path correct. 5664 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 5665 pkg, forceDex, (scanMode & SCAN_DEFER_DEX) != 0); 5666 } 5667 5668 if ((scanMode&SCAN_NO_DEX) == 0) { 5669 if (performDexOptLI(pkg, null /* instruction sets */, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5670 == DEX_OPT_FAILED) { 5671 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5672 removeDataDirsLI(pkg.packageName); 5673 } 5674 5675 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 5676 } 5677 } 5678 5679 if (mFactoryTest && pkg.requestedPermissions.contains( 5680 android.Manifest.permission.FACTORY_TEST)) { 5681 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 5682 } 5683 5684 ArrayList<PackageParser.Package> clientLibPkgs = null; 5685 5686 // writer 5687 synchronized (mPackages) { 5688 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5689 // Only system apps can add new shared libraries. 5690 if (pkg.libraryNames != null) { 5691 for (int i=0; i<pkg.libraryNames.size(); i++) { 5692 String name = pkg.libraryNames.get(i); 5693 boolean allowed = false; 5694 if (isUpdatedSystemApp(pkg)) { 5695 // New library entries can only be added through the 5696 // system image. This is important to get rid of a lot 5697 // of nasty edge cases: for example if we allowed a non- 5698 // system update of the app to add a library, then uninstalling 5699 // the update would make the library go away, and assumptions 5700 // we made such as through app install filtering would now 5701 // have allowed apps on the device which aren't compatible 5702 // with it. Better to just have the restriction here, be 5703 // conservative, and create many fewer cases that can negatively 5704 // impact the user experience. 5705 final PackageSetting sysPs = mSettings 5706 .getDisabledSystemPkgLPr(pkg.packageName); 5707 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 5708 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 5709 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 5710 allowed = true; 5711 allowed = true; 5712 break; 5713 } 5714 } 5715 } 5716 } else { 5717 allowed = true; 5718 } 5719 if (allowed) { 5720 if (!mSharedLibraries.containsKey(name)) { 5721 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 5722 } else if (!name.equals(pkg.packageName)) { 5723 Slog.w(TAG, "Package " + pkg.packageName + " library " 5724 + name + " already exists; skipping"); 5725 } 5726 } else { 5727 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 5728 + name + " that is not declared on system image; skipping"); 5729 } 5730 } 5731 if ((scanMode&SCAN_BOOTING) == 0) { 5732 // If we are not booting, we need to update any applications 5733 // that are clients of our shared library. If we are booting, 5734 // this will all be done once the scan is complete. 5735 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 5736 } 5737 } 5738 } 5739 } 5740 5741 // We also need to dexopt any apps that are dependent on this library. Note that 5742 // if these fail, we should abort the install since installing the library will 5743 // result in some apps being broken. 5744 if (clientLibPkgs != null) { 5745 if ((scanMode&SCAN_NO_DEX) == 0) { 5746 for (int i=0; i<clientLibPkgs.size(); i++) { 5747 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5748 if (performDexOptLI(clientPkg, null /* instruction sets */, 5749 forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5750 == DEX_OPT_FAILED) { 5751 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5752 removeDataDirsLI(pkg.packageName); 5753 } 5754 5755 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 5756 "scanPackageLI failed to dexopt clientLibPkgs"); 5757 } 5758 } 5759 } 5760 } 5761 5762 // Request the ActivityManager to kill the process(only for existing packages) 5763 // so that we do not end up in a confused state while the user is still using the older 5764 // version of the application while the new one gets installed. 5765 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 5766 // If the package lives in an asec, tell everyone that the container is going 5767 // away so they can clean up any references to its resources (which would prevent 5768 // vold from being able to unmount the asec) 5769 if (isForwardLocked(pkg) || isExternal(pkg)) { 5770 if (DEBUG_INSTALL) { 5771 Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE"); 5772 } 5773 final int[] uidArray = new int[] { pkg.applicationInfo.uid }; 5774 final ArrayList<String> pkgList = new ArrayList<String>(1); 5775 pkgList.add(pkg.applicationInfo.packageName); 5776 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 5777 } 5778 5779 // Post the request that it be killed now that the going-away broadcast is en route 5780 killApplication(pkg.applicationInfo.packageName, 5781 pkg.applicationInfo.uid, "update pkg"); 5782 } 5783 5784 // Also need to kill any apps that are dependent on the library. 5785 if (clientLibPkgs != null) { 5786 for (int i=0; i<clientLibPkgs.size(); i++) { 5787 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5788 killApplication(clientPkg.applicationInfo.packageName, 5789 clientPkg.applicationInfo.uid, "update lib"); 5790 } 5791 } 5792 5793 // writer 5794 synchronized (mPackages) { 5795 // We don't expect installation to fail beyond this point, 5796 if ((scanMode&SCAN_MONITOR) != 0) { 5797 mAppDirs.put(pkg.codePath, pkg); 5798 } 5799 // Add the new setting to mSettings 5800 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 5801 // Add the new setting to mPackages 5802 mPackages.put(pkg.applicationInfo.packageName, pkg); 5803 // Make sure we don't accidentally delete its data. 5804 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 5805 while (iter.hasNext()) { 5806 PackageCleanItem item = iter.next(); 5807 if (pkgName.equals(item.packageName)) { 5808 iter.remove(); 5809 } 5810 } 5811 5812 // Take care of first install / last update times. 5813 if (currentTime != 0) { 5814 if (pkgSetting.firstInstallTime == 0) { 5815 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 5816 } else if ((scanMode&SCAN_UPDATE_TIME) != 0) { 5817 pkgSetting.lastUpdateTime = currentTime; 5818 } 5819 } else if (pkgSetting.firstInstallTime == 0) { 5820 // We need *something*. Take time time stamp of the file. 5821 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 5822 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 5823 if (scanFileTime != pkgSetting.timeStamp) { 5824 // A package on the system image has changed; consider this 5825 // to be an update. 5826 pkgSetting.lastUpdateTime = scanFileTime; 5827 } 5828 } 5829 5830 // Add the package's KeySets to the global KeySetManagerService 5831 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5832 try { 5833 // Old KeySetData no longer valid. 5834 ksms.removeAppKeySetDataLPw(pkg.packageName); 5835 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 5836 if (pkg.mKeySetMapping != null) { 5837 for (Map.Entry<String, ArraySet<PublicKey>> entry : 5838 pkg.mKeySetMapping.entrySet()) { 5839 if (entry.getValue() != null) { 5840 ksms.addDefinedKeySetToPackageLPw(pkg.packageName, 5841 entry.getValue(), entry.getKey()); 5842 } 5843 } 5844 if (pkg.mUpgradeKeySets != null) { 5845 for (String upgradeAlias : pkg.mUpgradeKeySets) { 5846 ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias); 5847 } 5848 } 5849 } 5850 } catch (NullPointerException e) { 5851 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 5852 } catch (IllegalArgumentException e) { 5853 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 5854 } 5855 5856 int N = pkg.providers.size(); 5857 StringBuilder r = null; 5858 int i; 5859 for (i=0; i<N; i++) { 5860 PackageParser.Provider p = pkg.providers.get(i); 5861 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 5862 p.info.processName, pkg.applicationInfo.uid); 5863 mProviders.addProvider(p); 5864 p.syncable = p.info.isSyncable; 5865 if (p.info.authority != null) { 5866 String names[] = p.info.authority.split(";"); 5867 p.info.authority = null; 5868 for (int j = 0; j < names.length; j++) { 5869 if (j == 1 && p.syncable) { 5870 // We only want the first authority for a provider to possibly be 5871 // syncable, so if we already added this provider using a different 5872 // authority clear the syncable flag. We copy the provider before 5873 // changing it because the mProviders object contains a reference 5874 // to a provider that we don't want to change. 5875 // Only do this for the second authority since the resulting provider 5876 // object can be the same for all future authorities for this provider. 5877 p = new PackageParser.Provider(p); 5878 p.syncable = false; 5879 } 5880 if (!mProvidersByAuthority.containsKey(names[j])) { 5881 mProvidersByAuthority.put(names[j], p); 5882 if (p.info.authority == null) { 5883 p.info.authority = names[j]; 5884 } else { 5885 p.info.authority = p.info.authority + ";" + names[j]; 5886 } 5887 if (DEBUG_PACKAGE_SCANNING) { 5888 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5889 Log.d(TAG, "Registered content provider: " + names[j] 5890 + ", className = " + p.info.name + ", isSyncable = " 5891 + p.info.isSyncable); 5892 } 5893 } else { 5894 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5895 Slog.w(TAG, "Skipping provider name " + names[j] + 5896 " (in package " + pkg.applicationInfo.packageName + 5897 "): name already used by " 5898 + ((other != null && other.getComponentName() != null) 5899 ? other.getComponentName().getPackageName() : "?")); 5900 } 5901 } 5902 } 5903 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5904 if (r == null) { 5905 r = new StringBuilder(256); 5906 } else { 5907 r.append(' '); 5908 } 5909 r.append(p.info.name); 5910 } 5911 } 5912 if (r != null) { 5913 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 5914 } 5915 5916 N = pkg.services.size(); 5917 r = null; 5918 for (i=0; i<N; i++) { 5919 PackageParser.Service s = pkg.services.get(i); 5920 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 5921 s.info.processName, pkg.applicationInfo.uid); 5922 mServices.addService(s); 5923 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5924 if (r == null) { 5925 r = new StringBuilder(256); 5926 } else { 5927 r.append(' '); 5928 } 5929 r.append(s.info.name); 5930 } 5931 } 5932 if (r != null) { 5933 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 5934 } 5935 5936 N = pkg.receivers.size(); 5937 r = null; 5938 for (i=0; i<N; i++) { 5939 PackageParser.Activity a = pkg.receivers.get(i); 5940 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5941 a.info.processName, pkg.applicationInfo.uid); 5942 mReceivers.addActivity(a, "receiver"); 5943 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5944 if (r == null) { 5945 r = new StringBuilder(256); 5946 } else { 5947 r.append(' '); 5948 } 5949 r.append(a.info.name); 5950 } 5951 } 5952 if (r != null) { 5953 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 5954 } 5955 5956 N = pkg.activities.size(); 5957 r = null; 5958 for (i=0; i<N; i++) { 5959 PackageParser.Activity a = pkg.activities.get(i); 5960 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5961 a.info.processName, pkg.applicationInfo.uid); 5962 mActivities.addActivity(a, "activity"); 5963 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5964 if (r == null) { 5965 r = new StringBuilder(256); 5966 } else { 5967 r.append(' '); 5968 } 5969 r.append(a.info.name); 5970 } 5971 } 5972 if (r != null) { 5973 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 5974 } 5975 5976 N = pkg.permissionGroups.size(); 5977 r = null; 5978 for (i=0; i<N; i++) { 5979 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 5980 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 5981 if (cur == null) { 5982 mPermissionGroups.put(pg.info.name, pg); 5983 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5984 if (r == null) { 5985 r = new StringBuilder(256); 5986 } else { 5987 r.append(' '); 5988 } 5989 r.append(pg.info.name); 5990 } 5991 } else { 5992 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 5993 + pg.info.packageName + " ignored: original from " 5994 + cur.info.packageName); 5995 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5996 if (r == null) { 5997 r = new StringBuilder(256); 5998 } else { 5999 r.append(' '); 6000 } 6001 r.append("DUP:"); 6002 r.append(pg.info.name); 6003 } 6004 } 6005 } 6006 if (r != null) { 6007 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6008 } 6009 6010 N = pkg.permissions.size(); 6011 r = null; 6012 for (i=0; i<N; i++) { 6013 PackageParser.Permission p = pkg.permissions.get(i); 6014 HashMap<String, BasePermission> permissionMap = 6015 p.tree ? mSettings.mPermissionTrees 6016 : mSettings.mPermissions; 6017 p.group = mPermissionGroups.get(p.info.group); 6018 if (p.info.group == null || p.group != null) { 6019 BasePermission bp = permissionMap.get(p.info.name); 6020 if (bp == null) { 6021 bp = new BasePermission(p.info.name, p.info.packageName, 6022 BasePermission.TYPE_NORMAL); 6023 permissionMap.put(p.info.name, bp); 6024 } 6025 if (bp.perm == null) { 6026 if (bp.sourcePackage != null 6027 && !bp.sourcePackage.equals(p.info.packageName)) { 6028 // If this is a permission that was formerly defined by a non-system 6029 // app, but is now defined by a system app (following an upgrade), 6030 // discard the previous declaration and consider the system's to be 6031 // canonical. 6032 if (isSystemApp(p.owner)) { 6033 String msg = "New decl " + p.owner + " of permission " 6034 + p.info.name + " is system"; 6035 reportSettingsProblem(Log.WARN, msg); 6036 bp.sourcePackage = null; 6037 } 6038 } 6039 if (bp.sourcePackage == null 6040 || bp.sourcePackage.equals(p.info.packageName)) { 6041 BasePermission tree = findPermissionTreeLP(p.info.name); 6042 if (tree == null 6043 || tree.sourcePackage.equals(p.info.packageName)) { 6044 bp.packageSetting = pkgSetting; 6045 bp.perm = p; 6046 bp.uid = pkg.applicationInfo.uid; 6047 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6048 if (r == null) { 6049 r = new StringBuilder(256); 6050 } else { 6051 r.append(' '); 6052 } 6053 r.append(p.info.name); 6054 } 6055 } else { 6056 Slog.w(TAG, "Permission " + p.info.name + " from package " 6057 + p.info.packageName + " ignored: base tree " 6058 + tree.name + " is from package " 6059 + tree.sourcePackage); 6060 } 6061 } else { 6062 Slog.w(TAG, "Permission " + p.info.name + " from package " 6063 + p.info.packageName + " ignored: original from " 6064 + bp.sourcePackage); 6065 } 6066 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6067 if (r == null) { 6068 r = new StringBuilder(256); 6069 } else { 6070 r.append(' '); 6071 } 6072 r.append("DUP:"); 6073 r.append(p.info.name); 6074 } 6075 if (bp.perm == p) { 6076 bp.protectionLevel = p.info.protectionLevel; 6077 } 6078 } else { 6079 Slog.w(TAG, "Permission " + p.info.name + " from package " 6080 + p.info.packageName + " ignored: no group " 6081 + p.group); 6082 } 6083 } 6084 if (r != null) { 6085 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6086 } 6087 6088 N = pkg.instrumentation.size(); 6089 r = null; 6090 for (i=0; i<N; i++) { 6091 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6092 a.info.packageName = pkg.applicationInfo.packageName; 6093 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6094 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6095 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6096 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6097 a.info.dataDir = pkg.applicationInfo.dataDir; 6098 6099 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6100 // need other information about the application, like the ABI and what not ? 6101 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6102 mInstrumentation.put(a.getComponentName(), a); 6103 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6104 if (r == null) { 6105 r = new StringBuilder(256); 6106 } else { 6107 r.append(' '); 6108 } 6109 r.append(a.info.name); 6110 } 6111 } 6112 if (r != null) { 6113 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6114 } 6115 6116 if (pkg.protectedBroadcasts != null) { 6117 N = pkg.protectedBroadcasts.size(); 6118 for (i=0; i<N; i++) { 6119 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6120 } 6121 } 6122 6123 pkgSetting.setTimeStamp(scanFileTime); 6124 6125 // Create idmap files for pairs of (packages, overlay packages). 6126 // Note: "android", ie framework-res.apk, is handled by native layers. 6127 if (pkg.mOverlayTarget != null) { 6128 // This is an overlay package. 6129 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6130 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6131 mOverlays.put(pkg.mOverlayTarget, 6132 new HashMap<String, PackageParser.Package>()); 6133 } 6134 HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6135 map.put(pkg.packageName, pkg); 6136 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6137 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6138 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6139 "scanPackageLI failed to createIdmap"); 6140 } 6141 } 6142 } else if (mOverlays.containsKey(pkg.packageName) && 6143 !pkg.packageName.equals("android")) { 6144 // This is a regular package, with one or more known overlay packages. 6145 createIdmapsForPackageLI(pkg); 6146 } 6147 } 6148 6149 return pkg; 6150 } 6151 6152 /** 6153 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6154 * i.e, so that all packages can be run inside a single process if required. 6155 * 6156 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6157 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6158 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6159 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6160 * updating a package that belongs to a shared user. 6161 * 6162 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6163 * adds unnecessary complexity. 6164 */ 6165 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6166 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6167 String requiredInstructionSet = null; 6168 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6169 requiredInstructionSet = VMRuntime.getInstructionSet( 6170 scannedPackage.applicationInfo.primaryCpuAbi); 6171 } 6172 6173 PackageSetting requirer = null; 6174 for (PackageSetting ps : packagesForUser) { 6175 // If packagesForUser contains scannedPackage, we skip it. This will happen 6176 // when scannedPackage is an update of an existing package. Without this check, 6177 // we will never be able to change the ABI of any package belonging to a shared 6178 // user, even if it's compatible with other packages. 6179 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6180 if (ps.primaryCpuAbiString == null) { 6181 continue; 6182 } 6183 6184 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6185 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6186 // We have a mismatch between instruction sets (say arm vs arm64) warn about 6187 // this but there's not much we can do. 6188 String errorMessage = "Instruction set mismatch, " 6189 + ((requirer == null) ? "[caller]" : requirer) 6190 + " requires " + requiredInstructionSet + " whereas " + ps 6191 + " requires " + instructionSet; 6192 Slog.w(TAG, errorMessage); 6193 } 6194 6195 if (requiredInstructionSet == null) { 6196 requiredInstructionSet = instructionSet; 6197 requirer = ps; 6198 } 6199 } 6200 } 6201 6202 if (requiredInstructionSet != null) { 6203 String adjustedAbi; 6204 if (requirer != null) { 6205 // requirer != null implies that either scannedPackage was null or that scannedPackage 6206 // did not require an ABI, in which case we have to adjust scannedPackage to match 6207 // the ABI of the set (which is the same as requirer's ABI) 6208 adjustedAbi = requirer.primaryCpuAbiString; 6209 if (scannedPackage != null) { 6210 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6211 } 6212 } else { 6213 // requirer == null implies that we're updating all ABIs in the set to 6214 // match scannedPackage. 6215 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6216 } 6217 6218 for (PackageSetting ps : packagesForUser) { 6219 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6220 if (ps.primaryCpuAbiString != null) { 6221 continue; 6222 } 6223 6224 ps.primaryCpuAbiString = adjustedAbi; 6225 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6226 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6227 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6228 6229 if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt, 6230 deferDexOpt, true) == DEX_OPT_FAILED) { 6231 ps.primaryCpuAbiString = null; 6232 ps.pkg.applicationInfo.primaryCpuAbi = null; 6233 return; 6234 } else { 6235 mInstaller.rmdex(ps.codePathString, 6236 getDexCodeInstructionSet(getPreferredInstructionSet())); 6237 } 6238 } 6239 } 6240 } 6241 } 6242 } 6243 6244 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6245 synchronized (mPackages) { 6246 mResolverReplaced = true; 6247 // Set up information for custom user intent resolution activity. 6248 mResolveActivity.applicationInfo = pkg.applicationInfo; 6249 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6250 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6251 mResolveActivity.processName = null; 6252 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6253 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6254 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6255 mResolveActivity.theme = 0; 6256 mResolveActivity.exported = true; 6257 mResolveActivity.enabled = true; 6258 mResolveInfo.activityInfo = mResolveActivity; 6259 mResolveInfo.priority = 0; 6260 mResolveInfo.preferredOrder = 0; 6261 mResolveInfo.match = 0; 6262 mResolveComponentName = mCustomResolverComponentName; 6263 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6264 mResolveComponentName); 6265 } 6266 } 6267 6268 private static String calculateBundledApkRoot(final String codePathString) { 6269 final File codePath = new File(codePathString); 6270 final File codeRoot; 6271 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6272 codeRoot = Environment.getRootDirectory(); 6273 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6274 codeRoot = Environment.getOemDirectory(); 6275 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6276 codeRoot = Environment.getVendorDirectory(); 6277 } else { 6278 // Unrecognized code path; take its top real segment as the apk root: 6279 // e.g. /something/app/blah.apk => /something 6280 try { 6281 File f = codePath.getCanonicalFile(); 6282 File parent = f.getParentFile(); // non-null because codePath is a file 6283 File tmp; 6284 while ((tmp = parent.getParentFile()) != null) { 6285 f = parent; 6286 parent = tmp; 6287 } 6288 codeRoot = f; 6289 Slog.w(TAG, "Unrecognized code path " 6290 + codePath + " - using " + codeRoot); 6291 } catch (IOException e) { 6292 // Can't canonicalize the code path -- shenanigans? 6293 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6294 return Environment.getRootDirectory().getPath(); 6295 } 6296 } 6297 return codeRoot.getPath(); 6298 } 6299 6300 /** 6301 * Derive and set the location of native libraries for the given package, 6302 * which varies depending on where and how the package was installed. 6303 */ 6304 private void setNativeLibraryPaths(PackageParser.Package pkg) { 6305 final ApplicationInfo info = pkg.applicationInfo; 6306 final String codePath = pkg.codePath; 6307 final File codeFile = new File(codePath); 6308 final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info); 6309 final boolean asecApp = isForwardLocked(info) || isExternal(info); 6310 6311 info.nativeLibraryRootDir = null; 6312 info.nativeLibraryRootRequiresIsa = false; 6313 info.nativeLibraryDir = null; 6314 info.secondaryNativeLibraryDir = null; 6315 6316 if (isApkFile(codeFile)) { 6317 // Monolithic install 6318 if (bundledApp) { 6319 // If "/system/lib64/apkname" exists, assume that is the per-package 6320 // native library directory to use; otherwise use "/system/lib/apkname". 6321 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 6322 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 6323 getPrimaryInstructionSet(info)); 6324 6325 // This is a bundled system app so choose the path based on the ABI. 6326 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 6327 // is just the default path. 6328 final String apkName = deriveCodePathName(codePath); 6329 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 6330 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 6331 apkName).getAbsolutePath(); 6332 6333 if (info.secondaryCpuAbi != null) { 6334 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 6335 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 6336 secondaryLibDir, apkName).getAbsolutePath(); 6337 } 6338 } else if (asecApp) { 6339 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 6340 .getAbsolutePath(); 6341 } else { 6342 final String apkName = deriveCodePathName(codePath); 6343 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 6344 .getAbsolutePath(); 6345 } 6346 6347 info.nativeLibraryRootRequiresIsa = false; 6348 info.nativeLibraryDir = info.nativeLibraryRootDir; 6349 } else { 6350 // Cluster install 6351 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 6352 info.nativeLibraryRootRequiresIsa = true; 6353 6354 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 6355 getPrimaryInstructionSet(info)).getAbsolutePath(); 6356 6357 if (info.secondaryCpuAbi != null) { 6358 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 6359 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 6360 } 6361 } 6362 } 6363 6364 /** 6365 * Calculate the abis and roots for a bundled app. These can uniquely 6366 * be determined from the contents of the system partition, i.e whether 6367 * it contains 64 or 32 bit shared libraries etc. We do not validate any 6368 * of this information, and instead assume that the system was built 6369 * sensibly. 6370 */ 6371 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 6372 PackageSetting pkgSetting) { 6373 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 6374 6375 // If "/system/lib64/apkname" exists, assume that is the per-package 6376 // native library directory to use; otherwise use "/system/lib/apkname". 6377 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 6378 setBundledAppAbi(pkg, apkRoot, apkName); 6379 // pkgSetting might be null during rescan following uninstall of updates 6380 // to a bundled app, so accommodate that possibility. The settings in 6381 // that case will be established later from the parsed package. 6382 // 6383 // If the settings aren't null, sync them up with what we've just derived. 6384 // note that apkRoot isn't stored in the package settings. 6385 if (pkgSetting != null) { 6386 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6387 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6388 } 6389 } 6390 6391 /** 6392 * Deduces the ABI of a bundled app and sets the relevant fields on the 6393 * parsed pkg object. 6394 * 6395 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 6396 * under which system libraries are installed. 6397 * @param apkName the name of the installed package. 6398 */ 6399 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 6400 final File codeFile = new File(pkg.codePath); 6401 6402 final boolean has64BitLibs; 6403 final boolean has32BitLibs; 6404 if (isApkFile(codeFile)) { 6405 // Monolithic install 6406 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 6407 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 6408 } else { 6409 // Cluster install 6410 final File rootDir = new File(codeFile, LIB_DIR_NAME); 6411 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 6412 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 6413 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 6414 has64BitLibs = (new File(rootDir, isa)).exists(); 6415 } else { 6416 has64BitLibs = false; 6417 } 6418 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 6419 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 6420 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 6421 has32BitLibs = (new File(rootDir, isa)).exists(); 6422 } else { 6423 has32BitLibs = false; 6424 } 6425 } 6426 6427 if (has64BitLibs && !has32BitLibs) { 6428 // The package has 64 bit libs, but not 32 bit libs. Its primary 6429 // ABI should be 64 bit. We can safely assume here that the bundled 6430 // native libraries correspond to the most preferred ABI in the list. 6431 6432 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6433 pkg.applicationInfo.secondaryCpuAbi = null; 6434 } else if (has32BitLibs && !has64BitLibs) { 6435 // The package has 32 bit libs but not 64 bit libs. Its primary 6436 // ABI should be 32 bit. 6437 6438 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6439 pkg.applicationInfo.secondaryCpuAbi = null; 6440 } else if (has32BitLibs && has64BitLibs) { 6441 // The application has both 64 and 32 bit bundled libraries. We check 6442 // here that the app declares multiArch support, and warn if it doesn't. 6443 // 6444 // We will be lenient here and record both ABIs. The primary will be the 6445 // ABI that's higher on the list, i.e, a device that's configured to prefer 6446 // 64 bit apps will see a 64 bit primary ABI, 6447 6448 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 6449 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 6450 } 6451 6452 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 6453 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6454 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6455 } else { 6456 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6457 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6458 } 6459 } else { 6460 pkg.applicationInfo.primaryCpuAbi = null; 6461 pkg.applicationInfo.secondaryCpuAbi = null; 6462 } 6463 } 6464 6465 private void killApplication(String pkgName, int appId, String reason) { 6466 // Request the ActivityManager to kill the process(only for existing packages) 6467 // so that we do not end up in a confused state while the user is still using the older 6468 // version of the application while the new one gets installed. 6469 IActivityManager am = ActivityManagerNative.getDefault(); 6470 if (am != null) { 6471 try { 6472 am.killApplicationWithAppId(pkgName, appId, reason); 6473 } catch (RemoteException e) { 6474 } 6475 } 6476 } 6477 6478 void removePackageLI(PackageSetting ps, boolean chatty) { 6479 if (DEBUG_INSTALL) { 6480 if (chatty) 6481 Log.d(TAG, "Removing package " + ps.name); 6482 } 6483 6484 // writer 6485 synchronized (mPackages) { 6486 mPackages.remove(ps.name); 6487 if (ps.codePathString != null) { 6488 mAppDirs.remove(ps.codePathString); 6489 } 6490 6491 final PackageParser.Package pkg = ps.pkg; 6492 if (pkg != null) { 6493 cleanPackageDataStructuresLILPw(pkg, chatty); 6494 } 6495 } 6496 } 6497 6498 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 6499 if (DEBUG_INSTALL) { 6500 if (chatty) 6501 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 6502 } 6503 6504 // writer 6505 synchronized (mPackages) { 6506 mPackages.remove(pkg.applicationInfo.packageName); 6507 if (pkg.codePath != null) { 6508 mAppDirs.remove(pkg.codePath); 6509 } 6510 cleanPackageDataStructuresLILPw(pkg, chatty); 6511 } 6512 } 6513 6514 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 6515 int N = pkg.providers.size(); 6516 StringBuilder r = null; 6517 int i; 6518 for (i=0; i<N; i++) { 6519 PackageParser.Provider p = pkg.providers.get(i); 6520 mProviders.removeProvider(p); 6521 if (p.info.authority == null) { 6522 6523 /* There was another ContentProvider with this authority when 6524 * this app was installed so this authority is null, 6525 * Ignore it as we don't have to unregister the provider. 6526 */ 6527 continue; 6528 } 6529 String names[] = p.info.authority.split(";"); 6530 for (int j = 0; j < names.length; j++) { 6531 if (mProvidersByAuthority.get(names[j]) == p) { 6532 mProvidersByAuthority.remove(names[j]); 6533 if (DEBUG_REMOVE) { 6534 if (chatty) 6535 Log.d(TAG, "Unregistered content provider: " + names[j] 6536 + ", className = " + p.info.name + ", isSyncable = " 6537 + p.info.isSyncable); 6538 } 6539 } 6540 } 6541 if (DEBUG_REMOVE && chatty) { 6542 if (r == null) { 6543 r = new StringBuilder(256); 6544 } else { 6545 r.append(' '); 6546 } 6547 r.append(p.info.name); 6548 } 6549 } 6550 if (r != null) { 6551 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 6552 } 6553 6554 N = pkg.services.size(); 6555 r = null; 6556 for (i=0; i<N; i++) { 6557 PackageParser.Service s = pkg.services.get(i); 6558 mServices.removeService(s); 6559 if (chatty) { 6560 if (r == null) { 6561 r = new StringBuilder(256); 6562 } else { 6563 r.append(' '); 6564 } 6565 r.append(s.info.name); 6566 } 6567 } 6568 if (r != null) { 6569 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 6570 } 6571 6572 N = pkg.receivers.size(); 6573 r = null; 6574 for (i=0; i<N; i++) { 6575 PackageParser.Activity a = pkg.receivers.get(i); 6576 mReceivers.removeActivity(a, "receiver"); 6577 if (DEBUG_REMOVE && chatty) { 6578 if (r == null) { 6579 r = new StringBuilder(256); 6580 } else { 6581 r.append(' '); 6582 } 6583 r.append(a.info.name); 6584 } 6585 } 6586 if (r != null) { 6587 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 6588 } 6589 6590 N = pkg.activities.size(); 6591 r = null; 6592 for (i=0; i<N; i++) { 6593 PackageParser.Activity a = pkg.activities.get(i); 6594 mActivities.removeActivity(a, "activity"); 6595 if (DEBUG_REMOVE && chatty) { 6596 if (r == null) { 6597 r = new StringBuilder(256); 6598 } else { 6599 r.append(' '); 6600 } 6601 r.append(a.info.name); 6602 } 6603 } 6604 if (r != null) { 6605 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 6606 } 6607 6608 N = pkg.permissions.size(); 6609 r = null; 6610 for (i=0; i<N; i++) { 6611 PackageParser.Permission p = pkg.permissions.get(i); 6612 BasePermission bp = mSettings.mPermissions.get(p.info.name); 6613 if (bp == null) { 6614 bp = mSettings.mPermissionTrees.get(p.info.name); 6615 } 6616 if (bp != null && bp.perm == p) { 6617 bp.perm = null; 6618 if (DEBUG_REMOVE && chatty) { 6619 if (r == null) { 6620 r = new StringBuilder(256); 6621 } else { 6622 r.append(' '); 6623 } 6624 r.append(p.info.name); 6625 } 6626 } 6627 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6628 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 6629 if (appOpPerms != null) { 6630 appOpPerms.remove(pkg.packageName); 6631 } 6632 } 6633 } 6634 if (r != null) { 6635 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6636 } 6637 6638 N = pkg.requestedPermissions.size(); 6639 r = null; 6640 for (i=0; i<N; i++) { 6641 String perm = pkg.requestedPermissions.get(i); 6642 BasePermission bp = mSettings.mPermissions.get(perm); 6643 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6644 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 6645 if (appOpPerms != null) { 6646 appOpPerms.remove(pkg.packageName); 6647 if (appOpPerms.isEmpty()) { 6648 mAppOpPermissionPackages.remove(perm); 6649 } 6650 } 6651 } 6652 } 6653 if (r != null) { 6654 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6655 } 6656 6657 N = pkg.instrumentation.size(); 6658 r = null; 6659 for (i=0; i<N; i++) { 6660 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6661 mInstrumentation.remove(a.getComponentName()); 6662 if (DEBUG_REMOVE && chatty) { 6663 if (r == null) { 6664 r = new StringBuilder(256); 6665 } else { 6666 r.append(' '); 6667 } 6668 r.append(a.info.name); 6669 } 6670 } 6671 if (r != null) { 6672 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 6673 } 6674 6675 r = null; 6676 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6677 // Only system apps can hold shared libraries. 6678 if (pkg.libraryNames != null) { 6679 for (i=0; i<pkg.libraryNames.size(); i++) { 6680 String name = pkg.libraryNames.get(i); 6681 SharedLibraryEntry cur = mSharedLibraries.get(name); 6682 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 6683 mSharedLibraries.remove(name); 6684 if (DEBUG_REMOVE && chatty) { 6685 if (r == null) { 6686 r = new StringBuilder(256); 6687 } else { 6688 r.append(' '); 6689 } 6690 r.append(name); 6691 } 6692 } 6693 } 6694 } 6695 } 6696 if (r != null) { 6697 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 6698 } 6699 } 6700 6701 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 6702 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 6703 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 6704 return true; 6705 } 6706 } 6707 return false; 6708 } 6709 6710 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 6711 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 6712 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 6713 6714 private void updatePermissionsLPw(String changingPkg, 6715 PackageParser.Package pkgInfo, int flags) { 6716 // Make sure there are no dangling permission trees. 6717 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 6718 while (it.hasNext()) { 6719 final BasePermission bp = it.next(); 6720 if (bp.packageSetting == null) { 6721 // We may not yet have parsed the package, so just see if 6722 // we still know about its settings. 6723 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6724 } 6725 if (bp.packageSetting == null) { 6726 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 6727 + " from package " + bp.sourcePackage); 6728 it.remove(); 6729 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6730 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6731 Slog.i(TAG, "Removing old permission tree: " + bp.name 6732 + " from package " + bp.sourcePackage); 6733 flags |= UPDATE_PERMISSIONS_ALL; 6734 it.remove(); 6735 } 6736 } 6737 } 6738 6739 // Make sure all dynamic permissions have been assigned to a package, 6740 // and make sure there are no dangling permissions. 6741 it = mSettings.mPermissions.values().iterator(); 6742 while (it.hasNext()) { 6743 final BasePermission bp = it.next(); 6744 if (bp.type == BasePermission.TYPE_DYNAMIC) { 6745 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 6746 + bp.name + " pkg=" + bp.sourcePackage 6747 + " info=" + bp.pendingInfo); 6748 if (bp.packageSetting == null && bp.pendingInfo != null) { 6749 final BasePermission tree = findPermissionTreeLP(bp.name); 6750 if (tree != null && tree.perm != null) { 6751 bp.packageSetting = tree.packageSetting; 6752 bp.perm = new PackageParser.Permission(tree.perm.owner, 6753 new PermissionInfo(bp.pendingInfo)); 6754 bp.perm.info.packageName = tree.perm.info.packageName; 6755 bp.perm.info.name = bp.name; 6756 bp.uid = tree.uid; 6757 } 6758 } 6759 } 6760 if (bp.packageSetting == null) { 6761 // We may not yet have parsed the package, so just see if 6762 // we still know about its settings. 6763 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6764 } 6765 if (bp.packageSetting == null) { 6766 Slog.w(TAG, "Removing dangling permission: " + bp.name 6767 + " from package " + bp.sourcePackage); 6768 it.remove(); 6769 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6770 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6771 Slog.i(TAG, "Removing old permission: " + bp.name 6772 + " from package " + bp.sourcePackage); 6773 flags |= UPDATE_PERMISSIONS_ALL; 6774 it.remove(); 6775 } 6776 } 6777 } 6778 6779 // Now update the permissions for all packages, in particular 6780 // replace the granted permissions of the system packages. 6781 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 6782 for (PackageParser.Package pkg : mPackages.values()) { 6783 if (pkg != pkgInfo) { 6784 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0); 6785 } 6786 } 6787 } 6788 6789 if (pkgInfo != null) { 6790 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0); 6791 } 6792 } 6793 6794 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) { 6795 final PackageSetting ps = (PackageSetting) pkg.mExtras; 6796 if (ps == null) { 6797 return; 6798 } 6799 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 6800 HashSet<String> origPermissions = gp.grantedPermissions; 6801 boolean changedPermission = false; 6802 6803 if (replace) { 6804 ps.permissionsFixed = false; 6805 if (gp == ps) { 6806 origPermissions = new HashSet<String>(gp.grantedPermissions); 6807 gp.grantedPermissions.clear(); 6808 gp.gids = mGlobalGids; 6809 } 6810 } 6811 6812 if (gp.gids == null) { 6813 gp.gids = mGlobalGids; 6814 } 6815 6816 final int N = pkg.requestedPermissions.size(); 6817 for (int i=0; i<N; i++) { 6818 final String name = pkg.requestedPermissions.get(i); 6819 final boolean required = pkg.requestedPermissionsRequired.get(i); 6820 final BasePermission bp = mSettings.mPermissions.get(name); 6821 if (DEBUG_INSTALL) { 6822 if (gp != ps) { 6823 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 6824 } 6825 } 6826 6827 if (bp == null || bp.packageSetting == null) { 6828 Slog.w(TAG, "Unknown permission " + name 6829 + " in package " + pkg.packageName); 6830 continue; 6831 } 6832 6833 final String perm = bp.name; 6834 boolean allowed; 6835 boolean allowedSig = false; 6836 if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6837 // Keep track of app op permissions. 6838 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 6839 if (pkgs == null) { 6840 pkgs = new ArraySet<>(); 6841 mAppOpPermissionPackages.put(bp.name, pkgs); 6842 } 6843 pkgs.add(pkg.packageName); 6844 } 6845 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 6846 if (level == PermissionInfo.PROTECTION_NORMAL 6847 || level == PermissionInfo.PROTECTION_DANGEROUS) { 6848 // We grant a normal or dangerous permission if any of the following 6849 // are true: 6850 // 1) The permission is required 6851 // 2) The permission is optional, but was granted in the past 6852 // 3) The permission is optional, but was requested by an 6853 // app in /system (not /data) 6854 // 6855 // Otherwise, reject the permission. 6856 allowed = (required || origPermissions.contains(perm) 6857 || (isSystemApp(ps) && !isUpdatedSystemApp(ps))); 6858 } else if (bp.packageSetting == null) { 6859 // This permission is invalid; skip it. 6860 allowed = false; 6861 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 6862 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions); 6863 if (allowed) { 6864 allowedSig = true; 6865 } 6866 } else { 6867 allowed = false; 6868 } 6869 if (DEBUG_INSTALL) { 6870 if (gp != ps) { 6871 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 6872 } 6873 } 6874 if (allowed) { 6875 if (!isSystemApp(ps) && ps.permissionsFixed) { 6876 // If this is an existing, non-system package, then 6877 // we can't add any new permissions to it. 6878 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 6879 // Except... if this is a permission that was added 6880 // to the platform (note: need to only do this when 6881 // updating the platform). 6882 allowed = isNewPlatformPermissionForPackage(perm, pkg); 6883 } 6884 } 6885 if (allowed) { 6886 if (!gp.grantedPermissions.contains(perm)) { 6887 changedPermission = true; 6888 gp.grantedPermissions.add(perm); 6889 gp.gids = appendInts(gp.gids, bp.gids); 6890 } else if (!ps.haveGids) { 6891 gp.gids = appendInts(gp.gids, bp.gids); 6892 } 6893 } else { 6894 Slog.w(TAG, "Not granting permission " + perm 6895 + " to package " + pkg.packageName 6896 + " because it was previously installed without"); 6897 } 6898 } else { 6899 if (gp.grantedPermissions.remove(perm)) { 6900 changedPermission = true; 6901 gp.gids = removeInts(gp.gids, bp.gids); 6902 Slog.i(TAG, "Un-granting permission " + perm 6903 + " from package " + pkg.packageName 6904 + " (protectionLevel=" + bp.protectionLevel 6905 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6906 + ")"); 6907 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 6908 // Don't print warning for app op permissions, since it is fine for them 6909 // not to be granted, there is a UI for the user to decide. 6910 Slog.w(TAG, "Not granting permission " + perm 6911 + " to package " + pkg.packageName 6912 + " (protectionLevel=" + bp.protectionLevel 6913 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6914 + ")"); 6915 } 6916 } 6917 } 6918 6919 if ((changedPermission || replace) && !ps.permissionsFixed && 6920 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 6921 // This is the first that we have heard about this package, so the 6922 // permissions we have now selected are fixed until explicitly 6923 // changed. 6924 ps.permissionsFixed = true; 6925 } 6926 ps.haveGids = true; 6927 } 6928 6929 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 6930 boolean allowed = false; 6931 final int NP = PackageParser.NEW_PERMISSIONS.length; 6932 for (int ip=0; ip<NP; ip++) { 6933 final PackageParser.NewPermissionInfo npi 6934 = PackageParser.NEW_PERMISSIONS[ip]; 6935 if (npi.name.equals(perm) 6936 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 6937 allowed = true; 6938 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 6939 + pkg.packageName); 6940 break; 6941 } 6942 } 6943 return allowed; 6944 } 6945 6946 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 6947 BasePermission bp, HashSet<String> origPermissions) { 6948 boolean allowed; 6949 allowed = (compareSignatures( 6950 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 6951 == PackageManager.SIGNATURE_MATCH) 6952 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 6953 == PackageManager.SIGNATURE_MATCH); 6954 if (!allowed && (bp.protectionLevel 6955 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 6956 if (isSystemApp(pkg)) { 6957 // For updated system applications, a system permission 6958 // is granted only if it had been defined by the original application. 6959 if (isUpdatedSystemApp(pkg)) { 6960 final PackageSetting sysPs = mSettings 6961 .getDisabledSystemPkgLPr(pkg.packageName); 6962 final GrantedPermissions origGp = sysPs.sharedUser != null 6963 ? sysPs.sharedUser : sysPs; 6964 6965 if (origGp.grantedPermissions.contains(perm)) { 6966 // If the original was granted this permission, we take 6967 // that grant decision as read and propagate it to the 6968 // update. 6969 allowed = true; 6970 } else { 6971 // The system apk may have been updated with an older 6972 // version of the one on the data partition, but which 6973 // granted a new system permission that it didn't have 6974 // before. In this case we do want to allow the app to 6975 // now get the new permission if the ancestral apk is 6976 // privileged to get it. 6977 if (sysPs.pkg != null && sysPs.isPrivileged()) { 6978 for (int j=0; 6979 j<sysPs.pkg.requestedPermissions.size(); j++) { 6980 if (perm.equals( 6981 sysPs.pkg.requestedPermissions.get(j))) { 6982 allowed = true; 6983 break; 6984 } 6985 } 6986 } 6987 } 6988 } else { 6989 allowed = isPrivilegedApp(pkg); 6990 } 6991 } 6992 } 6993 if (!allowed && (bp.protectionLevel 6994 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 6995 // For development permissions, a development permission 6996 // is granted only if it was already granted. 6997 allowed = origPermissions.contains(perm); 6998 } 6999 return allowed; 7000 } 7001 7002 final class ActivityIntentResolver 7003 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 7004 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7005 boolean defaultOnly, int userId) { 7006 if (!sUserManager.exists(userId)) return null; 7007 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7008 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7009 } 7010 7011 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7012 int userId) { 7013 if (!sUserManager.exists(userId)) return null; 7014 mFlags = flags; 7015 return super.queryIntent(intent, resolvedType, 7016 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7017 } 7018 7019 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7020 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 7021 if (!sUserManager.exists(userId)) return null; 7022 if (packageActivities == null) { 7023 return null; 7024 } 7025 mFlags = flags; 7026 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7027 final int N = packageActivities.size(); 7028 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 7029 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 7030 7031 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 7032 for (int i = 0; i < N; ++i) { 7033 intentFilters = packageActivities.get(i).intents; 7034 if (intentFilters != null && intentFilters.size() > 0) { 7035 PackageParser.ActivityIntentInfo[] array = 7036 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 7037 intentFilters.toArray(array); 7038 listCut.add(array); 7039 } 7040 } 7041 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7042 } 7043 7044 public final void addActivity(PackageParser.Activity a, String type) { 7045 final boolean systemApp = isSystemApp(a.info.applicationInfo); 7046 mActivities.put(a.getComponentName(), a); 7047 if (DEBUG_SHOW_INFO) 7048 Log.v( 7049 TAG, " " + type + " " + 7050 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 7051 if (DEBUG_SHOW_INFO) 7052 Log.v(TAG, " Class=" + a.info.name); 7053 final int NI = a.intents.size(); 7054 for (int j=0; j<NI; j++) { 7055 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7056 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 7057 intent.setPriority(0); 7058 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 7059 + a.className + " with priority > 0, forcing to 0"); 7060 } 7061 if (DEBUG_SHOW_INFO) { 7062 Log.v(TAG, " IntentFilter:"); 7063 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7064 } 7065 if (!intent.debugCheck()) { 7066 Log.w(TAG, "==> For Activity " + a.info.name); 7067 } 7068 addFilter(intent); 7069 } 7070 } 7071 7072 public final void removeActivity(PackageParser.Activity a, String type) { 7073 mActivities.remove(a.getComponentName()); 7074 if (DEBUG_SHOW_INFO) { 7075 Log.v(TAG, " " + type + " " 7076 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 7077 : a.info.name) + ":"); 7078 Log.v(TAG, " Class=" + a.info.name); 7079 } 7080 final int NI = a.intents.size(); 7081 for (int j=0; j<NI; j++) { 7082 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7083 if (DEBUG_SHOW_INFO) { 7084 Log.v(TAG, " IntentFilter:"); 7085 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7086 } 7087 removeFilter(intent); 7088 } 7089 } 7090 7091 @Override 7092 protected boolean allowFilterResult( 7093 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 7094 ActivityInfo filterAi = filter.activity.info; 7095 for (int i=dest.size()-1; i>=0; i--) { 7096 ActivityInfo destAi = dest.get(i).activityInfo; 7097 if (destAi.name == filterAi.name 7098 && destAi.packageName == filterAi.packageName) { 7099 return false; 7100 } 7101 } 7102 return true; 7103 } 7104 7105 @Override 7106 protected ActivityIntentInfo[] newArray(int size) { 7107 return new ActivityIntentInfo[size]; 7108 } 7109 7110 @Override 7111 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 7112 if (!sUserManager.exists(userId)) return true; 7113 PackageParser.Package p = filter.activity.owner; 7114 if (p != null) { 7115 PackageSetting ps = (PackageSetting)p.mExtras; 7116 if (ps != null) { 7117 // System apps are never considered stopped for purposes of 7118 // filtering, because there may be no way for the user to 7119 // actually re-launch them. 7120 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 7121 && ps.getStopped(userId); 7122 } 7123 } 7124 return false; 7125 } 7126 7127 @Override 7128 protected boolean isPackageForFilter(String packageName, 7129 PackageParser.ActivityIntentInfo info) { 7130 return packageName.equals(info.activity.owner.packageName); 7131 } 7132 7133 @Override 7134 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7135 int match, int userId) { 7136 if (!sUserManager.exists(userId)) return null; 7137 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7138 return null; 7139 } 7140 final PackageParser.Activity activity = info.activity; 7141 if (mSafeMode && (activity.info.applicationInfo.flags 7142 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7143 return null; 7144 } 7145 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7146 if (ps == null) { 7147 return null; 7148 } 7149 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7150 ps.readUserState(userId), userId); 7151 if (ai == null) { 7152 return null; 7153 } 7154 final ResolveInfo res = new ResolveInfo(); 7155 res.activityInfo = ai; 7156 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7157 res.filter = info; 7158 } 7159 res.priority = info.getPriority(); 7160 res.preferredOrder = activity.owner.mPreferredOrder; 7161 //System.out.println("Result: " + res.activityInfo.className + 7162 // " = " + res.priority); 7163 res.match = match; 7164 res.isDefault = info.hasDefault; 7165 res.labelRes = info.labelRes; 7166 res.nonLocalizedLabel = info.nonLocalizedLabel; 7167 if (userNeedsBadging(userId)) { 7168 res.noResourceId = true; 7169 } else { 7170 res.icon = info.icon; 7171 } 7172 res.system = isSystemApp(res.activityInfo.applicationInfo); 7173 return res; 7174 } 7175 7176 @Override 7177 protected void sortResults(List<ResolveInfo> results) { 7178 Collections.sort(results, mResolvePrioritySorter); 7179 } 7180 7181 @Override 7182 protected void dumpFilter(PrintWriter out, String prefix, 7183 PackageParser.ActivityIntentInfo filter) { 7184 out.print(prefix); out.print( 7185 Integer.toHexString(System.identityHashCode(filter.activity))); 7186 out.print(' '); 7187 filter.activity.printComponentShortName(out); 7188 out.print(" filter "); 7189 out.println(Integer.toHexString(System.identityHashCode(filter))); 7190 } 7191 7192// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7193// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7194// final List<ResolveInfo> retList = Lists.newArrayList(); 7195// while (i.hasNext()) { 7196// final ResolveInfo resolveInfo = i.next(); 7197// if (isEnabledLP(resolveInfo.activityInfo)) { 7198// retList.add(resolveInfo); 7199// } 7200// } 7201// return retList; 7202// } 7203 7204 // Keys are String (activity class name), values are Activity. 7205 private final HashMap<ComponentName, PackageParser.Activity> mActivities 7206 = new HashMap<ComponentName, PackageParser.Activity>(); 7207 private int mFlags; 7208 } 7209 7210 private final class ServiceIntentResolver 7211 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 7212 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7213 boolean defaultOnly, int userId) { 7214 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7215 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7216 } 7217 7218 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7219 int userId) { 7220 if (!sUserManager.exists(userId)) return null; 7221 mFlags = flags; 7222 return super.queryIntent(intent, resolvedType, 7223 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7224 } 7225 7226 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7227 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 7228 if (!sUserManager.exists(userId)) return null; 7229 if (packageServices == null) { 7230 return null; 7231 } 7232 mFlags = flags; 7233 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7234 final int N = packageServices.size(); 7235 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 7236 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 7237 7238 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 7239 for (int i = 0; i < N; ++i) { 7240 intentFilters = packageServices.get(i).intents; 7241 if (intentFilters != null && intentFilters.size() > 0) { 7242 PackageParser.ServiceIntentInfo[] array = 7243 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 7244 intentFilters.toArray(array); 7245 listCut.add(array); 7246 } 7247 } 7248 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7249 } 7250 7251 public final void addService(PackageParser.Service s) { 7252 mServices.put(s.getComponentName(), s); 7253 if (DEBUG_SHOW_INFO) { 7254 Log.v(TAG, " " 7255 + (s.info.nonLocalizedLabel != null 7256 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7257 Log.v(TAG, " Class=" + s.info.name); 7258 } 7259 final int NI = s.intents.size(); 7260 int j; 7261 for (j=0; j<NI; j++) { 7262 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7263 if (DEBUG_SHOW_INFO) { 7264 Log.v(TAG, " IntentFilter:"); 7265 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7266 } 7267 if (!intent.debugCheck()) { 7268 Log.w(TAG, "==> For Service " + s.info.name); 7269 } 7270 addFilter(intent); 7271 } 7272 } 7273 7274 public final void removeService(PackageParser.Service s) { 7275 mServices.remove(s.getComponentName()); 7276 if (DEBUG_SHOW_INFO) { 7277 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 7278 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7279 Log.v(TAG, " Class=" + s.info.name); 7280 } 7281 final int NI = s.intents.size(); 7282 int j; 7283 for (j=0; j<NI; j++) { 7284 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7285 if (DEBUG_SHOW_INFO) { 7286 Log.v(TAG, " IntentFilter:"); 7287 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7288 } 7289 removeFilter(intent); 7290 } 7291 } 7292 7293 @Override 7294 protected boolean allowFilterResult( 7295 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 7296 ServiceInfo filterSi = filter.service.info; 7297 for (int i=dest.size()-1; i>=0; i--) { 7298 ServiceInfo destAi = dest.get(i).serviceInfo; 7299 if (destAi.name == filterSi.name 7300 && destAi.packageName == filterSi.packageName) { 7301 return false; 7302 } 7303 } 7304 return true; 7305 } 7306 7307 @Override 7308 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 7309 return new PackageParser.ServiceIntentInfo[size]; 7310 } 7311 7312 @Override 7313 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 7314 if (!sUserManager.exists(userId)) return true; 7315 PackageParser.Package p = filter.service.owner; 7316 if (p != null) { 7317 PackageSetting ps = (PackageSetting)p.mExtras; 7318 if (ps != null) { 7319 // System apps are never considered stopped for purposes of 7320 // filtering, because there may be no way for the user to 7321 // actually re-launch them. 7322 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7323 && ps.getStopped(userId); 7324 } 7325 } 7326 return false; 7327 } 7328 7329 @Override 7330 protected boolean isPackageForFilter(String packageName, 7331 PackageParser.ServiceIntentInfo info) { 7332 return packageName.equals(info.service.owner.packageName); 7333 } 7334 7335 @Override 7336 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 7337 int match, int userId) { 7338 if (!sUserManager.exists(userId)) return null; 7339 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 7340 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 7341 return null; 7342 } 7343 final PackageParser.Service service = info.service; 7344 if (mSafeMode && (service.info.applicationInfo.flags 7345 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7346 return null; 7347 } 7348 PackageSetting ps = (PackageSetting) service.owner.mExtras; 7349 if (ps == null) { 7350 return null; 7351 } 7352 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 7353 ps.readUserState(userId), userId); 7354 if (si == null) { 7355 return null; 7356 } 7357 final ResolveInfo res = new ResolveInfo(); 7358 res.serviceInfo = si; 7359 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7360 res.filter = filter; 7361 } 7362 res.priority = info.getPriority(); 7363 res.preferredOrder = service.owner.mPreferredOrder; 7364 //System.out.println("Result: " + res.activityInfo.className + 7365 // " = " + res.priority); 7366 res.match = match; 7367 res.isDefault = info.hasDefault; 7368 res.labelRes = info.labelRes; 7369 res.nonLocalizedLabel = info.nonLocalizedLabel; 7370 res.icon = info.icon; 7371 res.system = isSystemApp(res.serviceInfo.applicationInfo); 7372 return res; 7373 } 7374 7375 @Override 7376 protected void sortResults(List<ResolveInfo> results) { 7377 Collections.sort(results, mResolvePrioritySorter); 7378 } 7379 7380 @Override 7381 protected void dumpFilter(PrintWriter out, String prefix, 7382 PackageParser.ServiceIntentInfo filter) { 7383 out.print(prefix); out.print( 7384 Integer.toHexString(System.identityHashCode(filter.service))); 7385 out.print(' '); 7386 filter.service.printComponentShortName(out); 7387 out.print(" filter "); 7388 out.println(Integer.toHexString(System.identityHashCode(filter))); 7389 } 7390 7391// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7392// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7393// final List<ResolveInfo> retList = Lists.newArrayList(); 7394// while (i.hasNext()) { 7395// final ResolveInfo resolveInfo = (ResolveInfo) i; 7396// if (isEnabledLP(resolveInfo.serviceInfo)) { 7397// retList.add(resolveInfo); 7398// } 7399// } 7400// return retList; 7401// } 7402 7403 // Keys are String (activity class name), values are Activity. 7404 private final HashMap<ComponentName, PackageParser.Service> mServices 7405 = new HashMap<ComponentName, PackageParser.Service>(); 7406 private int mFlags; 7407 }; 7408 7409 private final class ProviderIntentResolver 7410 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 7411 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7412 boolean defaultOnly, int userId) { 7413 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7414 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7415 } 7416 7417 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7418 int userId) { 7419 if (!sUserManager.exists(userId)) 7420 return null; 7421 mFlags = flags; 7422 return super.queryIntent(intent, resolvedType, 7423 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7424 } 7425 7426 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7427 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 7428 if (!sUserManager.exists(userId)) 7429 return null; 7430 if (packageProviders == null) { 7431 return null; 7432 } 7433 mFlags = flags; 7434 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 7435 final int N = packageProviders.size(); 7436 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 7437 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 7438 7439 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 7440 for (int i = 0; i < N; ++i) { 7441 intentFilters = packageProviders.get(i).intents; 7442 if (intentFilters != null && intentFilters.size() > 0) { 7443 PackageParser.ProviderIntentInfo[] array = 7444 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 7445 intentFilters.toArray(array); 7446 listCut.add(array); 7447 } 7448 } 7449 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7450 } 7451 7452 public final void addProvider(PackageParser.Provider p) { 7453 if (mProviders.containsKey(p.getComponentName())) { 7454 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 7455 return; 7456 } 7457 7458 mProviders.put(p.getComponentName(), p); 7459 if (DEBUG_SHOW_INFO) { 7460 Log.v(TAG, " " 7461 + (p.info.nonLocalizedLabel != null 7462 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7463 Log.v(TAG, " Class=" + p.info.name); 7464 } 7465 final int NI = p.intents.size(); 7466 int j; 7467 for (j = 0; j < NI; j++) { 7468 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7469 if (DEBUG_SHOW_INFO) { 7470 Log.v(TAG, " IntentFilter:"); 7471 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7472 } 7473 if (!intent.debugCheck()) { 7474 Log.w(TAG, "==> For Provider " + p.info.name); 7475 } 7476 addFilter(intent); 7477 } 7478 } 7479 7480 public final void removeProvider(PackageParser.Provider p) { 7481 mProviders.remove(p.getComponentName()); 7482 if (DEBUG_SHOW_INFO) { 7483 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 7484 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7485 Log.v(TAG, " Class=" + p.info.name); 7486 } 7487 final int NI = p.intents.size(); 7488 int j; 7489 for (j = 0; j < NI; j++) { 7490 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7491 if (DEBUG_SHOW_INFO) { 7492 Log.v(TAG, " IntentFilter:"); 7493 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7494 } 7495 removeFilter(intent); 7496 } 7497 } 7498 7499 @Override 7500 protected boolean allowFilterResult( 7501 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 7502 ProviderInfo filterPi = filter.provider.info; 7503 for (int i = dest.size() - 1; i >= 0; i--) { 7504 ProviderInfo destPi = dest.get(i).providerInfo; 7505 if (destPi.name == filterPi.name 7506 && destPi.packageName == filterPi.packageName) { 7507 return false; 7508 } 7509 } 7510 return true; 7511 } 7512 7513 @Override 7514 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 7515 return new PackageParser.ProviderIntentInfo[size]; 7516 } 7517 7518 @Override 7519 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 7520 if (!sUserManager.exists(userId)) 7521 return true; 7522 PackageParser.Package p = filter.provider.owner; 7523 if (p != null) { 7524 PackageSetting ps = (PackageSetting) p.mExtras; 7525 if (ps != null) { 7526 // System apps are never considered stopped for purposes of 7527 // filtering, because there may be no way for the user to 7528 // actually re-launch them. 7529 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7530 && ps.getStopped(userId); 7531 } 7532 } 7533 return false; 7534 } 7535 7536 @Override 7537 protected boolean isPackageForFilter(String packageName, 7538 PackageParser.ProviderIntentInfo info) { 7539 return packageName.equals(info.provider.owner.packageName); 7540 } 7541 7542 @Override 7543 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 7544 int match, int userId) { 7545 if (!sUserManager.exists(userId)) 7546 return null; 7547 final PackageParser.ProviderIntentInfo info = filter; 7548 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 7549 return null; 7550 } 7551 final PackageParser.Provider provider = info.provider; 7552 if (mSafeMode && (provider.info.applicationInfo.flags 7553 & ApplicationInfo.FLAG_SYSTEM) == 0) { 7554 return null; 7555 } 7556 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 7557 if (ps == null) { 7558 return null; 7559 } 7560 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 7561 ps.readUserState(userId), userId); 7562 if (pi == null) { 7563 return null; 7564 } 7565 final ResolveInfo res = new ResolveInfo(); 7566 res.providerInfo = pi; 7567 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 7568 res.filter = filter; 7569 } 7570 res.priority = info.getPriority(); 7571 res.preferredOrder = provider.owner.mPreferredOrder; 7572 res.match = match; 7573 res.isDefault = info.hasDefault; 7574 res.labelRes = info.labelRes; 7575 res.nonLocalizedLabel = info.nonLocalizedLabel; 7576 res.icon = info.icon; 7577 res.system = isSystemApp(res.providerInfo.applicationInfo); 7578 return res; 7579 } 7580 7581 @Override 7582 protected void sortResults(List<ResolveInfo> results) { 7583 Collections.sort(results, mResolvePrioritySorter); 7584 } 7585 7586 @Override 7587 protected void dumpFilter(PrintWriter out, String prefix, 7588 PackageParser.ProviderIntentInfo filter) { 7589 out.print(prefix); 7590 out.print( 7591 Integer.toHexString(System.identityHashCode(filter.provider))); 7592 out.print(' '); 7593 filter.provider.printComponentShortName(out); 7594 out.print(" filter "); 7595 out.println(Integer.toHexString(System.identityHashCode(filter))); 7596 } 7597 7598 private final HashMap<ComponentName, PackageParser.Provider> mProviders 7599 = new HashMap<ComponentName, PackageParser.Provider>(); 7600 private int mFlags; 7601 }; 7602 7603 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 7604 new Comparator<ResolveInfo>() { 7605 public int compare(ResolveInfo r1, ResolveInfo r2) { 7606 int v1 = r1.priority; 7607 int v2 = r2.priority; 7608 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 7609 if (v1 != v2) { 7610 return (v1 > v2) ? -1 : 1; 7611 } 7612 v1 = r1.preferredOrder; 7613 v2 = r2.preferredOrder; 7614 if (v1 != v2) { 7615 return (v1 > v2) ? -1 : 1; 7616 } 7617 if (r1.isDefault != r2.isDefault) { 7618 return r1.isDefault ? -1 : 1; 7619 } 7620 v1 = r1.match; 7621 v2 = r2.match; 7622 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 7623 if (v1 != v2) { 7624 return (v1 > v2) ? -1 : 1; 7625 } 7626 if (r1.system != r2.system) { 7627 return r1.system ? -1 : 1; 7628 } 7629 return 0; 7630 } 7631 }; 7632 7633 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 7634 new Comparator<ProviderInfo>() { 7635 public int compare(ProviderInfo p1, ProviderInfo p2) { 7636 final int v1 = p1.initOrder; 7637 final int v2 = p2.initOrder; 7638 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 7639 } 7640 }; 7641 7642 static final void sendPackageBroadcast(String action, String pkg, 7643 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 7644 int[] userIds) { 7645 IActivityManager am = ActivityManagerNative.getDefault(); 7646 if (am != null) { 7647 try { 7648 if (userIds == null) { 7649 userIds = am.getRunningUserIds(); 7650 } 7651 for (int id : userIds) { 7652 final Intent intent = new Intent(action, 7653 pkg != null ? Uri.fromParts("package", pkg, null) : null); 7654 if (extras != null) { 7655 intent.putExtras(extras); 7656 } 7657 if (targetPkg != null) { 7658 intent.setPackage(targetPkg); 7659 } 7660 // Modify the UID when posting to other users 7661 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 7662 if (uid > 0 && UserHandle.getUserId(uid) != id) { 7663 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 7664 intent.putExtra(Intent.EXTRA_UID, uid); 7665 } 7666 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 7667 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 7668 if (DEBUG_BROADCASTS) { 7669 RuntimeException here = new RuntimeException("here"); 7670 here.fillInStackTrace(); 7671 Slog.d(TAG, "Sending to user " + id + ": " 7672 + intent.toShortString(false, true, false, false) 7673 + " " + intent.getExtras(), here); 7674 } 7675 am.broadcastIntent(null, intent, null, finishedReceiver, 7676 0, null, null, null, android.app.AppOpsManager.OP_NONE, 7677 finishedReceiver != null, false, id); 7678 } 7679 } catch (RemoteException ex) { 7680 } 7681 } 7682 } 7683 7684 /** 7685 * Check if the external storage media is available. This is true if there 7686 * is a mounted external storage medium or if the external storage is 7687 * emulated. 7688 */ 7689 private boolean isExternalMediaAvailable() { 7690 return mMediaMounted || Environment.isExternalStorageEmulated(); 7691 } 7692 7693 @Override 7694 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 7695 // writer 7696 synchronized (mPackages) { 7697 if (!isExternalMediaAvailable()) { 7698 // If the external storage is no longer mounted at this point, 7699 // the caller may not have been able to delete all of this 7700 // packages files and can not delete any more. Bail. 7701 return null; 7702 } 7703 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 7704 if (lastPackage != null) { 7705 pkgs.remove(lastPackage); 7706 } 7707 if (pkgs.size() > 0) { 7708 return pkgs.get(0); 7709 } 7710 } 7711 return null; 7712 } 7713 7714 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 7715 if (false) { 7716 RuntimeException here = new RuntimeException("here"); 7717 here.fillInStackTrace(); 7718 Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId 7719 + " andCode=" + andCode, here); 7720 } 7721 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, 7722 userId, andCode ? 1 : 0, packageName)); 7723 } 7724 7725 void startCleaningPackages() { 7726 // reader 7727 synchronized (mPackages) { 7728 if (!isExternalMediaAvailable()) { 7729 return; 7730 } 7731 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 7732 return; 7733 } 7734 } 7735 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 7736 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 7737 IActivityManager am = ActivityManagerNative.getDefault(); 7738 if (am != null) { 7739 try { 7740 am.startService(null, intent, null, UserHandle.USER_OWNER); 7741 } catch (RemoteException e) { 7742 } 7743 } 7744 } 7745 7746 @Override 7747 public void installPackage(String originPath, IPackageInstallObserver2 observer, int flags, 7748 String installerPackageName, VerificationParams verificationParams, 7749 String packageAbiOverride) { 7750 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7751 null); 7752 7753 final File originFile = new File(originPath); 7754 final int uid = Binder.getCallingUid(); 7755 if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) { 7756 try { 7757 if (observer != null) { 7758 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 7759 } 7760 } catch (RemoteException re) { 7761 } 7762 return; 7763 } 7764 7765 UserHandle user; 7766 if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) { 7767 user = UserHandle.ALL; 7768 } else { 7769 user = new UserHandle(UserHandle.getUserId(uid)); 7770 } 7771 7772 final int filteredFlags; 7773 if (uid == Process.SHELL_UID || uid == 0) { 7774 if (DEBUG_INSTALL) { 7775 Slog.v(TAG, "Install from ADB"); 7776 } 7777 filteredFlags = flags | PackageManager.INSTALL_FROM_ADB; 7778 } else { 7779 filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB; 7780 } 7781 7782 verificationParams.setInstallerUid(uid); 7783 7784 final Message msg = mHandler.obtainMessage(INIT_COPY); 7785 msg.obj = new InstallParams(originFile, null, false, observer, filteredFlags, 7786 installerPackageName, verificationParams, user, packageAbiOverride); 7787 mHandler.sendMessage(msg); 7788 } 7789 7790 void installStage(String packageName, File stagedDir, String stagedCid, 7791 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 7792 String installerPackageName, int installerUid, UserHandle user) { 7793 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 7794 params.referrerUri, installerUid, null); 7795 7796 final Message msg = mHandler.obtainMessage(INIT_COPY); 7797 msg.obj = new InstallParams(stagedDir, stagedCid, true, observer, params.installFlags, 7798 installerPackageName, verifParams, user, params.abiOverride); 7799 mHandler.sendMessage(msg); 7800 } 7801 7802 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 7803 Bundle extras = new Bundle(1); 7804 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 7805 7806 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 7807 packageName, extras, null, null, new int[] {userId}); 7808 try { 7809 IActivityManager am = ActivityManagerNative.getDefault(); 7810 final boolean isSystem = 7811 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 7812 if (isSystem && am.isUserRunning(userId, false)) { 7813 // The just-installed/enabled app is bundled on the system, so presumed 7814 // to be able to run automatically without needing an explicit launch. 7815 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 7816 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 7817 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 7818 .setPackage(packageName); 7819 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 7820 android.app.AppOpsManager.OP_NONE, false, false, userId); 7821 } 7822 } catch (RemoteException e) { 7823 // shouldn't happen 7824 Slog.w(TAG, "Unable to bootstrap installed package", e); 7825 } 7826 } 7827 7828 @Override 7829 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 7830 int userId) { 7831 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7832 PackageSetting pkgSetting; 7833 final int uid = Binder.getCallingUid(); 7834 if (UserHandle.getUserId(uid) != userId) { 7835 mContext.enforceCallingOrSelfPermission( 7836 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 7837 "setApplicationHiddenSetting for user " + userId); 7838 } 7839 7840 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 7841 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 7842 return false; 7843 } 7844 7845 long callingId = Binder.clearCallingIdentity(); 7846 try { 7847 boolean sendAdded = false; 7848 boolean sendRemoved = false; 7849 // writer 7850 synchronized (mPackages) { 7851 pkgSetting = mSettings.mPackages.get(packageName); 7852 if (pkgSetting == null) { 7853 return false; 7854 } 7855 if (pkgSetting.getHidden(userId) != hidden) { 7856 pkgSetting.setHidden(hidden, userId); 7857 mSettings.writePackageRestrictionsLPr(userId); 7858 if (hidden) { 7859 sendRemoved = true; 7860 } else { 7861 sendAdded = true; 7862 } 7863 } 7864 } 7865 if (sendAdded) { 7866 sendPackageAddedForUser(packageName, pkgSetting, userId); 7867 return true; 7868 } 7869 if (sendRemoved) { 7870 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 7871 "hiding pkg"); 7872 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 7873 } 7874 } finally { 7875 Binder.restoreCallingIdentity(callingId); 7876 } 7877 return false; 7878 } 7879 7880 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 7881 int userId) { 7882 final PackageRemovedInfo info = new PackageRemovedInfo(); 7883 info.removedPackage = packageName; 7884 info.removedUsers = new int[] {userId}; 7885 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 7886 info.sendBroadcast(false, false, false); 7887 } 7888 7889 /** 7890 * Returns true if application is not found or there was an error. Otherwise it returns 7891 * the hidden state of the package for the given user. 7892 */ 7893 @Override 7894 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 7895 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7896 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 7897 "getApplicationHidden for user " + userId); 7898 PackageSetting pkgSetting; 7899 long callingId = Binder.clearCallingIdentity(); 7900 try { 7901 // writer 7902 synchronized (mPackages) { 7903 pkgSetting = mSettings.mPackages.get(packageName); 7904 if (pkgSetting == null) { 7905 return true; 7906 } 7907 return pkgSetting.getHidden(userId); 7908 } 7909 } finally { 7910 Binder.restoreCallingIdentity(callingId); 7911 } 7912 } 7913 7914 /** 7915 * @hide 7916 */ 7917 @Override 7918 public int installExistingPackageAsUser(String packageName, int userId) { 7919 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7920 null); 7921 PackageSetting pkgSetting; 7922 final int uid = Binder.getCallingUid(); 7923 enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId); 7924 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 7925 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 7926 } 7927 7928 long callingId = Binder.clearCallingIdentity(); 7929 try { 7930 boolean sendAdded = false; 7931 Bundle extras = new Bundle(1); 7932 7933 // writer 7934 synchronized (mPackages) { 7935 pkgSetting = mSettings.mPackages.get(packageName); 7936 if (pkgSetting == null) { 7937 return PackageManager.INSTALL_FAILED_INVALID_URI; 7938 } 7939 if (!pkgSetting.getInstalled(userId)) { 7940 pkgSetting.setInstalled(true, userId); 7941 pkgSetting.setHidden(false, userId); 7942 mSettings.writePackageRestrictionsLPr(userId); 7943 sendAdded = true; 7944 } 7945 } 7946 7947 if (sendAdded) { 7948 sendPackageAddedForUser(packageName, pkgSetting, userId); 7949 } 7950 } finally { 7951 Binder.restoreCallingIdentity(callingId); 7952 } 7953 7954 return PackageManager.INSTALL_SUCCEEDED; 7955 } 7956 7957 boolean isUserRestricted(int userId, String restrictionKey) { 7958 Bundle restrictions = sUserManager.getUserRestrictions(userId); 7959 if (restrictions.getBoolean(restrictionKey, false)) { 7960 Log.w(TAG, "User is restricted: " + restrictionKey); 7961 return true; 7962 } 7963 return false; 7964 } 7965 7966 @Override 7967 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 7968 mContext.enforceCallingOrSelfPermission( 7969 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7970 "Only package verification agents can verify applications"); 7971 7972 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7973 final PackageVerificationResponse response = new PackageVerificationResponse( 7974 verificationCode, Binder.getCallingUid()); 7975 msg.arg1 = id; 7976 msg.obj = response; 7977 mHandler.sendMessage(msg); 7978 } 7979 7980 @Override 7981 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 7982 long millisecondsToDelay) { 7983 mContext.enforceCallingOrSelfPermission( 7984 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7985 "Only package verification agents can extend verification timeouts"); 7986 7987 final PackageVerificationState state = mPendingVerification.get(id); 7988 final PackageVerificationResponse response = new PackageVerificationResponse( 7989 verificationCodeAtTimeout, Binder.getCallingUid()); 7990 7991 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 7992 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 7993 } 7994 if (millisecondsToDelay < 0) { 7995 millisecondsToDelay = 0; 7996 } 7997 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 7998 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 7999 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 8000 } 8001 8002 if ((state != null) && !state.timeoutExtended()) { 8003 state.extendTimeout(); 8004 8005 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8006 msg.arg1 = id; 8007 msg.obj = response; 8008 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 8009 } 8010 } 8011 8012 private void broadcastPackageVerified(int verificationId, Uri packageUri, 8013 int verificationCode, UserHandle user) { 8014 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 8015 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 8016 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8017 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8018 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 8019 8020 mContext.sendBroadcastAsUser(intent, user, 8021 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 8022 } 8023 8024 private ComponentName matchComponentForVerifier(String packageName, 8025 List<ResolveInfo> receivers) { 8026 ActivityInfo targetReceiver = null; 8027 8028 final int NR = receivers.size(); 8029 for (int i = 0; i < NR; i++) { 8030 final ResolveInfo info = receivers.get(i); 8031 if (info.activityInfo == null) { 8032 continue; 8033 } 8034 8035 if (packageName.equals(info.activityInfo.packageName)) { 8036 targetReceiver = info.activityInfo; 8037 break; 8038 } 8039 } 8040 8041 if (targetReceiver == null) { 8042 return null; 8043 } 8044 8045 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8046 } 8047 8048 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8049 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8050 if (pkgInfo.verifiers.length == 0) { 8051 return null; 8052 } 8053 8054 final int N = pkgInfo.verifiers.length; 8055 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8056 for (int i = 0; i < N; i++) { 8057 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8058 8059 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8060 receivers); 8061 if (comp == null) { 8062 continue; 8063 } 8064 8065 final int verifierUid = getUidForVerifier(verifierInfo); 8066 if (verifierUid == -1) { 8067 continue; 8068 } 8069 8070 if (DEBUG_VERIFY) { 8071 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8072 + " with the correct signature"); 8073 } 8074 sufficientVerifiers.add(comp); 8075 verificationState.addSufficientVerifier(verifierUid); 8076 } 8077 8078 return sufficientVerifiers; 8079 } 8080 8081 private int getUidForVerifier(VerifierInfo verifierInfo) { 8082 synchronized (mPackages) { 8083 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8084 if (pkg == null) { 8085 return -1; 8086 } else if (pkg.mSignatures.length != 1) { 8087 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8088 + " has more than one signature; ignoring"); 8089 return -1; 8090 } 8091 8092 /* 8093 * If the public key of the package's signature does not match 8094 * our expected public key, then this is a different package and 8095 * we should skip. 8096 */ 8097 8098 final byte[] expectedPublicKey; 8099 try { 8100 final Signature verifierSig = pkg.mSignatures[0]; 8101 final PublicKey publicKey = verifierSig.getPublicKey(); 8102 expectedPublicKey = publicKey.getEncoded(); 8103 } catch (CertificateException e) { 8104 return -1; 8105 } 8106 8107 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8108 8109 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8110 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8111 + " does not have the expected public key; ignoring"); 8112 return -1; 8113 } 8114 8115 return pkg.applicationInfo.uid; 8116 } 8117 } 8118 8119 @Override 8120 public void finishPackageInstall(int token) { 8121 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8122 8123 if (DEBUG_INSTALL) { 8124 Slog.v(TAG, "BM finishing package install for " + token); 8125 } 8126 8127 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8128 mHandler.sendMessage(msg); 8129 } 8130 8131 /** 8132 * Get the verification agent timeout. 8133 * 8134 * @return verification timeout in milliseconds 8135 */ 8136 private long getVerificationTimeout() { 8137 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8138 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8139 DEFAULT_VERIFICATION_TIMEOUT); 8140 } 8141 8142 /** 8143 * Get the default verification agent response code. 8144 * 8145 * @return default verification response code 8146 */ 8147 private int getDefaultVerificationResponse() { 8148 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8149 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8150 DEFAULT_VERIFICATION_RESPONSE); 8151 } 8152 8153 /** 8154 * Check whether or not package verification has been enabled. 8155 * 8156 * @return true if verification should be performed 8157 */ 8158 private boolean isVerificationEnabled(int userId, int flags) { 8159 if (!DEFAULT_VERIFY_ENABLE) { 8160 return false; 8161 } 8162 8163 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 8164 8165 // Check if installing from ADB 8166 if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) { 8167 // Do not run verification in a test harness environment 8168 if (ActivityManager.isRunningInTestHarness()) { 8169 return false; 8170 } 8171 if (ensureVerifyAppsEnabled) { 8172 return true; 8173 } 8174 // Check if the developer does not want package verification for ADB installs 8175 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8176 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8177 return false; 8178 } 8179 } 8180 8181 if (ensureVerifyAppsEnabled) { 8182 return true; 8183 } 8184 8185 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8186 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8187 } 8188 8189 /** 8190 * Get the "allow unknown sources" setting. 8191 * 8192 * @return the current "allow unknown sources" setting 8193 */ 8194 private int getUnknownSourcesSettings() { 8195 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8196 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 8197 -1); 8198 } 8199 8200 @Override 8201 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 8202 final int uid = Binder.getCallingUid(); 8203 // writer 8204 synchronized (mPackages) { 8205 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 8206 if (targetPackageSetting == null) { 8207 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 8208 } 8209 8210 PackageSetting installerPackageSetting; 8211 if (installerPackageName != null) { 8212 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 8213 if (installerPackageSetting == null) { 8214 throw new IllegalArgumentException("Unknown installer package: " 8215 + installerPackageName); 8216 } 8217 } else { 8218 installerPackageSetting = null; 8219 } 8220 8221 Signature[] callerSignature; 8222 Object obj = mSettings.getUserIdLPr(uid); 8223 if (obj != null) { 8224 if (obj instanceof SharedUserSetting) { 8225 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 8226 } else if (obj instanceof PackageSetting) { 8227 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 8228 } else { 8229 throw new SecurityException("Bad object " + obj + " for uid " + uid); 8230 } 8231 } else { 8232 throw new SecurityException("Unknown calling uid " + uid); 8233 } 8234 8235 // Verify: can't set installerPackageName to a package that is 8236 // not signed with the same cert as the caller. 8237 if (installerPackageSetting != null) { 8238 if (compareSignatures(callerSignature, 8239 installerPackageSetting.signatures.mSignatures) 8240 != PackageManager.SIGNATURE_MATCH) { 8241 throw new SecurityException( 8242 "Caller does not have same cert as new installer package " 8243 + installerPackageName); 8244 } 8245 } 8246 8247 // Verify: if target already has an installer package, it must 8248 // be signed with the same cert as the caller. 8249 if (targetPackageSetting.installerPackageName != null) { 8250 PackageSetting setting = mSettings.mPackages.get( 8251 targetPackageSetting.installerPackageName); 8252 // If the currently set package isn't valid, then it's always 8253 // okay to change it. 8254 if (setting != null) { 8255 if (compareSignatures(callerSignature, 8256 setting.signatures.mSignatures) 8257 != PackageManager.SIGNATURE_MATCH) { 8258 throw new SecurityException( 8259 "Caller does not have same cert as old installer package " 8260 + targetPackageSetting.installerPackageName); 8261 } 8262 } 8263 } 8264 8265 // Okay! 8266 targetPackageSetting.installerPackageName = installerPackageName; 8267 scheduleWriteSettingsLocked(); 8268 } 8269 } 8270 8271 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 8272 // Queue up an async operation since the package installation may take a little while. 8273 mHandler.post(new Runnable() { 8274 public void run() { 8275 mHandler.removeCallbacks(this); 8276 // Result object to be returned 8277 PackageInstalledInfo res = new PackageInstalledInfo(); 8278 res.returnCode = currentStatus; 8279 res.uid = -1; 8280 res.pkg = null; 8281 res.removedInfo = new PackageRemovedInfo(); 8282 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 8283 args.doPreInstall(res.returnCode); 8284 synchronized (mInstallLock) { 8285 installPackageLI(args, true, res); 8286 } 8287 args.doPostInstall(res.returnCode, res.uid); 8288 } 8289 8290 // A restore should be performed at this point if (a) the install 8291 // succeeded, (b) the operation is not an update, and (c) the new 8292 // package has not opted out of backup participation. 8293 final boolean update = res.removedInfo.removedPackage != null; 8294 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 8295 boolean doRestore = !update 8296 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 8297 8298 // Set up the post-install work request bookkeeping. This will be used 8299 // and cleaned up by the post-install event handling regardless of whether 8300 // there's a restore pass performed. Token values are >= 1. 8301 int token; 8302 if (mNextInstallToken < 0) mNextInstallToken = 1; 8303 token = mNextInstallToken++; 8304 8305 PostInstallData data = new PostInstallData(args, res); 8306 mRunningInstalls.put(token, data); 8307 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 8308 8309 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 8310 // Pass responsibility to the Backup Manager. It will perform a 8311 // restore if appropriate, then pass responsibility back to the 8312 // Package Manager to run the post-install observer callbacks 8313 // and broadcasts. 8314 IBackupManager bm = IBackupManager.Stub.asInterface( 8315 ServiceManager.getService(Context.BACKUP_SERVICE)); 8316 if (bm != null) { 8317 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 8318 + " to BM for possible restore"); 8319 try { 8320 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 8321 } catch (RemoteException e) { 8322 // can't happen; the backup manager is local 8323 } catch (Exception e) { 8324 Slog.e(TAG, "Exception trying to enqueue restore", e); 8325 doRestore = false; 8326 } 8327 } else { 8328 Slog.e(TAG, "Backup Manager not found!"); 8329 doRestore = false; 8330 } 8331 } 8332 8333 if (!doRestore) { 8334 // No restore possible, or the Backup Manager was mysteriously not 8335 // available -- just fire the post-install work request directly. 8336 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 8337 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8338 mHandler.sendMessage(msg); 8339 } 8340 } 8341 }); 8342 } 8343 8344 private abstract class HandlerParams { 8345 private static final int MAX_RETRIES = 4; 8346 8347 /** 8348 * Number of times startCopy() has been attempted and had a non-fatal 8349 * error. 8350 */ 8351 private int mRetries = 0; 8352 8353 /** User handle for the user requesting the information or installation. */ 8354 private final UserHandle mUser; 8355 8356 HandlerParams(UserHandle user) { 8357 mUser = user; 8358 } 8359 8360 UserHandle getUser() { 8361 return mUser; 8362 } 8363 8364 final boolean startCopy() { 8365 boolean res; 8366 try { 8367 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 8368 8369 if (++mRetries > MAX_RETRIES) { 8370 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 8371 mHandler.sendEmptyMessage(MCS_GIVE_UP); 8372 handleServiceError(); 8373 return false; 8374 } else { 8375 handleStartCopy(); 8376 res = true; 8377 } 8378 } catch (RemoteException e) { 8379 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 8380 mHandler.sendEmptyMessage(MCS_RECONNECT); 8381 res = false; 8382 } 8383 handleReturnCode(); 8384 return res; 8385 } 8386 8387 final void serviceError() { 8388 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 8389 handleServiceError(); 8390 handleReturnCode(); 8391 } 8392 8393 abstract void handleStartCopy() throws RemoteException; 8394 abstract void handleServiceError(); 8395 abstract void handleReturnCode(); 8396 } 8397 8398 class MeasureParams extends HandlerParams { 8399 private final PackageStats mStats; 8400 private boolean mSuccess; 8401 8402 private final IPackageStatsObserver mObserver; 8403 8404 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 8405 super(new UserHandle(stats.userHandle)); 8406 mObserver = observer; 8407 mStats = stats; 8408 } 8409 8410 @Override 8411 public String toString() { 8412 return "MeasureParams{" 8413 + Integer.toHexString(System.identityHashCode(this)) 8414 + " " + mStats.packageName + "}"; 8415 } 8416 8417 @Override 8418 void handleStartCopy() throws RemoteException { 8419 synchronized (mInstallLock) { 8420 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 8421 } 8422 8423 if (mSuccess) { 8424 final boolean mounted; 8425 if (Environment.isExternalStorageEmulated()) { 8426 mounted = true; 8427 } else { 8428 final String status = Environment.getExternalStorageState(); 8429 mounted = (Environment.MEDIA_MOUNTED.equals(status) 8430 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 8431 } 8432 8433 if (mounted) { 8434 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 8435 8436 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 8437 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 8438 8439 mStats.externalDataSize = calculateDirectorySize(mContainerService, 8440 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 8441 8442 // Always subtract cache size, since it's a subdirectory 8443 mStats.externalDataSize -= mStats.externalCacheSize; 8444 8445 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 8446 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 8447 8448 mStats.externalObbSize = calculateDirectorySize(mContainerService, 8449 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 8450 } 8451 } 8452 } 8453 8454 @Override 8455 void handleReturnCode() { 8456 if (mObserver != null) { 8457 try { 8458 mObserver.onGetStatsCompleted(mStats, mSuccess); 8459 } catch (RemoteException e) { 8460 Slog.i(TAG, "Observer no longer exists."); 8461 } 8462 } 8463 } 8464 8465 @Override 8466 void handleServiceError() { 8467 Slog.e(TAG, "Could not measure application " + mStats.packageName 8468 + " external storage"); 8469 } 8470 } 8471 8472 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 8473 throws RemoteException { 8474 long result = 0; 8475 for (File path : paths) { 8476 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 8477 } 8478 return result; 8479 } 8480 8481 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 8482 for (File path : paths) { 8483 try { 8484 mcs.clearDirectory(path.getAbsolutePath()); 8485 } catch (RemoteException e) { 8486 } 8487 } 8488 } 8489 8490 class InstallParams extends HandlerParams { 8491 /** 8492 * Location where install is coming from, before it has been 8493 * copied/renamed into place. This could be a single monolithic APK 8494 * file, or a cluster directory. This location may be untrusted. 8495 */ 8496 final File originFile; 8497 final String originCid; 8498 8499 /** 8500 * Flag indicating that {@link #originFile} or {@link #originCid} has 8501 * already been staged, meaning downstream users don't need to 8502 * defensively copy the contents. 8503 */ 8504 boolean originStaged; 8505 8506 final IPackageInstallObserver2 observer; 8507 int flags; 8508 final String installerPackageName; 8509 final VerificationParams verificationParams; 8510 private InstallArgs mArgs; 8511 private int mRet; 8512 final String packageAbiOverride; 8513 boolean multiArch; 8514 8515 InstallParams(File originFile, String originCid, boolean originStaged, 8516 IPackageInstallObserver2 observer, int flags, String installerPackageName, 8517 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 8518 super(user); 8519 this.originFile = originFile; 8520 this.originCid = originCid; 8521 this.originStaged = originStaged; 8522 this.observer = observer; 8523 this.flags = flags; 8524 this.installerPackageName = installerPackageName; 8525 this.verificationParams = verificationParams; 8526 this.packageAbiOverride = packageAbiOverride; 8527 } 8528 8529 @Override 8530 public String toString() { 8531 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 8532 + " file=" + originFile + " cid=" + originCid + "}"; 8533 } 8534 8535 public ManifestDigest getManifestDigest() { 8536 if (verificationParams == null) { 8537 return null; 8538 } 8539 return verificationParams.getManifestDigest(); 8540 } 8541 8542 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) { 8543 String packageName = pkgLite.packageName; 8544 int installLocation = pkgLite.installLocation; 8545 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8546 // reader 8547 synchronized (mPackages) { 8548 PackageParser.Package pkg = mPackages.get(packageName); 8549 if (pkg != null) { 8550 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 8551 // Check for downgrading. 8552 if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 8553 if (pkgLite.versionCode < pkg.mVersionCode) { 8554 Slog.w(TAG, "Can't install update of " + packageName 8555 + " update version " + pkgLite.versionCode 8556 + " is older than installed version " 8557 + pkg.mVersionCode); 8558 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 8559 } 8560 } 8561 // Check for updated system application. 8562 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8563 if (onSd) { 8564 Slog.w(TAG, "Cannot install update to system app on sdcard"); 8565 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 8566 } 8567 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8568 } else { 8569 if (onSd) { 8570 // Install flag overrides everything. 8571 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8572 } 8573 // If current upgrade specifies particular preference 8574 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 8575 // Application explicitly specified internal. 8576 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8577 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 8578 // App explictly prefers external. Let policy decide 8579 } else { 8580 // Prefer previous location 8581 if (isExternal(pkg)) { 8582 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8583 } 8584 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8585 } 8586 } 8587 } else { 8588 // Invalid install. Return error code 8589 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 8590 } 8591 } 8592 } 8593 // All the special cases have been taken care of. 8594 // Return result based on recommended install location. 8595 if (onSd) { 8596 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8597 } 8598 return pkgLite.recommendedInstallLocation; 8599 } 8600 8601 /* 8602 * Invoke remote method to get package information and install 8603 * location values. Override install location based on default 8604 * policy if needed and then create install arguments based 8605 * on the install location. 8606 */ 8607 public void handleStartCopy() throws RemoteException { 8608 int ret = PackageManager.INSTALL_SUCCEEDED; 8609 8610 // If we're already staged, we've firmly committed to an install location 8611 if (originStaged) { 8612 if (originFile != null) { 8613 flags |= PackageManager.INSTALL_INTERNAL; 8614 flags &= ~PackageManager.INSTALL_EXTERNAL; 8615 } else if (originCid != null) { 8616 flags |= PackageManager.INSTALL_EXTERNAL; 8617 flags &= ~PackageManager.INSTALL_INTERNAL; 8618 } else { 8619 throw new IllegalStateException("Invalid stage location"); 8620 } 8621 } 8622 8623 final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8624 final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0; 8625 PackageInfoLite pkgLite = null; 8626 8627 if (onInt && onSd) { 8628 // Check if both bits are set. 8629 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 8630 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8631 } else { 8632 // Remote call to find out default install location 8633 final String originPath = originFile.getAbsolutePath(); 8634 pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags, 8635 packageAbiOverride); 8636 // Keep track of whether this package is a multiArch package until 8637 // we perform a full scan of it. We need to do this because we might 8638 // end up extracting the package shared libraries before we perform 8639 // a full scan. 8640 multiArch = pkgLite.multiArch; 8641 8642 /* 8643 * If we have too little free space, try to free cache 8644 * before giving up. 8645 */ 8646 if (!originStaged && pkgLite.recommendedInstallLocation 8647 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8648 // TODO: focus freeing disk space on the target device 8649 final StorageManager storage = StorageManager.from(mContext); 8650 final long lowThreshold = storage.getStorageLowBytes( 8651 Environment.getDataDirectory()); 8652 8653 final long sizeBytes = mContainerService.calculateInstalledSize( 8654 originPath, isForwardLocked(), packageAbiOverride); 8655 8656 if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) { 8657 pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags, 8658 packageAbiOverride); 8659 } 8660 8661 /* 8662 * The cache free must have deleted the file we 8663 * downloaded to install. 8664 * 8665 * TODO: fix the "freeCache" call to not delete 8666 * the file we care about. 8667 */ 8668 if (pkgLite.recommendedInstallLocation 8669 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8670 pkgLite.recommendedInstallLocation 8671 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 8672 } 8673 } 8674 } 8675 8676 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8677 int loc = pkgLite.recommendedInstallLocation; 8678 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 8679 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8680 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 8681 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 8682 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8683 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8684 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 8685 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 8686 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8687 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 8688 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 8689 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 8690 } else { 8691 // Override with defaults if needed. 8692 loc = installLocationPolicy(pkgLite, flags); 8693 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 8694 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 8695 } else if (!onSd && !onInt) { 8696 // Override install location with flags 8697 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 8698 // Set the flag to install on external media. 8699 flags |= PackageManager.INSTALL_EXTERNAL; 8700 flags &= ~PackageManager.INSTALL_INTERNAL; 8701 } else { 8702 // Make sure the flag for installing on external 8703 // media is unset 8704 flags |= PackageManager.INSTALL_INTERNAL; 8705 flags &= ~PackageManager.INSTALL_EXTERNAL; 8706 } 8707 } 8708 } 8709 } 8710 8711 final InstallArgs args = createInstallArgs(this); 8712 mArgs = args; 8713 8714 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8715 /* 8716 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 8717 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 8718 */ 8719 int userIdentifier = getUser().getIdentifier(); 8720 if (userIdentifier == UserHandle.USER_ALL 8721 && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) { 8722 userIdentifier = UserHandle.USER_OWNER; 8723 } 8724 8725 /* 8726 * Determine if we have any installed package verifiers. If we 8727 * do, then we'll defer to them to verify the packages. 8728 */ 8729 final int requiredUid = mRequiredVerifierPackage == null ? -1 8730 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 8731 if (requiredUid != -1 && isVerificationEnabled(userIdentifier, flags)) { 8732 // TODO: send verifier the install session instead of uri 8733 final Intent verification = new Intent( 8734 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 8735 verification.setDataAndType(Uri.fromFile(originFile), PACKAGE_MIME_TYPE); 8736 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8737 8738 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 8739 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 8740 0 /* TODO: Which userId? */); 8741 8742 if (DEBUG_VERIFY) { 8743 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 8744 + verification.toString() + " with " + pkgLite.verifiers.length 8745 + " optional verifiers"); 8746 } 8747 8748 final int verificationId = mPendingVerificationToken++; 8749 8750 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8751 8752 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 8753 installerPackageName); 8754 8755 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags); 8756 8757 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 8758 pkgLite.packageName); 8759 8760 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 8761 pkgLite.versionCode); 8762 8763 if (verificationParams != null) { 8764 if (verificationParams.getVerificationURI() != null) { 8765 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 8766 verificationParams.getVerificationURI()); 8767 } 8768 if (verificationParams.getOriginatingURI() != null) { 8769 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 8770 verificationParams.getOriginatingURI()); 8771 } 8772 if (verificationParams.getReferrer() != null) { 8773 verification.putExtra(Intent.EXTRA_REFERRER, 8774 verificationParams.getReferrer()); 8775 } 8776 if (verificationParams.getOriginatingUid() >= 0) { 8777 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 8778 verificationParams.getOriginatingUid()); 8779 } 8780 if (verificationParams.getInstallerUid() >= 0) { 8781 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 8782 verificationParams.getInstallerUid()); 8783 } 8784 } 8785 8786 final PackageVerificationState verificationState = new PackageVerificationState( 8787 requiredUid, args); 8788 8789 mPendingVerification.append(verificationId, verificationState); 8790 8791 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 8792 receivers, verificationState); 8793 8794 /* 8795 * If any sufficient verifiers were listed in the package 8796 * manifest, attempt to ask them. 8797 */ 8798 if (sufficientVerifiers != null) { 8799 final int N = sufficientVerifiers.size(); 8800 if (N == 0) { 8801 Slog.i(TAG, "Additional verifiers required, but none installed."); 8802 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 8803 } else { 8804 for (int i = 0; i < N; i++) { 8805 final ComponentName verifierComponent = sufficientVerifiers.get(i); 8806 8807 final Intent sufficientIntent = new Intent(verification); 8808 sufficientIntent.setComponent(verifierComponent); 8809 8810 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 8811 } 8812 } 8813 } 8814 8815 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 8816 mRequiredVerifierPackage, receivers); 8817 if (ret == PackageManager.INSTALL_SUCCEEDED 8818 && mRequiredVerifierPackage != null) { 8819 /* 8820 * Send the intent to the required verification agent, 8821 * but only start the verification timeout after the 8822 * target BroadcastReceivers have run. 8823 */ 8824 verification.setComponent(requiredVerifierComponent); 8825 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 8826 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8827 new BroadcastReceiver() { 8828 @Override 8829 public void onReceive(Context context, Intent intent) { 8830 final Message msg = mHandler 8831 .obtainMessage(CHECK_PENDING_VERIFICATION); 8832 msg.arg1 = verificationId; 8833 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 8834 } 8835 }, null, 0, null, null); 8836 8837 /* 8838 * We don't want the copy to proceed until verification 8839 * succeeds, so null out this field. 8840 */ 8841 mArgs = null; 8842 } 8843 } else { 8844 /* 8845 * No package verification is enabled, so immediately start 8846 * the remote call to initiate copy using temporary file. 8847 */ 8848 ret = args.copyApk(mContainerService, true); 8849 } 8850 } 8851 8852 mRet = ret; 8853 } 8854 8855 @Override 8856 void handleReturnCode() { 8857 // If mArgs is null, then MCS couldn't be reached. When it 8858 // reconnects, it will try again to install. At that point, this 8859 // will succeed. 8860 if (mArgs != null) { 8861 processPendingInstall(mArgs, mRet); 8862 } 8863 } 8864 8865 @Override 8866 void handleServiceError() { 8867 mArgs = createInstallArgs(this); 8868 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8869 } 8870 8871 public boolean isForwardLocked() { 8872 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8873 } 8874 } 8875 8876 /* 8877 * Utility class used in movePackage api. 8878 * srcArgs and targetArgs are not set for invalid flags and make 8879 * sure to do null checks when invoking methods on them. 8880 * We probably want to return ErrorPrams for both failed installs 8881 * and moves. 8882 */ 8883 class MoveParams extends HandlerParams { 8884 final IPackageMoveObserver observer; 8885 final int flags; 8886 final String packageName; 8887 final InstallArgs srcArgs; 8888 final InstallArgs targetArgs; 8889 int uid; 8890 int mRet; 8891 8892 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags, 8893 String packageName, String[] instructionSets, int uid, UserHandle user, 8894 boolean isMultiArch) { 8895 super(user); 8896 this.srcArgs = srcArgs; 8897 this.observer = observer; 8898 this.flags = flags; 8899 this.packageName = packageName; 8900 this.uid = uid; 8901 if (srcArgs != null) { 8902 final String codePath = srcArgs.getCodePath(); 8903 targetArgs = createInstallArgsForMoveTarget(codePath, flags, packageName, 8904 instructionSets, isMultiArch); 8905 } else { 8906 targetArgs = null; 8907 } 8908 } 8909 8910 @Override 8911 public String toString() { 8912 return "MoveParams{" 8913 + Integer.toHexString(System.identityHashCode(this)) 8914 + " " + packageName + "}"; 8915 } 8916 8917 public void handleStartCopy() throws RemoteException { 8918 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8919 // Check for storage space on target medium 8920 if (!targetArgs.checkFreeStorage(mContainerService)) { 8921 Log.w(TAG, "Insufficient storage to install"); 8922 return; 8923 } 8924 8925 mRet = srcArgs.doPreCopy(); 8926 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8927 return; 8928 } 8929 8930 mRet = targetArgs.copyApk(mContainerService, false); 8931 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8932 srcArgs.doPostCopy(uid); 8933 return; 8934 } 8935 8936 mRet = srcArgs.doPostCopy(uid); 8937 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8938 return; 8939 } 8940 8941 mRet = targetArgs.doPreInstall(mRet); 8942 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8943 return; 8944 } 8945 8946 if (DEBUG_SD_INSTALL) { 8947 StringBuilder builder = new StringBuilder(); 8948 if (srcArgs != null) { 8949 builder.append("src: "); 8950 builder.append(srcArgs.getCodePath()); 8951 } 8952 if (targetArgs != null) { 8953 builder.append(" target : "); 8954 builder.append(targetArgs.getCodePath()); 8955 } 8956 Log.i(TAG, builder.toString()); 8957 } 8958 } 8959 8960 @Override 8961 void handleReturnCode() { 8962 targetArgs.doPostInstall(mRet, uid); 8963 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 8964 if (mRet == PackageManager.INSTALL_SUCCEEDED) { 8965 currentStatus = PackageManager.MOVE_SUCCEEDED; 8966 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){ 8967 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 8968 } 8969 processPendingMove(this, currentStatus); 8970 } 8971 8972 @Override 8973 void handleServiceError() { 8974 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8975 } 8976 } 8977 8978 /** 8979 * Used during creation of InstallArgs 8980 * 8981 * @param flags package installation flags 8982 * @return true if should be installed on external storage 8983 */ 8984 private static boolean installOnSd(int flags) { 8985 if ((flags & PackageManager.INSTALL_INTERNAL) != 0) { 8986 return false; 8987 } 8988 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) { 8989 return true; 8990 } 8991 return false; 8992 } 8993 8994 /** 8995 * Used during creation of InstallArgs 8996 * 8997 * @param flags package installation flags 8998 * @return true if should be installed as forward locked 8999 */ 9000 private static boolean installForwardLocked(int flags) { 9001 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9002 } 9003 9004 private InstallArgs createInstallArgs(InstallParams params) { 9005 // TODO: extend to support incoming zero-copy locations 9006 9007 if (installOnSd(params.flags) || params.isForwardLocked()) { 9008 return new AsecInstallArgs(params); 9009 } else { 9010 return new FileInstallArgs(params); 9011 } 9012 } 9013 9014 /** 9015 * Create args that describe an existing installed package. Typically used 9016 * when cleaning up old installs, or used as a move source. 9017 */ 9018 private InstallArgs createInstallArgsForExisting(int flags, String codePath, 9019 String resourcePath, String nativeLibraryRoot, String[] instructionSets, 9020 boolean isMultiArch) { 9021 final boolean isInAsec; 9022 if (installOnSd(flags)) { 9023 /* Apps on SD card are always in ASEC containers. */ 9024 isInAsec = true; 9025 } else if (installForwardLocked(flags) 9026 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 9027 /* 9028 * Forward-locked apps are only in ASEC containers if they're the 9029 * new style 9030 */ 9031 isInAsec = true; 9032 } else { 9033 isInAsec = false; 9034 } 9035 9036 if (isInAsec) { 9037 return new AsecInstallArgs(codePath, instructionSets, 9038 installOnSd(flags), installForwardLocked(flags), isMultiArch); 9039 } else { 9040 return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot, 9041 instructionSets, isMultiArch); 9042 } 9043 } 9044 9045 private InstallArgs createInstallArgsForMoveTarget(String codePath, int flags, String pkgName, 9046 String[] instructionSets, boolean isMultiArch) { 9047 final File codeFile = new File(codePath); 9048 if (installOnSd(flags) || installForwardLocked(flags)) { 9049 String cid = getNextCodePath(codePath, pkgName, "/" 9050 + AsecInstallArgs.RES_FILE_NAME); 9051 return new AsecInstallArgs(codeFile, cid, instructionSets, installOnSd(flags), 9052 installForwardLocked(flags), isMultiArch); 9053 } else { 9054 return new FileInstallArgs(codeFile, instructionSets, isMultiArch); 9055 } 9056 } 9057 9058 static abstract class InstallArgs { 9059 /** @see InstallParams#originFile */ 9060 final File originFile; 9061 /** @see InstallParams#originStaged */ 9062 final boolean originStaged; 9063 9064 // TODO: define inherit location 9065 9066 final IPackageInstallObserver2 observer; 9067 // Always refers to PackageManager flags only 9068 final int flags; 9069 final String installerPackageName; 9070 final ManifestDigest manifestDigest; 9071 final UserHandle user; 9072 final String abiOverride; 9073 final boolean multiArch; 9074 9075 // The list of instruction sets supported by this app. This is currently 9076 // only used during the rmdex() phase to clean up resources. We can get rid of this 9077 // if we move dex files under the common app path. 9078 /* nullable */ String[] instructionSets; 9079 9080 InstallArgs(File originFile, boolean originStaged, IPackageInstallObserver2 observer, 9081 int flags, String installerPackageName, ManifestDigest manifestDigest, 9082 UserHandle user, String[] instructionSets, 9083 String abiOverride, boolean multiArch) { 9084 this.originFile = originFile; 9085 this.originStaged = originStaged; 9086 this.flags = flags; 9087 this.observer = observer; 9088 this.installerPackageName = installerPackageName; 9089 this.manifestDigest = manifestDigest; 9090 this.user = user; 9091 this.instructionSets = instructionSets; 9092 this.abiOverride = abiOverride; 9093 this.multiArch = multiArch; 9094 } 9095 9096 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 9097 abstract int doPreInstall(int status); 9098 9099 /** 9100 * Rename package into final resting place. All paths on the given 9101 * scanned package should be updated to reflect the rename. 9102 */ 9103 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 9104 abstract int doPostInstall(int status, int uid); 9105 9106 /** @see PackageSettingBase#codePathString */ 9107 abstract String getCodePath(); 9108 /** @see PackageSettingBase#resourcePathString */ 9109 abstract String getResourcePath(); 9110 abstract String getLegacyNativeLibraryPath(); 9111 9112 // Need installer lock especially for dex file removal. 9113 abstract void cleanUpResourcesLI(); 9114 abstract boolean doPostDeleteLI(boolean delete); 9115 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9116 9117 /** 9118 * Called before the source arguments are copied. This is used mostly 9119 * for MoveParams when it needs to read the source file to put it in the 9120 * destination. 9121 */ 9122 int doPreCopy() { 9123 return PackageManager.INSTALL_SUCCEEDED; 9124 } 9125 9126 /** 9127 * Called after the source arguments are copied. This is used mostly for 9128 * MoveParams when it needs to read the source file to put it in the 9129 * destination. 9130 * 9131 * @return 9132 */ 9133 int doPostCopy(int uid) { 9134 return PackageManager.INSTALL_SUCCEEDED; 9135 } 9136 9137 protected boolean isFwdLocked() { 9138 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9139 } 9140 9141 UserHandle getUser() { 9142 return user; 9143 } 9144 } 9145 9146 /** 9147 * Logic to handle installation of non-ASEC applications, including copying 9148 * and renaming logic. 9149 */ 9150 class FileInstallArgs extends InstallArgs { 9151 private File codeFile; 9152 private File resourceFile; 9153 private File legacyNativeLibraryPath; 9154 9155 // Example topology: 9156 // /data/app/com.example/base.apk 9157 // /data/app/com.example/split_foo.apk 9158 // /data/app/com.example/lib/arm/libfoo.so 9159 // /data/app/com.example/lib/arm64/libfoo.so 9160 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 9161 9162 /** New install */ 9163 FileInstallArgs(InstallParams params) { 9164 super(params.originFile, params.originStaged, params.observer, params.flags, 9165 params.installerPackageName, params.getManifestDigest(), params.getUser(), 9166 null /* instruction sets */, params.packageAbiOverride, 9167 params.multiArch); 9168 if (isFwdLocked()) { 9169 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 9170 } 9171 } 9172 9173 /** Existing install */ 9174 FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath, 9175 String[] instructionSets, boolean isMultiArch) { 9176 super(null, false, null, 0, null, null, null, instructionSets, null, isMultiArch); 9177 this.codeFile = (codePath != null) ? new File(codePath) : null; 9178 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 9179 this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ? 9180 new File(legacyNativeLibraryPath) : null; 9181 } 9182 9183 /** New install from existing */ 9184 FileInstallArgs(File originFile, String[] instructionSets, boolean isMultiArch) { 9185 super(originFile, false, null, 0, null, null, null, instructionSets, null, 9186 isMultiArch); 9187 } 9188 9189 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9190 final long sizeBytes = imcs.calculateInstalledSize(originFile.getAbsolutePath(), 9191 isFwdLocked(), abiOverride); 9192 9193 final StorageManager storage = StorageManager.from(mContext); 9194 return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory())); 9195 } 9196 9197 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9198 int ret = PackageManager.INSTALL_SUCCEEDED; 9199 9200 if (originStaged) { 9201 Slog.d(TAG, originFile + " already staged; skipping copy"); 9202 codeFile = originFile; 9203 resourceFile = originFile; 9204 } else { 9205 try { 9206 final File tempDir = mInstallerService.allocateInternalStageDirLegacy(); 9207 codeFile = tempDir; 9208 resourceFile = tempDir; 9209 } catch (IOException e) { 9210 Slog.w(TAG, "Failed to create copy file: " + e); 9211 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9212 } 9213 9214 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 9215 @Override 9216 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 9217 if (!FileUtils.isValidExtFilename(name)) { 9218 throw new IllegalArgumentException("Invalid filename: " + name); 9219 } 9220 try { 9221 final File file = new File(codeFile, name); 9222 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 9223 O_RDWR | O_CREAT, 0644); 9224 Os.chmod(file.getAbsolutePath(), 0644); 9225 return new ParcelFileDescriptor(fd); 9226 } catch (ErrnoException e) { 9227 throw new RemoteException("Failed to open: " + e.getMessage()); 9228 } 9229 } 9230 }; 9231 9232 ret = imcs.copyPackage(originFile.getAbsolutePath(), target); 9233 if (ret != PackageManager.INSTALL_SUCCEEDED) { 9234 Slog.e(TAG, "Failed to copy package"); 9235 return ret; 9236 } 9237 } 9238 9239 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 9240 NativeLibraryHelper.Handle handle = null; 9241 try { 9242 handle = NativeLibraryHelper.Handle.create(codeFile); 9243 ret = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle, libraryRoot, 9244 abiOverride, multiArch); 9245 } catch (IOException e) { 9246 Slog.e(TAG, "Copying native libraries failed", e); 9247 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9248 } finally { 9249 IoUtils.closeQuietly(handle); 9250 } 9251 9252 return ret; 9253 } 9254 9255 int doPreInstall(int status) { 9256 if (status != PackageManager.INSTALL_SUCCEEDED) { 9257 cleanUp(); 9258 } 9259 return status; 9260 } 9261 9262 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9263 if (status != PackageManager.INSTALL_SUCCEEDED) { 9264 cleanUp(); 9265 return false; 9266 } else { 9267 final File beforeCodeFile = codeFile; 9268 final File afterCodeFile = getNextCodePath(pkg.packageName); 9269 9270 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 9271 try { 9272 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 9273 } catch (ErrnoException e) { 9274 Slog.d(TAG, "Failed to rename", e); 9275 return false; 9276 } 9277 9278 if (!SELinux.restoreconRecursive(afterCodeFile)) { 9279 Slog.d(TAG, "Failed to restorecon"); 9280 return false; 9281 } 9282 9283 // Reflect the rename internally 9284 codeFile = afterCodeFile; 9285 resourceFile = afterCodeFile; 9286 9287 // Reflect the rename in scanned details 9288 pkg.codePath = afterCodeFile.getAbsolutePath(); 9289 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9290 pkg.baseCodePath); 9291 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9292 pkg.splitCodePaths); 9293 9294 // Reflect the rename in app info 9295 pkg.applicationInfo.setCodePath(pkg.codePath); 9296 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9297 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9298 pkg.applicationInfo.setResourcePath(pkg.codePath); 9299 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9300 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9301 9302 return true; 9303 } 9304 } 9305 9306 int doPostInstall(int status, int uid) { 9307 if (status != PackageManager.INSTALL_SUCCEEDED) { 9308 cleanUp(); 9309 } 9310 return status; 9311 } 9312 9313 @Override 9314 String getCodePath() { 9315 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 9316 } 9317 9318 @Override 9319 String getResourcePath() { 9320 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 9321 } 9322 9323 @Override 9324 String getLegacyNativeLibraryPath() { 9325 return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null; 9326 } 9327 9328 private boolean cleanUp() { 9329 if (codeFile == null || !codeFile.exists()) { 9330 return false; 9331 } 9332 9333 if (codeFile.isDirectory()) { 9334 FileUtils.deleteContents(codeFile); 9335 } 9336 codeFile.delete(); 9337 9338 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 9339 resourceFile.delete(); 9340 } 9341 9342 if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) { 9343 if (!FileUtils.deleteContents(legacyNativeLibraryPath)) { 9344 Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath); 9345 } 9346 legacyNativeLibraryPath.delete(); 9347 } 9348 9349 return true; 9350 } 9351 9352 void cleanUpResourcesLI() { 9353 // Try enumerating all code paths before deleting 9354 List<String> allCodePaths = Collections.EMPTY_LIST; 9355 if (codeFile != null && codeFile.exists()) { 9356 try { 9357 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9358 allCodePaths = pkg.getAllCodePaths(); 9359 } catch (PackageParserException e) { 9360 // Ignored; we tried our best 9361 } 9362 } 9363 9364 cleanUp(); 9365 9366 if (!allCodePaths.isEmpty()) { 9367 if (instructionSets == null) { 9368 throw new IllegalStateException("instructionSet == null"); 9369 } 9370 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9371 for (String codePath : allCodePaths) { 9372 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9373 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9374 if (retCode < 0) { 9375 Slog.w(TAG, "Couldn't remove dex file for package: " 9376 + " at location " + codePath + ", retcode=" + retCode); 9377 // we don't consider this to be a failure of the core package deletion 9378 } 9379 } 9380 } 9381 } 9382 } 9383 9384 boolean doPostDeleteLI(boolean delete) { 9385 // XXX err, shouldn't we respect the delete flag? 9386 cleanUpResourcesLI(); 9387 return true; 9388 } 9389 } 9390 9391 private boolean isAsecExternal(String cid) { 9392 final String asecPath = PackageHelper.getSdFilesystem(cid); 9393 return !asecPath.startsWith(mAsecInternalPath); 9394 } 9395 9396 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 9397 PackageManagerException { 9398 if (copyRet < 0) { 9399 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 9400 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 9401 throw new PackageManagerException(copyRet, message); 9402 } 9403 } 9404 } 9405 9406 /** 9407 * Extract the MountService "container ID" from the full code path of an 9408 * .apk. 9409 */ 9410 static String cidFromCodePath(String fullCodePath) { 9411 int eidx = fullCodePath.lastIndexOf("/"); 9412 String subStr1 = fullCodePath.substring(0, eidx); 9413 int sidx = subStr1.lastIndexOf("/"); 9414 return subStr1.substring(sidx+1, eidx); 9415 } 9416 9417 /** 9418 * Logic to handle installation of ASEC applications, including copying and 9419 * renaming logic. 9420 */ 9421 class AsecInstallArgs extends InstallArgs { 9422 static final String RES_FILE_NAME = "pkg.apk"; 9423 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 9424 9425 String cid; 9426 String packagePath; 9427 String resourcePath; 9428 String legacyNativeLibraryDir; 9429 9430 /** New install */ 9431 AsecInstallArgs(InstallParams params) { 9432 super(params.originFile, params.originStaged, params.observer, params.flags, 9433 params.installerPackageName, params.getManifestDigest(), 9434 params.getUser(), null /* instruction sets */, 9435 params.packageAbiOverride, params.multiArch); 9436 } 9437 9438 /** Existing install */ 9439 AsecInstallArgs(String fullCodePath, String[] instructionSets, 9440 boolean isExternal, boolean isForwardLocked, boolean isMultiArch) { 9441 super(null, false, null, (isExternal ? INSTALL_EXTERNAL : 0) 9442 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9443 instructionSets, null, isMultiArch); 9444 // Hackily pretend we're still looking at a full code path 9445 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 9446 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 9447 } 9448 9449 // Extract cid from fullCodePath 9450 int eidx = fullCodePath.lastIndexOf("/"); 9451 String subStr1 = fullCodePath.substring(0, eidx); 9452 int sidx = subStr1.lastIndexOf("/"); 9453 cid = subStr1.substring(sidx+1, eidx); 9454 setMountPath(subStr1); 9455 } 9456 9457 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked, 9458 boolean isMultiArch) { 9459 super(null, false, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 9460 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9461 instructionSets, null, isMultiArch); 9462 this.cid = cid; 9463 setMountPath(PackageHelper.getSdDir(cid)); 9464 } 9465 9466 /** New install from existing */ 9467 AsecInstallArgs(File originPackageFile, String cid, String[] instructionSets, 9468 boolean isExternal, boolean isForwardLocked, boolean isMultiArch) { 9469 super(originPackageFile, false, null, (isExternal ? INSTALL_EXTERNAL : 0) 9470 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9471 instructionSets, null, isMultiArch); 9472 this.cid = cid; 9473 } 9474 9475 void createCopyFile() { 9476 cid = mInstallerService.allocateExternalStageCidLegacy(); 9477 } 9478 9479 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9480 final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(), 9481 abiOverride); 9482 9483 final File target; 9484 if (isExternal()) { 9485 target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory(); 9486 } else { 9487 target = Environment.getDataDirectory(); 9488 } 9489 9490 final StorageManager storage = StorageManager.from(mContext); 9491 return (sizeBytes <= storage.getStorageBytesUntilLow(target)); 9492 } 9493 9494 private final boolean isExternal() { 9495 return (flags & PackageManager.INSTALL_EXTERNAL) != 0; 9496 } 9497 9498 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9499 // TODO: if already staged, we only need to extract native code 9500 if (temp) { 9501 createCopyFile(); 9502 } else { 9503 /* 9504 * Pre-emptively destroy the container since it's destroyed if 9505 * copying fails due to it existing anyway. 9506 */ 9507 PackageHelper.destroySdDir(cid); 9508 } 9509 9510 final String newMountPath = imcs.copyPackageToContainer( 9511 originFile.getAbsolutePath(), cid, getEncryptKey(), isExternal(), 9512 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 9513 9514 if (newMountPath != null) { 9515 setMountPath(newMountPath); 9516 return PackageManager.INSTALL_SUCCEEDED; 9517 } else { 9518 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9519 } 9520 } 9521 9522 @Override 9523 String getCodePath() { 9524 return packagePath; 9525 } 9526 9527 @Override 9528 String getResourcePath() { 9529 return resourcePath; 9530 } 9531 9532 @Override 9533 String getLegacyNativeLibraryPath() { 9534 return legacyNativeLibraryDir; 9535 } 9536 9537 int doPreInstall(int status) { 9538 if (status != PackageManager.INSTALL_SUCCEEDED) { 9539 // Destroy container 9540 PackageHelper.destroySdDir(cid); 9541 } else { 9542 boolean mounted = PackageHelper.isContainerMounted(cid); 9543 if (!mounted) { 9544 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 9545 Process.SYSTEM_UID); 9546 if (newMountPath != null) { 9547 setMountPath(newMountPath); 9548 } else { 9549 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9550 } 9551 } 9552 } 9553 return status; 9554 } 9555 9556 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9557 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 9558 String newMountPath = null; 9559 if (PackageHelper.isContainerMounted(cid)) { 9560 // Unmount the container 9561 if (!PackageHelper.unMountSdDir(cid)) { 9562 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9563 return false; 9564 } 9565 } 9566 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9567 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9568 " which might be stale. Will try to clean up."); 9569 // Clean up the stale container and proceed to recreate. 9570 if (!PackageHelper.destroySdDir(newCacheId)) { 9571 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9572 return false; 9573 } 9574 // Successfully cleaned up stale container. Try to rename again. 9575 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9576 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9577 + " inspite of cleaning it up."); 9578 return false; 9579 } 9580 } 9581 if (!PackageHelper.isContainerMounted(newCacheId)) { 9582 Slog.w(TAG, "Mounting container " + newCacheId); 9583 newMountPath = PackageHelper.mountSdDir(newCacheId, 9584 getEncryptKey(), Process.SYSTEM_UID); 9585 } else { 9586 newMountPath = PackageHelper.getSdDir(newCacheId); 9587 } 9588 if (newMountPath == null) { 9589 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9590 return false; 9591 } 9592 Log.i(TAG, "Succesfully renamed " + cid + 9593 " to " + newCacheId + 9594 " at new path: " + newMountPath); 9595 cid = newCacheId; 9596 9597 final File beforeCodeFile = new File(packagePath); 9598 setMountPath(newMountPath); 9599 final File afterCodeFile = new File(packagePath); 9600 9601 // Reflect the rename in scanned details 9602 pkg.codePath = afterCodeFile.getAbsolutePath(); 9603 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9604 pkg.baseCodePath); 9605 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9606 pkg.splitCodePaths); 9607 9608 // Reflect the rename in app info 9609 pkg.applicationInfo.setCodePath(pkg.codePath); 9610 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9611 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9612 pkg.applicationInfo.setResourcePath(pkg.codePath); 9613 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9614 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9615 9616 return true; 9617 } 9618 9619 private void setMountPath(String mountPath) { 9620 final File mountFile = new File(mountPath); 9621 9622 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 9623 if (monolithicFile.exists()) { 9624 packagePath = monolithicFile.getAbsolutePath(); 9625 if (isFwdLocked()) { 9626 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 9627 } else { 9628 resourcePath = packagePath; 9629 } 9630 } else { 9631 packagePath = mountFile.getAbsolutePath(); 9632 resourcePath = packagePath; 9633 } 9634 9635 legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath(); 9636 } 9637 9638 int doPostInstall(int status, int uid) { 9639 if (status != PackageManager.INSTALL_SUCCEEDED) { 9640 cleanUp(); 9641 } else { 9642 final int groupOwner; 9643 final String protectedFile; 9644 if (isFwdLocked()) { 9645 groupOwner = UserHandle.getSharedAppGid(uid); 9646 protectedFile = RES_FILE_NAME; 9647 } else { 9648 groupOwner = -1; 9649 protectedFile = null; 9650 } 9651 9652 if (uid < Process.FIRST_APPLICATION_UID 9653 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9654 Slog.e(TAG, "Failed to finalize " + cid); 9655 PackageHelper.destroySdDir(cid); 9656 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9657 } 9658 9659 boolean mounted = PackageHelper.isContainerMounted(cid); 9660 if (!mounted) { 9661 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9662 } 9663 } 9664 return status; 9665 } 9666 9667 private void cleanUp() { 9668 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9669 9670 // Destroy secure container 9671 PackageHelper.destroySdDir(cid); 9672 } 9673 9674 private List<String> getAllCodePaths() { 9675 final File codeFile = new File(getCodePath()); 9676 if (codeFile != null && codeFile.exists()) { 9677 try { 9678 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9679 return pkg.getAllCodePaths(); 9680 } catch (PackageParserException e) { 9681 // Ignored; we tried our best 9682 } 9683 } 9684 return Collections.EMPTY_LIST; 9685 } 9686 9687 void cleanUpResourcesLI() { 9688 // Enumerate all code paths before deleting 9689 cleanUpResourcesLI(getAllCodePaths()); 9690 } 9691 9692 private void cleanUpResourcesLI(List<String> allCodePaths) { 9693 cleanUp(); 9694 9695 if (!allCodePaths.isEmpty()) { 9696 if (instructionSets == null) { 9697 throw new IllegalStateException("instructionSet == null"); 9698 } 9699 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9700 for (String codePath : allCodePaths) { 9701 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9702 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9703 if (retCode < 0) { 9704 Slog.w(TAG, "Couldn't remove dex file for package: " 9705 + " at location " + codePath + ", retcode=" + retCode); 9706 // we don't consider this to be a failure of the core package deletion 9707 } 9708 } 9709 } 9710 } 9711 } 9712 9713 boolean matchContainer(String app) { 9714 if (cid.startsWith(app)) { 9715 return true; 9716 } 9717 return false; 9718 } 9719 9720 String getPackageName() { 9721 return getAsecPackageName(cid); 9722 } 9723 9724 boolean doPostDeleteLI(boolean delete) { 9725 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 9726 final List<String> allCodePaths = getAllCodePaths(); 9727 boolean mounted = PackageHelper.isContainerMounted(cid); 9728 if (mounted) { 9729 // Unmount first 9730 if (PackageHelper.unMountSdDir(cid)) { 9731 mounted = false; 9732 } 9733 } 9734 if (!mounted && delete) { 9735 cleanUpResourcesLI(allCodePaths); 9736 } 9737 return !mounted; 9738 } 9739 9740 @Override 9741 int doPreCopy() { 9742 if (isFwdLocked()) { 9743 if (!PackageHelper.fixSdPermissions(cid, 9744 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 9745 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9746 } 9747 } 9748 9749 return PackageManager.INSTALL_SUCCEEDED; 9750 } 9751 9752 @Override 9753 int doPostCopy(int uid) { 9754 if (isFwdLocked()) { 9755 if (uid < Process.FIRST_APPLICATION_UID 9756 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 9757 RES_FILE_NAME)) { 9758 Slog.e(TAG, "Failed to finalize " + cid); 9759 PackageHelper.destroySdDir(cid); 9760 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9761 } 9762 } 9763 9764 return PackageManager.INSTALL_SUCCEEDED; 9765 } 9766 } 9767 9768 static String getAsecPackageName(String packageCid) { 9769 int idx = packageCid.lastIndexOf("-"); 9770 if (idx == -1) { 9771 return packageCid; 9772 } 9773 return packageCid.substring(0, idx); 9774 } 9775 9776 // Utility method used to create code paths based on package name and available index. 9777 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 9778 String idxStr = ""; 9779 int idx = 1; 9780 // Fall back to default value of idx=1 if prefix is not 9781 // part of oldCodePath 9782 if (oldCodePath != null) { 9783 String subStr = oldCodePath; 9784 // Drop the suffix right away 9785 if (suffix != null && subStr.endsWith(suffix)) { 9786 subStr = subStr.substring(0, subStr.length() - suffix.length()); 9787 } 9788 // If oldCodePath already contains prefix find out the 9789 // ending index to either increment or decrement. 9790 int sidx = subStr.lastIndexOf(prefix); 9791 if (sidx != -1) { 9792 subStr = subStr.substring(sidx + prefix.length()); 9793 if (subStr != null) { 9794 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 9795 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 9796 } 9797 try { 9798 idx = Integer.parseInt(subStr); 9799 if (idx <= 1) { 9800 idx++; 9801 } else { 9802 idx--; 9803 } 9804 } catch(NumberFormatException e) { 9805 } 9806 } 9807 } 9808 } 9809 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 9810 return prefix + idxStr; 9811 } 9812 9813 private File getNextCodePath(String packageName) { 9814 int suffix = 1; 9815 File result; 9816 do { 9817 result = new File(mAppInstallDir, packageName + "-" + suffix); 9818 suffix++; 9819 } while (result.exists()); 9820 return result; 9821 } 9822 9823 // Utility method used to ignore ADD/REMOVE events 9824 // by directory observer. 9825 private static boolean ignoreCodePath(String fullPathStr) { 9826 String apkName = deriveCodePathName(fullPathStr); 9827 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 9828 if (idx != -1 && ((idx+1) < apkName.length())) { 9829 // Make sure the package ends with a numeral 9830 String version = apkName.substring(idx+1); 9831 try { 9832 Integer.parseInt(version); 9833 return true; 9834 } catch (NumberFormatException e) {} 9835 } 9836 return false; 9837 } 9838 9839 // Utility method that returns the relative package path with respect 9840 // to the installation directory. Like say for /data/data/com.test-1.apk 9841 // string com.test-1 is returned. 9842 static String deriveCodePathName(String codePath) { 9843 if (codePath == null) { 9844 return null; 9845 } 9846 final File codeFile = new File(codePath); 9847 final String name = codeFile.getName(); 9848 if (codeFile.isDirectory()) { 9849 return name; 9850 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 9851 final int lastDot = name.lastIndexOf('.'); 9852 return name.substring(0, lastDot); 9853 } else { 9854 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 9855 return null; 9856 } 9857 } 9858 9859 class PackageInstalledInfo { 9860 String name; 9861 int uid; 9862 // The set of users that originally had this package installed. 9863 int[] origUsers; 9864 // The set of users that now have this package installed. 9865 int[] newUsers; 9866 PackageParser.Package pkg; 9867 int returnCode; 9868 String returnMsg; 9869 PackageRemovedInfo removedInfo; 9870 9871 public void setError(int code, String msg) { 9872 returnCode = code; 9873 returnMsg = msg; 9874 Slog.w(TAG, msg); 9875 } 9876 9877 public void setError(String msg, PackageParserException e) { 9878 returnCode = e.error; 9879 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9880 Slog.w(TAG, msg, e); 9881 } 9882 9883 public void setError(String msg, PackageManagerException e) { 9884 returnCode = e.error; 9885 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9886 Slog.w(TAG, msg, e); 9887 } 9888 9889 // In some error cases we want to convey more info back to the observer 9890 String origPackage; 9891 String origPermission; 9892 } 9893 9894 /* 9895 * Install a non-existing package. 9896 */ 9897 private void installNewPackageLI(PackageParser.Package pkg, 9898 int parseFlags, int scanMode, UserHandle user, 9899 String installerPackageName, PackageInstalledInfo res) { 9900 // Remember this for later, in case we need to rollback this install 9901 String pkgName = pkg.packageName; 9902 9903 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 9904 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 9905 synchronized(mPackages) { 9906 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 9907 // A package with the same name is already installed, though 9908 // it has been renamed to an older name. The package we 9909 // are trying to install should be installed as an update to 9910 // the existing one, but that has not been requested, so bail. 9911 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9912 + " without first uninstalling package running as " 9913 + mSettings.mRenamedPackages.get(pkgName)); 9914 return; 9915 } 9916 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.codePath)) { 9917 // Don't allow installation over an existing package with the same name. 9918 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9919 + " without first uninstalling."); 9920 return; 9921 } 9922 } 9923 9924 try { 9925 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode, 9926 System.currentTimeMillis(), user); 9927 9928 updateSettingsLI(newPackage, installerPackageName, null, null, res); 9929 // delete the partially installed application. the data directory will have to be 9930 // restored if it was already existing 9931 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9932 // remove package from internal structures. Note that we want deletePackageX to 9933 // delete the package data and cache directories that it created in 9934 // scanPackageLocked, unless those directories existed before we even tried to 9935 // install. 9936 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 9937 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 9938 res.removedInfo, true); 9939 } 9940 9941 } catch (PackageManagerException e) { 9942 res.setError("Package couldn't be installed in " + pkg.codePath, e); 9943 } 9944 } 9945 9946 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 9947 // Upgrade keysets are being used. Determine if new package has a superset of the 9948 // required keys. 9949 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 9950 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9951 for (int i = 0; i < upgradeKeySets.length; i++) { 9952 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 9953 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 9954 return true; 9955 } 9956 } 9957 return false; 9958 } 9959 9960 private void replacePackageLI(PackageParser.Package pkg, 9961 int parseFlags, int scanMode, UserHandle user, 9962 String installerPackageName, PackageInstalledInfo res) { 9963 PackageParser.Package oldPackage; 9964 String pkgName = pkg.packageName; 9965 int[] allUsers; 9966 boolean[] perUserInstalled; 9967 9968 // First find the old package info and check signatures 9969 synchronized(mPackages) { 9970 oldPackage = mPackages.get(pkgName); 9971 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 9972 PackageSetting ps = mSettings.mPackages.get(pkgName); 9973 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 9974 // default to original signature matching 9975 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 9976 != PackageManager.SIGNATURE_MATCH) { 9977 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9978 "New package has a different signature: " + pkgName); 9979 return; 9980 } 9981 } else { 9982 if(!checkUpgradeKeySetLP(ps, pkg)) { 9983 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9984 "New package not signed by keys specified by upgrade-keysets: " 9985 + pkgName); 9986 return; 9987 } 9988 } 9989 9990 // In case of rollback, remember per-user/profile install state 9991 allUsers = sUserManager.getUserIds(); 9992 perUserInstalled = new boolean[allUsers.length]; 9993 for (int i = 0; i < allUsers.length; i++) { 9994 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 9995 } 9996 } 9997 9998 boolean sysPkg = (isSystemApp(oldPackage)); 9999 if (sysPkg) { 10000 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 10001 user, allUsers, perUserInstalled, installerPackageName, res); 10002 } else { 10003 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 10004 user, allUsers, perUserInstalled, installerPackageName, res); 10005 } 10006 } 10007 10008 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 10009 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 10010 int[] allUsers, boolean[] perUserInstalled, 10011 String installerPackageName, PackageInstalledInfo res) { 10012 String pkgName = deletedPackage.packageName; 10013 boolean deletedPkg = true; 10014 boolean updatedSettings = false; 10015 10016 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 10017 + deletedPackage); 10018 long origUpdateTime; 10019 if (pkg.mExtras != null) { 10020 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 10021 } else { 10022 origUpdateTime = 0; 10023 } 10024 10025 // First delete the existing package while retaining the data directory 10026 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 10027 res.removedInfo, true)) { 10028 // If the existing package wasn't successfully deleted 10029 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 10030 deletedPkg = false; 10031 } else { 10032 // Successfully deleted the old package. Now proceed with re-installation 10033 deleteCodeCacheDirsLI(pkgName); 10034 try { 10035 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 10036 scanMode | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 10037 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10038 updatedSettings = true; 10039 } catch (PackageManagerException e) { 10040 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10041 } 10042 } 10043 10044 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10045 // remove package from internal structures. Note that we want deletePackageX to 10046 // delete the package data and cache directories that it created in 10047 // scanPackageLocked, unless those directories existed before we even tried to 10048 // install. 10049 if(updatedSettings) { 10050 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 10051 deletePackageLI( 10052 pkgName, null, true, allUsers, perUserInstalled, 10053 PackageManager.DELETE_KEEP_DATA, 10054 res.removedInfo, true); 10055 } 10056 // Since we failed to install the new package we need to restore the old 10057 // package that we deleted. 10058 if (deletedPkg) { 10059 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 10060 File restoreFile = new File(deletedPackage.codePath); 10061 // Parse old package 10062 boolean oldOnSd = isExternal(deletedPackage); 10063 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 10064 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) | 10065 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 10066 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE 10067 | SCAN_UPDATE_TIME; 10068 try { 10069 scanPackageLI(restoreFile, oldParseFlags, oldScanMode, origUpdateTime, null); 10070 } catch (PackageManagerException e) { 10071 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 10072 + e.getMessage()); 10073 return; 10074 } 10075 // Restore of old package succeeded. Update permissions. 10076 // writer 10077 synchronized (mPackages) { 10078 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 10079 UPDATE_PERMISSIONS_ALL); 10080 // can downgrade to reader 10081 mSettings.writeLPr(); 10082 } 10083 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 10084 } 10085 } 10086 } 10087 10088 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 10089 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 10090 int[] allUsers, boolean[] perUserInstalled, 10091 String installerPackageName, PackageInstalledInfo res) { 10092 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 10093 + ", old=" + deletedPackage); 10094 boolean updatedSettings = false; 10095 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING | 10096 PackageParser.PARSE_IS_SYSTEM; 10097 if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) { 10098 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10099 } 10100 String packageName = deletedPackage.packageName; 10101 if (packageName == null) { 10102 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10103 "Attempt to delete null packageName."); 10104 return; 10105 } 10106 PackageParser.Package oldPkg; 10107 PackageSetting oldPkgSetting; 10108 // reader 10109 synchronized (mPackages) { 10110 oldPkg = mPackages.get(packageName); 10111 oldPkgSetting = mSettings.mPackages.get(packageName); 10112 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 10113 (oldPkgSetting == null)) { 10114 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10115 "Couldn't find package:" + packageName + " information"); 10116 return; 10117 } 10118 } 10119 10120 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 10121 10122 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10123 res.removedInfo.removedPackage = packageName; 10124 // Remove existing system package 10125 removePackageLI(oldPkgSetting, true); 10126 // writer 10127 synchronized (mPackages) { 10128 if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) { 10129 // We didn't need to disable the .apk as a current system package, 10130 // which means we are replacing another update that is already 10131 // installed. We need to make sure to delete the older one's .apk. 10132 res.removedInfo.args = createInstallArgsForExisting(0, 10133 deletedPackage.applicationInfo.getCodePath(), 10134 deletedPackage.applicationInfo.getResourcePath(), 10135 deletedPackage.applicationInfo.nativeLibraryRootDir, 10136 getAppDexInstructionSets(deletedPackage.applicationInfo), 10137 isMultiArch(deletedPackage.applicationInfo)); 10138 } else { 10139 res.removedInfo.args = null; 10140 } 10141 } 10142 10143 // Successfully disabled the old package. Now proceed with re-installation 10144 deleteCodeCacheDirsLI(packageName); 10145 10146 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10147 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10148 10149 PackageParser.Package newPackage = null; 10150 try { 10151 newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user); 10152 if (newPackage.mExtras != null) { 10153 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 10154 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10155 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10156 10157 // is the update attempting to change shared user? that isn't going to work... 10158 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10159 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 10160 "Forbidding shared user change from " + oldPkgSetting.sharedUser 10161 + " to " + newPkgSetting.sharedUser); 10162 updatedSettings = true; 10163 } 10164 } 10165 10166 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10167 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10168 updatedSettings = true; 10169 } 10170 10171 } catch (PackageManagerException e) { 10172 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10173 } 10174 10175 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10176 // Re installation failed. Restore old information 10177 // Remove new pkg information 10178 if (newPackage != null) { 10179 removeInstalledPackageLI(newPackage, true); 10180 } 10181 // Add back the old system package 10182 try { 10183 scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user); 10184 } catch (PackageManagerException e) { 10185 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 10186 } 10187 // Restore the old system information in Settings 10188 synchronized(mPackages) { 10189 if (updatedSettings) { 10190 mSettings.enableSystemPackageLPw(packageName); 10191 mSettings.setInstallerPackageName(packageName, 10192 oldPkgSetting.installerPackageName); 10193 } 10194 mSettings.writeLPr(); 10195 } 10196 } 10197 } 10198 10199 // Utility method used to move dex files during install. 10200 private int moveDexFilesLI(String oldCodePath, PackageParser.Package newPackage) { 10201 // TODO: extend to move split APK dex files 10202 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) { 10203 final String[] instructionSets = getAppDexInstructionSets(newPackage.applicationInfo); 10204 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10205 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10206 int retCode = mInstaller.movedex(oldCodePath, newPackage.baseCodePath, 10207 dexCodeInstructionSet); 10208 if (retCode != 0) { 10209 /* 10210 * Programs may be lazily run through dexopt, so the 10211 * source may not exist. However, something seems to 10212 * have gone wrong, so note that dexopt needs to be 10213 * run again and remove the source file. In addition, 10214 * remove the target to make sure there isn't a stale 10215 * file from a previous version of the package. 10216 */ 10217 newPackage.mDexOptPerformed.clear(); 10218 mInstaller.rmdex(oldCodePath, dexCodeInstructionSet); 10219 mInstaller.rmdex(newPackage.baseCodePath, dexCodeInstructionSet); 10220 } 10221 } 10222 } 10223 return PackageManager.INSTALL_SUCCEEDED; 10224 } 10225 10226 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10227 int[] allUsers, boolean[] perUserInstalled, 10228 PackageInstalledInfo res) { 10229 String pkgName = newPackage.packageName; 10230 synchronized (mPackages) { 10231 //write settings. the installStatus will be incomplete at this stage. 10232 //note that the new package setting would have already been 10233 //added to mPackages. It hasn't been persisted yet. 10234 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10235 mSettings.writeLPr(); 10236 } 10237 10238 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10239 10240 synchronized (mPackages) { 10241 updatePermissionsLPw(newPackage.packageName, newPackage, 10242 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10243 ? UPDATE_PERMISSIONS_ALL : 0)); 10244 // For system-bundled packages, we assume that installing an upgraded version 10245 // of the package implies that the user actually wants to run that new code, 10246 // so we enable the package. 10247 if (isSystemApp(newPackage)) { 10248 // NB: implicit assumption that system package upgrades apply to all users 10249 if (DEBUG_INSTALL) { 10250 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10251 } 10252 PackageSetting ps = mSettings.mPackages.get(pkgName); 10253 if (ps != null) { 10254 if (res.origUsers != null) { 10255 for (int userHandle : res.origUsers) { 10256 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10257 userHandle, installerPackageName); 10258 } 10259 } 10260 // Also convey the prior install/uninstall state 10261 if (allUsers != null && perUserInstalled != null) { 10262 for (int i = 0; i < allUsers.length; i++) { 10263 if (DEBUG_INSTALL) { 10264 Slog.d(TAG, " user " + allUsers[i] 10265 + " => " + perUserInstalled[i]); 10266 } 10267 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10268 } 10269 // these install state changes will be persisted in the 10270 // upcoming call to mSettings.writeLPr(). 10271 } 10272 } 10273 } 10274 res.name = pkgName; 10275 res.uid = newPackage.applicationInfo.uid; 10276 res.pkg = newPackage; 10277 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10278 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10279 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10280 //to update install status 10281 mSettings.writeLPr(); 10282 } 10283 } 10284 10285 private void installPackageLI(InstallArgs args, boolean newInstall, PackageInstalledInfo res) { 10286 int pFlags = args.flags; 10287 String installerPackageName = args.installerPackageName; 10288 File tmpPackageFile = new File(args.getCodePath()); 10289 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10290 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0); 10291 boolean replace = false; 10292 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE 10293 | (newInstall ? SCAN_NEW_INSTALL : 0); 10294 // Result object to be returned 10295 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10296 10297 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10298 // Retrieve PackageSettings and parse package 10299 int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10300 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10301 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 10302 PackageParser pp = new PackageParser(); 10303 pp.setSeparateProcesses(mSeparateProcesses); 10304 pp.setDisplayMetrics(mMetrics); 10305 10306 final PackageParser.Package pkg; 10307 try { 10308 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 10309 } catch (PackageParserException e) { 10310 res.setError("Failed parse during installPackageLI", e); 10311 return; 10312 } 10313 10314 // Mark that we have an install time CPU ABI override. 10315 pkg.cpuAbiOverride = args.abiOverride; 10316 10317 String pkgName = res.name = pkg.packageName; 10318 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 10319 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) { 10320 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 10321 return; 10322 } 10323 } 10324 10325 try { 10326 pp.collectCertificates(pkg, parseFlags); 10327 pp.collectManifestDigest(pkg); 10328 } catch (PackageParserException e) { 10329 res.setError("Failed collect during installPackageLI", e); 10330 return; 10331 } 10332 10333 /* If the installer passed in a manifest digest, compare it now. */ 10334 if (args.manifestDigest != null) { 10335 if (DEBUG_INSTALL) { 10336 final String parsedManifest = pkg.manifestDigest == null ? "null" 10337 : pkg.manifestDigest.toString(); 10338 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 10339 + parsedManifest); 10340 } 10341 10342 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 10343 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 10344 return; 10345 } 10346 } else if (DEBUG_INSTALL) { 10347 final String parsedManifest = pkg.manifestDigest == null 10348 ? "null" : pkg.manifestDigest.toString(); 10349 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 10350 } 10351 10352 // Get rid of all references to package scan path via parser. 10353 pp = null; 10354 String oldCodePath = null; 10355 boolean systemApp = false; 10356 synchronized (mPackages) { 10357 // Check whether the newly-scanned package wants to define an already-defined perm 10358 int N = pkg.permissions.size(); 10359 for (int i = N-1; i >= 0; i--) { 10360 PackageParser.Permission perm = pkg.permissions.get(i); 10361 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 10362 if (bp != null) { 10363 // If the defining package is signed with our cert, it's okay. This 10364 // also includes the "updating the same package" case, of course. 10365 if (compareSignatures(bp.packageSetting.signatures.mSignatures, 10366 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 10367 // If the owning package is the system itself, we log but allow 10368 // install to proceed; we fail the install on all other permission 10369 // redefinitions. 10370 if (!bp.sourcePackage.equals("android")) { 10371 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 10372 + pkg.packageName + " attempting to redeclare permission " 10373 + perm.info.name + " already owned by " + bp.sourcePackage); 10374 res.origPermission = perm.info.name; 10375 res.origPackage = bp.sourcePackage; 10376 return; 10377 } else { 10378 Slog.w(TAG, "Package " + pkg.packageName 10379 + " attempting to redeclare system permission " 10380 + perm.info.name + "; ignoring new declaration"); 10381 pkg.permissions.remove(i); 10382 } 10383 } 10384 } 10385 } 10386 10387 // Check if installing already existing package 10388 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10389 String oldName = mSettings.mRenamedPackages.get(pkgName); 10390 if (pkg.mOriginalPackages != null 10391 && pkg.mOriginalPackages.contains(oldName) 10392 && mPackages.containsKey(oldName)) { 10393 // This package is derived from an original package, 10394 // and this device has been updating from that original 10395 // name. We must continue using the original name, so 10396 // rename the new package here. 10397 pkg.setPackageName(oldName); 10398 pkgName = pkg.packageName; 10399 replace = true; 10400 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 10401 + oldName + " pkgName=" + pkgName); 10402 } else if (mPackages.containsKey(pkgName)) { 10403 // This package, under its official name, already exists 10404 // on the device; we should replace it. 10405 replace = true; 10406 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 10407 } 10408 } 10409 PackageSetting ps = mSettings.mPackages.get(pkgName); 10410 if (ps != null) { 10411 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 10412 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 10413 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 10414 systemApp = (ps.pkg.applicationInfo.flags & 10415 ApplicationInfo.FLAG_SYSTEM) != 0; 10416 } 10417 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10418 } 10419 } 10420 10421 if (systemApp && onSd) { 10422 // Disable updates to system apps on sdcard 10423 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 10424 "Cannot install updates to system apps on sdcard"); 10425 return; 10426 } 10427 10428 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 10429 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 10430 return; 10431 } 10432 10433 if (replace) { 10434 replacePackageLI(pkg, parseFlags, scanMode, args.user, 10435 installerPackageName, res); 10436 } else { 10437 installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user, 10438 installerPackageName, res); 10439 } 10440 synchronized (mPackages) { 10441 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10442 if (ps != null) { 10443 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10444 } 10445 } 10446 } 10447 10448 private static boolean isForwardLocked(PackageParser.Package pkg) { 10449 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10450 } 10451 10452 private static boolean isForwardLocked(ApplicationInfo info) { 10453 return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10454 } 10455 10456 private boolean isForwardLocked(PackageSetting ps) { 10457 return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10458 } 10459 10460 private static boolean isMultiArch(PackageSetting ps) { 10461 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10462 } 10463 10464 private static boolean isMultiArch(ApplicationInfo info) { 10465 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10466 } 10467 10468 private static boolean isExternal(PackageParser.Package pkg) { 10469 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10470 } 10471 10472 private static boolean isExternal(PackageSetting ps) { 10473 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10474 } 10475 10476 private static boolean isExternal(ApplicationInfo info) { 10477 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10478 } 10479 10480 private static boolean isSystemApp(PackageParser.Package pkg) { 10481 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10482 } 10483 10484 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 10485 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0; 10486 } 10487 10488 private static boolean isSystemApp(ApplicationInfo info) { 10489 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10490 } 10491 10492 private static boolean isSystemApp(PackageSetting ps) { 10493 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 10494 } 10495 10496 private static boolean isUpdatedSystemApp(PackageSetting ps) { 10497 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10498 } 10499 10500 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 10501 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10502 } 10503 10504 private static boolean isUpdatedSystemApp(ApplicationInfo info) { 10505 return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10506 } 10507 10508 private int packageFlagsToInstallFlags(PackageSetting ps) { 10509 int installFlags = 0; 10510 if (isExternal(ps)) { 10511 installFlags |= PackageManager.INSTALL_EXTERNAL; 10512 } 10513 if (isForwardLocked(ps)) { 10514 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 10515 } 10516 return installFlags; 10517 } 10518 10519 private void deleteTempPackageFiles() { 10520 final FilenameFilter filter = new FilenameFilter() { 10521 public boolean accept(File dir, String name) { 10522 return name.startsWith("vmdl") && name.endsWith(".tmp"); 10523 } 10524 }; 10525 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 10526 file.delete(); 10527 } 10528 } 10529 10530 @Override 10531 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 10532 int flags) { 10533 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 10534 flags); 10535 } 10536 10537 @Override 10538 public void deletePackage(final String packageName, 10539 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 10540 mContext.enforceCallingOrSelfPermission( 10541 android.Manifest.permission.DELETE_PACKAGES, null); 10542 final int uid = Binder.getCallingUid(); 10543 if (UserHandle.getUserId(uid) != userId) { 10544 mContext.enforceCallingPermission( 10545 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 10546 "deletePackage for user " + userId); 10547 } 10548 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 10549 try { 10550 observer.onPackageDeleted(packageName, 10551 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 10552 } catch (RemoteException re) { 10553 } 10554 return; 10555 } 10556 10557 boolean uninstallBlocked = false; 10558 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 10559 int[] users = sUserManager.getUserIds(); 10560 for (int i = 0; i < users.length; ++i) { 10561 if (getBlockUninstallForUser(packageName, users[i])) { 10562 uninstallBlocked = true; 10563 break; 10564 } 10565 } 10566 } else { 10567 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 10568 } 10569 if (uninstallBlocked) { 10570 try { 10571 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 10572 null); 10573 } catch (RemoteException re) { 10574 } 10575 return; 10576 } 10577 10578 if (DEBUG_REMOVE) { 10579 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 10580 } 10581 // Queue up an async operation since the package deletion may take a little while. 10582 mHandler.post(new Runnable() { 10583 public void run() { 10584 mHandler.removeCallbacks(this); 10585 final int returnCode = deletePackageX(packageName, userId, flags); 10586 if (observer != null) { 10587 try { 10588 observer.onPackageDeleted(packageName, returnCode, null); 10589 } catch (RemoteException e) { 10590 Log.i(TAG, "Observer no longer exists."); 10591 } //end catch 10592 } //end if 10593 } //end run 10594 }); 10595 } 10596 10597 private boolean isPackageDeviceAdmin(String packageName, int userId) { 10598 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 10599 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 10600 try { 10601 if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId) 10602 || dpm.isDeviceOwner(packageName))) { 10603 return true; 10604 } 10605 } catch (RemoteException e) { 10606 } 10607 return false; 10608 } 10609 10610 /** 10611 * This method is an internal method that could be get invoked either 10612 * to delete an installed package or to clean up a failed installation. 10613 * After deleting an installed package, a broadcast is sent to notify any 10614 * listeners that the package has been installed. For cleaning up a failed 10615 * installation, the broadcast is not necessary since the package's 10616 * installation wouldn't have sent the initial broadcast either 10617 * The key steps in deleting a package are 10618 * deleting the package information in internal structures like mPackages, 10619 * deleting the packages base directories through installd 10620 * updating mSettings to reflect current status 10621 * persisting settings for later use 10622 * sending a broadcast if necessary 10623 */ 10624 private int deletePackageX(String packageName, int userId, int flags) { 10625 final PackageRemovedInfo info = new PackageRemovedInfo(); 10626 final boolean res; 10627 10628 if (isPackageDeviceAdmin(packageName, userId)) { 10629 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 10630 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 10631 } 10632 10633 boolean removedForAllUsers = false; 10634 boolean systemUpdate = false; 10635 10636 // for the uninstall-updates case and restricted profiles, remember the per- 10637 // userhandle installed state 10638 int[] allUsers; 10639 boolean[] perUserInstalled; 10640 synchronized (mPackages) { 10641 PackageSetting ps = mSettings.mPackages.get(packageName); 10642 allUsers = sUserManager.getUserIds(); 10643 perUserInstalled = new boolean[allUsers.length]; 10644 for (int i = 0; i < allUsers.length; i++) { 10645 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10646 } 10647 } 10648 10649 synchronized (mInstallLock) { 10650 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 10651 res = deletePackageLI(packageName, 10652 (flags & PackageManager.DELETE_ALL_USERS) != 0 10653 ? UserHandle.ALL : new UserHandle(userId), 10654 true, allUsers, perUserInstalled, 10655 flags | REMOVE_CHATTY, info, true); 10656 systemUpdate = info.isRemovedPackageSystemUpdate; 10657 if (res && !systemUpdate && mPackages.get(packageName) == null) { 10658 removedForAllUsers = true; 10659 } 10660 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 10661 + " removedForAllUsers=" + removedForAllUsers); 10662 } 10663 10664 if (res) { 10665 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 10666 10667 // If the removed package was a system update, the old system package 10668 // was re-enabled; we need to broadcast this information 10669 if (systemUpdate) { 10670 Bundle extras = new Bundle(1); 10671 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 10672 ? info.removedAppId : info.uid); 10673 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10674 10675 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 10676 extras, null, null, null); 10677 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 10678 extras, null, null, null); 10679 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 10680 null, packageName, null, null); 10681 } 10682 } 10683 // Force a gc here. 10684 Runtime.getRuntime().gc(); 10685 // Delete the resources here after sending the broadcast to let 10686 // other processes clean up before deleting resources. 10687 if (info.args != null) { 10688 synchronized (mInstallLock) { 10689 info.args.doPostDeleteLI(true); 10690 } 10691 } 10692 10693 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10694 } 10695 10696 static class PackageRemovedInfo { 10697 String removedPackage; 10698 int uid = -1; 10699 int removedAppId = -1; 10700 int[] removedUsers = null; 10701 boolean isRemovedPackageSystemUpdate = false; 10702 // Clean up resources deleted packages. 10703 InstallArgs args = null; 10704 10705 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 10706 Bundle extras = new Bundle(1); 10707 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 10708 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 10709 if (replacing) { 10710 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10711 } 10712 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 10713 if (removedPackage != null) { 10714 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 10715 extras, null, null, removedUsers); 10716 if (fullRemove && !replacing) { 10717 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 10718 extras, null, null, removedUsers); 10719 } 10720 } 10721 if (removedAppId >= 0) { 10722 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 10723 removedUsers); 10724 } 10725 } 10726 } 10727 10728 /* 10729 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 10730 * flag is not set, the data directory is removed as well. 10731 * make sure this flag is set for partially installed apps. If not its meaningless to 10732 * delete a partially installed application. 10733 */ 10734 private void removePackageDataLI(PackageSetting ps, 10735 int[] allUserHandles, boolean[] perUserInstalled, 10736 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 10737 String packageName = ps.name; 10738 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 10739 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 10740 // Retrieve object to delete permissions for shared user later on 10741 final PackageSetting deletedPs; 10742 // reader 10743 synchronized (mPackages) { 10744 deletedPs = mSettings.mPackages.get(packageName); 10745 if (outInfo != null) { 10746 outInfo.removedPackage = packageName; 10747 outInfo.removedUsers = deletedPs != null 10748 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 10749 : null; 10750 } 10751 } 10752 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10753 removeDataDirsLI(packageName); 10754 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 10755 } 10756 // writer 10757 synchronized (mPackages) { 10758 if (deletedPs != null) { 10759 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10760 if (outInfo != null) { 10761 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 10762 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 10763 } 10764 if (deletedPs != null) { 10765 updatePermissionsLPw(deletedPs.name, null, 0); 10766 if (deletedPs.sharedUser != null) { 10767 // remove permissions associated with package 10768 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 10769 } 10770 } 10771 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 10772 } 10773 // make sure to preserve per-user disabled state if this removal was just 10774 // a downgrade of a system app to the factory package 10775 if (allUserHandles != null && perUserInstalled != null) { 10776 if (DEBUG_REMOVE) { 10777 Slog.d(TAG, "Propagating install state across downgrade"); 10778 } 10779 for (int i = 0; i < allUserHandles.length; i++) { 10780 if (DEBUG_REMOVE) { 10781 Slog.d(TAG, " user " + allUserHandles[i] 10782 + " => " + perUserInstalled[i]); 10783 } 10784 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10785 } 10786 } 10787 } 10788 // can downgrade to reader 10789 if (writeSettings) { 10790 // Save settings now 10791 mSettings.writeLPr(); 10792 } 10793 } 10794 if (outInfo != null) { 10795 // A user ID was deleted here. Go through all users and remove it 10796 // from KeyStore. 10797 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 10798 } 10799 } 10800 10801 static boolean locationIsPrivileged(File path) { 10802 try { 10803 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 10804 .getCanonicalPath(); 10805 return path.getCanonicalPath().startsWith(privilegedAppDir); 10806 } catch (IOException e) { 10807 Slog.e(TAG, "Unable to access code path " + path); 10808 } 10809 return false; 10810 } 10811 10812 /* 10813 * Tries to delete system package. 10814 */ 10815 private boolean deleteSystemPackageLI(PackageSetting newPs, 10816 int[] allUserHandles, boolean[] perUserInstalled, 10817 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 10818 final boolean applyUserRestrictions 10819 = (allUserHandles != null) && (perUserInstalled != null); 10820 PackageSetting disabledPs = null; 10821 // Confirm if the system package has been updated 10822 // An updated system app can be deleted. This will also have to restore 10823 // the system pkg from system partition 10824 // reader 10825 synchronized (mPackages) { 10826 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 10827 } 10828 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 10829 + " disabledPs=" + disabledPs); 10830 if (disabledPs == null) { 10831 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 10832 return false; 10833 } else if (DEBUG_REMOVE) { 10834 Slog.d(TAG, "Deleting system pkg from data partition"); 10835 } 10836 if (DEBUG_REMOVE) { 10837 if (applyUserRestrictions) { 10838 Slog.d(TAG, "Remembering install states:"); 10839 for (int i = 0; i < allUserHandles.length; i++) { 10840 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 10841 } 10842 } 10843 } 10844 // Delete the updated package 10845 outInfo.isRemovedPackageSystemUpdate = true; 10846 if (disabledPs.versionCode < newPs.versionCode) { 10847 // Delete data for downgrades 10848 flags &= ~PackageManager.DELETE_KEEP_DATA; 10849 } else { 10850 // Preserve data by setting flag 10851 flags |= PackageManager.DELETE_KEEP_DATA; 10852 } 10853 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 10854 allUserHandles, perUserInstalled, outInfo, writeSettings); 10855 if (!ret) { 10856 return false; 10857 } 10858 // writer 10859 synchronized (mPackages) { 10860 // Reinstate the old system package 10861 mSettings.enableSystemPackageLPw(newPs.name); 10862 // Remove any native libraries from the upgraded package. 10863 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 10864 } 10865 // Install the system package 10866 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 10867 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 10868 if (locationIsPrivileged(disabledPs.codePath)) { 10869 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10870 } 10871 10872 final PackageParser.Package newPkg; 10873 try { 10874 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, null); 10875 } catch (PackageManagerException e) { 10876 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 10877 return false; 10878 } 10879 10880 // writer 10881 synchronized (mPackages) { 10882 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 10883 updatePermissionsLPw(newPkg.packageName, newPkg, 10884 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 10885 if (applyUserRestrictions) { 10886 if (DEBUG_REMOVE) { 10887 Slog.d(TAG, "Propagating install state across reinstall"); 10888 } 10889 for (int i = 0; i < allUserHandles.length; i++) { 10890 if (DEBUG_REMOVE) { 10891 Slog.d(TAG, " user " + allUserHandles[i] 10892 + " => " + perUserInstalled[i]); 10893 } 10894 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10895 } 10896 // Regardless of writeSettings we need to ensure that this restriction 10897 // state propagation is persisted 10898 mSettings.writeAllUsersPackageRestrictionsLPr(); 10899 } 10900 // can downgrade to reader here 10901 if (writeSettings) { 10902 mSettings.writeLPr(); 10903 } 10904 } 10905 return true; 10906 } 10907 10908 private boolean deleteInstalledPackageLI(PackageSetting ps, 10909 boolean deleteCodeAndResources, int flags, 10910 int[] allUserHandles, boolean[] perUserInstalled, 10911 PackageRemovedInfo outInfo, boolean writeSettings) { 10912 if (outInfo != null) { 10913 outInfo.uid = ps.appId; 10914 } 10915 10916 // Delete package data from internal structures and also remove data if flag is set 10917 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 10918 10919 // Delete application code and resources 10920 if (deleteCodeAndResources && (outInfo != null)) { 10921 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 10922 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 10923 getAppDexInstructionSets(ps), isMultiArch(ps)); 10924 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 10925 } 10926 return true; 10927 } 10928 10929 @Override 10930 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 10931 int userId) { 10932 mContext.enforceCallingOrSelfPermission( 10933 android.Manifest.permission.DELETE_PACKAGES, null); 10934 synchronized (mPackages) { 10935 PackageSetting ps = mSettings.mPackages.get(packageName); 10936 if (ps == null) { 10937 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 10938 return false; 10939 } 10940 if (!ps.getInstalled(userId)) { 10941 // Can't block uninstall for an app that is not installed or enabled. 10942 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 10943 return false; 10944 } 10945 ps.setBlockUninstall(blockUninstall, userId); 10946 mSettings.writePackageRestrictionsLPr(userId); 10947 } 10948 return true; 10949 } 10950 10951 @Override 10952 public boolean getBlockUninstallForUser(String packageName, int userId) { 10953 synchronized (mPackages) { 10954 PackageSetting ps = mSettings.mPackages.get(packageName); 10955 if (ps == null) { 10956 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 10957 return false; 10958 } 10959 return ps.getBlockUninstall(userId); 10960 } 10961 } 10962 10963 /* 10964 * This method handles package deletion in general 10965 */ 10966 private boolean deletePackageLI(String packageName, UserHandle user, 10967 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 10968 int flags, PackageRemovedInfo outInfo, 10969 boolean writeSettings) { 10970 if (packageName == null) { 10971 Slog.w(TAG, "Attempt to delete null packageName."); 10972 return false; 10973 } 10974 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 10975 PackageSetting ps; 10976 boolean dataOnly = false; 10977 int removeUser = -1; 10978 int appId = -1; 10979 synchronized (mPackages) { 10980 ps = mSettings.mPackages.get(packageName); 10981 if (ps == null) { 10982 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 10983 return false; 10984 } 10985 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 10986 && user.getIdentifier() != UserHandle.USER_ALL) { 10987 // The caller is asking that the package only be deleted for a single 10988 // user. To do this, we just mark its uninstalled state and delete 10989 // its data. If this is a system app, we only allow this to happen if 10990 // they have set the special DELETE_SYSTEM_APP which requests different 10991 // semantics than normal for uninstalling system apps. 10992 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 10993 ps.setUserState(user.getIdentifier(), 10994 COMPONENT_ENABLED_STATE_DEFAULT, 10995 false, //installed 10996 true, //stopped 10997 true, //notLaunched 10998 false, //hidden 10999 null, null, null, 11000 false // blockUninstall 11001 ); 11002 if (!isSystemApp(ps)) { 11003 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 11004 // Other user still have this package installed, so all 11005 // we need to do is clear this user's data and save that 11006 // it is uninstalled. 11007 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 11008 removeUser = user.getIdentifier(); 11009 appId = ps.appId; 11010 mSettings.writePackageRestrictionsLPr(removeUser); 11011 } else { 11012 // We need to set it back to 'installed' so the uninstall 11013 // broadcasts will be sent correctly. 11014 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 11015 ps.setInstalled(true, user.getIdentifier()); 11016 } 11017 } else { 11018 // This is a system app, so we assume that the 11019 // other users still have this package installed, so all 11020 // we need to do is clear this user's data and save that 11021 // it is uninstalled. 11022 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 11023 removeUser = user.getIdentifier(); 11024 appId = ps.appId; 11025 mSettings.writePackageRestrictionsLPr(removeUser); 11026 } 11027 } 11028 } 11029 11030 if (removeUser >= 0) { 11031 // From above, we determined that we are deleting this only 11032 // for a single user. Continue the work here. 11033 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 11034 if (outInfo != null) { 11035 outInfo.removedPackage = packageName; 11036 outInfo.removedAppId = appId; 11037 outInfo.removedUsers = new int[] {removeUser}; 11038 } 11039 mInstaller.clearUserData(packageName, removeUser); 11040 removeKeystoreDataIfNeeded(removeUser, appId); 11041 schedulePackageCleaning(packageName, removeUser, false); 11042 return true; 11043 } 11044 11045 if (dataOnly) { 11046 // Delete application data first 11047 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 11048 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 11049 return true; 11050 } 11051 11052 boolean ret = false; 11053 if (isSystemApp(ps)) { 11054 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 11055 // When an updated system application is deleted we delete the existing resources as well and 11056 // fall back to existing code in system partition 11057 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 11058 flags, outInfo, writeSettings); 11059 } else { 11060 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 11061 // Kill application pre-emptively especially for apps on sd. 11062 killApplication(packageName, ps.appId, "uninstall pkg"); 11063 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 11064 allUserHandles, perUserInstalled, 11065 outInfo, writeSettings); 11066 } 11067 11068 return ret; 11069 } 11070 11071 private final class ClearStorageConnection implements ServiceConnection { 11072 IMediaContainerService mContainerService; 11073 11074 @Override 11075 public void onServiceConnected(ComponentName name, IBinder service) { 11076 synchronized (this) { 11077 mContainerService = IMediaContainerService.Stub.asInterface(service); 11078 notifyAll(); 11079 } 11080 } 11081 11082 @Override 11083 public void onServiceDisconnected(ComponentName name) { 11084 } 11085 } 11086 11087 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 11088 final boolean mounted; 11089 if (Environment.isExternalStorageEmulated()) { 11090 mounted = true; 11091 } else { 11092 final String status = Environment.getExternalStorageState(); 11093 11094 mounted = status.equals(Environment.MEDIA_MOUNTED) 11095 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 11096 } 11097 11098 if (!mounted) { 11099 return; 11100 } 11101 11102 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 11103 int[] users; 11104 if (userId == UserHandle.USER_ALL) { 11105 users = sUserManager.getUserIds(); 11106 } else { 11107 users = new int[] { userId }; 11108 } 11109 final ClearStorageConnection conn = new ClearStorageConnection(); 11110 if (mContext.bindServiceAsUser( 11111 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 11112 try { 11113 for (int curUser : users) { 11114 long timeout = SystemClock.uptimeMillis() + 5000; 11115 synchronized (conn) { 11116 long now = SystemClock.uptimeMillis(); 11117 while (conn.mContainerService == null && now < timeout) { 11118 try { 11119 conn.wait(timeout - now); 11120 } catch (InterruptedException e) { 11121 } 11122 } 11123 } 11124 if (conn.mContainerService == null) { 11125 return; 11126 } 11127 11128 final UserEnvironment userEnv = new UserEnvironment(curUser); 11129 clearDirectory(conn.mContainerService, 11130 userEnv.buildExternalStorageAppCacheDirs(packageName)); 11131 if (allData) { 11132 clearDirectory(conn.mContainerService, 11133 userEnv.buildExternalStorageAppDataDirs(packageName)); 11134 clearDirectory(conn.mContainerService, 11135 userEnv.buildExternalStorageAppMediaDirs(packageName)); 11136 } 11137 } 11138 } finally { 11139 mContext.unbindService(conn); 11140 } 11141 } 11142 } 11143 11144 @Override 11145 public void clearApplicationUserData(final String packageName, 11146 final IPackageDataObserver observer, final int userId) { 11147 mContext.enforceCallingOrSelfPermission( 11148 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 11149 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data"); 11150 // Queue up an async operation since the package deletion may take a little while. 11151 mHandler.post(new Runnable() { 11152 public void run() { 11153 mHandler.removeCallbacks(this); 11154 final boolean succeeded; 11155 synchronized (mInstallLock) { 11156 succeeded = clearApplicationUserDataLI(packageName, userId); 11157 } 11158 clearExternalStorageDataSync(packageName, userId, true); 11159 if (succeeded) { 11160 // invoke DeviceStorageMonitor's update method to clear any notifications 11161 DeviceStorageMonitorInternal 11162 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 11163 if (dsm != null) { 11164 dsm.checkMemory(); 11165 } 11166 } 11167 if(observer != null) { 11168 try { 11169 observer.onRemoveCompleted(packageName, succeeded); 11170 } catch (RemoteException e) { 11171 Log.i(TAG, "Observer no longer exists."); 11172 } 11173 } //end if observer 11174 } //end run 11175 }); 11176 } 11177 11178 private boolean clearApplicationUserDataLI(String packageName, int userId) { 11179 if (packageName == null) { 11180 Slog.w(TAG, "Attempt to delete null packageName."); 11181 return false; 11182 } 11183 PackageParser.Package p; 11184 boolean dataOnly = false; 11185 final int appId; 11186 synchronized (mPackages) { 11187 p = mPackages.get(packageName); 11188 if (p == null) { 11189 dataOnly = true; 11190 PackageSetting ps = mSettings.mPackages.get(packageName); 11191 if ((ps == null) || (ps.pkg == null)) { 11192 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11193 return false; 11194 } 11195 p = ps.pkg; 11196 } 11197 if (!dataOnly) { 11198 // need to check this only for fully installed applications 11199 if (p == null) { 11200 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11201 return false; 11202 } 11203 final ApplicationInfo applicationInfo = p.applicationInfo; 11204 if (applicationInfo == null) { 11205 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11206 return false; 11207 } 11208 } 11209 if (p != null && p.applicationInfo != null) { 11210 appId = p.applicationInfo.uid; 11211 } else { 11212 appId = -1; 11213 } 11214 } 11215 int retCode = mInstaller.clearUserData(packageName, userId); 11216 if (retCode < 0) { 11217 Slog.w(TAG, "Couldn't remove cache files for package: " 11218 + packageName); 11219 return false; 11220 } 11221 removeKeystoreDataIfNeeded(userId, appId); 11222 return true; 11223 } 11224 11225 /** 11226 * Remove entries from the keystore daemon. Will only remove it if the 11227 * {@code appId} is valid. 11228 */ 11229 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 11230 if (appId < 0) { 11231 return; 11232 } 11233 11234 final KeyStore keyStore = KeyStore.getInstance(); 11235 if (keyStore != null) { 11236 if (userId == UserHandle.USER_ALL) { 11237 for (final int individual : sUserManager.getUserIds()) { 11238 keyStore.clearUid(UserHandle.getUid(individual, appId)); 11239 } 11240 } else { 11241 keyStore.clearUid(UserHandle.getUid(userId, appId)); 11242 } 11243 } else { 11244 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 11245 } 11246 } 11247 11248 @Override 11249 public void deleteApplicationCacheFiles(final String packageName, 11250 final IPackageDataObserver observer) { 11251 mContext.enforceCallingOrSelfPermission( 11252 android.Manifest.permission.DELETE_CACHE_FILES, null); 11253 // Queue up an async operation since the package deletion may take a little while. 11254 final int userId = UserHandle.getCallingUserId(); 11255 mHandler.post(new Runnable() { 11256 public void run() { 11257 mHandler.removeCallbacks(this); 11258 final boolean succeded; 11259 synchronized (mInstallLock) { 11260 succeded = deleteApplicationCacheFilesLI(packageName, userId); 11261 } 11262 clearExternalStorageDataSync(packageName, userId, false); 11263 if(observer != null) { 11264 try { 11265 observer.onRemoveCompleted(packageName, succeded); 11266 } catch (RemoteException e) { 11267 Log.i(TAG, "Observer no longer exists."); 11268 } 11269 } //end if observer 11270 } //end run 11271 }); 11272 } 11273 11274 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 11275 if (packageName == null) { 11276 Slog.w(TAG, "Attempt to delete null packageName."); 11277 return false; 11278 } 11279 PackageParser.Package p; 11280 synchronized (mPackages) { 11281 p = mPackages.get(packageName); 11282 } 11283 if (p == null) { 11284 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11285 return false; 11286 } 11287 final ApplicationInfo applicationInfo = p.applicationInfo; 11288 if (applicationInfo == null) { 11289 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11290 return false; 11291 } 11292 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 11293 if (retCode < 0) { 11294 Slog.w(TAG, "Couldn't remove cache files for package: " 11295 + packageName + " u" + userId); 11296 return false; 11297 } 11298 return true; 11299 } 11300 11301 @Override 11302 public void getPackageSizeInfo(final String packageName, int userHandle, 11303 final IPackageStatsObserver observer) { 11304 mContext.enforceCallingOrSelfPermission( 11305 android.Manifest.permission.GET_PACKAGE_SIZE, null); 11306 if (packageName == null) { 11307 throw new IllegalArgumentException("Attempt to get size of null packageName"); 11308 } 11309 11310 PackageStats stats = new PackageStats(packageName, userHandle); 11311 11312 /* 11313 * Queue up an async operation since the package measurement may take a 11314 * little while. 11315 */ 11316 Message msg = mHandler.obtainMessage(INIT_COPY); 11317 msg.obj = new MeasureParams(stats, observer); 11318 mHandler.sendMessage(msg); 11319 } 11320 11321 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 11322 PackageStats pStats) { 11323 if (packageName == null) { 11324 Slog.w(TAG, "Attempt to get size of null packageName."); 11325 return false; 11326 } 11327 PackageParser.Package p; 11328 boolean dataOnly = false; 11329 String libDirRoot = null; 11330 String asecPath = null; 11331 PackageSetting ps = null; 11332 synchronized (mPackages) { 11333 p = mPackages.get(packageName); 11334 ps = mSettings.mPackages.get(packageName); 11335 if(p == null) { 11336 dataOnly = true; 11337 if((ps == null) || (ps.pkg == null)) { 11338 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11339 return false; 11340 } 11341 p = ps.pkg; 11342 } 11343 if (ps != null) { 11344 libDirRoot = ps.legacyNativeLibraryPathString; 11345 } 11346 if (p != null && (isExternal(p) || isForwardLocked(p))) { 11347 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 11348 if (secureContainerId != null) { 11349 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 11350 } 11351 } 11352 } 11353 String publicSrcDir = null; 11354 if(!dataOnly) { 11355 final ApplicationInfo applicationInfo = p.applicationInfo; 11356 if (applicationInfo == null) { 11357 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11358 return false; 11359 } 11360 if (isForwardLocked(p)) { 11361 publicSrcDir = applicationInfo.getBaseResourcePath(); 11362 } 11363 } 11364 // TODO: extend to measure size of split APKs 11365 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 11366 // not just the first level. 11367 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 11368 // just the primary. 11369 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 11370 int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot, 11371 publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 11372 if (res < 0) { 11373 return false; 11374 } 11375 11376 // Fix-up for forward-locked applications in ASEC containers. 11377 if (!isExternal(p)) { 11378 pStats.codeSize += pStats.externalCodeSize; 11379 pStats.externalCodeSize = 0L; 11380 } 11381 11382 return true; 11383 } 11384 11385 11386 @Override 11387 public void addPackageToPreferred(String packageName) { 11388 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 11389 } 11390 11391 @Override 11392 public void removePackageFromPreferred(String packageName) { 11393 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 11394 } 11395 11396 @Override 11397 public List<PackageInfo> getPreferredPackages(int flags) { 11398 return new ArrayList<PackageInfo>(); 11399 } 11400 11401 private int getUidTargetSdkVersionLockedLPr(int uid) { 11402 Object obj = mSettings.getUserIdLPr(uid); 11403 if (obj instanceof SharedUserSetting) { 11404 final SharedUserSetting sus = (SharedUserSetting) obj; 11405 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 11406 final Iterator<PackageSetting> it = sus.packages.iterator(); 11407 while (it.hasNext()) { 11408 final PackageSetting ps = it.next(); 11409 if (ps.pkg != null) { 11410 int v = ps.pkg.applicationInfo.targetSdkVersion; 11411 if (v < vers) vers = v; 11412 } 11413 } 11414 return vers; 11415 } else if (obj instanceof PackageSetting) { 11416 final PackageSetting ps = (PackageSetting) obj; 11417 if (ps.pkg != null) { 11418 return ps.pkg.applicationInfo.targetSdkVersion; 11419 } 11420 } 11421 return Build.VERSION_CODES.CUR_DEVELOPMENT; 11422 } 11423 11424 @Override 11425 public void addPreferredActivity(IntentFilter filter, int match, 11426 ComponentName[] set, ComponentName activity, int userId) { 11427 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11428 "Adding preferred"); 11429 } 11430 11431 private void addPreferredActivityInternal(IntentFilter filter, int match, 11432 ComponentName[] set, ComponentName activity, boolean always, int userId, 11433 String opname) { 11434 // writer 11435 int callingUid = Binder.getCallingUid(); 11436 enforceCrossUserPermission(callingUid, userId, true, "add preferred activity"); 11437 if (filter.countActions() == 0) { 11438 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11439 return; 11440 } 11441 synchronized (mPackages) { 11442 if (mContext.checkCallingOrSelfPermission( 11443 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11444 != PackageManager.PERMISSION_GRANTED) { 11445 if (getUidTargetSdkVersionLockedLPr(callingUid) 11446 < Build.VERSION_CODES.FROYO) { 11447 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 11448 + callingUid); 11449 return; 11450 } 11451 mContext.enforceCallingOrSelfPermission( 11452 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11453 } 11454 11455 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 11456 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 11457 + userId + ":"); 11458 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11459 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 11460 mSettings.writePackageRestrictionsLPr(userId); 11461 } 11462 } 11463 11464 @Override 11465 public void replacePreferredActivity(IntentFilter filter, int match, 11466 ComponentName[] set, ComponentName activity, int userId) { 11467 if (filter.countActions() != 1) { 11468 throw new IllegalArgumentException( 11469 "replacePreferredActivity expects filter to have only 1 action."); 11470 } 11471 if (filter.countDataAuthorities() != 0 11472 || filter.countDataPaths() != 0 11473 || filter.countDataSchemes() > 1 11474 || filter.countDataTypes() != 0) { 11475 throw new IllegalArgumentException( 11476 "replacePreferredActivity expects filter to have no data authorities, " + 11477 "paths, or types; and at most one scheme."); 11478 } 11479 11480 final int callingUid = Binder.getCallingUid(); 11481 enforceCrossUserPermission(callingUid, userId, true, "replace preferred activity"); 11482 synchronized (mPackages) { 11483 if (mContext.checkCallingOrSelfPermission( 11484 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11485 != PackageManager.PERMISSION_GRANTED) { 11486 if (getUidTargetSdkVersionLockedLPr(callingUid) 11487 < Build.VERSION_CODES.FROYO) { 11488 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 11489 + Binder.getCallingUid()); 11490 return; 11491 } 11492 mContext.enforceCallingOrSelfPermission( 11493 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11494 } 11495 11496 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11497 if (pir != null) { 11498 // Get all of the existing entries that exactly match this filter. 11499 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 11500 if (existing != null && existing.size() == 1) { 11501 PreferredActivity cur = existing.get(0); 11502 if (DEBUG_PREFERRED) { 11503 Slog.i(TAG, "Checking replace of preferred:"); 11504 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11505 if (!cur.mPref.mAlways) { 11506 Slog.i(TAG, " -- CUR; not mAlways!"); 11507 } else { 11508 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 11509 Slog.i(TAG, " -- CUR: mSet=" 11510 + Arrays.toString(cur.mPref.mSetComponents)); 11511 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 11512 Slog.i(TAG, " -- NEW: mMatch=" 11513 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 11514 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 11515 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 11516 } 11517 } 11518 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 11519 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 11520 && cur.mPref.sameSet(set)) { 11521 if (DEBUG_PREFERRED) { 11522 Slog.i(TAG, "Replacing with same preferred activity " 11523 + cur.mPref.mShortComponent + " for user " 11524 + userId + ":"); 11525 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11526 } else { 11527 Slog.i(TAG, "Replacing with same preferred activity " 11528 + cur.mPref.mShortComponent + " for user " 11529 + userId); 11530 } 11531 return; 11532 } 11533 } 11534 11535 if (existing != null) { 11536 if (DEBUG_PREFERRED) { 11537 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 11538 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11539 } 11540 for (int i = 0; i < existing.size(); i++) { 11541 PreferredActivity pa = existing.get(i); 11542 if (DEBUG_PREFERRED) { 11543 Slog.i(TAG, "Removing existing preferred activity " 11544 + pa.mPref.mComponent + ":"); 11545 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 11546 } 11547 pir.removeFilter(pa); 11548 } 11549 } 11550 } 11551 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11552 "Replacing preferred"); 11553 } 11554 } 11555 11556 @Override 11557 public void clearPackagePreferredActivities(String packageName) { 11558 final int uid = Binder.getCallingUid(); 11559 // writer 11560 synchronized (mPackages) { 11561 PackageParser.Package pkg = mPackages.get(packageName); 11562 if (pkg == null || pkg.applicationInfo.uid != uid) { 11563 if (mContext.checkCallingOrSelfPermission( 11564 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11565 != PackageManager.PERMISSION_GRANTED) { 11566 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11567 < Build.VERSION_CODES.FROYO) { 11568 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 11569 + Binder.getCallingUid()); 11570 return; 11571 } 11572 mContext.enforceCallingOrSelfPermission( 11573 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11574 } 11575 } 11576 11577 int user = UserHandle.getCallingUserId(); 11578 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 11579 mSettings.writePackageRestrictionsLPr(user); 11580 scheduleWriteSettingsLocked(); 11581 } 11582 } 11583 } 11584 11585 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 11586 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 11587 ArrayList<PreferredActivity> removed = null; 11588 boolean changed = false; 11589 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11590 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 11591 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11592 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 11593 continue; 11594 } 11595 Iterator<PreferredActivity> it = pir.filterIterator(); 11596 while (it.hasNext()) { 11597 PreferredActivity pa = it.next(); 11598 // Mark entry for removal only if it matches the package name 11599 // and the entry is of type "always". 11600 if (packageName == null || 11601 (pa.mPref.mComponent.getPackageName().equals(packageName) 11602 && pa.mPref.mAlways)) { 11603 if (removed == null) { 11604 removed = new ArrayList<PreferredActivity>(); 11605 } 11606 removed.add(pa); 11607 } 11608 } 11609 if (removed != null) { 11610 for (int j=0; j<removed.size(); j++) { 11611 PreferredActivity pa = removed.get(j); 11612 pir.removeFilter(pa); 11613 } 11614 changed = true; 11615 } 11616 } 11617 return changed; 11618 } 11619 11620 @Override 11621 public void resetPreferredActivities(int userId) { 11622 mContext.enforceCallingOrSelfPermission( 11623 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11624 // writer 11625 synchronized (mPackages) { 11626 int user = UserHandle.getCallingUserId(); 11627 clearPackagePreferredActivitiesLPw(null, user); 11628 mSettings.readDefaultPreferredAppsLPw(this, user); 11629 mSettings.writePackageRestrictionsLPr(user); 11630 scheduleWriteSettingsLocked(); 11631 } 11632 } 11633 11634 @Override 11635 public int getPreferredActivities(List<IntentFilter> outFilters, 11636 List<ComponentName> outActivities, String packageName) { 11637 11638 int num = 0; 11639 final int userId = UserHandle.getCallingUserId(); 11640 // reader 11641 synchronized (mPackages) { 11642 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11643 if (pir != null) { 11644 final Iterator<PreferredActivity> it = pir.filterIterator(); 11645 while (it.hasNext()) { 11646 final PreferredActivity pa = it.next(); 11647 if (packageName == null 11648 || (pa.mPref.mComponent.getPackageName().equals(packageName) 11649 && pa.mPref.mAlways)) { 11650 if (outFilters != null) { 11651 outFilters.add(new IntentFilter(pa)); 11652 } 11653 if (outActivities != null) { 11654 outActivities.add(pa.mPref.mComponent); 11655 } 11656 } 11657 } 11658 } 11659 } 11660 11661 return num; 11662 } 11663 11664 @Override 11665 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 11666 int userId) { 11667 int callingUid = Binder.getCallingUid(); 11668 if (callingUid != Process.SYSTEM_UID) { 11669 throw new SecurityException( 11670 "addPersistentPreferredActivity can only be run by the system"); 11671 } 11672 if (filter.countActions() == 0) { 11673 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11674 return; 11675 } 11676 synchronized (mPackages) { 11677 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 11678 " :"); 11679 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11680 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 11681 new PersistentPreferredActivity(filter, activity)); 11682 mSettings.writePackageRestrictionsLPr(userId); 11683 } 11684 } 11685 11686 @Override 11687 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 11688 int callingUid = Binder.getCallingUid(); 11689 if (callingUid != Process.SYSTEM_UID) { 11690 throw new SecurityException( 11691 "clearPackagePersistentPreferredActivities can only be run by the system"); 11692 } 11693 ArrayList<PersistentPreferredActivity> removed = null; 11694 boolean changed = false; 11695 synchronized (mPackages) { 11696 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 11697 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 11698 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 11699 .valueAt(i); 11700 if (userId != thisUserId) { 11701 continue; 11702 } 11703 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 11704 while (it.hasNext()) { 11705 PersistentPreferredActivity ppa = it.next(); 11706 // Mark entry for removal only if it matches the package name. 11707 if (ppa.mComponent.getPackageName().equals(packageName)) { 11708 if (removed == null) { 11709 removed = new ArrayList<PersistentPreferredActivity>(); 11710 } 11711 removed.add(ppa); 11712 } 11713 } 11714 if (removed != null) { 11715 for (int j=0; j<removed.size(); j++) { 11716 PersistentPreferredActivity ppa = removed.get(j); 11717 ppir.removeFilter(ppa); 11718 } 11719 changed = true; 11720 } 11721 } 11722 11723 if (changed) { 11724 mSettings.writePackageRestrictionsLPr(userId); 11725 } 11726 } 11727 } 11728 11729 @Override 11730 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 11731 int ownerUserId, int sourceUserId, int targetUserId, int flags) { 11732 mContext.enforceCallingOrSelfPermission( 11733 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11734 int callingUid = Binder.getCallingUid(); 11735 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11736 if (intentFilter.countActions() == 0) { 11737 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 11738 return; 11739 } 11740 synchronized (mPackages) { 11741 CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter, 11742 ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags); 11743 mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter); 11744 mSettings.writePackageRestrictionsLPr(sourceUserId); 11745 } 11746 } 11747 11748 @Override 11749 public void addCrossProfileIntentsForPackage(String packageName, 11750 int sourceUserId, int targetUserId) { 11751 mContext.enforceCallingOrSelfPermission( 11752 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11753 mSettings.addCrossProfilePackage(packageName, sourceUserId, targetUserId); 11754 mSettings.writePackageRestrictionsLPr(sourceUserId); 11755 } 11756 11757 @Override 11758 public void removeCrossProfileIntentsForPackage(String packageName, 11759 int sourceUserId, int targetUserId) { 11760 mContext.enforceCallingOrSelfPermission( 11761 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11762 mSettings.removeCrossProfilePackage(packageName, sourceUserId, targetUserId); 11763 mSettings.writePackageRestrictionsLPr(sourceUserId); 11764 } 11765 11766 @Override 11767 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage, 11768 int ownerUserId) { 11769 mContext.enforceCallingOrSelfPermission( 11770 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11771 int callingUid = Binder.getCallingUid(); 11772 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11773 int callingUserId = UserHandle.getUserId(callingUid); 11774 synchronized (mPackages) { 11775 CrossProfileIntentResolver resolver = 11776 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11777 HashSet<CrossProfileIntentFilter> set = 11778 new HashSet<CrossProfileIntentFilter>(resolver.filterSet()); 11779 for (CrossProfileIntentFilter filter : set) { 11780 if (filter.getOwnerPackage().equals(ownerPackage) 11781 && filter.getOwnerUserId() == callingUserId) { 11782 resolver.removeFilter(filter); 11783 } 11784 } 11785 mSettings.writePackageRestrictionsLPr(sourceUserId); 11786 } 11787 } 11788 11789 // Enforcing that callingUid is owning pkg on userId 11790 private void enforceOwnerRights(String pkg, int userId, int callingUid) { 11791 // The system owns everything. 11792 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 11793 return; 11794 } 11795 int callingUserId = UserHandle.getUserId(callingUid); 11796 if (callingUserId != userId) { 11797 throw new SecurityException("calling uid " + callingUid 11798 + " pretends to own " + pkg + " on user " + userId + " but belongs to user " 11799 + callingUserId); 11800 } 11801 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 11802 if (pi == null) { 11803 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 11804 + callingUserId); 11805 } 11806 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 11807 throw new SecurityException("Calling uid " + callingUid 11808 + " does not own package " + pkg); 11809 } 11810 } 11811 11812 @Override 11813 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 11814 Intent intent = new Intent(Intent.ACTION_MAIN); 11815 intent.addCategory(Intent.CATEGORY_HOME); 11816 11817 final int callingUserId = UserHandle.getCallingUserId(); 11818 List<ResolveInfo> list = queryIntentActivities(intent, null, 11819 PackageManager.GET_META_DATA, callingUserId); 11820 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 11821 true, false, false, callingUserId); 11822 11823 allHomeCandidates.clear(); 11824 if (list != null) { 11825 for (ResolveInfo ri : list) { 11826 allHomeCandidates.add(ri); 11827 } 11828 } 11829 return (preferred == null || preferred.activityInfo == null) 11830 ? null 11831 : new ComponentName(preferred.activityInfo.packageName, 11832 preferred.activityInfo.name); 11833 } 11834 11835 /** 11836 * Check if calling UID is the current home app. This handles both the case 11837 * where the user has selected a specific home app, and where there is only 11838 * one home app. 11839 */ 11840 public boolean checkCallerIsHomeApp() { 11841 final Intent intent = new Intent(Intent.ACTION_MAIN); 11842 intent.addCategory(Intent.CATEGORY_HOME); 11843 11844 final int callingUid = Binder.getCallingUid(); 11845 final int callingUserId = UserHandle.getCallingUserId(); 11846 final List<ResolveInfo> allHomes = queryIntentActivities(intent, null, 0, callingUserId); 11847 final ResolveInfo preferredHome = findPreferredActivity(intent, null, 0, allHomes, 0, true, 11848 false, false, callingUserId); 11849 11850 if (preferredHome != null) { 11851 if (callingUid == preferredHome.activityInfo.applicationInfo.uid) { 11852 return true; 11853 } 11854 } else { 11855 for (ResolveInfo info : allHomes) { 11856 if (callingUid == info.activityInfo.applicationInfo.uid) { 11857 return true; 11858 } 11859 } 11860 } 11861 11862 return false; 11863 } 11864 11865 /** 11866 * Enforce that calling UID is the current home app. This handles both the 11867 * case where the user has selected a specific home app, and where there is 11868 * only one home app. 11869 */ 11870 public void enforceCallerIsHomeApp() { 11871 if (!checkCallerIsHomeApp()) { 11872 throw new SecurityException("Caller is not currently selected home app"); 11873 } 11874 } 11875 11876 @Override 11877 public void setApplicationEnabledSetting(String appPackageName, 11878 int newState, int flags, int userId, String callingPackage) { 11879 if (!sUserManager.exists(userId)) return; 11880 if (callingPackage == null) { 11881 callingPackage = Integer.toString(Binder.getCallingUid()); 11882 } 11883 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 11884 } 11885 11886 @Override 11887 public void setComponentEnabledSetting(ComponentName componentName, 11888 int newState, int flags, int userId) { 11889 if (!sUserManager.exists(userId)) return; 11890 setEnabledSetting(componentName.getPackageName(), 11891 componentName.getClassName(), newState, flags, userId, null); 11892 } 11893 11894 private void setEnabledSetting(final String packageName, String className, int newState, 11895 final int flags, int userId, String callingPackage) { 11896 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 11897 || newState == COMPONENT_ENABLED_STATE_ENABLED 11898 || newState == COMPONENT_ENABLED_STATE_DISABLED 11899 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 11900 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 11901 throw new IllegalArgumentException("Invalid new component state: " 11902 + newState); 11903 } 11904 PackageSetting pkgSetting; 11905 final int uid = Binder.getCallingUid(); 11906 final int permission = mContext.checkCallingOrSelfPermission( 11907 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11908 enforceCrossUserPermission(uid, userId, false, "set enabled"); 11909 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11910 boolean sendNow = false; 11911 boolean isApp = (className == null); 11912 String componentName = isApp ? packageName : className; 11913 int packageUid = -1; 11914 ArrayList<String> components; 11915 11916 // writer 11917 synchronized (mPackages) { 11918 pkgSetting = mSettings.mPackages.get(packageName); 11919 if (pkgSetting == null) { 11920 if (className == null) { 11921 throw new IllegalArgumentException( 11922 "Unknown package: " + packageName); 11923 } 11924 throw new IllegalArgumentException( 11925 "Unknown component: " + packageName 11926 + "/" + className); 11927 } 11928 // Allow root and verify that userId is not being specified by a different user 11929 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 11930 throw new SecurityException( 11931 "Permission Denial: attempt to change component state from pid=" 11932 + Binder.getCallingPid() 11933 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 11934 } 11935 if (className == null) { 11936 // We're dealing with an application/package level state change 11937 if (pkgSetting.getEnabled(userId) == newState) { 11938 // Nothing to do 11939 return; 11940 } 11941 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 11942 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 11943 // Don't care about who enables an app. 11944 callingPackage = null; 11945 } 11946 pkgSetting.setEnabled(newState, userId, callingPackage); 11947 // pkgSetting.pkg.mSetEnabled = newState; 11948 } else { 11949 // We're dealing with a component level state change 11950 // First, verify that this is a valid class name. 11951 PackageParser.Package pkg = pkgSetting.pkg; 11952 if (pkg == null || !pkg.hasComponentClassName(className)) { 11953 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 11954 throw new IllegalArgumentException("Component class " + className 11955 + " does not exist in " + packageName); 11956 } else { 11957 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 11958 + className + " does not exist in " + packageName); 11959 } 11960 } 11961 switch (newState) { 11962 case COMPONENT_ENABLED_STATE_ENABLED: 11963 if (!pkgSetting.enableComponentLPw(className, userId)) { 11964 return; 11965 } 11966 break; 11967 case COMPONENT_ENABLED_STATE_DISABLED: 11968 if (!pkgSetting.disableComponentLPw(className, userId)) { 11969 return; 11970 } 11971 break; 11972 case COMPONENT_ENABLED_STATE_DEFAULT: 11973 if (!pkgSetting.restoreComponentLPw(className, userId)) { 11974 return; 11975 } 11976 break; 11977 default: 11978 Slog.e(TAG, "Invalid new component state: " + newState); 11979 return; 11980 } 11981 } 11982 mSettings.writePackageRestrictionsLPr(userId); 11983 components = mPendingBroadcasts.get(userId, packageName); 11984 final boolean newPackage = components == null; 11985 if (newPackage) { 11986 components = new ArrayList<String>(); 11987 } 11988 if (!components.contains(componentName)) { 11989 components.add(componentName); 11990 } 11991 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 11992 sendNow = true; 11993 // Purge entry from pending broadcast list if another one exists already 11994 // since we are sending one right away. 11995 mPendingBroadcasts.remove(userId, packageName); 11996 } else { 11997 if (newPackage) { 11998 mPendingBroadcasts.put(userId, packageName, components); 11999 } 12000 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 12001 // Schedule a message 12002 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 12003 } 12004 } 12005 } 12006 12007 long callingId = Binder.clearCallingIdentity(); 12008 try { 12009 if (sendNow) { 12010 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 12011 sendPackageChangedBroadcast(packageName, 12012 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 12013 } 12014 } finally { 12015 Binder.restoreCallingIdentity(callingId); 12016 } 12017 } 12018 12019 private void sendPackageChangedBroadcast(String packageName, 12020 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 12021 if (DEBUG_INSTALL) 12022 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 12023 + componentNames); 12024 Bundle extras = new Bundle(4); 12025 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 12026 String nameList[] = new String[componentNames.size()]; 12027 componentNames.toArray(nameList); 12028 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 12029 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 12030 extras.putInt(Intent.EXTRA_UID, packageUid); 12031 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 12032 new int[] {UserHandle.getUserId(packageUid)}); 12033 } 12034 12035 @Override 12036 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 12037 if (!sUserManager.exists(userId)) return; 12038 final int uid = Binder.getCallingUid(); 12039 final int permission = mContext.checkCallingOrSelfPermission( 12040 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 12041 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 12042 enforceCrossUserPermission(uid, userId, true, "stop package"); 12043 // writer 12044 synchronized (mPackages) { 12045 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 12046 uid, userId)) { 12047 scheduleWritePackageRestrictionsLocked(userId); 12048 } 12049 } 12050 } 12051 12052 @Override 12053 public String getInstallerPackageName(String packageName) { 12054 // reader 12055 synchronized (mPackages) { 12056 return mSettings.getInstallerPackageNameLPr(packageName); 12057 } 12058 } 12059 12060 @Override 12061 public int getApplicationEnabledSetting(String packageName, int userId) { 12062 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12063 int uid = Binder.getCallingUid(); 12064 enforceCrossUserPermission(uid, userId, false, "get enabled"); 12065 // reader 12066 synchronized (mPackages) { 12067 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 12068 } 12069 } 12070 12071 @Override 12072 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 12073 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12074 int uid = Binder.getCallingUid(); 12075 enforceCrossUserPermission(uid, userId, false, "get component enabled"); 12076 // reader 12077 synchronized (mPackages) { 12078 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 12079 } 12080 } 12081 12082 @Override 12083 public void enterSafeMode() { 12084 enforceSystemOrRoot("Only the system can request entering safe mode"); 12085 12086 if (!mSystemReady) { 12087 mSafeMode = true; 12088 } 12089 } 12090 12091 @Override 12092 public void systemReady() { 12093 mSystemReady = true; 12094 12095 // Read the compatibilty setting when the system is ready. 12096 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 12097 mContext.getContentResolver(), 12098 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 12099 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 12100 if (DEBUG_SETTINGS) { 12101 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 12102 } 12103 12104 synchronized (mPackages) { 12105 // Verify that all of the preferred activity components actually 12106 // exist. It is possible for applications to be updated and at 12107 // that point remove a previously declared activity component that 12108 // had been set as a preferred activity. We try to clean this up 12109 // the next time we encounter that preferred activity, but it is 12110 // possible for the user flow to never be able to return to that 12111 // situation so here we do a sanity check to make sure we haven't 12112 // left any junk around. 12113 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 12114 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12115 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12116 removed.clear(); 12117 for (PreferredActivity pa : pir.filterSet()) { 12118 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 12119 removed.add(pa); 12120 } 12121 } 12122 if (removed.size() > 0) { 12123 for (int r=0; r<removed.size(); r++) { 12124 PreferredActivity pa = removed.get(r); 12125 Slog.w(TAG, "Removing dangling preferred activity: " 12126 + pa.mPref.mComponent); 12127 pir.removeFilter(pa); 12128 } 12129 mSettings.writePackageRestrictionsLPr( 12130 mSettings.mPreferredActivities.keyAt(i)); 12131 } 12132 } 12133 } 12134 sUserManager.systemReady(); 12135 } 12136 12137 @Override 12138 public boolean isSafeMode() { 12139 return mSafeMode; 12140 } 12141 12142 @Override 12143 public boolean hasSystemUidErrors() { 12144 return mHasSystemUidErrors; 12145 } 12146 12147 static String arrayToString(int[] array) { 12148 StringBuffer buf = new StringBuffer(128); 12149 buf.append('['); 12150 if (array != null) { 12151 for (int i=0; i<array.length; i++) { 12152 if (i > 0) buf.append(", "); 12153 buf.append(array[i]); 12154 } 12155 } 12156 buf.append(']'); 12157 return buf.toString(); 12158 } 12159 12160 static class DumpState { 12161 public static final int DUMP_LIBS = 1 << 0; 12162 public static final int DUMP_FEATURES = 1 << 1; 12163 public static final int DUMP_RESOLVERS = 1 << 2; 12164 public static final int DUMP_PERMISSIONS = 1 << 3; 12165 public static final int DUMP_PACKAGES = 1 << 4; 12166 public static final int DUMP_SHARED_USERS = 1 << 5; 12167 public static final int DUMP_MESSAGES = 1 << 6; 12168 public static final int DUMP_PROVIDERS = 1 << 7; 12169 public static final int DUMP_VERIFIERS = 1 << 8; 12170 public static final int DUMP_PREFERRED = 1 << 9; 12171 public static final int DUMP_PREFERRED_XML = 1 << 10; 12172 public static final int DUMP_KEYSETS = 1 << 11; 12173 public static final int DUMP_VERSION = 1 << 12; 12174 public static final int DUMP_INSTALLS = 1 << 13; 12175 12176 public static final int OPTION_SHOW_FILTERS = 1 << 0; 12177 12178 private int mTypes; 12179 12180 private int mOptions; 12181 12182 private boolean mTitlePrinted; 12183 12184 private SharedUserSetting mSharedUser; 12185 12186 public boolean isDumping(int type) { 12187 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 12188 return true; 12189 } 12190 12191 return (mTypes & type) != 0; 12192 } 12193 12194 public void setDump(int type) { 12195 mTypes |= type; 12196 } 12197 12198 public boolean isOptionEnabled(int option) { 12199 return (mOptions & option) != 0; 12200 } 12201 12202 public void setOptionEnabled(int option) { 12203 mOptions |= option; 12204 } 12205 12206 public boolean onTitlePrinted() { 12207 final boolean printed = mTitlePrinted; 12208 mTitlePrinted = true; 12209 return printed; 12210 } 12211 12212 public boolean getTitlePrinted() { 12213 return mTitlePrinted; 12214 } 12215 12216 public void setTitlePrinted(boolean enabled) { 12217 mTitlePrinted = enabled; 12218 } 12219 12220 public SharedUserSetting getSharedUser() { 12221 return mSharedUser; 12222 } 12223 12224 public void setSharedUser(SharedUserSetting user) { 12225 mSharedUser = user; 12226 } 12227 } 12228 12229 @Override 12230 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 12231 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 12232 != PackageManager.PERMISSION_GRANTED) { 12233 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 12234 + Binder.getCallingPid() 12235 + ", uid=" + Binder.getCallingUid() 12236 + " without permission " 12237 + android.Manifest.permission.DUMP); 12238 return; 12239 } 12240 12241 DumpState dumpState = new DumpState(); 12242 boolean fullPreferred = false; 12243 boolean checkin = false; 12244 12245 String packageName = null; 12246 12247 int opti = 0; 12248 while (opti < args.length) { 12249 String opt = args[opti]; 12250 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 12251 break; 12252 } 12253 opti++; 12254 if ("-a".equals(opt)) { 12255 // Right now we only know how to print all. 12256 } else if ("-h".equals(opt)) { 12257 pw.println("Package manager dump options:"); 12258 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 12259 pw.println(" --checkin: dump for a checkin"); 12260 pw.println(" -f: print details of intent filters"); 12261 pw.println(" -h: print this help"); 12262 pw.println(" cmd may be one of:"); 12263 pw.println(" l[ibraries]: list known shared libraries"); 12264 pw.println(" f[ibraries]: list device features"); 12265 pw.println(" k[eysets]: print known keysets"); 12266 pw.println(" r[esolvers]: dump intent resolvers"); 12267 pw.println(" perm[issions]: dump permissions"); 12268 pw.println(" pref[erred]: print preferred package settings"); 12269 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 12270 pw.println(" prov[iders]: dump content providers"); 12271 pw.println(" p[ackages]: dump installed packages"); 12272 pw.println(" s[hared-users]: dump shared user IDs"); 12273 pw.println(" m[essages]: print collected runtime messages"); 12274 pw.println(" v[erifiers]: print package verifier info"); 12275 pw.println(" version: print database version info"); 12276 pw.println(" write: write current settings now"); 12277 pw.println(" <package.name>: info about given package"); 12278 pw.println(" installs: details about install sessions"); 12279 return; 12280 } else if ("--checkin".equals(opt)) { 12281 checkin = true; 12282 } else if ("-f".equals(opt)) { 12283 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12284 } else { 12285 pw.println("Unknown argument: " + opt + "; use -h for help"); 12286 } 12287 } 12288 12289 // Is the caller requesting to dump a particular piece of data? 12290 if (opti < args.length) { 12291 String cmd = args[opti]; 12292 opti++; 12293 // Is this a package name? 12294 if ("android".equals(cmd) || cmd.contains(".")) { 12295 packageName = cmd; 12296 // When dumping a single package, we always dump all of its 12297 // filter information since the amount of data will be reasonable. 12298 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12299 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 12300 dumpState.setDump(DumpState.DUMP_LIBS); 12301 } else if ("f".equals(cmd) || "features".equals(cmd)) { 12302 dumpState.setDump(DumpState.DUMP_FEATURES); 12303 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 12304 dumpState.setDump(DumpState.DUMP_RESOLVERS); 12305 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 12306 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 12307 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 12308 dumpState.setDump(DumpState.DUMP_PREFERRED); 12309 } else if ("preferred-xml".equals(cmd)) { 12310 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 12311 if (opti < args.length && "--full".equals(args[opti])) { 12312 fullPreferred = true; 12313 opti++; 12314 } 12315 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 12316 dumpState.setDump(DumpState.DUMP_PACKAGES); 12317 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 12318 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 12319 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 12320 dumpState.setDump(DumpState.DUMP_PROVIDERS); 12321 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 12322 dumpState.setDump(DumpState.DUMP_MESSAGES); 12323 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 12324 dumpState.setDump(DumpState.DUMP_VERIFIERS); 12325 } else if ("version".equals(cmd)) { 12326 dumpState.setDump(DumpState.DUMP_VERSION); 12327 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 12328 dumpState.setDump(DumpState.DUMP_KEYSETS); 12329 } else if ("write".equals(cmd)) { 12330 synchronized (mPackages) { 12331 mSettings.writeLPr(); 12332 pw.println("Settings written."); 12333 return; 12334 } 12335 } else if ("installs".equals(cmd)) { 12336 dumpState.setDump(DumpState.DUMP_INSTALLS); 12337 } 12338 } 12339 12340 if (checkin) { 12341 pw.println("vers,1"); 12342 } 12343 12344 // reader 12345 synchronized (mPackages) { 12346 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 12347 if (!checkin) { 12348 if (dumpState.onTitlePrinted()) 12349 pw.println(); 12350 pw.println("Database versions:"); 12351 pw.print(" SDK Version:"); 12352 pw.print(" internal="); 12353 pw.print(mSettings.mInternalSdkPlatform); 12354 pw.print(" external="); 12355 pw.println(mSettings.mExternalSdkPlatform); 12356 pw.print(" DB Version:"); 12357 pw.print(" internal="); 12358 pw.print(mSettings.mInternalDatabaseVersion); 12359 pw.print(" external="); 12360 pw.println(mSettings.mExternalDatabaseVersion); 12361 } 12362 } 12363 12364 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 12365 if (!checkin) { 12366 if (dumpState.onTitlePrinted()) 12367 pw.println(); 12368 pw.println("Verifiers:"); 12369 pw.print(" Required: "); 12370 pw.print(mRequiredVerifierPackage); 12371 pw.print(" (uid="); 12372 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 12373 pw.println(")"); 12374 } else if (mRequiredVerifierPackage != null) { 12375 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 12376 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 12377 } 12378 } 12379 12380 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 12381 boolean printedHeader = false; 12382 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 12383 while (it.hasNext()) { 12384 String name = it.next(); 12385 SharedLibraryEntry ent = mSharedLibraries.get(name); 12386 if (!checkin) { 12387 if (!printedHeader) { 12388 if (dumpState.onTitlePrinted()) 12389 pw.println(); 12390 pw.println("Libraries:"); 12391 printedHeader = true; 12392 } 12393 pw.print(" "); 12394 } else { 12395 pw.print("lib,"); 12396 } 12397 pw.print(name); 12398 if (!checkin) { 12399 pw.print(" -> "); 12400 } 12401 if (ent.path != null) { 12402 if (!checkin) { 12403 pw.print("(jar) "); 12404 pw.print(ent.path); 12405 } else { 12406 pw.print(",jar,"); 12407 pw.print(ent.path); 12408 } 12409 } else { 12410 if (!checkin) { 12411 pw.print("(apk) "); 12412 pw.print(ent.apk); 12413 } else { 12414 pw.print(",apk,"); 12415 pw.print(ent.apk); 12416 } 12417 } 12418 pw.println(); 12419 } 12420 } 12421 12422 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 12423 if (dumpState.onTitlePrinted()) 12424 pw.println(); 12425 if (!checkin) { 12426 pw.println("Features:"); 12427 } 12428 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 12429 while (it.hasNext()) { 12430 String name = it.next(); 12431 if (!checkin) { 12432 pw.print(" "); 12433 } else { 12434 pw.print("feat,"); 12435 } 12436 pw.println(name); 12437 } 12438 } 12439 12440 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 12441 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 12442 : "Activity Resolver Table:", " ", packageName, 12443 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12444 dumpState.setTitlePrinted(true); 12445 } 12446 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 12447 : "Receiver Resolver Table:", " ", packageName, 12448 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12449 dumpState.setTitlePrinted(true); 12450 } 12451 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 12452 : "Service Resolver Table:", " ", packageName, 12453 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12454 dumpState.setTitlePrinted(true); 12455 } 12456 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 12457 : "Provider Resolver Table:", " ", packageName, 12458 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12459 dumpState.setTitlePrinted(true); 12460 } 12461 } 12462 12463 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 12464 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12465 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12466 int user = mSettings.mPreferredActivities.keyAt(i); 12467 if (pir.dump(pw, 12468 dumpState.getTitlePrinted() 12469 ? "\nPreferred Activities User " + user + ":" 12470 : "Preferred Activities User " + user + ":", " ", 12471 packageName, true)) { 12472 dumpState.setTitlePrinted(true); 12473 } 12474 } 12475 } 12476 12477 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 12478 pw.flush(); 12479 FileOutputStream fout = new FileOutputStream(fd); 12480 BufferedOutputStream str = new BufferedOutputStream(fout); 12481 XmlSerializer serializer = new FastXmlSerializer(); 12482 try { 12483 serializer.setOutput(str, "utf-8"); 12484 serializer.startDocument(null, true); 12485 serializer.setFeature( 12486 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 12487 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 12488 serializer.endDocument(); 12489 serializer.flush(); 12490 } catch (IllegalArgumentException e) { 12491 pw.println("Failed writing: " + e); 12492 } catch (IllegalStateException e) { 12493 pw.println("Failed writing: " + e); 12494 } catch (IOException e) { 12495 pw.println("Failed writing: " + e); 12496 } 12497 } 12498 12499 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 12500 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 12501 if (packageName == null) { 12502 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 12503 if (iperm == 0) { 12504 if (dumpState.onTitlePrinted()) 12505 pw.println(); 12506 pw.println("AppOp Permissions:"); 12507 } 12508 pw.print(" AppOp Permission "); 12509 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 12510 pw.println(":"); 12511 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 12512 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 12513 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 12514 } 12515 } 12516 } 12517 } 12518 12519 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 12520 boolean printedSomething = false; 12521 for (PackageParser.Provider p : mProviders.mProviders.values()) { 12522 if (packageName != null && !packageName.equals(p.info.packageName)) { 12523 continue; 12524 } 12525 if (!printedSomething) { 12526 if (dumpState.onTitlePrinted()) 12527 pw.println(); 12528 pw.println("Registered ContentProviders:"); 12529 printedSomething = true; 12530 } 12531 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 12532 pw.print(" "); pw.println(p.toString()); 12533 } 12534 printedSomething = false; 12535 for (Map.Entry<String, PackageParser.Provider> entry : 12536 mProvidersByAuthority.entrySet()) { 12537 PackageParser.Provider p = entry.getValue(); 12538 if (packageName != null && !packageName.equals(p.info.packageName)) { 12539 continue; 12540 } 12541 if (!printedSomething) { 12542 if (dumpState.onTitlePrinted()) 12543 pw.println(); 12544 pw.println("ContentProvider Authorities:"); 12545 printedSomething = true; 12546 } 12547 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 12548 pw.print(" "); pw.println(p.toString()); 12549 if (p.info != null && p.info.applicationInfo != null) { 12550 final String appInfo = p.info.applicationInfo.toString(); 12551 pw.print(" applicationInfo="); pw.println(appInfo); 12552 } 12553 } 12554 } 12555 12556 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 12557 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 12558 } 12559 12560 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 12561 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 12562 } 12563 12564 if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 12565 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState); 12566 } 12567 12568 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS)) { 12569 if (dumpState.onTitlePrinted()) pw.println(); 12570 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 12571 } 12572 12573 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 12574 if (dumpState.onTitlePrinted()) pw.println(); 12575 mSettings.dumpReadMessagesLPr(pw, dumpState); 12576 12577 pw.println(); 12578 pw.println("Package warning messages:"); 12579 final File fname = getSettingsProblemFile(); 12580 FileInputStream in = null; 12581 try { 12582 in = new FileInputStream(fname); 12583 final int avail = in.available(); 12584 final byte[] data = new byte[avail]; 12585 in.read(data); 12586 pw.print(new String(data)); 12587 } catch (FileNotFoundException e) { 12588 } catch (IOException e) { 12589 } finally { 12590 if (in != null) { 12591 try { 12592 in.close(); 12593 } catch (IOException e) { 12594 } 12595 } 12596 } 12597 } 12598 } 12599 } 12600 12601 // ------- apps on sdcard specific code ------- 12602 static final boolean DEBUG_SD_INSTALL = false; 12603 12604 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 12605 12606 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 12607 12608 private boolean mMediaMounted = false; 12609 12610 static String getEncryptKey() { 12611 try { 12612 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 12613 SD_ENCRYPTION_KEYSTORE_NAME); 12614 if (sdEncKey == null) { 12615 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 12616 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 12617 if (sdEncKey == null) { 12618 Slog.e(TAG, "Failed to create encryption keys"); 12619 return null; 12620 } 12621 } 12622 return sdEncKey; 12623 } catch (NoSuchAlgorithmException nsae) { 12624 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 12625 return null; 12626 } catch (IOException ioe) { 12627 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 12628 return null; 12629 } 12630 } 12631 12632 /* 12633 * Update media status on PackageManager. 12634 */ 12635 @Override 12636 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 12637 int callingUid = Binder.getCallingUid(); 12638 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 12639 throw new SecurityException("Media status can only be updated by the system"); 12640 } 12641 // reader; this apparently protects mMediaMounted, but should probably 12642 // be a different lock in that case. 12643 synchronized (mPackages) { 12644 Log.i(TAG, "Updating external media status from " 12645 + (mMediaMounted ? "mounted" : "unmounted") + " to " 12646 + (mediaStatus ? "mounted" : "unmounted")); 12647 if (DEBUG_SD_INSTALL) 12648 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 12649 + ", mMediaMounted=" + mMediaMounted); 12650 if (mediaStatus == mMediaMounted) { 12651 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 12652 : 0, -1); 12653 mHandler.sendMessage(msg); 12654 return; 12655 } 12656 mMediaMounted = mediaStatus; 12657 } 12658 // Queue up an async operation since the package installation may take a 12659 // little while. 12660 mHandler.post(new Runnable() { 12661 public void run() { 12662 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 12663 } 12664 }); 12665 } 12666 12667 /** 12668 * Called by MountService when the initial ASECs to scan are available. 12669 * Should block until all the ASEC containers are finished being scanned. 12670 */ 12671 public void scanAvailableAsecs() { 12672 updateExternalMediaStatusInner(true, false, false); 12673 if (mShouldRestoreconData) { 12674 SELinuxMMAC.setRestoreconDone(); 12675 mShouldRestoreconData = false; 12676 } 12677 } 12678 12679 /* 12680 * Collect information of applications on external media, map them against 12681 * existing containers and update information based on current mount status. 12682 * Please note that we always have to report status if reportStatus has been 12683 * set to true especially when unloading packages. 12684 */ 12685 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 12686 boolean externalStorage) { 12687 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 12688 int[] uidArr = EmptyArray.INT; 12689 12690 final String[] list = PackageHelper.getSecureContainerList(); 12691 if (ArrayUtils.isEmpty(list)) { 12692 Log.i(TAG, "No secure containers found"); 12693 } else { 12694 // Process list of secure containers and categorize them 12695 // as active or stale based on their package internal state. 12696 12697 // reader 12698 synchronized (mPackages) { 12699 for (String cid : list) { 12700 // Leave stages untouched for now; installer service owns them 12701 if (PackageInstallerService.isStageName(cid)) continue; 12702 12703 if (DEBUG_SD_INSTALL) 12704 Log.i(TAG, "Processing container " + cid); 12705 String pkgName = getAsecPackageName(cid); 12706 if (pkgName == null) { 12707 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 12708 continue; 12709 } 12710 if (DEBUG_SD_INSTALL) 12711 Log.i(TAG, "Looking for pkg : " + pkgName); 12712 12713 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12714 if (ps == null) { 12715 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 12716 continue; 12717 } 12718 12719 /* 12720 * Skip packages that are not external if we're unmounting 12721 * external storage. 12722 */ 12723 if (externalStorage && !isMounted && !isExternal(ps)) { 12724 continue; 12725 } 12726 12727 final AsecInstallArgs args = new AsecInstallArgs(cid, 12728 getAppDexInstructionSets(ps), isForwardLocked(ps), isMultiArch(ps)); 12729 // The package status is changed only if the code path 12730 // matches between settings and the container id. 12731 if (ps.codePathString != null 12732 && ps.codePathString.startsWith(args.getCodePath())) { 12733 if (DEBUG_SD_INSTALL) { 12734 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 12735 + " at code path: " + ps.codePathString); 12736 } 12737 12738 // We do have a valid package installed on sdcard 12739 processCids.put(args, ps.codePathString); 12740 final int uid = ps.appId; 12741 if (uid != -1) { 12742 uidArr = ArrayUtils.appendInt(uidArr, uid); 12743 } 12744 } else { 12745 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 12746 + ps.codePathString); 12747 } 12748 } 12749 } 12750 12751 Arrays.sort(uidArr); 12752 } 12753 12754 // Process packages with valid entries. 12755 if (isMounted) { 12756 if (DEBUG_SD_INSTALL) 12757 Log.i(TAG, "Loading packages"); 12758 loadMediaPackages(processCids, uidArr); 12759 startCleaningPackages(); 12760 mInstallerService.onSecureContainersAvailable(); 12761 } else { 12762 if (DEBUG_SD_INSTALL) 12763 Log.i(TAG, "Unloading packages"); 12764 unloadMediaPackages(processCids, uidArr, reportStatus); 12765 } 12766 } 12767 12768 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 12769 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 12770 int size = pkgList.size(); 12771 if (size > 0) { 12772 // Send broadcasts here 12773 Bundle extras = new Bundle(); 12774 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 12775 .toArray(new String[size])); 12776 if (uidArr != null) { 12777 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 12778 } 12779 if (replacing) { 12780 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 12781 } 12782 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 12783 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 12784 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 12785 } 12786 } 12787 12788 /* 12789 * Look at potentially valid container ids from processCids If package 12790 * information doesn't match the one on record or package scanning fails, 12791 * the cid is added to list of removeCids. We currently don't delete stale 12792 * containers. 12793 */ 12794 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 12795 ArrayList<String> pkgList = new ArrayList<String>(); 12796 Set<AsecInstallArgs> keys = processCids.keySet(); 12797 12798 for (AsecInstallArgs args : keys) { 12799 String codePath = processCids.get(args); 12800 if (DEBUG_SD_INSTALL) 12801 Log.i(TAG, "Loading container : " + args.cid); 12802 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12803 try { 12804 // Make sure there are no container errors first. 12805 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 12806 Slog.e(TAG, "Failed to mount cid : " + args.cid 12807 + " when installing from sdcard"); 12808 continue; 12809 } 12810 // Check code path here. 12811 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 12812 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 12813 + " does not match one in settings " + codePath); 12814 continue; 12815 } 12816 // Parse package 12817 int parseFlags = mDefParseFlags; 12818 if (args.isExternal()) { 12819 parseFlags |= PackageParser.PARSE_ON_SDCARD; 12820 } 12821 if (args.isFwdLocked()) { 12822 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 12823 } 12824 12825 synchronized (mInstallLock) { 12826 PackageParser.Package pkg = null; 12827 try { 12828 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 12829 } catch (PackageManagerException e) { 12830 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 12831 } 12832 // Scan the package 12833 if (pkg != null) { 12834 /* 12835 * TODO why is the lock being held? doPostInstall is 12836 * called in other places without the lock. This needs 12837 * to be straightened out. 12838 */ 12839 // writer 12840 synchronized (mPackages) { 12841 retCode = PackageManager.INSTALL_SUCCEEDED; 12842 pkgList.add(pkg.packageName); 12843 // Post process args 12844 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 12845 pkg.applicationInfo.uid); 12846 } 12847 } else { 12848 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 12849 } 12850 } 12851 12852 } finally { 12853 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 12854 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 12855 } 12856 } 12857 } 12858 // writer 12859 synchronized (mPackages) { 12860 // If the platform SDK has changed since the last time we booted, 12861 // we need to re-grant app permission to catch any new ones that 12862 // appear. This is really a hack, and means that apps can in some 12863 // cases get permissions that the user didn't initially explicitly 12864 // allow... it would be nice to have some better way to handle 12865 // this situation. 12866 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 12867 if (regrantPermissions) 12868 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 12869 + mSdkVersion + "; regranting permissions for external storage"); 12870 mSettings.mExternalSdkPlatform = mSdkVersion; 12871 12872 // Make sure group IDs have been assigned, and any permission 12873 // changes in other apps are accounted for 12874 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 12875 | (regrantPermissions 12876 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 12877 : 0)); 12878 12879 mSettings.updateExternalDatabaseVersion(); 12880 12881 // can downgrade to reader 12882 // Persist settings 12883 mSettings.writeLPr(); 12884 } 12885 // Send a broadcast to let everyone know we are done processing 12886 if (pkgList.size() > 0) { 12887 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12888 } 12889 } 12890 12891 /* 12892 * Utility method to unload a list of specified containers 12893 */ 12894 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 12895 // Just unmount all valid containers. 12896 for (AsecInstallArgs arg : cidArgs) { 12897 synchronized (mInstallLock) { 12898 arg.doPostDeleteLI(false); 12899 } 12900 } 12901 } 12902 12903 /* 12904 * Unload packages mounted on external media. This involves deleting package 12905 * data from internal structures, sending broadcasts about diabled packages, 12906 * gc'ing to free up references, unmounting all secure containers 12907 * corresponding to packages on external media, and posting a 12908 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 12909 * that we always have to post this message if status has been requested no 12910 * matter what. 12911 */ 12912 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 12913 final boolean reportStatus) { 12914 if (DEBUG_SD_INSTALL) 12915 Log.i(TAG, "unloading media packages"); 12916 ArrayList<String> pkgList = new ArrayList<String>(); 12917 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 12918 final Set<AsecInstallArgs> keys = processCids.keySet(); 12919 for (AsecInstallArgs args : keys) { 12920 String pkgName = args.getPackageName(); 12921 if (DEBUG_SD_INSTALL) 12922 Log.i(TAG, "Trying to unload pkg : " + pkgName); 12923 // Delete package internally 12924 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 12925 synchronized (mInstallLock) { 12926 boolean res = deletePackageLI(pkgName, null, false, null, null, 12927 PackageManager.DELETE_KEEP_DATA, outInfo, false); 12928 if (res) { 12929 pkgList.add(pkgName); 12930 } else { 12931 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 12932 failedList.add(args); 12933 } 12934 } 12935 } 12936 12937 // reader 12938 synchronized (mPackages) { 12939 // We didn't update the settings after removing each package; 12940 // write them now for all packages. 12941 mSettings.writeLPr(); 12942 } 12943 12944 // We have to absolutely send UPDATED_MEDIA_STATUS only 12945 // after confirming that all the receivers processed the ordered 12946 // broadcast when packages get disabled, force a gc to clean things up. 12947 // and unload all the containers. 12948 if (pkgList.size() > 0) { 12949 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 12950 new IIntentReceiver.Stub() { 12951 public void performReceive(Intent intent, int resultCode, String data, 12952 Bundle extras, boolean ordered, boolean sticky, 12953 int sendingUser) throws RemoteException { 12954 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 12955 reportStatus ? 1 : 0, 1, keys); 12956 mHandler.sendMessage(msg); 12957 } 12958 }); 12959 } else { 12960 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 12961 keys); 12962 mHandler.sendMessage(msg); 12963 } 12964 } 12965 12966 /** Binder call */ 12967 @Override 12968 public void movePackage(final String packageName, final IPackageMoveObserver observer, 12969 final int flags) { 12970 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 12971 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 12972 int returnCode = PackageManager.MOVE_SUCCEEDED; 12973 int currFlags = 0; 12974 int newFlags = 0; 12975 // reader 12976 synchronized (mPackages) { 12977 PackageParser.Package pkg = mPackages.get(packageName); 12978 if (pkg == null) { 12979 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12980 } else { 12981 // Disable moving fwd locked apps and system packages 12982 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 12983 Slog.w(TAG, "Cannot move system application"); 12984 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 12985 } else if (pkg.mOperationPending) { 12986 Slog.w(TAG, "Attempt to move package which has pending operations"); 12987 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 12988 } else { 12989 // Find install location first 12990 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 12991 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 12992 Slog.w(TAG, "Ambigous flags specified for move location."); 12993 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12994 } else { 12995 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL 12996 : PackageManager.INSTALL_INTERNAL; 12997 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL 12998 : PackageManager.INSTALL_INTERNAL; 12999 13000 if (newFlags == currFlags) { 13001 Slog.w(TAG, "No move required. Trying to move to same location"); 13002 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 13003 } else { 13004 if (isForwardLocked(pkg)) { 13005 currFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13006 newFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13007 } 13008 } 13009 } 13010 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13011 pkg.mOperationPending = true; 13012 } 13013 } 13014 } 13015 13016 /* 13017 * TODO this next block probably shouldn't be inside the lock. We 13018 * can't guarantee these won't change after this is fired off 13019 * anyway. 13020 */ 13021 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 13022 processPendingMove(new MoveParams(null, observer, 0, packageName, null, -1, user, false), 13023 returnCode); 13024 } else { 13025 Message msg = mHandler.obtainMessage(INIT_COPY); 13026 final String[] instructionSets = getAppDexInstructionSets(pkg.applicationInfo); 13027 final boolean multiArch = isMultiArch(pkg.applicationInfo); 13028 InstallArgs srcArgs = createInstallArgsForExisting(currFlags, 13029 pkg.applicationInfo.getCodePath(), pkg.applicationInfo.getResourcePath(), 13030 pkg.applicationInfo.nativeLibraryRootDir, instructionSets, multiArch); 13031 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName, 13032 instructionSets, pkg.applicationInfo.uid, user, multiArch); 13033 msg.obj = mp; 13034 mHandler.sendMessage(msg); 13035 } 13036 } 13037 } 13038 13039 private void processPendingMove(final MoveParams mp, final int currentStatus) { 13040 // Queue up an async operation since the package deletion may take a 13041 // little while. 13042 mHandler.post(new Runnable() { 13043 public void run() { 13044 // TODO fix this; this does nothing. 13045 mHandler.removeCallbacks(this); 13046 int returnCode = currentStatus; 13047 if (currentStatus == PackageManager.MOVE_SUCCEEDED) { 13048 int uidArr[] = null; 13049 ArrayList<String> pkgList = null; 13050 synchronized (mPackages) { 13051 PackageParser.Package pkg = mPackages.get(mp.packageName); 13052 if (pkg == null) { 13053 Slog.w(TAG, " Package " + mp.packageName 13054 + " doesn't exist. Aborting move"); 13055 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 13056 } else if (!mp.srcArgs.getCodePath().equals( 13057 pkg.applicationInfo.getCodePath())) { 13058 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " 13059 + mp.srcArgs.getCodePath() + " to " 13060 + pkg.applicationInfo.getCodePath() 13061 + " Aborting move and returning error"); 13062 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 13063 } else { 13064 uidArr = new int[] { 13065 pkg.applicationInfo.uid 13066 }; 13067 pkgList = new ArrayList<String>(); 13068 pkgList.add(mp.packageName); 13069 } 13070 } 13071 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13072 // Send resources unavailable broadcast 13073 sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null); 13074 // Update package code and resource paths 13075 synchronized (mInstallLock) { 13076 synchronized (mPackages) { 13077 PackageParser.Package pkg = mPackages.get(mp.packageName); 13078 // Recheck for package again. 13079 if (pkg == null) { 13080 Slog.w(TAG, " Package " + mp.packageName 13081 + " doesn't exist. Aborting move"); 13082 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 13083 } else if (!mp.srcArgs.getCodePath().equals( 13084 pkg.applicationInfo.getCodePath())) { 13085 Slog.w(TAG, "Package " + mp.packageName 13086 + " code path changed from " + mp.srcArgs.getCodePath() 13087 + " to " + pkg.applicationInfo.getCodePath() 13088 + " Aborting move and returning error"); 13089 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 13090 } else { 13091 final String oldCodePath = pkg.codePath; 13092 final String newCodePath = mp.targetArgs.getCodePath(); 13093 final String newResPath = mp.targetArgs.getResourcePath(); 13094 // TODO: This assumes the new style of installation. 13095 // should we look at legacyNativeLibraryPath ? 13096 final String newNativeRoot = new File(pkg.codePath, LIB_DIR_NAME).getAbsolutePath(); 13097 final File newNativeDir = new File(newNativeRoot); 13098 13099 if (!isForwardLocked(pkg) && !isExternal(pkg)) { 13100 // TODO(multiArch): Fix this so that it looks at the existing 13101 // recorded CPU abis from the package. There's no need for a separate 13102 // round of ABI scanning here. 13103 NativeLibraryHelper.Handle handle = null; 13104 try { 13105 handle = NativeLibraryHelper.Handle.create( 13106 new File(newCodePath)); 13107 final int abi = NativeLibraryHelper.findSupportedAbi( 13108 handle, Build.SUPPORTED_ABIS); 13109 if (abi >= 0) { 13110 NativeLibraryHelper.copyNativeBinariesIfNeededLI( 13111 handle, newNativeDir, Build.SUPPORTED_ABIS[abi]); 13112 } 13113 } catch (IOException ioe) { 13114 Slog.w(TAG, "Unable to extract native libs for package :" 13115 + mp.packageName, ioe); 13116 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 13117 } finally { 13118 IoUtils.closeQuietly(handle); 13119 } 13120 } 13121 13122 final int[] users = sUserManager.getUserIds(); 13123 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13124 for (int user : users) { 13125 // TODO(multiArch): Fix this so that it links to the 13126 // correct directory. We're currently pointing to root. but we 13127 // must point to the arch specific subdirectory (if applicable). 13128 // 13129 // TODO(multiArch): Bogus reference to nativeLibraryDir. 13130 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, 13131 newNativeRoot, user) < 0) { 13132 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 13133 } 13134 } 13135 } 13136 13137 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13138 pkg.codePath = newCodePath; 13139 pkg.baseCodePath = newCodePath; 13140 // Move dex files around 13141 if (moveDexFilesLI(oldCodePath, pkg) != PackageManager.INSTALL_SUCCEEDED) { 13142 // Moving of dex files failed. Set 13143 // error code and abort move. 13144 pkg.codePath = oldCodePath; 13145 pkg.baseCodePath = oldCodePath; 13146 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 13147 } 13148 } 13149 13150 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13151 pkg.applicationInfo.setCodePath(newCodePath); 13152 pkg.applicationInfo.setBaseCodePath(newCodePath); 13153 pkg.applicationInfo.setSplitCodePaths(null); 13154 pkg.applicationInfo.setResourcePath(newResPath); 13155 pkg.applicationInfo.setBaseResourcePath(newResPath); 13156 pkg.applicationInfo.setSplitResourcePaths(null); 13157 13158 PackageSetting ps = (PackageSetting) pkg.mExtras; 13159 ps.codePath = new File(pkg.applicationInfo.getCodePath()); 13160 ps.codePathString = ps.codePath.getPath(); 13161 ps.resourcePath = new File(pkg.applicationInfo.getResourcePath()); 13162 ps.resourcePathString = ps.resourcePath.getPath(); 13163 13164 // Note that we don't have to recalculate the primary and secondary 13165 // CPU ABIs because they must already have been calculated during the 13166 // initial install of the app. 13167 ps.legacyNativeLibraryPathString = null; 13168 13169 // Set the application info flag 13170 // correctly. 13171 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) { 13172 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE; 13173 } else { 13174 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE; 13175 } 13176 ps.setFlags(pkg.applicationInfo.flags); 13177 mAppDirs.remove(oldCodePath); 13178 mAppDirs.put(newCodePath, pkg); 13179 // Persist settings 13180 mSettings.writeLPr(); 13181 } 13182 } 13183 } 13184 } 13185 // Send resources available broadcast 13186 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 13187 } 13188 } 13189 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 13190 // Clean up failed installation 13191 if (mp.targetArgs != null) { 13192 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR, 13193 -1); 13194 } 13195 } else { 13196 // Force a gc to clear things up. 13197 Runtime.getRuntime().gc(); 13198 // Delete older code 13199 synchronized (mInstallLock) { 13200 mp.srcArgs.doPostDeleteLI(true); 13201 } 13202 } 13203 13204 // Allow more operations on this file if we didn't fail because 13205 // an operation was already pending for this package. 13206 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) { 13207 synchronized (mPackages) { 13208 PackageParser.Package pkg = mPackages.get(mp.packageName); 13209 if (pkg != null) { 13210 pkg.mOperationPending = false; 13211 } 13212 } 13213 } 13214 13215 IPackageMoveObserver observer = mp.observer; 13216 if (observer != null) { 13217 try { 13218 observer.packageMoved(mp.packageName, returnCode); 13219 } catch (RemoteException e) { 13220 Log.i(TAG, "Observer no longer exists."); 13221 } 13222 } 13223 } 13224 }); 13225 } 13226 13227 @Override 13228 public boolean setInstallLocation(int loc) { 13229 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 13230 null); 13231 if (getInstallLocation() == loc) { 13232 return true; 13233 } 13234 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 13235 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 13236 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 13237 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 13238 return true; 13239 } 13240 return false; 13241 } 13242 13243 @Override 13244 public int getInstallLocation() { 13245 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13246 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 13247 PackageHelper.APP_INSTALL_AUTO); 13248 } 13249 13250 /** Called by UserManagerService */ 13251 void cleanUpUserLILPw(int userHandle) { 13252 mDirtyUsers.remove(userHandle); 13253 mSettings.removeUserLPw(userHandle); 13254 mPendingBroadcasts.remove(userHandle); 13255 if (mInstaller != null) { 13256 // Technically, we shouldn't be doing this with the package lock 13257 // held. However, this is very rare, and there is already so much 13258 // other disk I/O going on, that we'll let it slide for now. 13259 mInstaller.removeUserDataDirs(userHandle); 13260 } 13261 mUserNeedsBadging.delete(userHandle); 13262 } 13263 13264 /** Called by UserManagerService */ 13265 void createNewUserLILPw(int userHandle, File path) { 13266 if (mInstaller != null) { 13267 mInstaller.createUserConfig(userHandle); 13268 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 13269 } 13270 } 13271 13272 @Override 13273 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 13274 mContext.enforceCallingOrSelfPermission( 13275 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13276 "Only package verification agents can read the verifier device identity"); 13277 13278 synchronized (mPackages) { 13279 return mSettings.getVerifierDeviceIdentityLPw(); 13280 } 13281 } 13282 13283 @Override 13284 public void setPermissionEnforced(String permission, boolean enforced) { 13285 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 13286 if (READ_EXTERNAL_STORAGE.equals(permission)) { 13287 synchronized (mPackages) { 13288 if (mSettings.mReadExternalStorageEnforced == null 13289 || mSettings.mReadExternalStorageEnforced != enforced) { 13290 mSettings.mReadExternalStorageEnforced = enforced; 13291 mSettings.writeLPr(); 13292 } 13293 } 13294 // kill any non-foreground processes so we restart them and 13295 // grant/revoke the GID. 13296 final IActivityManager am = ActivityManagerNative.getDefault(); 13297 if (am != null) { 13298 final long token = Binder.clearCallingIdentity(); 13299 try { 13300 am.killProcessesBelowForeground("setPermissionEnforcement"); 13301 } catch (RemoteException e) { 13302 } finally { 13303 Binder.restoreCallingIdentity(token); 13304 } 13305 } 13306 } else { 13307 throw new IllegalArgumentException("No selective enforcement for " + permission); 13308 } 13309 } 13310 13311 @Override 13312 @Deprecated 13313 public boolean isPermissionEnforced(String permission) { 13314 return true; 13315 } 13316 13317 @Override 13318 public boolean isStorageLow() { 13319 final long token = Binder.clearCallingIdentity(); 13320 try { 13321 final DeviceStorageMonitorInternal 13322 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13323 if (dsm != null) { 13324 return dsm.isMemoryLow(); 13325 } else { 13326 return false; 13327 } 13328 } finally { 13329 Binder.restoreCallingIdentity(token); 13330 } 13331 } 13332 13333 @Override 13334 public IPackageInstaller getPackageInstaller() { 13335 return mInstallerService; 13336 } 13337 13338 private boolean userNeedsBadging(int userId) { 13339 int index = mUserNeedsBadging.indexOfKey(userId); 13340 if (index < 0) { 13341 final UserInfo userInfo; 13342 final long token = Binder.clearCallingIdentity(); 13343 try { 13344 userInfo = sUserManager.getUserInfo(userId); 13345 } finally { 13346 Binder.restoreCallingIdentity(token); 13347 } 13348 final boolean b; 13349 if (userInfo != null && userInfo.isManagedProfile()) { 13350 b = true; 13351 } else { 13352 b = false; 13353 } 13354 mUserNeedsBadging.put(userId, b); 13355 return b; 13356 } 13357 return mUserNeedsBadging.valueAt(index); 13358 } 13359 13360 @Override 13361 public KeySetHandle getKeySetByAlias(String packageName, String alias) { 13362 if (packageName == null || alias == null) { 13363 return null; 13364 } 13365 synchronized(mPackages) { 13366 final PackageParser.Package pkg = mPackages.get(packageName); 13367 if (pkg == null) { 13368 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13369 throw new IllegalArgumentException("Unknown package: " + packageName); 13370 } 13371 if (pkg.applicationInfo.uid != Binder.getCallingUid() 13372 && Process.SYSTEM_UID != Binder.getCallingUid()) { 13373 throw new SecurityException("May not access KeySets defined by" 13374 + " aliases in other applications."); 13375 } 13376 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13377 return ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias); 13378 } 13379 } 13380 13381 @Override 13382 public KeySetHandle getSigningKeySet(String packageName) { 13383 if (packageName == null) { 13384 return null; 13385 } 13386 synchronized(mPackages) { 13387 final PackageParser.Package pkg = mPackages.get(packageName); 13388 if (pkg == null) { 13389 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13390 throw new IllegalArgumentException("Unknown package: " + packageName); 13391 } 13392 if (pkg.applicationInfo.uid != Binder.getCallingUid() 13393 && Process.SYSTEM_UID != Binder.getCallingUid()) { 13394 throw new SecurityException("May not access signing KeySet of other apps."); 13395 } 13396 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13397 return ksms.getSigningKeySetByPackageNameLPr(packageName); 13398 } 13399 } 13400 13401 @Override 13402 public boolean isPackageSignedByKeySet(String packageName, IBinder ks) { 13403 if (packageName == null || ks == null) { 13404 return false; 13405 } 13406 synchronized(mPackages) { 13407 final PackageParser.Package pkg = mPackages.get(packageName); 13408 if (pkg == null) { 13409 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13410 throw new IllegalArgumentException("Unknown package: " + packageName); 13411 } 13412 if (ks instanceof KeySetHandle) { 13413 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13414 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ks); 13415 } 13416 return false; 13417 } 13418 } 13419 13420 @Override 13421 public boolean isPackageSignedByKeySetExactly(String packageName, IBinder ks) { 13422 if (packageName == null || ks == null) { 13423 return false; 13424 } 13425 synchronized(mPackages) { 13426 final PackageParser.Package pkg = mPackages.get(packageName); 13427 if (pkg == null) { 13428 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13429 throw new IllegalArgumentException("Unknown package: " + packageName); 13430 } 13431 if (ks instanceof KeySetHandle) { 13432 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13433 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ks); 13434 } 13435 return false; 13436 } 13437 } 13438} 13439