PackageManagerService.java revision feb193085adbdc379ee70dbb7dc6ae4c9f2971dd
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 boolean vmSafeMode = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0; 4639 4640 final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly(); 4641 boolean performedDexOpt = false; 4642 // There are three basic cases here: 4643 // 1.) we need to dexopt, either because we are forced or it is needed 4644 // 2.) we are defering a needed dexopt 4645 // 3.) we are skipping an unneeded dexopt 4646 final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 4647 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 4648 if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) { 4649 continue; 4650 } 4651 4652 for (String path : paths) { 4653 try { 4654 // This will return DEXOPT_NEEDED if we either cannot find any odex file for this 4655 // patckage or the one we find does not match the image checksum (i.e. it was 4656 // compiled against an old image). It will return PATCHOAT_NEEDED if we can find a 4657 // odex file and it matches the checksum of the image but not its base address, 4658 // meaning we need to move it. 4659 final byte isDexOptNeeded = DexFile.isDexOptNeededInternal(path, 4660 pkg.packageName, dexCodeInstructionSet, defer); 4661 if (forceDex || (!defer && isDexOptNeeded == DexFile.DEXOPT_NEEDED)) { 4662 Log.i(TAG, "Running dexopt on: " + path + " pkg=" 4663 + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet 4664 + " vmSafeMode=" + vmSafeMode); 4665 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4666 final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg), 4667 pkg.packageName, dexCodeInstructionSet, vmSafeMode); 4668 4669 if (ret < 0) { 4670 // Don't bother running dexopt again if we failed, it will probably 4671 // just result in an error again. Also, don't bother dexopting for other 4672 // paths & ISAs. 4673 return DEX_OPT_FAILED; 4674 } 4675 4676 performedDexOpt = true; 4677 } else if (!defer && isDexOptNeeded == DexFile.PATCHOAT_NEEDED) { 4678 Log.i(TAG, "Running patchoat on: " + pkg.applicationInfo.packageName); 4679 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4680 final int ret = mInstaller.patchoat(path, sharedGid, !isForwardLocked(pkg), 4681 pkg.packageName, dexCodeInstructionSet); 4682 4683 if (ret < 0) { 4684 // Don't bother running patchoat again if we failed, it will probably 4685 // just result in an error again. Also, don't bother dexopting for other 4686 // paths & ISAs. 4687 return DEX_OPT_FAILED; 4688 } 4689 4690 performedDexOpt = true; 4691 } 4692 4693 // We're deciding to defer a needed dexopt. Don't bother dexopting for other 4694 // paths and instruction sets. We'll deal with them all together when we process 4695 // our list of deferred dexopts. 4696 if (defer && isDexOptNeeded != DexFile.UP_TO_DATE) { 4697 if (mDeferredDexOpt == null) { 4698 mDeferredDexOpt = new HashSet<PackageParser.Package>(); 4699 } 4700 mDeferredDexOpt.add(pkg); 4701 return DEX_OPT_DEFERRED; 4702 } 4703 } catch (FileNotFoundException e) { 4704 Slog.w(TAG, "Apk not found for dexopt: " + path); 4705 return DEX_OPT_FAILED; 4706 } catch (IOException e) { 4707 Slog.w(TAG, "IOException reading apk: " + path, e); 4708 return DEX_OPT_FAILED; 4709 } catch (StaleDexCacheError e) { 4710 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e); 4711 return DEX_OPT_FAILED; 4712 } catch (Exception e) { 4713 Slog.w(TAG, "Exception when doing dexopt : ", e); 4714 return DEX_OPT_FAILED; 4715 } 4716 } 4717 4718 // At this point we haven't failed dexopt and we haven't deferred dexopt. We must 4719 // either have either succeeded dexopt, or have had isDexOptNeededInternal tell us 4720 // it isn't required. We therefore mark that this package doesn't need dexopt unless 4721 // it's forced. performedDexOpt will tell us whether we performed dex-opt or skipped 4722 // it. 4723 pkg.mDexOptPerformed.add(dexCodeInstructionSet); 4724 } 4725 4726 // If we've gotten here, we're sure that no error occurred and that we haven't 4727 // deferred dex-opt. We've either dex-opted one more paths or instruction sets or 4728 // we've skipped all of them because they are up to date. In both cases this 4729 // package doesn't need dexopt any longer. 4730 return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED; 4731 } 4732 4733 private static String[] getAppDexInstructionSets(ApplicationInfo info) { 4734 if (info.primaryCpuAbi != null) { 4735 if (info.secondaryCpuAbi != null) { 4736 return new String[] { 4737 VMRuntime.getInstructionSet(info.primaryCpuAbi), 4738 VMRuntime.getInstructionSet(info.secondaryCpuAbi) }; 4739 } else { 4740 return new String[] { 4741 VMRuntime.getInstructionSet(info.primaryCpuAbi) }; 4742 } 4743 } 4744 4745 return new String[] { getPreferredInstructionSet() }; 4746 } 4747 4748 private static String[] getAppDexInstructionSets(PackageSetting ps) { 4749 if (ps.primaryCpuAbiString != null) { 4750 if (ps.secondaryCpuAbiString != null) { 4751 return new String[] { 4752 VMRuntime.getInstructionSet(ps.primaryCpuAbiString), 4753 VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) }; 4754 } else { 4755 return new String[] { 4756 VMRuntime.getInstructionSet(ps.primaryCpuAbiString) }; 4757 } 4758 } 4759 4760 return new String[] { getPreferredInstructionSet() }; 4761 } 4762 4763 private static String getPreferredInstructionSet() { 4764 if (sPreferredInstructionSet == null) { 4765 sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]); 4766 } 4767 4768 return sPreferredInstructionSet; 4769 } 4770 4771 private static List<String> getAllInstructionSets() { 4772 final String[] allAbis = Build.SUPPORTED_ABIS; 4773 final List<String> allInstructionSets = new ArrayList<String>(allAbis.length); 4774 4775 for (String abi : allAbis) { 4776 final String instructionSet = VMRuntime.getInstructionSet(abi); 4777 if (!allInstructionSets.contains(instructionSet)) { 4778 allInstructionSets.add(instructionSet); 4779 } 4780 } 4781 4782 return allInstructionSets; 4783 } 4784 4785 /** 4786 * Returns the instruction set that should be used to compile dex code. In the presence of 4787 * a native bridge this might be different than the one shared libraries use. 4788 */ 4789 private static String getDexCodeInstructionSet(String sharedLibraryIsa) { 4790 String dexCodeIsa = SystemProperties.get("ro.dalvik.vm.isa." + sharedLibraryIsa); 4791 return (dexCodeIsa.isEmpty() ? sharedLibraryIsa : dexCodeIsa); 4792 } 4793 4794 private static String[] getDexCodeInstructionSets(String[] instructionSets) { 4795 HashSet<String> dexCodeInstructionSets = new HashSet<String>(instructionSets.length); 4796 for (String instructionSet : instructionSets) { 4797 dexCodeInstructionSets.add(getDexCodeInstructionSet(instructionSet)); 4798 } 4799 return dexCodeInstructionSets.toArray(new String[dexCodeInstructionSets.size()]); 4800 } 4801 4802 @Override 4803 public void forceDexOpt(String packageName) { 4804 enforceSystemOrRoot("forceDexOpt"); 4805 4806 PackageParser.Package pkg; 4807 synchronized (mPackages) { 4808 pkg = mPackages.get(packageName); 4809 if (pkg == null) { 4810 throw new IllegalArgumentException("Missing package: " + packageName); 4811 } 4812 } 4813 4814 synchronized (mInstallLock) { 4815 final String[] instructionSets = new String[] { 4816 getPrimaryInstructionSet(pkg.applicationInfo) }; 4817 final int res = performDexOptLI(pkg, instructionSets, true, false, true); 4818 if (res != DEX_OPT_PERFORMED) { 4819 throw new IllegalStateException("Failed to dexopt: " + res); 4820 } 4821 } 4822 } 4823 4824 private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets, 4825 boolean forceDex, boolean defer, boolean inclDependencies) { 4826 HashSet<String> done; 4827 if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) { 4828 done = new HashSet<String>(); 4829 done.add(pkg.packageName); 4830 } else { 4831 done = null; 4832 } 4833 return performDexOptLI(pkg, instructionSets, forceDex, defer, done); 4834 } 4835 4836 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 4837 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 4838 Slog.w(TAG, "Unable to update from " + oldPkg.name 4839 + " to " + newPkg.packageName 4840 + ": old package not in system partition"); 4841 return false; 4842 } else if (mPackages.get(oldPkg.name) != null) { 4843 Slog.w(TAG, "Unable to update from " + oldPkg.name 4844 + " to " + newPkg.packageName 4845 + ": old package still exists"); 4846 return false; 4847 } 4848 return true; 4849 } 4850 4851 File getDataPathForUser(int userId) { 4852 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId); 4853 } 4854 4855 private File getDataPathForPackage(String packageName, int userId) { 4856 /* 4857 * Until we fully support multiple users, return the directory we 4858 * previously would have. The PackageManagerTests will need to be 4859 * revised when this is changed back.. 4860 */ 4861 if (userId == 0) { 4862 return new File(mAppDataDir, packageName); 4863 } else { 4864 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 4865 + File.separator + packageName); 4866 } 4867 } 4868 4869 private int createDataDirsLI(String packageName, int uid, String seinfo) { 4870 int[] users = sUserManager.getUserIds(); 4871 int res = mInstaller.install(packageName, uid, uid, seinfo); 4872 if (res < 0) { 4873 return res; 4874 } 4875 for (int user : users) { 4876 if (user != 0) { 4877 res = mInstaller.createUserData(packageName, 4878 UserHandle.getUid(user, uid), user, seinfo); 4879 if (res < 0) { 4880 return res; 4881 } 4882 } 4883 } 4884 return res; 4885 } 4886 4887 private int removeDataDirsLI(String packageName) { 4888 int[] users = sUserManager.getUserIds(); 4889 int res = 0; 4890 for (int user : users) { 4891 int resInner = mInstaller.remove(packageName, user); 4892 if (resInner < 0) { 4893 res = resInner; 4894 } 4895 } 4896 4897 return res; 4898 } 4899 4900 private int deleteCodeCacheDirsLI(String packageName) { 4901 int[] users = sUserManager.getUserIds(); 4902 int res = 0; 4903 for (int user : users) { 4904 int resInner = mInstaller.deleteCodeCacheFiles(packageName, user); 4905 if (resInner < 0) { 4906 res = resInner; 4907 } 4908 } 4909 return res; 4910 } 4911 4912 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 4913 PackageParser.Package changingLib) { 4914 if (file.path != null) { 4915 usesLibraryFiles.add(file.path); 4916 return; 4917 } 4918 PackageParser.Package p = mPackages.get(file.apk); 4919 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 4920 // If we are doing this while in the middle of updating a library apk, 4921 // then we need to make sure to use that new apk for determining the 4922 // dependencies here. (We haven't yet finished committing the new apk 4923 // to the package manager state.) 4924 if (p == null || p.packageName.equals(changingLib.packageName)) { 4925 p = changingLib; 4926 } 4927 } 4928 if (p != null) { 4929 usesLibraryFiles.addAll(p.getAllCodePaths()); 4930 } 4931 } 4932 4933 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 4934 PackageParser.Package changingLib) throws PackageManagerException { 4935 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 4936 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 4937 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 4938 for (int i=0; i<N; i++) { 4939 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 4940 if (file == null) { 4941 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 4942 "Package " + pkg.packageName + " requires unavailable shared library " 4943 + pkg.usesLibraries.get(i) + "; failing!"); 4944 } 4945 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4946 } 4947 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 4948 for (int i=0; i<N; i++) { 4949 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 4950 if (file == null) { 4951 Slog.w(TAG, "Package " + pkg.packageName 4952 + " desires unavailable shared library " 4953 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 4954 } else { 4955 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4956 } 4957 } 4958 N = usesLibraryFiles.size(); 4959 if (N > 0) { 4960 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 4961 } else { 4962 pkg.usesLibraryFiles = null; 4963 } 4964 } 4965 } 4966 4967 private static boolean hasString(List<String> list, List<String> which) { 4968 if (list == null) { 4969 return false; 4970 } 4971 for (int i=list.size()-1; i>=0; i--) { 4972 for (int j=which.size()-1; j>=0; j--) { 4973 if (which.get(j).equals(list.get(i))) { 4974 return true; 4975 } 4976 } 4977 } 4978 return false; 4979 } 4980 4981 private void updateAllSharedLibrariesLPw() { 4982 for (PackageParser.Package pkg : mPackages.values()) { 4983 try { 4984 updateSharedLibrariesLPw(pkg, null); 4985 } catch (PackageManagerException e) { 4986 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 4987 } 4988 } 4989 } 4990 4991 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 4992 PackageParser.Package changingPkg) { 4993 ArrayList<PackageParser.Package> res = null; 4994 for (PackageParser.Package pkg : mPackages.values()) { 4995 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 4996 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 4997 if (res == null) { 4998 res = new ArrayList<PackageParser.Package>(); 4999 } 5000 res.add(pkg); 5001 try { 5002 updateSharedLibrariesLPw(pkg, changingPkg); 5003 } catch (PackageManagerException e) { 5004 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5005 } 5006 } 5007 } 5008 return res; 5009 } 5010 5011 /** 5012 * Derive the value of the {@code cpuAbiOverride} based on the provided 5013 * value and an optional stored value from the package settings. 5014 */ 5015 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5016 String cpuAbiOverride = null; 5017 5018 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5019 cpuAbiOverride = null; 5020 } else if (abiOverride != null) { 5021 cpuAbiOverride = abiOverride; 5022 } else if (settings != null) { 5023 cpuAbiOverride = settings.cpuAbiOverrideString; 5024 } 5025 5026 return cpuAbiOverride; 5027 } 5028 5029 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5030 int scanMode, long currentTime, UserHandle user) 5031 throws PackageManagerException { 5032 final File scanFile = new File(pkg.codePath); 5033 if (pkg.applicationInfo.getCodePath() == null || 5034 pkg.applicationInfo.getResourcePath() == null) { 5035 // Bail out. The resource and code paths haven't been set. 5036 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5037 "Code and resource paths haven't been set correctly"); 5038 } 5039 5040 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5041 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5042 } 5043 5044 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5045 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED; 5046 } 5047 5048 if (mCustomResolverComponentName != null && 5049 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5050 setUpCustomResolverActivity(pkg); 5051 } 5052 5053 if (pkg.packageName.equals("android")) { 5054 synchronized (mPackages) { 5055 if (mAndroidApplication != null) { 5056 Slog.w(TAG, "*************************************************"); 5057 Slog.w(TAG, "Core android package being redefined. Skipping."); 5058 Slog.w(TAG, " file=" + scanFile); 5059 Slog.w(TAG, "*************************************************"); 5060 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5061 "Core android package being redefined. Skipping."); 5062 } 5063 5064 // Set up information for our fall-back user intent resolution activity. 5065 mPlatformPackage = pkg; 5066 pkg.mVersionCode = mSdkVersion; 5067 mAndroidApplication = pkg.applicationInfo; 5068 5069 if (!mResolverReplaced) { 5070 mResolveActivity.applicationInfo = mAndroidApplication; 5071 mResolveActivity.name = ResolverActivity.class.getName(); 5072 mResolveActivity.packageName = mAndroidApplication.packageName; 5073 mResolveActivity.processName = "system:ui"; 5074 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5075 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5076 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5077 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5078 mResolveActivity.exported = true; 5079 mResolveActivity.enabled = true; 5080 mResolveInfo.activityInfo = mResolveActivity; 5081 mResolveInfo.priority = 0; 5082 mResolveInfo.preferredOrder = 0; 5083 mResolveInfo.match = 0; 5084 mResolveComponentName = new ComponentName( 5085 mAndroidApplication.packageName, mResolveActivity.name); 5086 } 5087 } 5088 } 5089 5090 if (DEBUG_PACKAGE_SCANNING) { 5091 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5092 Log.d(TAG, "Scanning package " + pkg.packageName); 5093 } 5094 5095 if (mPackages.containsKey(pkg.packageName) 5096 || mSharedLibraries.containsKey(pkg.packageName)) { 5097 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5098 "Application package " + pkg.packageName 5099 + " already installed. Skipping duplicate."); 5100 } 5101 5102 // Initialize package source and resource directories 5103 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5104 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5105 5106 SharedUserSetting suid = null; 5107 PackageSetting pkgSetting = null; 5108 5109 if (!isSystemApp(pkg)) { 5110 // Only system apps can use these features. 5111 pkg.mOriginalPackages = null; 5112 pkg.mRealPackage = null; 5113 pkg.mAdoptPermissions = null; 5114 } 5115 5116 // writer 5117 synchronized (mPackages) { 5118 if (pkg.mSharedUserId != null) { 5119 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true); 5120 if (suid == null) { 5121 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5122 "Creating application package " + pkg.packageName 5123 + " for shared user failed"); 5124 } 5125 if (DEBUG_PACKAGE_SCANNING) { 5126 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5127 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5128 + "): packages=" + suid.packages); 5129 } 5130 } 5131 5132 // Check if we are renaming from an original package name. 5133 PackageSetting origPackage = null; 5134 String realName = null; 5135 if (pkg.mOriginalPackages != null) { 5136 // This package may need to be renamed to a previously 5137 // installed name. Let's check on that... 5138 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5139 if (pkg.mOriginalPackages.contains(renamed)) { 5140 // This package had originally been installed as the 5141 // original name, and we have already taken care of 5142 // transitioning to the new one. Just update the new 5143 // one to continue using the old name. 5144 realName = pkg.mRealPackage; 5145 if (!pkg.packageName.equals(renamed)) { 5146 // Callers into this function may have already taken 5147 // care of renaming the package; only do it here if 5148 // it is not already done. 5149 pkg.setPackageName(renamed); 5150 } 5151 5152 } else { 5153 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5154 if ((origPackage = mSettings.peekPackageLPr( 5155 pkg.mOriginalPackages.get(i))) != null) { 5156 // We do have the package already installed under its 5157 // original name... should we use it? 5158 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5159 // New package is not compatible with original. 5160 origPackage = null; 5161 continue; 5162 } else if (origPackage.sharedUser != null) { 5163 // Make sure uid is compatible between packages. 5164 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5165 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5166 + " to " + pkg.packageName + ": old uid " 5167 + origPackage.sharedUser.name 5168 + " differs from " + pkg.mSharedUserId); 5169 origPackage = null; 5170 continue; 5171 } 5172 } else { 5173 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5174 + pkg.packageName + " to old name " + origPackage.name); 5175 } 5176 break; 5177 } 5178 } 5179 } 5180 } 5181 5182 if (mTransferedPackages.contains(pkg.packageName)) { 5183 Slog.w(TAG, "Package " + pkg.packageName 5184 + " was transferred to another, but its .apk remains"); 5185 } 5186 5187 // Just create the setting, don't add it yet. For already existing packages 5188 // the PkgSetting exists already and doesn't have to be created. 5189 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5190 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 5191 pkg.applicationInfo.primaryCpuAbi, 5192 pkg.applicationInfo.secondaryCpuAbi, 5193 pkg.applicationInfo.flags, user, false); 5194 if (pkgSetting == null) { 5195 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5196 "Creating application package " + pkg.packageName + " failed"); 5197 } 5198 5199 if (pkgSetting.origPackage != null) { 5200 // If we are first transitioning from an original package, 5201 // fix up the new package's name now. We need to do this after 5202 // looking up the package under its new name, so getPackageLP 5203 // can take care of fiddling things correctly. 5204 pkg.setPackageName(origPackage.name); 5205 5206 // File a report about this. 5207 String msg = "New package " + pkgSetting.realName 5208 + " renamed to replace old package " + pkgSetting.name; 5209 reportSettingsProblem(Log.WARN, msg); 5210 5211 // Make a note of it. 5212 mTransferedPackages.add(origPackage.name); 5213 5214 // No longer need to retain this. 5215 pkgSetting.origPackage = null; 5216 } 5217 5218 if (realName != null) { 5219 // Make a note of it. 5220 mTransferedPackages.add(pkg.packageName); 5221 } 5222 5223 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5224 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5225 } 5226 5227 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5228 // Check all shared libraries and map to their actual file path. 5229 // We only do this here for apps not on a system dir, because those 5230 // are the only ones that can fail an install due to this. We 5231 // will take care of the system apps by updating all of their 5232 // library paths after the scan is done. 5233 updateSharedLibrariesLPw(pkg, null); 5234 } 5235 5236 if (mFoundPolicyFile) { 5237 SELinuxMMAC.assignSeinfoValue(pkg); 5238 } 5239 5240 pkg.applicationInfo.uid = pkgSetting.appId; 5241 pkg.mExtras = pkgSetting; 5242 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5243 try { 5244 verifySignaturesLP(pkgSetting, pkg); 5245 } catch (PackageManagerException e) { 5246 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5247 throw e; 5248 } 5249 // The signature has changed, but this package is in the system 5250 // image... let's recover! 5251 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5252 // However... if this package is part of a shared user, but it 5253 // doesn't match the signature of the shared user, let's fail. 5254 // What this means is that you can't change the signatures 5255 // associated with an overall shared user, which doesn't seem all 5256 // that unreasonable. 5257 if (pkgSetting.sharedUser != null) { 5258 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5259 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5260 throw new PackageManagerException( 5261 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 5262 "Signature mismatch for shared user : " 5263 + pkgSetting.sharedUser); 5264 } 5265 } 5266 // File a report about this. 5267 String msg = "System package " + pkg.packageName 5268 + " signature changed; retaining data."; 5269 reportSettingsProblem(Log.WARN, msg); 5270 } 5271 } else { 5272 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 5273 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5274 + pkg.packageName + " upgrade keys do not match the " 5275 + "previously installed version"); 5276 } else { 5277 // signatures may have changed as result of upgrade 5278 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5279 } 5280 } 5281 // Verify that this new package doesn't have any content providers 5282 // that conflict with existing packages. Only do this if the 5283 // package isn't already installed, since we don't want to break 5284 // things that are installed. 5285 if ((scanMode&SCAN_NEW_INSTALL) != 0) { 5286 final int N = pkg.providers.size(); 5287 int i; 5288 for (i=0; i<N; i++) { 5289 PackageParser.Provider p = pkg.providers.get(i); 5290 if (p.info.authority != null) { 5291 String names[] = p.info.authority.split(";"); 5292 for (int j = 0; j < names.length; j++) { 5293 if (mProvidersByAuthority.containsKey(names[j])) { 5294 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5295 final String otherPackageName = 5296 ((other != null && other.getComponentName() != null) ? 5297 other.getComponentName().getPackageName() : "?"); 5298 throw new PackageManagerException( 5299 INSTALL_FAILED_CONFLICTING_PROVIDER, 5300 "Can't install because provider name " + names[j] 5301 + " (in package " + pkg.applicationInfo.packageName 5302 + ") is already used by " + otherPackageName); 5303 } 5304 } 5305 } 5306 } 5307 } 5308 5309 if (pkg.mAdoptPermissions != null) { 5310 // This package wants to adopt ownership of permissions from 5311 // another package. 5312 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 5313 final String origName = pkg.mAdoptPermissions.get(i); 5314 final PackageSetting orig = mSettings.peekPackageLPr(origName); 5315 if (orig != null) { 5316 if (verifyPackageUpdateLPr(orig, pkg)) { 5317 Slog.i(TAG, "Adopting permissions from " + origName + " to " 5318 + pkg.packageName); 5319 mSettings.transferPermissionsLPw(origName, pkg.packageName); 5320 } 5321 } 5322 } 5323 } 5324 } 5325 5326 final String pkgName = pkg.packageName; 5327 5328 final long scanFileTime = scanFile.lastModified(); 5329 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0; 5330 pkg.applicationInfo.processName = fixProcessName( 5331 pkg.applicationInfo.packageName, 5332 pkg.applicationInfo.processName, 5333 pkg.applicationInfo.uid); 5334 5335 File dataPath; 5336 if (mPlatformPackage == pkg) { 5337 // The system package is special. 5338 dataPath = new File (Environment.getDataDirectory(), "system"); 5339 pkg.applicationInfo.dataDir = dataPath.getPath(); 5340 5341 } else { 5342 // This is a normal package, need to make its data directory. 5343 dataPath = getDataPathForPackage(pkg.packageName, 0); 5344 5345 boolean uidError = false; 5346 5347 if (dataPath.exists()) { 5348 int currentUid = 0; 5349 try { 5350 StructStat stat = Os.stat(dataPath.getPath()); 5351 currentUid = stat.st_uid; 5352 } catch (ErrnoException e) { 5353 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 5354 } 5355 5356 // If we have mismatched owners for the data path, we have a problem. 5357 if (currentUid != pkg.applicationInfo.uid) { 5358 boolean recovered = false; 5359 if (currentUid == 0) { 5360 // The directory somehow became owned by root. Wow. 5361 // This is probably because the system was stopped while 5362 // installd was in the middle of messing with its libs 5363 // directory. Ask installd to fix that. 5364 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 5365 pkg.applicationInfo.uid); 5366 if (ret >= 0) { 5367 recovered = true; 5368 String msg = "Package " + pkg.packageName 5369 + " unexpectedly changed to uid 0; recovered to " + 5370 + pkg.applicationInfo.uid; 5371 reportSettingsProblem(Log.WARN, msg); 5372 } 5373 } 5374 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5375 || (scanMode&SCAN_BOOTING) != 0)) { 5376 // If this is a system app, we can at least delete its 5377 // current data so the application will still work. 5378 int ret = removeDataDirsLI(pkgName); 5379 if (ret >= 0) { 5380 // TODO: Kill the processes first 5381 // Old data gone! 5382 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5383 ? "System package " : "Third party package "; 5384 String msg = prefix + pkg.packageName 5385 + " has changed from uid: " 5386 + currentUid + " to " 5387 + pkg.applicationInfo.uid + "; old data erased"; 5388 reportSettingsProblem(Log.WARN, msg); 5389 recovered = true; 5390 5391 // And now re-install the app. 5392 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5393 pkg.applicationInfo.seinfo); 5394 if (ret == -1) { 5395 // Ack should not happen! 5396 msg = prefix + pkg.packageName 5397 + " could not have data directory re-created after delete."; 5398 reportSettingsProblem(Log.WARN, msg); 5399 throw new PackageManagerException( 5400 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 5401 } 5402 } 5403 if (!recovered) { 5404 mHasSystemUidErrors = true; 5405 } 5406 } else if (!recovered) { 5407 // If we allow this install to proceed, we will be broken. 5408 // Abort, abort! 5409 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 5410 "scanPackageLI"); 5411 } 5412 if (!recovered) { 5413 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 5414 + pkg.applicationInfo.uid + "/fs_" 5415 + currentUid; 5416 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 5417 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 5418 String msg = "Package " + pkg.packageName 5419 + " has mismatched uid: " 5420 + currentUid + " on disk, " 5421 + pkg.applicationInfo.uid + " in settings"; 5422 // writer 5423 synchronized (mPackages) { 5424 mSettings.mReadMessages.append(msg); 5425 mSettings.mReadMessages.append('\n'); 5426 uidError = true; 5427 if (!pkgSetting.uidError) { 5428 reportSettingsProblem(Log.ERROR, msg); 5429 } 5430 } 5431 } 5432 } 5433 pkg.applicationInfo.dataDir = dataPath.getPath(); 5434 if (mShouldRestoreconData) { 5435 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 5436 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 5437 pkg.applicationInfo.uid); 5438 } 5439 } else { 5440 if (DEBUG_PACKAGE_SCANNING) { 5441 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5442 Log.v(TAG, "Want this data dir: " + dataPath); 5443 } 5444 //invoke installer to do the actual installation 5445 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5446 pkg.applicationInfo.seinfo); 5447 if (ret < 0) { 5448 // Error from installer 5449 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5450 "Unable to create data dirs [errorCode=" + ret + "]"); 5451 } 5452 5453 if (dataPath.exists()) { 5454 pkg.applicationInfo.dataDir = dataPath.getPath(); 5455 } else { 5456 Slog.w(TAG, "Unable to create data directory: " + dataPath); 5457 pkg.applicationInfo.dataDir = null; 5458 } 5459 } 5460 5461 pkgSetting.uidError = uidError; 5462 } 5463 5464 final String path = scanFile.getPath(); 5465 final String codePath = pkg.applicationInfo.getCodePath(); 5466 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 5467 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 5468 setBundledAppAbisAndRoots(pkg, pkgSetting); 5469 5470 // If we haven't found any native libraries for the app, check if it has 5471 // renderscript code. We'll need to force the app to 32 bit if it has 5472 // renderscript bitcode. 5473 if (pkg.applicationInfo.primaryCpuAbi == null 5474 && pkg.applicationInfo.secondaryCpuAbi == null 5475 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5476 NativeLibraryHelper.Handle handle = null; 5477 try { 5478 handle = NativeLibraryHelper.Handle.create(scanFile); 5479 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5480 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 5481 } 5482 } catch (IOException ioe) { 5483 Slog.w(TAG, "Error scanning system app : " + ioe); 5484 } finally { 5485 IoUtils.closeQuietly(handle); 5486 } 5487 } 5488 5489 setNativeLibraryPaths(pkg); 5490 } else { 5491 // TODO: We can probably be smarter about this stuff. For installed apps, 5492 // we can calculate this information at install time once and for all. For 5493 // system apps, we can probably assume that this information doesn't change 5494 // after the first boot scan. As things stand, we do lots of unnecessary work. 5495 5496 // Give ourselves some initial paths; we'll come back for another 5497 // pass once we've determined ABI below. 5498 setNativeLibraryPaths(pkg); 5499 5500 final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg); 5501 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 5502 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 5503 5504 NativeLibraryHelper.Handle handle = null; 5505 try { 5506 handle = NativeLibraryHelper.Handle.create(scanFile); 5507 // TODO(multiArch): This can be null for apps that didn't go through the 5508 // usual installation process. We can calculate it again, like we 5509 // do during install time. 5510 // 5511 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 5512 // unnecessary. 5513 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 5514 5515 // Null out the abis so that they can be recalculated. 5516 pkg.applicationInfo.primaryCpuAbi = null; 5517 pkg.applicationInfo.secondaryCpuAbi = null; 5518 if (isMultiArch(pkg.applicationInfo)) { 5519 // Warn if we've set an abiOverride for multi-lib packages.. 5520 // By definition, we need to copy both 32 and 64 bit libraries for 5521 // such packages. 5522 if (pkg.cpuAbiOverride != null 5523 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 5524 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 5525 } 5526 5527 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 5528 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 5529 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 5530 if (isAsec) { 5531 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 5532 } else { 5533 abi32 = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle, 5534 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, useIsaSpecificSubdirs); 5535 } 5536 } 5537 5538 maybeThrowExceptionForMultiArchCopy( 5539 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 5540 5541 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5542 if (isAsec) { 5543 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 5544 } else { 5545 abi64 = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle, 5546 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, useIsaSpecificSubdirs); 5547 } 5548 } 5549 5550 maybeThrowExceptionForMultiArchCopy( 5551 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 5552 5553 if (abi64 >= 0) { 5554 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 5555 } 5556 5557 if (abi32 >= 0) { 5558 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 5559 if (abi64 >= 0) { 5560 pkg.applicationInfo.secondaryCpuAbi = abi; 5561 } else { 5562 pkg.applicationInfo.primaryCpuAbi = abi; 5563 } 5564 } 5565 } else { 5566 String[] abiList = (cpuAbiOverride != null) ? 5567 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 5568 5569 // Enable gross and lame hacks for apps that are built with old 5570 // SDK tools. We must scan their APKs for renderscript bitcode and 5571 // not launch them if it's present. Don't bother checking on devices 5572 // that don't have 64 bit support. 5573 boolean needsRenderScriptOverride = false; 5574 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 5575 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5576 abiList = Build.SUPPORTED_32_BIT_ABIS; 5577 needsRenderScriptOverride = true; 5578 } 5579 5580 final int copyRet; 5581 if (isAsec) { 5582 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 5583 } else { 5584 copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle, 5585 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 5586 } 5587 5588 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5589 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5590 "Error unpackaging native libs for app, errorCode=" + copyRet); 5591 } 5592 5593 if (copyRet >= 0) { 5594 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 5595 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 5596 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 5597 } else if (needsRenderScriptOverride) { 5598 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 5599 } 5600 } 5601 } catch (IOException ioe) { 5602 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 5603 } finally { 5604 IoUtils.closeQuietly(handle); 5605 } 5606 5607 // Now that we've calculated the ABIs and determined if it's an internal app, 5608 // we will go ahead and populate the nativeLibraryPath. 5609 setNativeLibraryPaths(pkg); 5610 5611 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 5612 final int[] userIds = sUserManager.getUserIds(); 5613 synchronized (mInstallLock) { 5614 // Create a native library symlink only if we have native libraries 5615 // and if the native libraries are 32 bit libraries. We do not provide 5616 // this symlink for 64 bit libraries. 5617 if (pkg.applicationInfo.primaryCpuAbi != null && 5618 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 5619 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 5620 for (int userId : userIds) { 5621 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 5622 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5623 "Failed linking native library dir (user=" + userId + ")"); 5624 } 5625 } 5626 } 5627 } 5628 } 5629 5630 // This is a special case for the "system" package, where the ABI is 5631 // dictated by the zygote configuration (and init.rc). We should keep track 5632 // of this ABI so that we can deal with "normal" applications that run under 5633 // the same UID correctly. 5634 if (mPlatformPackage == pkg) { 5635 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 5636 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 5637 } 5638 5639 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 5640 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 5641 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 5642 // Copy the derived override back to the parsed package, so that we can 5643 // update the package settings accordingly. 5644 pkg.cpuAbiOverride = cpuAbiOverride; 5645 5646 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 5647 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 5648 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 5649 5650 // Push the derived path down into PackageSettings so we know what to 5651 // clean up at uninstall time. 5652 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 5653 5654 if (DEBUG_ABI_SELECTION) { 5655 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 5656 " primary=" + pkg.applicationInfo.primaryCpuAbi + 5657 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 5658 } 5659 5660 if ((scanMode&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 5661 // We don't do this here during boot because we can do it all 5662 // at once after scanning all existing packages. 5663 // 5664 // We also do this *before* we perform dexopt on this package, so that 5665 // we can avoid redundant dexopts, and also to make sure we've got the 5666 // code and package path correct. 5667 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 5668 pkg, forceDex, (scanMode & SCAN_DEFER_DEX) != 0); 5669 } 5670 5671 if ((scanMode&SCAN_NO_DEX) == 0) { 5672 if (performDexOptLI(pkg, null /* instruction sets */, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5673 == DEX_OPT_FAILED) { 5674 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5675 removeDataDirsLI(pkg.packageName); 5676 } 5677 5678 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 5679 } 5680 } 5681 5682 if (mFactoryTest && pkg.requestedPermissions.contains( 5683 android.Manifest.permission.FACTORY_TEST)) { 5684 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 5685 } 5686 5687 ArrayList<PackageParser.Package> clientLibPkgs = null; 5688 5689 // writer 5690 synchronized (mPackages) { 5691 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5692 // Only system apps can add new shared libraries. 5693 if (pkg.libraryNames != null) { 5694 for (int i=0; i<pkg.libraryNames.size(); i++) { 5695 String name = pkg.libraryNames.get(i); 5696 boolean allowed = false; 5697 if (isUpdatedSystemApp(pkg)) { 5698 // New library entries can only be added through the 5699 // system image. This is important to get rid of a lot 5700 // of nasty edge cases: for example if we allowed a non- 5701 // system update of the app to add a library, then uninstalling 5702 // the update would make the library go away, and assumptions 5703 // we made such as through app install filtering would now 5704 // have allowed apps on the device which aren't compatible 5705 // with it. Better to just have the restriction here, be 5706 // conservative, and create many fewer cases that can negatively 5707 // impact the user experience. 5708 final PackageSetting sysPs = mSettings 5709 .getDisabledSystemPkgLPr(pkg.packageName); 5710 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 5711 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 5712 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 5713 allowed = true; 5714 allowed = true; 5715 break; 5716 } 5717 } 5718 } 5719 } else { 5720 allowed = true; 5721 } 5722 if (allowed) { 5723 if (!mSharedLibraries.containsKey(name)) { 5724 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 5725 } else if (!name.equals(pkg.packageName)) { 5726 Slog.w(TAG, "Package " + pkg.packageName + " library " 5727 + name + " already exists; skipping"); 5728 } 5729 } else { 5730 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 5731 + name + " that is not declared on system image; skipping"); 5732 } 5733 } 5734 if ((scanMode&SCAN_BOOTING) == 0) { 5735 // If we are not booting, we need to update any applications 5736 // that are clients of our shared library. If we are booting, 5737 // this will all be done once the scan is complete. 5738 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 5739 } 5740 } 5741 } 5742 } 5743 5744 // We also need to dexopt any apps that are dependent on this library. Note that 5745 // if these fail, we should abort the install since installing the library will 5746 // result in some apps being broken. 5747 if (clientLibPkgs != null) { 5748 if ((scanMode&SCAN_NO_DEX) == 0) { 5749 for (int i=0; i<clientLibPkgs.size(); i++) { 5750 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5751 if (performDexOptLI(clientPkg, null /* instruction sets */, 5752 forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5753 == DEX_OPT_FAILED) { 5754 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5755 removeDataDirsLI(pkg.packageName); 5756 } 5757 5758 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 5759 "scanPackageLI failed to dexopt clientLibPkgs"); 5760 } 5761 } 5762 } 5763 } 5764 5765 // Request the ActivityManager to kill the process(only for existing packages) 5766 // so that we do not end up in a confused state while the user is still using the older 5767 // version of the application while the new one gets installed. 5768 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 5769 // If the package lives in an asec, tell everyone that the container is going 5770 // away so they can clean up any references to its resources (which would prevent 5771 // vold from being able to unmount the asec) 5772 if (isForwardLocked(pkg) || isExternal(pkg)) { 5773 if (DEBUG_INSTALL) { 5774 Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE"); 5775 } 5776 final int[] uidArray = new int[] { pkg.applicationInfo.uid }; 5777 final ArrayList<String> pkgList = new ArrayList<String>(1); 5778 pkgList.add(pkg.applicationInfo.packageName); 5779 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 5780 } 5781 5782 // Post the request that it be killed now that the going-away broadcast is en route 5783 killApplication(pkg.applicationInfo.packageName, 5784 pkg.applicationInfo.uid, "update pkg"); 5785 } 5786 5787 // Also need to kill any apps that are dependent on the library. 5788 if (clientLibPkgs != null) { 5789 for (int i=0; i<clientLibPkgs.size(); i++) { 5790 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5791 killApplication(clientPkg.applicationInfo.packageName, 5792 clientPkg.applicationInfo.uid, "update lib"); 5793 } 5794 } 5795 5796 // writer 5797 synchronized (mPackages) { 5798 // We don't expect installation to fail beyond this point, 5799 if ((scanMode&SCAN_MONITOR) != 0) { 5800 mAppDirs.put(pkg.codePath, pkg); 5801 } 5802 // Add the new setting to mSettings 5803 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 5804 // Add the new setting to mPackages 5805 mPackages.put(pkg.applicationInfo.packageName, pkg); 5806 // Make sure we don't accidentally delete its data. 5807 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 5808 while (iter.hasNext()) { 5809 PackageCleanItem item = iter.next(); 5810 if (pkgName.equals(item.packageName)) { 5811 iter.remove(); 5812 } 5813 } 5814 5815 // Take care of first install / last update times. 5816 if (currentTime != 0) { 5817 if (pkgSetting.firstInstallTime == 0) { 5818 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 5819 } else if ((scanMode&SCAN_UPDATE_TIME) != 0) { 5820 pkgSetting.lastUpdateTime = currentTime; 5821 } 5822 } else if (pkgSetting.firstInstallTime == 0) { 5823 // We need *something*. Take time time stamp of the file. 5824 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 5825 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 5826 if (scanFileTime != pkgSetting.timeStamp) { 5827 // A package on the system image has changed; consider this 5828 // to be an update. 5829 pkgSetting.lastUpdateTime = scanFileTime; 5830 } 5831 } 5832 5833 // Add the package's KeySets to the global KeySetManagerService 5834 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5835 try { 5836 // Old KeySetData no longer valid. 5837 ksms.removeAppKeySetDataLPw(pkg.packageName); 5838 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 5839 if (pkg.mKeySetMapping != null) { 5840 for (Map.Entry<String, ArraySet<PublicKey>> entry : 5841 pkg.mKeySetMapping.entrySet()) { 5842 if (entry.getValue() != null) { 5843 ksms.addDefinedKeySetToPackageLPw(pkg.packageName, 5844 entry.getValue(), entry.getKey()); 5845 } 5846 } 5847 if (pkg.mUpgradeKeySets != null) { 5848 for (String upgradeAlias : pkg.mUpgradeKeySets) { 5849 ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias); 5850 } 5851 } 5852 } 5853 } catch (NullPointerException e) { 5854 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 5855 } catch (IllegalArgumentException e) { 5856 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 5857 } 5858 5859 int N = pkg.providers.size(); 5860 StringBuilder r = null; 5861 int i; 5862 for (i=0; i<N; i++) { 5863 PackageParser.Provider p = pkg.providers.get(i); 5864 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 5865 p.info.processName, pkg.applicationInfo.uid); 5866 mProviders.addProvider(p); 5867 p.syncable = p.info.isSyncable; 5868 if (p.info.authority != null) { 5869 String names[] = p.info.authority.split(";"); 5870 p.info.authority = null; 5871 for (int j = 0; j < names.length; j++) { 5872 if (j == 1 && p.syncable) { 5873 // We only want the first authority for a provider to possibly be 5874 // syncable, so if we already added this provider using a different 5875 // authority clear the syncable flag. We copy the provider before 5876 // changing it because the mProviders object contains a reference 5877 // to a provider that we don't want to change. 5878 // Only do this for the second authority since the resulting provider 5879 // object can be the same for all future authorities for this provider. 5880 p = new PackageParser.Provider(p); 5881 p.syncable = false; 5882 } 5883 if (!mProvidersByAuthority.containsKey(names[j])) { 5884 mProvidersByAuthority.put(names[j], p); 5885 if (p.info.authority == null) { 5886 p.info.authority = names[j]; 5887 } else { 5888 p.info.authority = p.info.authority + ";" + names[j]; 5889 } 5890 if (DEBUG_PACKAGE_SCANNING) { 5891 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5892 Log.d(TAG, "Registered content provider: " + names[j] 5893 + ", className = " + p.info.name + ", isSyncable = " 5894 + p.info.isSyncable); 5895 } 5896 } else { 5897 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5898 Slog.w(TAG, "Skipping provider name " + names[j] + 5899 " (in package " + pkg.applicationInfo.packageName + 5900 "): name already used by " 5901 + ((other != null && other.getComponentName() != null) 5902 ? other.getComponentName().getPackageName() : "?")); 5903 } 5904 } 5905 } 5906 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5907 if (r == null) { 5908 r = new StringBuilder(256); 5909 } else { 5910 r.append(' '); 5911 } 5912 r.append(p.info.name); 5913 } 5914 } 5915 if (r != null) { 5916 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 5917 } 5918 5919 N = pkg.services.size(); 5920 r = null; 5921 for (i=0; i<N; i++) { 5922 PackageParser.Service s = pkg.services.get(i); 5923 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 5924 s.info.processName, pkg.applicationInfo.uid); 5925 mServices.addService(s); 5926 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5927 if (r == null) { 5928 r = new StringBuilder(256); 5929 } else { 5930 r.append(' '); 5931 } 5932 r.append(s.info.name); 5933 } 5934 } 5935 if (r != null) { 5936 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 5937 } 5938 5939 N = pkg.receivers.size(); 5940 r = null; 5941 for (i=0; i<N; i++) { 5942 PackageParser.Activity a = pkg.receivers.get(i); 5943 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5944 a.info.processName, pkg.applicationInfo.uid); 5945 mReceivers.addActivity(a, "receiver"); 5946 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5947 if (r == null) { 5948 r = new StringBuilder(256); 5949 } else { 5950 r.append(' '); 5951 } 5952 r.append(a.info.name); 5953 } 5954 } 5955 if (r != null) { 5956 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 5957 } 5958 5959 N = pkg.activities.size(); 5960 r = null; 5961 for (i=0; i<N; i++) { 5962 PackageParser.Activity a = pkg.activities.get(i); 5963 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5964 a.info.processName, pkg.applicationInfo.uid); 5965 mActivities.addActivity(a, "activity"); 5966 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5967 if (r == null) { 5968 r = new StringBuilder(256); 5969 } else { 5970 r.append(' '); 5971 } 5972 r.append(a.info.name); 5973 } 5974 } 5975 if (r != null) { 5976 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 5977 } 5978 5979 N = pkg.permissionGroups.size(); 5980 r = null; 5981 for (i=0; i<N; i++) { 5982 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 5983 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 5984 if (cur == null) { 5985 mPermissionGroups.put(pg.info.name, pg); 5986 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5987 if (r == null) { 5988 r = new StringBuilder(256); 5989 } else { 5990 r.append(' '); 5991 } 5992 r.append(pg.info.name); 5993 } 5994 } else { 5995 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 5996 + pg.info.packageName + " ignored: original from " 5997 + cur.info.packageName); 5998 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5999 if (r == null) { 6000 r = new StringBuilder(256); 6001 } else { 6002 r.append(' '); 6003 } 6004 r.append("DUP:"); 6005 r.append(pg.info.name); 6006 } 6007 } 6008 } 6009 if (r != null) { 6010 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6011 } 6012 6013 N = pkg.permissions.size(); 6014 r = null; 6015 for (i=0; i<N; i++) { 6016 PackageParser.Permission p = pkg.permissions.get(i); 6017 HashMap<String, BasePermission> permissionMap = 6018 p.tree ? mSettings.mPermissionTrees 6019 : mSettings.mPermissions; 6020 p.group = mPermissionGroups.get(p.info.group); 6021 if (p.info.group == null || p.group != null) { 6022 BasePermission bp = permissionMap.get(p.info.name); 6023 if (bp == null) { 6024 bp = new BasePermission(p.info.name, p.info.packageName, 6025 BasePermission.TYPE_NORMAL); 6026 permissionMap.put(p.info.name, bp); 6027 } 6028 if (bp.perm == null) { 6029 if (bp.sourcePackage != null 6030 && !bp.sourcePackage.equals(p.info.packageName)) { 6031 // If this is a permission that was formerly defined by a non-system 6032 // app, but is now defined by a system app (following an upgrade), 6033 // discard the previous declaration and consider the system's to be 6034 // canonical. 6035 if (isSystemApp(p.owner)) { 6036 String msg = "New decl " + p.owner + " of permission " 6037 + p.info.name + " is system"; 6038 reportSettingsProblem(Log.WARN, msg); 6039 bp.sourcePackage = null; 6040 } 6041 } 6042 if (bp.sourcePackage == null 6043 || bp.sourcePackage.equals(p.info.packageName)) { 6044 BasePermission tree = findPermissionTreeLP(p.info.name); 6045 if (tree == null 6046 || tree.sourcePackage.equals(p.info.packageName)) { 6047 bp.packageSetting = pkgSetting; 6048 bp.perm = p; 6049 bp.uid = pkg.applicationInfo.uid; 6050 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6051 if (r == null) { 6052 r = new StringBuilder(256); 6053 } else { 6054 r.append(' '); 6055 } 6056 r.append(p.info.name); 6057 } 6058 } else { 6059 Slog.w(TAG, "Permission " + p.info.name + " from package " 6060 + p.info.packageName + " ignored: base tree " 6061 + tree.name + " is from package " 6062 + tree.sourcePackage); 6063 } 6064 } else { 6065 Slog.w(TAG, "Permission " + p.info.name + " from package " 6066 + p.info.packageName + " ignored: original from " 6067 + bp.sourcePackage); 6068 } 6069 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6070 if (r == null) { 6071 r = new StringBuilder(256); 6072 } else { 6073 r.append(' '); 6074 } 6075 r.append("DUP:"); 6076 r.append(p.info.name); 6077 } 6078 if (bp.perm == p) { 6079 bp.protectionLevel = p.info.protectionLevel; 6080 } 6081 } else { 6082 Slog.w(TAG, "Permission " + p.info.name + " from package " 6083 + p.info.packageName + " ignored: no group " 6084 + p.group); 6085 } 6086 } 6087 if (r != null) { 6088 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6089 } 6090 6091 N = pkg.instrumentation.size(); 6092 r = null; 6093 for (i=0; i<N; i++) { 6094 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6095 a.info.packageName = pkg.applicationInfo.packageName; 6096 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6097 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6098 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6099 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6100 a.info.dataDir = pkg.applicationInfo.dataDir; 6101 6102 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6103 // need other information about the application, like the ABI and what not ? 6104 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6105 mInstrumentation.put(a.getComponentName(), a); 6106 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6107 if (r == null) { 6108 r = new StringBuilder(256); 6109 } else { 6110 r.append(' '); 6111 } 6112 r.append(a.info.name); 6113 } 6114 } 6115 if (r != null) { 6116 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6117 } 6118 6119 if (pkg.protectedBroadcasts != null) { 6120 N = pkg.protectedBroadcasts.size(); 6121 for (i=0; i<N; i++) { 6122 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6123 } 6124 } 6125 6126 pkgSetting.setTimeStamp(scanFileTime); 6127 6128 // Create idmap files for pairs of (packages, overlay packages). 6129 // Note: "android", ie framework-res.apk, is handled by native layers. 6130 if (pkg.mOverlayTarget != null) { 6131 // This is an overlay package. 6132 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6133 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6134 mOverlays.put(pkg.mOverlayTarget, 6135 new HashMap<String, PackageParser.Package>()); 6136 } 6137 HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6138 map.put(pkg.packageName, pkg); 6139 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6140 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6141 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6142 "scanPackageLI failed to createIdmap"); 6143 } 6144 } 6145 } else if (mOverlays.containsKey(pkg.packageName) && 6146 !pkg.packageName.equals("android")) { 6147 // This is a regular package, with one or more known overlay packages. 6148 createIdmapsForPackageLI(pkg); 6149 } 6150 } 6151 6152 return pkg; 6153 } 6154 6155 /** 6156 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6157 * i.e, so that all packages can be run inside a single process if required. 6158 * 6159 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6160 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6161 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6162 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6163 * updating a package that belongs to a shared user. 6164 * 6165 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6166 * adds unnecessary complexity. 6167 */ 6168 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6169 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6170 String requiredInstructionSet = null; 6171 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6172 requiredInstructionSet = VMRuntime.getInstructionSet( 6173 scannedPackage.applicationInfo.primaryCpuAbi); 6174 } 6175 6176 PackageSetting requirer = null; 6177 for (PackageSetting ps : packagesForUser) { 6178 // If packagesForUser contains scannedPackage, we skip it. This will happen 6179 // when scannedPackage is an update of an existing package. Without this check, 6180 // we will never be able to change the ABI of any package belonging to a shared 6181 // user, even if it's compatible with other packages. 6182 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6183 if (ps.primaryCpuAbiString == null) { 6184 continue; 6185 } 6186 6187 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6188 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6189 // We have a mismatch between instruction sets (say arm vs arm64) warn about 6190 // this but there's not much we can do. 6191 String errorMessage = "Instruction set mismatch, " 6192 + ((requirer == null) ? "[caller]" : requirer) 6193 + " requires " + requiredInstructionSet + " whereas " + ps 6194 + " requires " + instructionSet; 6195 Slog.w(TAG, errorMessage); 6196 } 6197 6198 if (requiredInstructionSet == null) { 6199 requiredInstructionSet = instructionSet; 6200 requirer = ps; 6201 } 6202 } 6203 } 6204 6205 if (requiredInstructionSet != null) { 6206 String adjustedAbi; 6207 if (requirer != null) { 6208 // requirer != null implies that either scannedPackage was null or that scannedPackage 6209 // did not require an ABI, in which case we have to adjust scannedPackage to match 6210 // the ABI of the set (which is the same as requirer's ABI) 6211 adjustedAbi = requirer.primaryCpuAbiString; 6212 if (scannedPackage != null) { 6213 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6214 } 6215 } else { 6216 // requirer == null implies that we're updating all ABIs in the set to 6217 // match scannedPackage. 6218 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6219 } 6220 6221 for (PackageSetting ps : packagesForUser) { 6222 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6223 if (ps.primaryCpuAbiString != null) { 6224 continue; 6225 } 6226 6227 ps.primaryCpuAbiString = adjustedAbi; 6228 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6229 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6230 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6231 6232 if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt, 6233 deferDexOpt, true) == DEX_OPT_FAILED) { 6234 ps.primaryCpuAbiString = null; 6235 ps.pkg.applicationInfo.primaryCpuAbi = null; 6236 return; 6237 } else { 6238 mInstaller.rmdex(ps.codePathString, 6239 getDexCodeInstructionSet(getPreferredInstructionSet())); 6240 } 6241 } 6242 } 6243 } 6244 } 6245 } 6246 6247 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6248 synchronized (mPackages) { 6249 mResolverReplaced = true; 6250 // Set up information for custom user intent resolution activity. 6251 mResolveActivity.applicationInfo = pkg.applicationInfo; 6252 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6253 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6254 mResolveActivity.processName = null; 6255 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6256 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6257 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6258 mResolveActivity.theme = 0; 6259 mResolveActivity.exported = true; 6260 mResolveActivity.enabled = true; 6261 mResolveInfo.activityInfo = mResolveActivity; 6262 mResolveInfo.priority = 0; 6263 mResolveInfo.preferredOrder = 0; 6264 mResolveInfo.match = 0; 6265 mResolveComponentName = mCustomResolverComponentName; 6266 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6267 mResolveComponentName); 6268 } 6269 } 6270 6271 private static String calculateBundledApkRoot(final String codePathString) { 6272 final File codePath = new File(codePathString); 6273 final File codeRoot; 6274 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6275 codeRoot = Environment.getRootDirectory(); 6276 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6277 codeRoot = Environment.getOemDirectory(); 6278 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6279 codeRoot = Environment.getVendorDirectory(); 6280 } else { 6281 // Unrecognized code path; take its top real segment as the apk root: 6282 // e.g. /something/app/blah.apk => /something 6283 try { 6284 File f = codePath.getCanonicalFile(); 6285 File parent = f.getParentFile(); // non-null because codePath is a file 6286 File tmp; 6287 while ((tmp = parent.getParentFile()) != null) { 6288 f = parent; 6289 parent = tmp; 6290 } 6291 codeRoot = f; 6292 Slog.w(TAG, "Unrecognized code path " 6293 + codePath + " - using " + codeRoot); 6294 } catch (IOException e) { 6295 // Can't canonicalize the code path -- shenanigans? 6296 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6297 return Environment.getRootDirectory().getPath(); 6298 } 6299 } 6300 return codeRoot.getPath(); 6301 } 6302 6303 /** 6304 * Derive and set the location of native libraries for the given package, 6305 * which varies depending on where and how the package was installed. 6306 */ 6307 private void setNativeLibraryPaths(PackageParser.Package pkg) { 6308 final ApplicationInfo info = pkg.applicationInfo; 6309 final String codePath = pkg.codePath; 6310 final File codeFile = new File(codePath); 6311 final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info); 6312 final boolean asecApp = isForwardLocked(info) || isExternal(info); 6313 6314 info.nativeLibraryRootDir = null; 6315 info.nativeLibraryRootRequiresIsa = false; 6316 info.nativeLibraryDir = null; 6317 info.secondaryNativeLibraryDir = null; 6318 6319 if (isApkFile(codeFile)) { 6320 // Monolithic install 6321 if (bundledApp) { 6322 // If "/system/lib64/apkname" exists, assume that is the per-package 6323 // native library directory to use; otherwise use "/system/lib/apkname". 6324 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 6325 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 6326 getPrimaryInstructionSet(info)); 6327 6328 // This is a bundled system app so choose the path based on the ABI. 6329 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 6330 // is just the default path. 6331 final String apkName = deriveCodePathName(codePath); 6332 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 6333 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 6334 apkName).getAbsolutePath(); 6335 6336 if (info.secondaryCpuAbi != null) { 6337 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 6338 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 6339 secondaryLibDir, apkName).getAbsolutePath(); 6340 } 6341 } else if (asecApp) { 6342 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 6343 .getAbsolutePath(); 6344 } else { 6345 final String apkName = deriveCodePathName(codePath); 6346 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 6347 .getAbsolutePath(); 6348 } 6349 6350 info.nativeLibraryRootRequiresIsa = false; 6351 info.nativeLibraryDir = info.nativeLibraryRootDir; 6352 } else { 6353 // Cluster install 6354 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 6355 info.nativeLibraryRootRequiresIsa = true; 6356 6357 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 6358 getPrimaryInstructionSet(info)).getAbsolutePath(); 6359 6360 if (info.secondaryCpuAbi != null) { 6361 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 6362 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 6363 } 6364 } 6365 } 6366 6367 /** 6368 * Calculate the abis and roots for a bundled app. These can uniquely 6369 * be determined from the contents of the system partition, i.e whether 6370 * it contains 64 or 32 bit shared libraries etc. We do not validate any 6371 * of this information, and instead assume that the system was built 6372 * sensibly. 6373 */ 6374 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 6375 PackageSetting pkgSetting) { 6376 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 6377 6378 // If "/system/lib64/apkname" exists, assume that is the per-package 6379 // native library directory to use; otherwise use "/system/lib/apkname". 6380 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 6381 setBundledAppAbi(pkg, apkRoot, apkName); 6382 // pkgSetting might be null during rescan following uninstall of updates 6383 // to a bundled app, so accommodate that possibility. The settings in 6384 // that case will be established later from the parsed package. 6385 // 6386 // If the settings aren't null, sync them up with what we've just derived. 6387 // note that apkRoot isn't stored in the package settings. 6388 if (pkgSetting != null) { 6389 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6390 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6391 } 6392 } 6393 6394 /** 6395 * Deduces the ABI of a bundled app and sets the relevant fields on the 6396 * parsed pkg object. 6397 * 6398 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 6399 * under which system libraries are installed. 6400 * @param apkName the name of the installed package. 6401 */ 6402 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 6403 final File codeFile = new File(pkg.codePath); 6404 6405 final boolean has64BitLibs; 6406 final boolean has32BitLibs; 6407 if (isApkFile(codeFile)) { 6408 // Monolithic install 6409 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 6410 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 6411 } else { 6412 // Cluster install 6413 final File rootDir = new File(codeFile, LIB_DIR_NAME); 6414 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 6415 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 6416 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 6417 has64BitLibs = (new File(rootDir, isa)).exists(); 6418 } else { 6419 has64BitLibs = false; 6420 } 6421 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 6422 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 6423 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 6424 has32BitLibs = (new File(rootDir, isa)).exists(); 6425 } else { 6426 has32BitLibs = false; 6427 } 6428 } 6429 6430 if (has64BitLibs && !has32BitLibs) { 6431 // The package has 64 bit libs, but not 32 bit libs. Its primary 6432 // ABI should be 64 bit. We can safely assume here that the bundled 6433 // native libraries correspond to the most preferred ABI in the list. 6434 6435 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6436 pkg.applicationInfo.secondaryCpuAbi = null; 6437 } else if (has32BitLibs && !has64BitLibs) { 6438 // The package has 32 bit libs but not 64 bit libs. Its primary 6439 // ABI should be 32 bit. 6440 6441 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6442 pkg.applicationInfo.secondaryCpuAbi = null; 6443 } else if (has32BitLibs && has64BitLibs) { 6444 // The application has both 64 and 32 bit bundled libraries. We check 6445 // here that the app declares multiArch support, and warn if it doesn't. 6446 // 6447 // We will be lenient here and record both ABIs. The primary will be the 6448 // ABI that's higher on the list, i.e, a device that's configured to prefer 6449 // 64 bit apps will see a 64 bit primary ABI, 6450 6451 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 6452 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 6453 } 6454 6455 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 6456 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6457 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6458 } else { 6459 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6460 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6461 } 6462 } else { 6463 pkg.applicationInfo.primaryCpuAbi = null; 6464 pkg.applicationInfo.secondaryCpuAbi = null; 6465 } 6466 } 6467 6468 private void killApplication(String pkgName, int appId, String reason) { 6469 // Request the ActivityManager to kill the process(only for existing packages) 6470 // so that we do not end up in a confused state while the user is still using the older 6471 // version of the application while the new one gets installed. 6472 IActivityManager am = ActivityManagerNative.getDefault(); 6473 if (am != null) { 6474 try { 6475 am.killApplicationWithAppId(pkgName, appId, reason); 6476 } catch (RemoteException e) { 6477 } 6478 } 6479 } 6480 6481 void removePackageLI(PackageSetting ps, boolean chatty) { 6482 if (DEBUG_INSTALL) { 6483 if (chatty) 6484 Log.d(TAG, "Removing package " + ps.name); 6485 } 6486 6487 // writer 6488 synchronized (mPackages) { 6489 mPackages.remove(ps.name); 6490 if (ps.codePathString != null) { 6491 mAppDirs.remove(ps.codePathString); 6492 } 6493 6494 final PackageParser.Package pkg = ps.pkg; 6495 if (pkg != null) { 6496 cleanPackageDataStructuresLILPw(pkg, chatty); 6497 } 6498 } 6499 } 6500 6501 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 6502 if (DEBUG_INSTALL) { 6503 if (chatty) 6504 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 6505 } 6506 6507 // writer 6508 synchronized (mPackages) { 6509 mPackages.remove(pkg.applicationInfo.packageName); 6510 if (pkg.codePath != null) { 6511 mAppDirs.remove(pkg.codePath); 6512 } 6513 cleanPackageDataStructuresLILPw(pkg, chatty); 6514 } 6515 } 6516 6517 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 6518 int N = pkg.providers.size(); 6519 StringBuilder r = null; 6520 int i; 6521 for (i=0; i<N; i++) { 6522 PackageParser.Provider p = pkg.providers.get(i); 6523 mProviders.removeProvider(p); 6524 if (p.info.authority == null) { 6525 6526 /* There was another ContentProvider with this authority when 6527 * this app was installed so this authority is null, 6528 * Ignore it as we don't have to unregister the provider. 6529 */ 6530 continue; 6531 } 6532 String names[] = p.info.authority.split(";"); 6533 for (int j = 0; j < names.length; j++) { 6534 if (mProvidersByAuthority.get(names[j]) == p) { 6535 mProvidersByAuthority.remove(names[j]); 6536 if (DEBUG_REMOVE) { 6537 if (chatty) 6538 Log.d(TAG, "Unregistered content provider: " + names[j] 6539 + ", className = " + p.info.name + ", isSyncable = " 6540 + p.info.isSyncable); 6541 } 6542 } 6543 } 6544 if (DEBUG_REMOVE && chatty) { 6545 if (r == null) { 6546 r = new StringBuilder(256); 6547 } else { 6548 r.append(' '); 6549 } 6550 r.append(p.info.name); 6551 } 6552 } 6553 if (r != null) { 6554 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 6555 } 6556 6557 N = pkg.services.size(); 6558 r = null; 6559 for (i=0; i<N; i++) { 6560 PackageParser.Service s = pkg.services.get(i); 6561 mServices.removeService(s); 6562 if (chatty) { 6563 if (r == null) { 6564 r = new StringBuilder(256); 6565 } else { 6566 r.append(' '); 6567 } 6568 r.append(s.info.name); 6569 } 6570 } 6571 if (r != null) { 6572 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 6573 } 6574 6575 N = pkg.receivers.size(); 6576 r = null; 6577 for (i=0; i<N; i++) { 6578 PackageParser.Activity a = pkg.receivers.get(i); 6579 mReceivers.removeActivity(a, "receiver"); 6580 if (DEBUG_REMOVE && chatty) { 6581 if (r == null) { 6582 r = new StringBuilder(256); 6583 } else { 6584 r.append(' '); 6585 } 6586 r.append(a.info.name); 6587 } 6588 } 6589 if (r != null) { 6590 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 6591 } 6592 6593 N = pkg.activities.size(); 6594 r = null; 6595 for (i=0; i<N; i++) { 6596 PackageParser.Activity a = pkg.activities.get(i); 6597 mActivities.removeActivity(a, "activity"); 6598 if (DEBUG_REMOVE && chatty) { 6599 if (r == null) { 6600 r = new StringBuilder(256); 6601 } else { 6602 r.append(' '); 6603 } 6604 r.append(a.info.name); 6605 } 6606 } 6607 if (r != null) { 6608 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 6609 } 6610 6611 N = pkg.permissions.size(); 6612 r = null; 6613 for (i=0; i<N; i++) { 6614 PackageParser.Permission p = pkg.permissions.get(i); 6615 BasePermission bp = mSettings.mPermissions.get(p.info.name); 6616 if (bp == null) { 6617 bp = mSettings.mPermissionTrees.get(p.info.name); 6618 } 6619 if (bp != null && bp.perm == p) { 6620 bp.perm = null; 6621 if (DEBUG_REMOVE && chatty) { 6622 if (r == null) { 6623 r = new StringBuilder(256); 6624 } else { 6625 r.append(' '); 6626 } 6627 r.append(p.info.name); 6628 } 6629 } 6630 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6631 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 6632 if (appOpPerms != null) { 6633 appOpPerms.remove(pkg.packageName); 6634 } 6635 } 6636 } 6637 if (r != null) { 6638 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6639 } 6640 6641 N = pkg.requestedPermissions.size(); 6642 r = null; 6643 for (i=0; i<N; i++) { 6644 String perm = pkg.requestedPermissions.get(i); 6645 BasePermission bp = mSettings.mPermissions.get(perm); 6646 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6647 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 6648 if (appOpPerms != null) { 6649 appOpPerms.remove(pkg.packageName); 6650 if (appOpPerms.isEmpty()) { 6651 mAppOpPermissionPackages.remove(perm); 6652 } 6653 } 6654 } 6655 } 6656 if (r != null) { 6657 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6658 } 6659 6660 N = pkg.instrumentation.size(); 6661 r = null; 6662 for (i=0; i<N; i++) { 6663 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6664 mInstrumentation.remove(a.getComponentName()); 6665 if (DEBUG_REMOVE && chatty) { 6666 if (r == null) { 6667 r = new StringBuilder(256); 6668 } else { 6669 r.append(' '); 6670 } 6671 r.append(a.info.name); 6672 } 6673 } 6674 if (r != null) { 6675 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 6676 } 6677 6678 r = null; 6679 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6680 // Only system apps can hold shared libraries. 6681 if (pkg.libraryNames != null) { 6682 for (i=0; i<pkg.libraryNames.size(); i++) { 6683 String name = pkg.libraryNames.get(i); 6684 SharedLibraryEntry cur = mSharedLibraries.get(name); 6685 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 6686 mSharedLibraries.remove(name); 6687 if (DEBUG_REMOVE && chatty) { 6688 if (r == null) { 6689 r = new StringBuilder(256); 6690 } else { 6691 r.append(' '); 6692 } 6693 r.append(name); 6694 } 6695 } 6696 } 6697 } 6698 } 6699 if (r != null) { 6700 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 6701 } 6702 } 6703 6704 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 6705 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 6706 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 6707 return true; 6708 } 6709 } 6710 return false; 6711 } 6712 6713 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 6714 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 6715 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 6716 6717 private void updatePermissionsLPw(String changingPkg, 6718 PackageParser.Package pkgInfo, int flags) { 6719 // Make sure there are no dangling permission trees. 6720 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 6721 while (it.hasNext()) { 6722 final BasePermission bp = it.next(); 6723 if (bp.packageSetting == null) { 6724 // We may not yet have parsed the package, so just see if 6725 // we still know about its settings. 6726 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6727 } 6728 if (bp.packageSetting == null) { 6729 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 6730 + " from package " + bp.sourcePackage); 6731 it.remove(); 6732 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6733 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6734 Slog.i(TAG, "Removing old permission tree: " + bp.name 6735 + " from package " + bp.sourcePackage); 6736 flags |= UPDATE_PERMISSIONS_ALL; 6737 it.remove(); 6738 } 6739 } 6740 } 6741 6742 // Make sure all dynamic permissions have been assigned to a package, 6743 // and make sure there are no dangling permissions. 6744 it = mSettings.mPermissions.values().iterator(); 6745 while (it.hasNext()) { 6746 final BasePermission bp = it.next(); 6747 if (bp.type == BasePermission.TYPE_DYNAMIC) { 6748 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 6749 + bp.name + " pkg=" + bp.sourcePackage 6750 + " info=" + bp.pendingInfo); 6751 if (bp.packageSetting == null && bp.pendingInfo != null) { 6752 final BasePermission tree = findPermissionTreeLP(bp.name); 6753 if (tree != null && tree.perm != null) { 6754 bp.packageSetting = tree.packageSetting; 6755 bp.perm = new PackageParser.Permission(tree.perm.owner, 6756 new PermissionInfo(bp.pendingInfo)); 6757 bp.perm.info.packageName = tree.perm.info.packageName; 6758 bp.perm.info.name = bp.name; 6759 bp.uid = tree.uid; 6760 } 6761 } 6762 } 6763 if (bp.packageSetting == null) { 6764 // We may not yet have parsed the package, so just see if 6765 // we still know about its settings. 6766 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6767 } 6768 if (bp.packageSetting == null) { 6769 Slog.w(TAG, "Removing dangling permission: " + bp.name 6770 + " from package " + bp.sourcePackage); 6771 it.remove(); 6772 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6773 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6774 Slog.i(TAG, "Removing old permission: " + bp.name 6775 + " from package " + bp.sourcePackage); 6776 flags |= UPDATE_PERMISSIONS_ALL; 6777 it.remove(); 6778 } 6779 } 6780 } 6781 6782 // Now update the permissions for all packages, in particular 6783 // replace the granted permissions of the system packages. 6784 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 6785 for (PackageParser.Package pkg : mPackages.values()) { 6786 if (pkg != pkgInfo) { 6787 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0); 6788 } 6789 } 6790 } 6791 6792 if (pkgInfo != null) { 6793 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0); 6794 } 6795 } 6796 6797 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) { 6798 final PackageSetting ps = (PackageSetting) pkg.mExtras; 6799 if (ps == null) { 6800 return; 6801 } 6802 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 6803 HashSet<String> origPermissions = gp.grantedPermissions; 6804 boolean changedPermission = false; 6805 6806 if (replace) { 6807 ps.permissionsFixed = false; 6808 if (gp == ps) { 6809 origPermissions = new HashSet<String>(gp.grantedPermissions); 6810 gp.grantedPermissions.clear(); 6811 gp.gids = mGlobalGids; 6812 } 6813 } 6814 6815 if (gp.gids == null) { 6816 gp.gids = mGlobalGids; 6817 } 6818 6819 final int N = pkg.requestedPermissions.size(); 6820 for (int i=0; i<N; i++) { 6821 final String name = pkg.requestedPermissions.get(i); 6822 final boolean required = pkg.requestedPermissionsRequired.get(i); 6823 final BasePermission bp = mSettings.mPermissions.get(name); 6824 if (DEBUG_INSTALL) { 6825 if (gp != ps) { 6826 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 6827 } 6828 } 6829 6830 if (bp == null || bp.packageSetting == null) { 6831 Slog.w(TAG, "Unknown permission " + name 6832 + " in package " + pkg.packageName); 6833 continue; 6834 } 6835 6836 final String perm = bp.name; 6837 boolean allowed; 6838 boolean allowedSig = false; 6839 if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6840 // Keep track of app op permissions. 6841 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 6842 if (pkgs == null) { 6843 pkgs = new ArraySet<>(); 6844 mAppOpPermissionPackages.put(bp.name, pkgs); 6845 } 6846 pkgs.add(pkg.packageName); 6847 } 6848 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 6849 if (level == PermissionInfo.PROTECTION_NORMAL 6850 || level == PermissionInfo.PROTECTION_DANGEROUS) { 6851 // We grant a normal or dangerous permission if any of the following 6852 // are true: 6853 // 1) The permission is required 6854 // 2) The permission is optional, but was granted in the past 6855 // 3) The permission is optional, but was requested by an 6856 // app in /system (not /data) 6857 // 6858 // Otherwise, reject the permission. 6859 allowed = (required || origPermissions.contains(perm) 6860 || (isSystemApp(ps) && !isUpdatedSystemApp(ps))); 6861 } else if (bp.packageSetting == null) { 6862 // This permission is invalid; skip it. 6863 allowed = false; 6864 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 6865 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions); 6866 if (allowed) { 6867 allowedSig = true; 6868 } 6869 } else { 6870 allowed = false; 6871 } 6872 if (DEBUG_INSTALL) { 6873 if (gp != ps) { 6874 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 6875 } 6876 } 6877 if (allowed) { 6878 if (!isSystemApp(ps) && ps.permissionsFixed) { 6879 // If this is an existing, non-system package, then 6880 // we can't add any new permissions to it. 6881 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 6882 // Except... if this is a permission that was added 6883 // to the platform (note: need to only do this when 6884 // updating the platform). 6885 allowed = isNewPlatformPermissionForPackage(perm, pkg); 6886 } 6887 } 6888 if (allowed) { 6889 if (!gp.grantedPermissions.contains(perm)) { 6890 changedPermission = true; 6891 gp.grantedPermissions.add(perm); 6892 gp.gids = appendInts(gp.gids, bp.gids); 6893 } else if (!ps.haveGids) { 6894 gp.gids = appendInts(gp.gids, bp.gids); 6895 } 6896 } else { 6897 Slog.w(TAG, "Not granting permission " + perm 6898 + " to package " + pkg.packageName 6899 + " because it was previously installed without"); 6900 } 6901 } else { 6902 if (gp.grantedPermissions.remove(perm)) { 6903 changedPermission = true; 6904 gp.gids = removeInts(gp.gids, bp.gids); 6905 Slog.i(TAG, "Un-granting permission " + perm 6906 + " from package " + pkg.packageName 6907 + " (protectionLevel=" + bp.protectionLevel 6908 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6909 + ")"); 6910 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 6911 // Don't print warning for app op permissions, since it is fine for them 6912 // not to be granted, there is a UI for the user to decide. 6913 Slog.w(TAG, "Not granting permission " + perm 6914 + " to package " + pkg.packageName 6915 + " (protectionLevel=" + bp.protectionLevel 6916 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6917 + ")"); 6918 } 6919 } 6920 } 6921 6922 if ((changedPermission || replace) && !ps.permissionsFixed && 6923 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 6924 // This is the first that we have heard about this package, so the 6925 // permissions we have now selected are fixed until explicitly 6926 // changed. 6927 ps.permissionsFixed = true; 6928 } 6929 ps.haveGids = true; 6930 } 6931 6932 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 6933 boolean allowed = false; 6934 final int NP = PackageParser.NEW_PERMISSIONS.length; 6935 for (int ip=0; ip<NP; ip++) { 6936 final PackageParser.NewPermissionInfo npi 6937 = PackageParser.NEW_PERMISSIONS[ip]; 6938 if (npi.name.equals(perm) 6939 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 6940 allowed = true; 6941 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 6942 + pkg.packageName); 6943 break; 6944 } 6945 } 6946 return allowed; 6947 } 6948 6949 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 6950 BasePermission bp, HashSet<String> origPermissions) { 6951 boolean allowed; 6952 allowed = (compareSignatures( 6953 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 6954 == PackageManager.SIGNATURE_MATCH) 6955 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 6956 == PackageManager.SIGNATURE_MATCH); 6957 if (!allowed && (bp.protectionLevel 6958 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 6959 if (isSystemApp(pkg)) { 6960 // For updated system applications, a system permission 6961 // is granted only if it had been defined by the original application. 6962 if (isUpdatedSystemApp(pkg)) { 6963 final PackageSetting sysPs = mSettings 6964 .getDisabledSystemPkgLPr(pkg.packageName); 6965 final GrantedPermissions origGp = sysPs.sharedUser != null 6966 ? sysPs.sharedUser : sysPs; 6967 6968 if (origGp.grantedPermissions.contains(perm)) { 6969 // If the original was granted this permission, we take 6970 // that grant decision as read and propagate it to the 6971 // update. 6972 allowed = true; 6973 } else { 6974 // The system apk may have been updated with an older 6975 // version of the one on the data partition, but which 6976 // granted a new system permission that it didn't have 6977 // before. In this case we do want to allow the app to 6978 // now get the new permission if the ancestral apk is 6979 // privileged to get it. 6980 if (sysPs.pkg != null && sysPs.isPrivileged()) { 6981 for (int j=0; 6982 j<sysPs.pkg.requestedPermissions.size(); j++) { 6983 if (perm.equals( 6984 sysPs.pkg.requestedPermissions.get(j))) { 6985 allowed = true; 6986 break; 6987 } 6988 } 6989 } 6990 } 6991 } else { 6992 allowed = isPrivilegedApp(pkg); 6993 } 6994 } 6995 } 6996 if (!allowed && (bp.protectionLevel 6997 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 6998 // For development permissions, a development permission 6999 // is granted only if it was already granted. 7000 allowed = origPermissions.contains(perm); 7001 } 7002 return allowed; 7003 } 7004 7005 final class ActivityIntentResolver 7006 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 7007 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7008 boolean defaultOnly, int userId) { 7009 if (!sUserManager.exists(userId)) return null; 7010 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7011 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7012 } 7013 7014 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7015 int userId) { 7016 if (!sUserManager.exists(userId)) return null; 7017 mFlags = flags; 7018 return super.queryIntent(intent, resolvedType, 7019 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7020 } 7021 7022 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7023 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 7024 if (!sUserManager.exists(userId)) return null; 7025 if (packageActivities == null) { 7026 return null; 7027 } 7028 mFlags = flags; 7029 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7030 final int N = packageActivities.size(); 7031 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 7032 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 7033 7034 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 7035 for (int i = 0; i < N; ++i) { 7036 intentFilters = packageActivities.get(i).intents; 7037 if (intentFilters != null && intentFilters.size() > 0) { 7038 PackageParser.ActivityIntentInfo[] array = 7039 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 7040 intentFilters.toArray(array); 7041 listCut.add(array); 7042 } 7043 } 7044 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7045 } 7046 7047 public final void addActivity(PackageParser.Activity a, String type) { 7048 final boolean systemApp = isSystemApp(a.info.applicationInfo); 7049 mActivities.put(a.getComponentName(), a); 7050 if (DEBUG_SHOW_INFO) 7051 Log.v( 7052 TAG, " " + type + " " + 7053 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 7054 if (DEBUG_SHOW_INFO) 7055 Log.v(TAG, " Class=" + a.info.name); 7056 final int NI = a.intents.size(); 7057 for (int j=0; j<NI; j++) { 7058 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7059 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 7060 intent.setPriority(0); 7061 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 7062 + a.className + " with priority > 0, forcing to 0"); 7063 } 7064 if (DEBUG_SHOW_INFO) { 7065 Log.v(TAG, " IntentFilter:"); 7066 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7067 } 7068 if (!intent.debugCheck()) { 7069 Log.w(TAG, "==> For Activity " + a.info.name); 7070 } 7071 addFilter(intent); 7072 } 7073 } 7074 7075 public final void removeActivity(PackageParser.Activity a, String type) { 7076 mActivities.remove(a.getComponentName()); 7077 if (DEBUG_SHOW_INFO) { 7078 Log.v(TAG, " " + type + " " 7079 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 7080 : a.info.name) + ":"); 7081 Log.v(TAG, " Class=" + a.info.name); 7082 } 7083 final int NI = a.intents.size(); 7084 for (int j=0; j<NI; j++) { 7085 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7086 if (DEBUG_SHOW_INFO) { 7087 Log.v(TAG, " IntentFilter:"); 7088 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7089 } 7090 removeFilter(intent); 7091 } 7092 } 7093 7094 @Override 7095 protected boolean allowFilterResult( 7096 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 7097 ActivityInfo filterAi = filter.activity.info; 7098 for (int i=dest.size()-1; i>=0; i--) { 7099 ActivityInfo destAi = dest.get(i).activityInfo; 7100 if (destAi.name == filterAi.name 7101 && destAi.packageName == filterAi.packageName) { 7102 return false; 7103 } 7104 } 7105 return true; 7106 } 7107 7108 @Override 7109 protected ActivityIntentInfo[] newArray(int size) { 7110 return new ActivityIntentInfo[size]; 7111 } 7112 7113 @Override 7114 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 7115 if (!sUserManager.exists(userId)) return true; 7116 PackageParser.Package p = filter.activity.owner; 7117 if (p != null) { 7118 PackageSetting ps = (PackageSetting)p.mExtras; 7119 if (ps != null) { 7120 // System apps are never considered stopped for purposes of 7121 // filtering, because there may be no way for the user to 7122 // actually re-launch them. 7123 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 7124 && ps.getStopped(userId); 7125 } 7126 } 7127 return false; 7128 } 7129 7130 @Override 7131 protected boolean isPackageForFilter(String packageName, 7132 PackageParser.ActivityIntentInfo info) { 7133 return packageName.equals(info.activity.owner.packageName); 7134 } 7135 7136 @Override 7137 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7138 int match, int userId) { 7139 if (!sUserManager.exists(userId)) return null; 7140 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7141 return null; 7142 } 7143 final PackageParser.Activity activity = info.activity; 7144 if (mSafeMode && (activity.info.applicationInfo.flags 7145 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7146 return null; 7147 } 7148 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7149 if (ps == null) { 7150 return null; 7151 } 7152 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7153 ps.readUserState(userId), userId); 7154 if (ai == null) { 7155 return null; 7156 } 7157 final ResolveInfo res = new ResolveInfo(); 7158 res.activityInfo = ai; 7159 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7160 res.filter = info; 7161 } 7162 res.priority = info.getPriority(); 7163 res.preferredOrder = activity.owner.mPreferredOrder; 7164 //System.out.println("Result: " + res.activityInfo.className + 7165 // " = " + res.priority); 7166 res.match = match; 7167 res.isDefault = info.hasDefault; 7168 res.labelRes = info.labelRes; 7169 res.nonLocalizedLabel = info.nonLocalizedLabel; 7170 if (userNeedsBadging(userId)) { 7171 res.noResourceId = true; 7172 } else { 7173 res.icon = info.icon; 7174 } 7175 res.system = isSystemApp(res.activityInfo.applicationInfo); 7176 return res; 7177 } 7178 7179 @Override 7180 protected void sortResults(List<ResolveInfo> results) { 7181 Collections.sort(results, mResolvePrioritySorter); 7182 } 7183 7184 @Override 7185 protected void dumpFilter(PrintWriter out, String prefix, 7186 PackageParser.ActivityIntentInfo filter) { 7187 out.print(prefix); out.print( 7188 Integer.toHexString(System.identityHashCode(filter.activity))); 7189 out.print(' '); 7190 filter.activity.printComponentShortName(out); 7191 out.print(" filter "); 7192 out.println(Integer.toHexString(System.identityHashCode(filter))); 7193 } 7194 7195// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7196// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7197// final List<ResolveInfo> retList = Lists.newArrayList(); 7198// while (i.hasNext()) { 7199// final ResolveInfo resolveInfo = i.next(); 7200// if (isEnabledLP(resolveInfo.activityInfo)) { 7201// retList.add(resolveInfo); 7202// } 7203// } 7204// return retList; 7205// } 7206 7207 // Keys are String (activity class name), values are Activity. 7208 private final HashMap<ComponentName, PackageParser.Activity> mActivities 7209 = new HashMap<ComponentName, PackageParser.Activity>(); 7210 private int mFlags; 7211 } 7212 7213 private final class ServiceIntentResolver 7214 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 7215 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7216 boolean defaultOnly, int userId) { 7217 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7218 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7219 } 7220 7221 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7222 int userId) { 7223 if (!sUserManager.exists(userId)) return null; 7224 mFlags = flags; 7225 return super.queryIntent(intent, resolvedType, 7226 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7227 } 7228 7229 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7230 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 7231 if (!sUserManager.exists(userId)) return null; 7232 if (packageServices == null) { 7233 return null; 7234 } 7235 mFlags = flags; 7236 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7237 final int N = packageServices.size(); 7238 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 7239 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 7240 7241 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 7242 for (int i = 0; i < N; ++i) { 7243 intentFilters = packageServices.get(i).intents; 7244 if (intentFilters != null && intentFilters.size() > 0) { 7245 PackageParser.ServiceIntentInfo[] array = 7246 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 7247 intentFilters.toArray(array); 7248 listCut.add(array); 7249 } 7250 } 7251 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7252 } 7253 7254 public final void addService(PackageParser.Service s) { 7255 mServices.put(s.getComponentName(), s); 7256 if (DEBUG_SHOW_INFO) { 7257 Log.v(TAG, " " 7258 + (s.info.nonLocalizedLabel != null 7259 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7260 Log.v(TAG, " Class=" + s.info.name); 7261 } 7262 final int NI = s.intents.size(); 7263 int j; 7264 for (j=0; j<NI; j++) { 7265 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7266 if (DEBUG_SHOW_INFO) { 7267 Log.v(TAG, " IntentFilter:"); 7268 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7269 } 7270 if (!intent.debugCheck()) { 7271 Log.w(TAG, "==> For Service " + s.info.name); 7272 } 7273 addFilter(intent); 7274 } 7275 } 7276 7277 public final void removeService(PackageParser.Service s) { 7278 mServices.remove(s.getComponentName()); 7279 if (DEBUG_SHOW_INFO) { 7280 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 7281 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7282 Log.v(TAG, " Class=" + s.info.name); 7283 } 7284 final int NI = s.intents.size(); 7285 int j; 7286 for (j=0; j<NI; j++) { 7287 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7288 if (DEBUG_SHOW_INFO) { 7289 Log.v(TAG, " IntentFilter:"); 7290 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7291 } 7292 removeFilter(intent); 7293 } 7294 } 7295 7296 @Override 7297 protected boolean allowFilterResult( 7298 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 7299 ServiceInfo filterSi = filter.service.info; 7300 for (int i=dest.size()-1; i>=0; i--) { 7301 ServiceInfo destAi = dest.get(i).serviceInfo; 7302 if (destAi.name == filterSi.name 7303 && destAi.packageName == filterSi.packageName) { 7304 return false; 7305 } 7306 } 7307 return true; 7308 } 7309 7310 @Override 7311 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 7312 return new PackageParser.ServiceIntentInfo[size]; 7313 } 7314 7315 @Override 7316 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 7317 if (!sUserManager.exists(userId)) return true; 7318 PackageParser.Package p = filter.service.owner; 7319 if (p != null) { 7320 PackageSetting ps = (PackageSetting)p.mExtras; 7321 if (ps != null) { 7322 // System apps are never considered stopped for purposes of 7323 // filtering, because there may be no way for the user to 7324 // actually re-launch them. 7325 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7326 && ps.getStopped(userId); 7327 } 7328 } 7329 return false; 7330 } 7331 7332 @Override 7333 protected boolean isPackageForFilter(String packageName, 7334 PackageParser.ServiceIntentInfo info) { 7335 return packageName.equals(info.service.owner.packageName); 7336 } 7337 7338 @Override 7339 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 7340 int match, int userId) { 7341 if (!sUserManager.exists(userId)) return null; 7342 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 7343 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 7344 return null; 7345 } 7346 final PackageParser.Service service = info.service; 7347 if (mSafeMode && (service.info.applicationInfo.flags 7348 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7349 return null; 7350 } 7351 PackageSetting ps = (PackageSetting) service.owner.mExtras; 7352 if (ps == null) { 7353 return null; 7354 } 7355 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 7356 ps.readUserState(userId), userId); 7357 if (si == null) { 7358 return null; 7359 } 7360 final ResolveInfo res = new ResolveInfo(); 7361 res.serviceInfo = si; 7362 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7363 res.filter = filter; 7364 } 7365 res.priority = info.getPriority(); 7366 res.preferredOrder = service.owner.mPreferredOrder; 7367 //System.out.println("Result: " + res.activityInfo.className + 7368 // " = " + res.priority); 7369 res.match = match; 7370 res.isDefault = info.hasDefault; 7371 res.labelRes = info.labelRes; 7372 res.nonLocalizedLabel = info.nonLocalizedLabel; 7373 res.icon = info.icon; 7374 res.system = isSystemApp(res.serviceInfo.applicationInfo); 7375 return res; 7376 } 7377 7378 @Override 7379 protected void sortResults(List<ResolveInfo> results) { 7380 Collections.sort(results, mResolvePrioritySorter); 7381 } 7382 7383 @Override 7384 protected void dumpFilter(PrintWriter out, String prefix, 7385 PackageParser.ServiceIntentInfo filter) { 7386 out.print(prefix); out.print( 7387 Integer.toHexString(System.identityHashCode(filter.service))); 7388 out.print(' '); 7389 filter.service.printComponentShortName(out); 7390 out.print(" filter "); 7391 out.println(Integer.toHexString(System.identityHashCode(filter))); 7392 } 7393 7394// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7395// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7396// final List<ResolveInfo> retList = Lists.newArrayList(); 7397// while (i.hasNext()) { 7398// final ResolveInfo resolveInfo = (ResolveInfo) i; 7399// if (isEnabledLP(resolveInfo.serviceInfo)) { 7400// retList.add(resolveInfo); 7401// } 7402// } 7403// return retList; 7404// } 7405 7406 // Keys are String (activity class name), values are Activity. 7407 private final HashMap<ComponentName, PackageParser.Service> mServices 7408 = new HashMap<ComponentName, PackageParser.Service>(); 7409 private int mFlags; 7410 }; 7411 7412 private final class ProviderIntentResolver 7413 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 7414 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7415 boolean defaultOnly, int userId) { 7416 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7417 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7418 } 7419 7420 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7421 int userId) { 7422 if (!sUserManager.exists(userId)) 7423 return null; 7424 mFlags = flags; 7425 return super.queryIntent(intent, resolvedType, 7426 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7427 } 7428 7429 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7430 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 7431 if (!sUserManager.exists(userId)) 7432 return null; 7433 if (packageProviders == null) { 7434 return null; 7435 } 7436 mFlags = flags; 7437 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 7438 final int N = packageProviders.size(); 7439 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 7440 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 7441 7442 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 7443 for (int i = 0; i < N; ++i) { 7444 intentFilters = packageProviders.get(i).intents; 7445 if (intentFilters != null && intentFilters.size() > 0) { 7446 PackageParser.ProviderIntentInfo[] array = 7447 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 7448 intentFilters.toArray(array); 7449 listCut.add(array); 7450 } 7451 } 7452 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7453 } 7454 7455 public final void addProvider(PackageParser.Provider p) { 7456 if (mProviders.containsKey(p.getComponentName())) { 7457 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 7458 return; 7459 } 7460 7461 mProviders.put(p.getComponentName(), p); 7462 if (DEBUG_SHOW_INFO) { 7463 Log.v(TAG, " " 7464 + (p.info.nonLocalizedLabel != null 7465 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7466 Log.v(TAG, " Class=" + p.info.name); 7467 } 7468 final int NI = p.intents.size(); 7469 int j; 7470 for (j = 0; j < NI; j++) { 7471 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7472 if (DEBUG_SHOW_INFO) { 7473 Log.v(TAG, " IntentFilter:"); 7474 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7475 } 7476 if (!intent.debugCheck()) { 7477 Log.w(TAG, "==> For Provider " + p.info.name); 7478 } 7479 addFilter(intent); 7480 } 7481 } 7482 7483 public final void removeProvider(PackageParser.Provider p) { 7484 mProviders.remove(p.getComponentName()); 7485 if (DEBUG_SHOW_INFO) { 7486 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 7487 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7488 Log.v(TAG, " Class=" + p.info.name); 7489 } 7490 final int NI = p.intents.size(); 7491 int j; 7492 for (j = 0; j < NI; j++) { 7493 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7494 if (DEBUG_SHOW_INFO) { 7495 Log.v(TAG, " IntentFilter:"); 7496 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7497 } 7498 removeFilter(intent); 7499 } 7500 } 7501 7502 @Override 7503 protected boolean allowFilterResult( 7504 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 7505 ProviderInfo filterPi = filter.provider.info; 7506 for (int i = dest.size() - 1; i >= 0; i--) { 7507 ProviderInfo destPi = dest.get(i).providerInfo; 7508 if (destPi.name == filterPi.name 7509 && destPi.packageName == filterPi.packageName) { 7510 return false; 7511 } 7512 } 7513 return true; 7514 } 7515 7516 @Override 7517 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 7518 return new PackageParser.ProviderIntentInfo[size]; 7519 } 7520 7521 @Override 7522 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 7523 if (!sUserManager.exists(userId)) 7524 return true; 7525 PackageParser.Package p = filter.provider.owner; 7526 if (p != null) { 7527 PackageSetting ps = (PackageSetting) p.mExtras; 7528 if (ps != null) { 7529 // System apps are never considered stopped for purposes of 7530 // filtering, because there may be no way for the user to 7531 // actually re-launch them. 7532 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7533 && ps.getStopped(userId); 7534 } 7535 } 7536 return false; 7537 } 7538 7539 @Override 7540 protected boolean isPackageForFilter(String packageName, 7541 PackageParser.ProviderIntentInfo info) { 7542 return packageName.equals(info.provider.owner.packageName); 7543 } 7544 7545 @Override 7546 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 7547 int match, int userId) { 7548 if (!sUserManager.exists(userId)) 7549 return null; 7550 final PackageParser.ProviderIntentInfo info = filter; 7551 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 7552 return null; 7553 } 7554 final PackageParser.Provider provider = info.provider; 7555 if (mSafeMode && (provider.info.applicationInfo.flags 7556 & ApplicationInfo.FLAG_SYSTEM) == 0) { 7557 return null; 7558 } 7559 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 7560 if (ps == null) { 7561 return null; 7562 } 7563 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 7564 ps.readUserState(userId), userId); 7565 if (pi == null) { 7566 return null; 7567 } 7568 final ResolveInfo res = new ResolveInfo(); 7569 res.providerInfo = pi; 7570 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 7571 res.filter = filter; 7572 } 7573 res.priority = info.getPriority(); 7574 res.preferredOrder = provider.owner.mPreferredOrder; 7575 res.match = match; 7576 res.isDefault = info.hasDefault; 7577 res.labelRes = info.labelRes; 7578 res.nonLocalizedLabel = info.nonLocalizedLabel; 7579 res.icon = info.icon; 7580 res.system = isSystemApp(res.providerInfo.applicationInfo); 7581 return res; 7582 } 7583 7584 @Override 7585 protected void sortResults(List<ResolveInfo> results) { 7586 Collections.sort(results, mResolvePrioritySorter); 7587 } 7588 7589 @Override 7590 protected void dumpFilter(PrintWriter out, String prefix, 7591 PackageParser.ProviderIntentInfo filter) { 7592 out.print(prefix); 7593 out.print( 7594 Integer.toHexString(System.identityHashCode(filter.provider))); 7595 out.print(' '); 7596 filter.provider.printComponentShortName(out); 7597 out.print(" filter "); 7598 out.println(Integer.toHexString(System.identityHashCode(filter))); 7599 } 7600 7601 private final HashMap<ComponentName, PackageParser.Provider> mProviders 7602 = new HashMap<ComponentName, PackageParser.Provider>(); 7603 private int mFlags; 7604 }; 7605 7606 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 7607 new Comparator<ResolveInfo>() { 7608 public int compare(ResolveInfo r1, ResolveInfo r2) { 7609 int v1 = r1.priority; 7610 int v2 = r2.priority; 7611 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 7612 if (v1 != v2) { 7613 return (v1 > v2) ? -1 : 1; 7614 } 7615 v1 = r1.preferredOrder; 7616 v2 = r2.preferredOrder; 7617 if (v1 != v2) { 7618 return (v1 > v2) ? -1 : 1; 7619 } 7620 if (r1.isDefault != r2.isDefault) { 7621 return r1.isDefault ? -1 : 1; 7622 } 7623 v1 = r1.match; 7624 v2 = r2.match; 7625 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 7626 if (v1 != v2) { 7627 return (v1 > v2) ? -1 : 1; 7628 } 7629 if (r1.system != r2.system) { 7630 return r1.system ? -1 : 1; 7631 } 7632 return 0; 7633 } 7634 }; 7635 7636 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 7637 new Comparator<ProviderInfo>() { 7638 public int compare(ProviderInfo p1, ProviderInfo p2) { 7639 final int v1 = p1.initOrder; 7640 final int v2 = p2.initOrder; 7641 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 7642 } 7643 }; 7644 7645 static final void sendPackageBroadcast(String action, String pkg, 7646 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 7647 int[] userIds) { 7648 IActivityManager am = ActivityManagerNative.getDefault(); 7649 if (am != null) { 7650 try { 7651 if (userIds == null) { 7652 userIds = am.getRunningUserIds(); 7653 } 7654 for (int id : userIds) { 7655 final Intent intent = new Intent(action, 7656 pkg != null ? Uri.fromParts("package", pkg, null) : null); 7657 if (extras != null) { 7658 intent.putExtras(extras); 7659 } 7660 if (targetPkg != null) { 7661 intent.setPackage(targetPkg); 7662 } 7663 // Modify the UID when posting to other users 7664 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 7665 if (uid > 0 && UserHandle.getUserId(uid) != id) { 7666 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 7667 intent.putExtra(Intent.EXTRA_UID, uid); 7668 } 7669 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 7670 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 7671 if (DEBUG_BROADCASTS) { 7672 RuntimeException here = new RuntimeException("here"); 7673 here.fillInStackTrace(); 7674 Slog.d(TAG, "Sending to user " + id + ": " 7675 + intent.toShortString(false, true, false, false) 7676 + " " + intent.getExtras(), here); 7677 } 7678 am.broadcastIntent(null, intent, null, finishedReceiver, 7679 0, null, null, null, android.app.AppOpsManager.OP_NONE, 7680 finishedReceiver != null, false, id); 7681 } 7682 } catch (RemoteException ex) { 7683 } 7684 } 7685 } 7686 7687 /** 7688 * Check if the external storage media is available. This is true if there 7689 * is a mounted external storage medium or if the external storage is 7690 * emulated. 7691 */ 7692 private boolean isExternalMediaAvailable() { 7693 return mMediaMounted || Environment.isExternalStorageEmulated(); 7694 } 7695 7696 @Override 7697 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 7698 // writer 7699 synchronized (mPackages) { 7700 if (!isExternalMediaAvailable()) { 7701 // If the external storage is no longer mounted at this point, 7702 // the caller may not have been able to delete all of this 7703 // packages files and can not delete any more. Bail. 7704 return null; 7705 } 7706 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 7707 if (lastPackage != null) { 7708 pkgs.remove(lastPackage); 7709 } 7710 if (pkgs.size() > 0) { 7711 return pkgs.get(0); 7712 } 7713 } 7714 return null; 7715 } 7716 7717 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 7718 if (false) { 7719 RuntimeException here = new RuntimeException("here"); 7720 here.fillInStackTrace(); 7721 Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId 7722 + " andCode=" + andCode, here); 7723 } 7724 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, 7725 userId, andCode ? 1 : 0, packageName)); 7726 } 7727 7728 void startCleaningPackages() { 7729 // reader 7730 synchronized (mPackages) { 7731 if (!isExternalMediaAvailable()) { 7732 return; 7733 } 7734 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 7735 return; 7736 } 7737 } 7738 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 7739 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 7740 IActivityManager am = ActivityManagerNative.getDefault(); 7741 if (am != null) { 7742 try { 7743 am.startService(null, intent, null, UserHandle.USER_OWNER); 7744 } catch (RemoteException e) { 7745 } 7746 } 7747 } 7748 7749 @Override 7750 public void installPackage(String originPath, IPackageInstallObserver2 observer, int flags, 7751 String installerPackageName, VerificationParams verificationParams, 7752 String packageAbiOverride) { 7753 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7754 null); 7755 7756 final File originFile = new File(originPath); 7757 final int uid = Binder.getCallingUid(); 7758 if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) { 7759 try { 7760 if (observer != null) { 7761 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 7762 } 7763 } catch (RemoteException re) { 7764 } 7765 return; 7766 } 7767 7768 UserHandle user; 7769 if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) { 7770 user = UserHandle.ALL; 7771 } else { 7772 user = new UserHandle(UserHandle.getUserId(uid)); 7773 } 7774 7775 final int filteredFlags; 7776 if (uid == Process.SHELL_UID || uid == 0) { 7777 if (DEBUG_INSTALL) { 7778 Slog.v(TAG, "Install from ADB"); 7779 } 7780 filteredFlags = flags | PackageManager.INSTALL_FROM_ADB; 7781 } else { 7782 filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB; 7783 } 7784 7785 verificationParams.setInstallerUid(uid); 7786 7787 final Message msg = mHandler.obtainMessage(INIT_COPY); 7788 msg.obj = new InstallParams(originFile, null, false, observer, filteredFlags, 7789 installerPackageName, verificationParams, user, packageAbiOverride); 7790 mHandler.sendMessage(msg); 7791 } 7792 7793 void installStage(String packageName, File stagedDir, String stagedCid, 7794 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 7795 String installerPackageName, int installerUid, UserHandle user) { 7796 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 7797 params.referrerUri, installerUid, null); 7798 7799 final Message msg = mHandler.obtainMessage(INIT_COPY); 7800 msg.obj = new InstallParams(stagedDir, stagedCid, true, observer, params.installFlags, 7801 installerPackageName, verifParams, user, params.abiOverride); 7802 mHandler.sendMessage(msg); 7803 } 7804 7805 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 7806 Bundle extras = new Bundle(1); 7807 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 7808 7809 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 7810 packageName, extras, null, null, new int[] {userId}); 7811 try { 7812 IActivityManager am = ActivityManagerNative.getDefault(); 7813 final boolean isSystem = 7814 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 7815 if (isSystem && am.isUserRunning(userId, false)) { 7816 // The just-installed/enabled app is bundled on the system, so presumed 7817 // to be able to run automatically without needing an explicit launch. 7818 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 7819 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 7820 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 7821 .setPackage(packageName); 7822 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 7823 android.app.AppOpsManager.OP_NONE, false, false, userId); 7824 } 7825 } catch (RemoteException e) { 7826 // shouldn't happen 7827 Slog.w(TAG, "Unable to bootstrap installed package", e); 7828 } 7829 } 7830 7831 @Override 7832 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 7833 int userId) { 7834 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7835 PackageSetting pkgSetting; 7836 final int uid = Binder.getCallingUid(); 7837 if (UserHandle.getUserId(uid) != userId) { 7838 mContext.enforceCallingOrSelfPermission( 7839 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 7840 "setApplicationHiddenSetting for user " + userId); 7841 } 7842 7843 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 7844 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 7845 return false; 7846 } 7847 7848 long callingId = Binder.clearCallingIdentity(); 7849 try { 7850 boolean sendAdded = false; 7851 boolean sendRemoved = false; 7852 // writer 7853 synchronized (mPackages) { 7854 pkgSetting = mSettings.mPackages.get(packageName); 7855 if (pkgSetting == null) { 7856 return false; 7857 } 7858 if (pkgSetting.getHidden(userId) != hidden) { 7859 pkgSetting.setHidden(hidden, userId); 7860 mSettings.writePackageRestrictionsLPr(userId); 7861 if (hidden) { 7862 sendRemoved = true; 7863 } else { 7864 sendAdded = true; 7865 } 7866 } 7867 } 7868 if (sendAdded) { 7869 sendPackageAddedForUser(packageName, pkgSetting, userId); 7870 return true; 7871 } 7872 if (sendRemoved) { 7873 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 7874 "hiding pkg"); 7875 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 7876 } 7877 } finally { 7878 Binder.restoreCallingIdentity(callingId); 7879 } 7880 return false; 7881 } 7882 7883 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 7884 int userId) { 7885 final PackageRemovedInfo info = new PackageRemovedInfo(); 7886 info.removedPackage = packageName; 7887 info.removedUsers = new int[] {userId}; 7888 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 7889 info.sendBroadcast(false, false, false); 7890 } 7891 7892 /** 7893 * Returns true if application is not found or there was an error. Otherwise it returns 7894 * the hidden state of the package for the given user. 7895 */ 7896 @Override 7897 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 7898 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7899 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 7900 "getApplicationHidden for user " + userId); 7901 PackageSetting pkgSetting; 7902 long callingId = Binder.clearCallingIdentity(); 7903 try { 7904 // writer 7905 synchronized (mPackages) { 7906 pkgSetting = mSettings.mPackages.get(packageName); 7907 if (pkgSetting == null) { 7908 return true; 7909 } 7910 return pkgSetting.getHidden(userId); 7911 } 7912 } finally { 7913 Binder.restoreCallingIdentity(callingId); 7914 } 7915 } 7916 7917 /** 7918 * @hide 7919 */ 7920 @Override 7921 public int installExistingPackageAsUser(String packageName, int userId) { 7922 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7923 null); 7924 PackageSetting pkgSetting; 7925 final int uid = Binder.getCallingUid(); 7926 enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId); 7927 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 7928 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 7929 } 7930 7931 long callingId = Binder.clearCallingIdentity(); 7932 try { 7933 boolean sendAdded = false; 7934 Bundle extras = new Bundle(1); 7935 7936 // writer 7937 synchronized (mPackages) { 7938 pkgSetting = mSettings.mPackages.get(packageName); 7939 if (pkgSetting == null) { 7940 return PackageManager.INSTALL_FAILED_INVALID_URI; 7941 } 7942 if (!pkgSetting.getInstalled(userId)) { 7943 pkgSetting.setInstalled(true, userId); 7944 pkgSetting.setHidden(false, userId); 7945 mSettings.writePackageRestrictionsLPr(userId); 7946 sendAdded = true; 7947 } 7948 } 7949 7950 if (sendAdded) { 7951 sendPackageAddedForUser(packageName, pkgSetting, userId); 7952 } 7953 } finally { 7954 Binder.restoreCallingIdentity(callingId); 7955 } 7956 7957 return PackageManager.INSTALL_SUCCEEDED; 7958 } 7959 7960 boolean isUserRestricted(int userId, String restrictionKey) { 7961 Bundle restrictions = sUserManager.getUserRestrictions(userId); 7962 if (restrictions.getBoolean(restrictionKey, false)) { 7963 Log.w(TAG, "User is restricted: " + restrictionKey); 7964 return true; 7965 } 7966 return false; 7967 } 7968 7969 @Override 7970 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 7971 mContext.enforceCallingOrSelfPermission( 7972 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7973 "Only package verification agents can verify applications"); 7974 7975 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7976 final PackageVerificationResponse response = new PackageVerificationResponse( 7977 verificationCode, Binder.getCallingUid()); 7978 msg.arg1 = id; 7979 msg.obj = response; 7980 mHandler.sendMessage(msg); 7981 } 7982 7983 @Override 7984 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 7985 long millisecondsToDelay) { 7986 mContext.enforceCallingOrSelfPermission( 7987 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7988 "Only package verification agents can extend verification timeouts"); 7989 7990 final PackageVerificationState state = mPendingVerification.get(id); 7991 final PackageVerificationResponse response = new PackageVerificationResponse( 7992 verificationCodeAtTimeout, Binder.getCallingUid()); 7993 7994 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 7995 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 7996 } 7997 if (millisecondsToDelay < 0) { 7998 millisecondsToDelay = 0; 7999 } 8000 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 8001 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 8002 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 8003 } 8004 8005 if ((state != null) && !state.timeoutExtended()) { 8006 state.extendTimeout(); 8007 8008 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8009 msg.arg1 = id; 8010 msg.obj = response; 8011 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 8012 } 8013 } 8014 8015 private void broadcastPackageVerified(int verificationId, Uri packageUri, 8016 int verificationCode, UserHandle user) { 8017 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 8018 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 8019 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8020 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8021 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 8022 8023 mContext.sendBroadcastAsUser(intent, user, 8024 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 8025 } 8026 8027 private ComponentName matchComponentForVerifier(String packageName, 8028 List<ResolveInfo> receivers) { 8029 ActivityInfo targetReceiver = null; 8030 8031 final int NR = receivers.size(); 8032 for (int i = 0; i < NR; i++) { 8033 final ResolveInfo info = receivers.get(i); 8034 if (info.activityInfo == null) { 8035 continue; 8036 } 8037 8038 if (packageName.equals(info.activityInfo.packageName)) { 8039 targetReceiver = info.activityInfo; 8040 break; 8041 } 8042 } 8043 8044 if (targetReceiver == null) { 8045 return null; 8046 } 8047 8048 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8049 } 8050 8051 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8052 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8053 if (pkgInfo.verifiers.length == 0) { 8054 return null; 8055 } 8056 8057 final int N = pkgInfo.verifiers.length; 8058 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8059 for (int i = 0; i < N; i++) { 8060 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8061 8062 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8063 receivers); 8064 if (comp == null) { 8065 continue; 8066 } 8067 8068 final int verifierUid = getUidForVerifier(verifierInfo); 8069 if (verifierUid == -1) { 8070 continue; 8071 } 8072 8073 if (DEBUG_VERIFY) { 8074 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8075 + " with the correct signature"); 8076 } 8077 sufficientVerifiers.add(comp); 8078 verificationState.addSufficientVerifier(verifierUid); 8079 } 8080 8081 return sufficientVerifiers; 8082 } 8083 8084 private int getUidForVerifier(VerifierInfo verifierInfo) { 8085 synchronized (mPackages) { 8086 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8087 if (pkg == null) { 8088 return -1; 8089 } else if (pkg.mSignatures.length != 1) { 8090 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8091 + " has more than one signature; ignoring"); 8092 return -1; 8093 } 8094 8095 /* 8096 * If the public key of the package's signature does not match 8097 * our expected public key, then this is a different package and 8098 * we should skip. 8099 */ 8100 8101 final byte[] expectedPublicKey; 8102 try { 8103 final Signature verifierSig = pkg.mSignatures[0]; 8104 final PublicKey publicKey = verifierSig.getPublicKey(); 8105 expectedPublicKey = publicKey.getEncoded(); 8106 } catch (CertificateException e) { 8107 return -1; 8108 } 8109 8110 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8111 8112 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8113 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8114 + " does not have the expected public key; ignoring"); 8115 return -1; 8116 } 8117 8118 return pkg.applicationInfo.uid; 8119 } 8120 } 8121 8122 @Override 8123 public void finishPackageInstall(int token) { 8124 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8125 8126 if (DEBUG_INSTALL) { 8127 Slog.v(TAG, "BM finishing package install for " + token); 8128 } 8129 8130 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8131 mHandler.sendMessage(msg); 8132 } 8133 8134 /** 8135 * Get the verification agent timeout. 8136 * 8137 * @return verification timeout in milliseconds 8138 */ 8139 private long getVerificationTimeout() { 8140 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8141 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8142 DEFAULT_VERIFICATION_TIMEOUT); 8143 } 8144 8145 /** 8146 * Get the default verification agent response code. 8147 * 8148 * @return default verification response code 8149 */ 8150 private int getDefaultVerificationResponse() { 8151 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8152 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8153 DEFAULT_VERIFICATION_RESPONSE); 8154 } 8155 8156 /** 8157 * Check whether or not package verification has been enabled. 8158 * 8159 * @return true if verification should be performed 8160 */ 8161 private boolean isVerificationEnabled(int userId, int flags) { 8162 if (!DEFAULT_VERIFY_ENABLE) { 8163 return false; 8164 } 8165 8166 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 8167 8168 // Check if installing from ADB 8169 if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) { 8170 // Do not run verification in a test harness environment 8171 if (ActivityManager.isRunningInTestHarness()) { 8172 return false; 8173 } 8174 if (ensureVerifyAppsEnabled) { 8175 return true; 8176 } 8177 // Check if the developer does not want package verification for ADB installs 8178 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8179 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8180 return false; 8181 } 8182 } 8183 8184 if (ensureVerifyAppsEnabled) { 8185 return true; 8186 } 8187 8188 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8189 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8190 } 8191 8192 /** 8193 * Get the "allow unknown sources" setting. 8194 * 8195 * @return the current "allow unknown sources" setting 8196 */ 8197 private int getUnknownSourcesSettings() { 8198 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8199 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 8200 -1); 8201 } 8202 8203 @Override 8204 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 8205 final int uid = Binder.getCallingUid(); 8206 // writer 8207 synchronized (mPackages) { 8208 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 8209 if (targetPackageSetting == null) { 8210 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 8211 } 8212 8213 PackageSetting installerPackageSetting; 8214 if (installerPackageName != null) { 8215 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 8216 if (installerPackageSetting == null) { 8217 throw new IllegalArgumentException("Unknown installer package: " 8218 + installerPackageName); 8219 } 8220 } else { 8221 installerPackageSetting = null; 8222 } 8223 8224 Signature[] callerSignature; 8225 Object obj = mSettings.getUserIdLPr(uid); 8226 if (obj != null) { 8227 if (obj instanceof SharedUserSetting) { 8228 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 8229 } else if (obj instanceof PackageSetting) { 8230 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 8231 } else { 8232 throw new SecurityException("Bad object " + obj + " for uid " + uid); 8233 } 8234 } else { 8235 throw new SecurityException("Unknown calling uid " + uid); 8236 } 8237 8238 // Verify: can't set installerPackageName to a package that is 8239 // not signed with the same cert as the caller. 8240 if (installerPackageSetting != null) { 8241 if (compareSignatures(callerSignature, 8242 installerPackageSetting.signatures.mSignatures) 8243 != PackageManager.SIGNATURE_MATCH) { 8244 throw new SecurityException( 8245 "Caller does not have same cert as new installer package " 8246 + installerPackageName); 8247 } 8248 } 8249 8250 // Verify: if target already has an installer package, it must 8251 // be signed with the same cert as the caller. 8252 if (targetPackageSetting.installerPackageName != null) { 8253 PackageSetting setting = mSettings.mPackages.get( 8254 targetPackageSetting.installerPackageName); 8255 // If the currently set package isn't valid, then it's always 8256 // okay to change it. 8257 if (setting != null) { 8258 if (compareSignatures(callerSignature, 8259 setting.signatures.mSignatures) 8260 != PackageManager.SIGNATURE_MATCH) { 8261 throw new SecurityException( 8262 "Caller does not have same cert as old installer package " 8263 + targetPackageSetting.installerPackageName); 8264 } 8265 } 8266 } 8267 8268 // Okay! 8269 targetPackageSetting.installerPackageName = installerPackageName; 8270 scheduleWriteSettingsLocked(); 8271 } 8272 } 8273 8274 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 8275 // Queue up an async operation since the package installation may take a little while. 8276 mHandler.post(new Runnable() { 8277 public void run() { 8278 mHandler.removeCallbacks(this); 8279 // Result object to be returned 8280 PackageInstalledInfo res = new PackageInstalledInfo(); 8281 res.returnCode = currentStatus; 8282 res.uid = -1; 8283 res.pkg = null; 8284 res.removedInfo = new PackageRemovedInfo(); 8285 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 8286 args.doPreInstall(res.returnCode); 8287 synchronized (mInstallLock) { 8288 installPackageLI(args, true, res); 8289 } 8290 args.doPostInstall(res.returnCode, res.uid); 8291 } 8292 8293 // A restore should be performed at this point if (a) the install 8294 // succeeded, (b) the operation is not an update, and (c) the new 8295 // package has not opted out of backup participation. 8296 final boolean update = res.removedInfo.removedPackage != null; 8297 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 8298 boolean doRestore = !update 8299 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 8300 8301 // Set up the post-install work request bookkeeping. This will be used 8302 // and cleaned up by the post-install event handling regardless of whether 8303 // there's a restore pass performed. Token values are >= 1. 8304 int token; 8305 if (mNextInstallToken < 0) mNextInstallToken = 1; 8306 token = mNextInstallToken++; 8307 8308 PostInstallData data = new PostInstallData(args, res); 8309 mRunningInstalls.put(token, data); 8310 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 8311 8312 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 8313 // Pass responsibility to the Backup Manager. It will perform a 8314 // restore if appropriate, then pass responsibility back to the 8315 // Package Manager to run the post-install observer callbacks 8316 // and broadcasts. 8317 IBackupManager bm = IBackupManager.Stub.asInterface( 8318 ServiceManager.getService(Context.BACKUP_SERVICE)); 8319 if (bm != null) { 8320 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 8321 + " to BM for possible restore"); 8322 try { 8323 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 8324 } catch (RemoteException e) { 8325 // can't happen; the backup manager is local 8326 } catch (Exception e) { 8327 Slog.e(TAG, "Exception trying to enqueue restore", e); 8328 doRestore = false; 8329 } 8330 } else { 8331 Slog.e(TAG, "Backup Manager not found!"); 8332 doRestore = false; 8333 } 8334 } 8335 8336 if (!doRestore) { 8337 // No restore possible, or the Backup Manager was mysteriously not 8338 // available -- just fire the post-install work request directly. 8339 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 8340 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8341 mHandler.sendMessage(msg); 8342 } 8343 } 8344 }); 8345 } 8346 8347 private abstract class HandlerParams { 8348 private static final int MAX_RETRIES = 4; 8349 8350 /** 8351 * Number of times startCopy() has been attempted and had a non-fatal 8352 * error. 8353 */ 8354 private int mRetries = 0; 8355 8356 /** User handle for the user requesting the information or installation. */ 8357 private final UserHandle mUser; 8358 8359 HandlerParams(UserHandle user) { 8360 mUser = user; 8361 } 8362 8363 UserHandle getUser() { 8364 return mUser; 8365 } 8366 8367 final boolean startCopy() { 8368 boolean res; 8369 try { 8370 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 8371 8372 if (++mRetries > MAX_RETRIES) { 8373 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 8374 mHandler.sendEmptyMessage(MCS_GIVE_UP); 8375 handleServiceError(); 8376 return false; 8377 } else { 8378 handleStartCopy(); 8379 res = true; 8380 } 8381 } catch (RemoteException e) { 8382 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 8383 mHandler.sendEmptyMessage(MCS_RECONNECT); 8384 res = false; 8385 } 8386 handleReturnCode(); 8387 return res; 8388 } 8389 8390 final void serviceError() { 8391 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 8392 handleServiceError(); 8393 handleReturnCode(); 8394 } 8395 8396 abstract void handleStartCopy() throws RemoteException; 8397 abstract void handleServiceError(); 8398 abstract void handleReturnCode(); 8399 } 8400 8401 class MeasureParams extends HandlerParams { 8402 private final PackageStats mStats; 8403 private boolean mSuccess; 8404 8405 private final IPackageStatsObserver mObserver; 8406 8407 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 8408 super(new UserHandle(stats.userHandle)); 8409 mObserver = observer; 8410 mStats = stats; 8411 } 8412 8413 @Override 8414 public String toString() { 8415 return "MeasureParams{" 8416 + Integer.toHexString(System.identityHashCode(this)) 8417 + " " + mStats.packageName + "}"; 8418 } 8419 8420 @Override 8421 void handleStartCopy() throws RemoteException { 8422 synchronized (mInstallLock) { 8423 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 8424 } 8425 8426 if (mSuccess) { 8427 final boolean mounted; 8428 if (Environment.isExternalStorageEmulated()) { 8429 mounted = true; 8430 } else { 8431 final String status = Environment.getExternalStorageState(); 8432 mounted = (Environment.MEDIA_MOUNTED.equals(status) 8433 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 8434 } 8435 8436 if (mounted) { 8437 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 8438 8439 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 8440 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 8441 8442 mStats.externalDataSize = calculateDirectorySize(mContainerService, 8443 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 8444 8445 // Always subtract cache size, since it's a subdirectory 8446 mStats.externalDataSize -= mStats.externalCacheSize; 8447 8448 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 8449 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 8450 8451 mStats.externalObbSize = calculateDirectorySize(mContainerService, 8452 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 8453 } 8454 } 8455 } 8456 8457 @Override 8458 void handleReturnCode() { 8459 if (mObserver != null) { 8460 try { 8461 mObserver.onGetStatsCompleted(mStats, mSuccess); 8462 } catch (RemoteException e) { 8463 Slog.i(TAG, "Observer no longer exists."); 8464 } 8465 } 8466 } 8467 8468 @Override 8469 void handleServiceError() { 8470 Slog.e(TAG, "Could not measure application " + mStats.packageName 8471 + " external storage"); 8472 } 8473 } 8474 8475 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 8476 throws RemoteException { 8477 long result = 0; 8478 for (File path : paths) { 8479 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 8480 } 8481 return result; 8482 } 8483 8484 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 8485 for (File path : paths) { 8486 try { 8487 mcs.clearDirectory(path.getAbsolutePath()); 8488 } catch (RemoteException e) { 8489 } 8490 } 8491 } 8492 8493 class InstallParams extends HandlerParams { 8494 /** 8495 * Location where install is coming from, before it has been 8496 * copied/renamed into place. This could be a single monolithic APK 8497 * file, or a cluster directory. This location may be untrusted. 8498 */ 8499 final File originFile; 8500 final String originCid; 8501 8502 /** 8503 * Flag indicating that {@link #originFile} or {@link #originCid} has 8504 * already been staged, meaning downstream users don't need to 8505 * defensively copy the contents. 8506 */ 8507 boolean originStaged; 8508 8509 final IPackageInstallObserver2 observer; 8510 int flags; 8511 final String installerPackageName; 8512 final VerificationParams verificationParams; 8513 private InstallArgs mArgs; 8514 private int mRet; 8515 final String packageAbiOverride; 8516 boolean multiArch; 8517 8518 InstallParams(File originFile, String originCid, boolean originStaged, 8519 IPackageInstallObserver2 observer, int flags, String installerPackageName, 8520 VerificationParams verificationParams, UserHandle user, String packageAbiOverride) { 8521 super(user); 8522 this.originFile = originFile; 8523 this.originCid = originCid; 8524 this.originStaged = originStaged; 8525 this.observer = observer; 8526 this.flags = flags; 8527 this.installerPackageName = installerPackageName; 8528 this.verificationParams = verificationParams; 8529 this.packageAbiOverride = packageAbiOverride; 8530 } 8531 8532 @Override 8533 public String toString() { 8534 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 8535 + " file=" + originFile + " cid=" + originCid + "}"; 8536 } 8537 8538 public ManifestDigest getManifestDigest() { 8539 if (verificationParams == null) { 8540 return null; 8541 } 8542 return verificationParams.getManifestDigest(); 8543 } 8544 8545 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) { 8546 String packageName = pkgLite.packageName; 8547 int installLocation = pkgLite.installLocation; 8548 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8549 // reader 8550 synchronized (mPackages) { 8551 PackageParser.Package pkg = mPackages.get(packageName); 8552 if (pkg != null) { 8553 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 8554 // Check for downgrading. 8555 if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 8556 if (pkgLite.versionCode < pkg.mVersionCode) { 8557 Slog.w(TAG, "Can't install update of " + packageName 8558 + " update version " + pkgLite.versionCode 8559 + " is older than installed version " 8560 + pkg.mVersionCode); 8561 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 8562 } 8563 } 8564 // Check for updated system application. 8565 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8566 if (onSd) { 8567 Slog.w(TAG, "Cannot install update to system app on sdcard"); 8568 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 8569 } 8570 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8571 } else { 8572 if (onSd) { 8573 // Install flag overrides everything. 8574 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8575 } 8576 // If current upgrade specifies particular preference 8577 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 8578 // Application explicitly specified internal. 8579 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8580 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 8581 // App explictly prefers external. Let policy decide 8582 } else { 8583 // Prefer previous location 8584 if (isExternal(pkg)) { 8585 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8586 } 8587 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8588 } 8589 } 8590 } else { 8591 // Invalid install. Return error code 8592 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 8593 } 8594 } 8595 } 8596 // All the special cases have been taken care of. 8597 // Return result based on recommended install location. 8598 if (onSd) { 8599 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8600 } 8601 return pkgLite.recommendedInstallLocation; 8602 } 8603 8604 /* 8605 * Invoke remote method to get package information and install 8606 * location values. Override install location based on default 8607 * policy if needed and then create install arguments based 8608 * on the install location. 8609 */ 8610 public void handleStartCopy() throws RemoteException { 8611 int ret = PackageManager.INSTALL_SUCCEEDED; 8612 8613 // If we're already staged, we've firmly committed to an install location 8614 if (originStaged) { 8615 if (originFile != null) { 8616 flags |= PackageManager.INSTALL_INTERNAL; 8617 flags &= ~PackageManager.INSTALL_EXTERNAL; 8618 } else if (originCid != null) { 8619 flags |= PackageManager.INSTALL_EXTERNAL; 8620 flags &= ~PackageManager.INSTALL_INTERNAL; 8621 } else { 8622 throw new IllegalStateException("Invalid stage location"); 8623 } 8624 } 8625 8626 final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8627 final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0; 8628 PackageInfoLite pkgLite = null; 8629 8630 if (onInt && onSd) { 8631 // Check if both bits are set. 8632 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 8633 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8634 } else { 8635 // Remote call to find out default install location 8636 final String originPath = originFile.getAbsolutePath(); 8637 pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags, 8638 packageAbiOverride); 8639 // Keep track of whether this package is a multiArch package until 8640 // we perform a full scan of it. We need to do this because we might 8641 // end up extracting the package shared libraries before we perform 8642 // a full scan. 8643 multiArch = pkgLite.multiArch; 8644 8645 /* 8646 * If we have too little free space, try to free cache 8647 * before giving up. 8648 */ 8649 if (!originStaged && pkgLite.recommendedInstallLocation 8650 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8651 // TODO: focus freeing disk space on the target device 8652 final StorageManager storage = StorageManager.from(mContext); 8653 final long lowThreshold = storage.getStorageLowBytes( 8654 Environment.getDataDirectory()); 8655 8656 final long sizeBytes = mContainerService.calculateInstalledSize( 8657 originPath, isForwardLocked(), packageAbiOverride); 8658 8659 if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) { 8660 pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags, 8661 packageAbiOverride); 8662 } 8663 8664 /* 8665 * The cache free must have deleted the file we 8666 * downloaded to install. 8667 * 8668 * TODO: fix the "freeCache" call to not delete 8669 * the file we care about. 8670 */ 8671 if (pkgLite.recommendedInstallLocation 8672 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8673 pkgLite.recommendedInstallLocation 8674 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 8675 } 8676 } 8677 } 8678 8679 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8680 int loc = pkgLite.recommendedInstallLocation; 8681 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 8682 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8683 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 8684 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 8685 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8686 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8687 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 8688 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 8689 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8690 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 8691 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 8692 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 8693 } else { 8694 // Override with defaults if needed. 8695 loc = installLocationPolicy(pkgLite, flags); 8696 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 8697 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 8698 } else if (!onSd && !onInt) { 8699 // Override install location with flags 8700 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 8701 // Set the flag to install on external media. 8702 flags |= PackageManager.INSTALL_EXTERNAL; 8703 flags &= ~PackageManager.INSTALL_INTERNAL; 8704 } else { 8705 // Make sure the flag for installing on external 8706 // media is unset 8707 flags |= PackageManager.INSTALL_INTERNAL; 8708 flags &= ~PackageManager.INSTALL_EXTERNAL; 8709 } 8710 } 8711 } 8712 } 8713 8714 final InstallArgs args = createInstallArgs(this); 8715 mArgs = args; 8716 8717 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8718 /* 8719 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 8720 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 8721 */ 8722 int userIdentifier = getUser().getIdentifier(); 8723 if (userIdentifier == UserHandle.USER_ALL 8724 && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) { 8725 userIdentifier = UserHandle.USER_OWNER; 8726 } 8727 8728 /* 8729 * Determine if we have any installed package verifiers. If we 8730 * do, then we'll defer to them to verify the packages. 8731 */ 8732 final int requiredUid = mRequiredVerifierPackage == null ? -1 8733 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 8734 if (requiredUid != -1 && isVerificationEnabled(userIdentifier, flags)) { 8735 // TODO: send verifier the install session instead of uri 8736 final Intent verification = new Intent( 8737 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 8738 verification.setDataAndType(Uri.fromFile(originFile), PACKAGE_MIME_TYPE); 8739 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8740 8741 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 8742 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 8743 0 /* TODO: Which userId? */); 8744 8745 if (DEBUG_VERIFY) { 8746 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 8747 + verification.toString() + " with " + pkgLite.verifiers.length 8748 + " optional verifiers"); 8749 } 8750 8751 final int verificationId = mPendingVerificationToken++; 8752 8753 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8754 8755 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 8756 installerPackageName); 8757 8758 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags); 8759 8760 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 8761 pkgLite.packageName); 8762 8763 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 8764 pkgLite.versionCode); 8765 8766 if (verificationParams != null) { 8767 if (verificationParams.getVerificationURI() != null) { 8768 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 8769 verificationParams.getVerificationURI()); 8770 } 8771 if (verificationParams.getOriginatingURI() != null) { 8772 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 8773 verificationParams.getOriginatingURI()); 8774 } 8775 if (verificationParams.getReferrer() != null) { 8776 verification.putExtra(Intent.EXTRA_REFERRER, 8777 verificationParams.getReferrer()); 8778 } 8779 if (verificationParams.getOriginatingUid() >= 0) { 8780 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 8781 verificationParams.getOriginatingUid()); 8782 } 8783 if (verificationParams.getInstallerUid() >= 0) { 8784 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 8785 verificationParams.getInstallerUid()); 8786 } 8787 } 8788 8789 final PackageVerificationState verificationState = new PackageVerificationState( 8790 requiredUid, args); 8791 8792 mPendingVerification.append(verificationId, verificationState); 8793 8794 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 8795 receivers, verificationState); 8796 8797 /* 8798 * If any sufficient verifiers were listed in the package 8799 * manifest, attempt to ask them. 8800 */ 8801 if (sufficientVerifiers != null) { 8802 final int N = sufficientVerifiers.size(); 8803 if (N == 0) { 8804 Slog.i(TAG, "Additional verifiers required, but none installed."); 8805 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 8806 } else { 8807 for (int i = 0; i < N; i++) { 8808 final ComponentName verifierComponent = sufficientVerifiers.get(i); 8809 8810 final Intent sufficientIntent = new Intent(verification); 8811 sufficientIntent.setComponent(verifierComponent); 8812 8813 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 8814 } 8815 } 8816 } 8817 8818 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 8819 mRequiredVerifierPackage, receivers); 8820 if (ret == PackageManager.INSTALL_SUCCEEDED 8821 && mRequiredVerifierPackage != null) { 8822 /* 8823 * Send the intent to the required verification agent, 8824 * but only start the verification timeout after the 8825 * target BroadcastReceivers have run. 8826 */ 8827 verification.setComponent(requiredVerifierComponent); 8828 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 8829 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8830 new BroadcastReceiver() { 8831 @Override 8832 public void onReceive(Context context, Intent intent) { 8833 final Message msg = mHandler 8834 .obtainMessage(CHECK_PENDING_VERIFICATION); 8835 msg.arg1 = verificationId; 8836 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 8837 } 8838 }, null, 0, null, null); 8839 8840 /* 8841 * We don't want the copy to proceed until verification 8842 * succeeds, so null out this field. 8843 */ 8844 mArgs = null; 8845 } 8846 } else { 8847 /* 8848 * No package verification is enabled, so immediately start 8849 * the remote call to initiate copy using temporary file. 8850 */ 8851 ret = args.copyApk(mContainerService, true); 8852 } 8853 } 8854 8855 mRet = ret; 8856 } 8857 8858 @Override 8859 void handleReturnCode() { 8860 // If mArgs is null, then MCS couldn't be reached. When it 8861 // reconnects, it will try again to install. At that point, this 8862 // will succeed. 8863 if (mArgs != null) { 8864 processPendingInstall(mArgs, mRet); 8865 } 8866 } 8867 8868 @Override 8869 void handleServiceError() { 8870 mArgs = createInstallArgs(this); 8871 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8872 } 8873 8874 public boolean isForwardLocked() { 8875 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8876 } 8877 } 8878 8879 /* 8880 * Utility class used in movePackage api. 8881 * srcArgs and targetArgs are not set for invalid flags and make 8882 * sure to do null checks when invoking methods on them. 8883 * We probably want to return ErrorPrams for both failed installs 8884 * and moves. 8885 */ 8886 class MoveParams extends HandlerParams { 8887 final IPackageMoveObserver observer; 8888 final int flags; 8889 final String packageName; 8890 final InstallArgs srcArgs; 8891 final InstallArgs targetArgs; 8892 int uid; 8893 int mRet; 8894 8895 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags, 8896 String packageName, String[] instructionSets, int uid, UserHandle user, 8897 boolean isMultiArch) { 8898 super(user); 8899 this.srcArgs = srcArgs; 8900 this.observer = observer; 8901 this.flags = flags; 8902 this.packageName = packageName; 8903 this.uid = uid; 8904 if (srcArgs != null) { 8905 final String codePath = srcArgs.getCodePath(); 8906 targetArgs = createInstallArgsForMoveTarget(codePath, flags, packageName, 8907 instructionSets, isMultiArch); 8908 } else { 8909 targetArgs = null; 8910 } 8911 } 8912 8913 @Override 8914 public String toString() { 8915 return "MoveParams{" 8916 + Integer.toHexString(System.identityHashCode(this)) 8917 + " " + packageName + "}"; 8918 } 8919 8920 public void handleStartCopy() throws RemoteException { 8921 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8922 // Check for storage space on target medium 8923 if (!targetArgs.checkFreeStorage(mContainerService)) { 8924 Log.w(TAG, "Insufficient storage to install"); 8925 return; 8926 } 8927 8928 mRet = srcArgs.doPreCopy(); 8929 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8930 return; 8931 } 8932 8933 mRet = targetArgs.copyApk(mContainerService, false); 8934 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8935 srcArgs.doPostCopy(uid); 8936 return; 8937 } 8938 8939 mRet = srcArgs.doPostCopy(uid); 8940 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8941 return; 8942 } 8943 8944 mRet = targetArgs.doPreInstall(mRet); 8945 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8946 return; 8947 } 8948 8949 if (DEBUG_SD_INSTALL) { 8950 StringBuilder builder = new StringBuilder(); 8951 if (srcArgs != null) { 8952 builder.append("src: "); 8953 builder.append(srcArgs.getCodePath()); 8954 } 8955 if (targetArgs != null) { 8956 builder.append(" target : "); 8957 builder.append(targetArgs.getCodePath()); 8958 } 8959 Log.i(TAG, builder.toString()); 8960 } 8961 } 8962 8963 @Override 8964 void handleReturnCode() { 8965 targetArgs.doPostInstall(mRet, uid); 8966 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 8967 if (mRet == PackageManager.INSTALL_SUCCEEDED) { 8968 currentStatus = PackageManager.MOVE_SUCCEEDED; 8969 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){ 8970 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 8971 } 8972 processPendingMove(this, currentStatus); 8973 } 8974 8975 @Override 8976 void handleServiceError() { 8977 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8978 } 8979 } 8980 8981 /** 8982 * Used during creation of InstallArgs 8983 * 8984 * @param flags package installation flags 8985 * @return true if should be installed on external storage 8986 */ 8987 private static boolean installOnSd(int flags) { 8988 if ((flags & PackageManager.INSTALL_INTERNAL) != 0) { 8989 return false; 8990 } 8991 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) { 8992 return true; 8993 } 8994 return false; 8995 } 8996 8997 /** 8998 * Used during creation of InstallArgs 8999 * 9000 * @param flags package installation flags 9001 * @return true if should be installed as forward locked 9002 */ 9003 private static boolean installForwardLocked(int flags) { 9004 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9005 } 9006 9007 private InstallArgs createInstallArgs(InstallParams params) { 9008 // TODO: extend to support incoming zero-copy locations 9009 9010 if (installOnSd(params.flags) || params.isForwardLocked()) { 9011 return new AsecInstallArgs(params); 9012 } else { 9013 return new FileInstallArgs(params); 9014 } 9015 } 9016 9017 /** 9018 * Create args that describe an existing installed package. Typically used 9019 * when cleaning up old installs, or used as a move source. 9020 */ 9021 private InstallArgs createInstallArgsForExisting(int flags, String codePath, 9022 String resourcePath, String nativeLibraryRoot, String[] instructionSets, 9023 boolean isMultiArch) { 9024 final boolean isInAsec; 9025 if (installOnSd(flags)) { 9026 /* Apps on SD card are always in ASEC containers. */ 9027 isInAsec = true; 9028 } else if (installForwardLocked(flags) 9029 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 9030 /* 9031 * Forward-locked apps are only in ASEC containers if they're the 9032 * new style 9033 */ 9034 isInAsec = true; 9035 } else { 9036 isInAsec = false; 9037 } 9038 9039 if (isInAsec) { 9040 return new AsecInstallArgs(codePath, instructionSets, 9041 installOnSd(flags), installForwardLocked(flags), isMultiArch); 9042 } else { 9043 return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot, 9044 instructionSets, isMultiArch); 9045 } 9046 } 9047 9048 private InstallArgs createInstallArgsForMoveTarget(String codePath, int flags, String pkgName, 9049 String[] instructionSets, boolean isMultiArch) { 9050 final File codeFile = new File(codePath); 9051 if (installOnSd(flags) || installForwardLocked(flags)) { 9052 String cid = getNextCodePath(codePath, pkgName, "/" 9053 + AsecInstallArgs.RES_FILE_NAME); 9054 return new AsecInstallArgs(codeFile, cid, instructionSets, installOnSd(flags), 9055 installForwardLocked(flags), isMultiArch); 9056 } else { 9057 return new FileInstallArgs(codeFile, instructionSets, isMultiArch); 9058 } 9059 } 9060 9061 static abstract class InstallArgs { 9062 /** @see InstallParams#originFile */ 9063 final File originFile; 9064 /** @see InstallParams#originStaged */ 9065 final boolean originStaged; 9066 9067 // TODO: define inherit location 9068 9069 final IPackageInstallObserver2 observer; 9070 // Always refers to PackageManager flags only 9071 final int flags; 9072 final String installerPackageName; 9073 final ManifestDigest manifestDigest; 9074 final UserHandle user; 9075 final String abiOverride; 9076 final boolean multiArch; 9077 9078 // The list of instruction sets supported by this app. This is currently 9079 // only used during the rmdex() phase to clean up resources. We can get rid of this 9080 // if we move dex files under the common app path. 9081 /* nullable */ String[] instructionSets; 9082 9083 InstallArgs(File originFile, boolean originStaged, IPackageInstallObserver2 observer, 9084 int flags, String installerPackageName, ManifestDigest manifestDigest, 9085 UserHandle user, String[] instructionSets, 9086 String abiOverride, boolean multiArch) { 9087 this.originFile = originFile; 9088 this.originStaged = originStaged; 9089 this.flags = flags; 9090 this.observer = observer; 9091 this.installerPackageName = installerPackageName; 9092 this.manifestDigest = manifestDigest; 9093 this.user = user; 9094 this.instructionSets = instructionSets; 9095 this.abiOverride = abiOverride; 9096 this.multiArch = multiArch; 9097 } 9098 9099 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 9100 abstract int doPreInstall(int status); 9101 9102 /** 9103 * Rename package into final resting place. All paths on the given 9104 * scanned package should be updated to reflect the rename. 9105 */ 9106 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 9107 abstract int doPostInstall(int status, int uid); 9108 9109 /** @see PackageSettingBase#codePathString */ 9110 abstract String getCodePath(); 9111 /** @see PackageSettingBase#resourcePathString */ 9112 abstract String getResourcePath(); 9113 abstract String getLegacyNativeLibraryPath(); 9114 9115 // Need installer lock especially for dex file removal. 9116 abstract void cleanUpResourcesLI(); 9117 abstract boolean doPostDeleteLI(boolean delete); 9118 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9119 9120 /** 9121 * Called before the source arguments are copied. This is used mostly 9122 * for MoveParams when it needs to read the source file to put it in the 9123 * destination. 9124 */ 9125 int doPreCopy() { 9126 return PackageManager.INSTALL_SUCCEEDED; 9127 } 9128 9129 /** 9130 * Called after the source arguments are copied. This is used mostly for 9131 * MoveParams when it needs to read the source file to put it in the 9132 * destination. 9133 * 9134 * @return 9135 */ 9136 int doPostCopy(int uid) { 9137 return PackageManager.INSTALL_SUCCEEDED; 9138 } 9139 9140 protected boolean isFwdLocked() { 9141 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9142 } 9143 9144 UserHandle getUser() { 9145 return user; 9146 } 9147 } 9148 9149 /** 9150 * Logic to handle installation of non-ASEC applications, including copying 9151 * and renaming logic. 9152 */ 9153 class FileInstallArgs extends InstallArgs { 9154 private File codeFile; 9155 private File resourceFile; 9156 private File legacyNativeLibraryPath; 9157 9158 // Example topology: 9159 // /data/app/com.example/base.apk 9160 // /data/app/com.example/split_foo.apk 9161 // /data/app/com.example/lib/arm/libfoo.so 9162 // /data/app/com.example/lib/arm64/libfoo.so 9163 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 9164 9165 /** New install */ 9166 FileInstallArgs(InstallParams params) { 9167 super(params.originFile, params.originStaged, params.observer, params.flags, 9168 params.installerPackageName, params.getManifestDigest(), params.getUser(), 9169 null /* instruction sets */, params.packageAbiOverride, 9170 params.multiArch); 9171 if (isFwdLocked()) { 9172 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 9173 } 9174 } 9175 9176 /** Existing install */ 9177 FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath, 9178 String[] instructionSets, boolean isMultiArch) { 9179 super(null, false, null, 0, null, null, null, instructionSets, null, isMultiArch); 9180 this.codeFile = (codePath != null) ? new File(codePath) : null; 9181 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 9182 this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ? 9183 new File(legacyNativeLibraryPath) : null; 9184 } 9185 9186 /** New install from existing */ 9187 FileInstallArgs(File originFile, String[] instructionSets, boolean isMultiArch) { 9188 super(originFile, false, null, 0, null, null, null, instructionSets, null, 9189 isMultiArch); 9190 } 9191 9192 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9193 final long sizeBytes = imcs.calculateInstalledSize(originFile.getAbsolutePath(), 9194 isFwdLocked(), abiOverride); 9195 9196 final StorageManager storage = StorageManager.from(mContext); 9197 return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory())); 9198 } 9199 9200 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9201 int ret = PackageManager.INSTALL_SUCCEEDED; 9202 9203 if (originStaged) { 9204 Slog.d(TAG, originFile + " already staged; skipping copy"); 9205 codeFile = originFile; 9206 resourceFile = originFile; 9207 } else { 9208 try { 9209 final File tempDir = mInstallerService.allocateInternalStageDirLegacy(); 9210 codeFile = tempDir; 9211 resourceFile = tempDir; 9212 } catch (IOException e) { 9213 Slog.w(TAG, "Failed to create copy file: " + e); 9214 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9215 } 9216 9217 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 9218 @Override 9219 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 9220 if (!FileUtils.isValidExtFilename(name)) { 9221 throw new IllegalArgumentException("Invalid filename: " + name); 9222 } 9223 try { 9224 final File file = new File(codeFile, name); 9225 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 9226 O_RDWR | O_CREAT, 0644); 9227 Os.chmod(file.getAbsolutePath(), 0644); 9228 return new ParcelFileDescriptor(fd); 9229 } catch (ErrnoException e) { 9230 throw new RemoteException("Failed to open: " + e.getMessage()); 9231 } 9232 } 9233 }; 9234 9235 ret = imcs.copyPackage(originFile.getAbsolutePath(), target); 9236 if (ret != PackageManager.INSTALL_SUCCEEDED) { 9237 Slog.e(TAG, "Failed to copy package"); 9238 return ret; 9239 } 9240 } 9241 9242 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 9243 NativeLibraryHelper.Handle handle = null; 9244 try { 9245 handle = NativeLibraryHelper.Handle.create(codeFile); 9246 ret = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle, libraryRoot, 9247 abiOverride, multiArch); 9248 } catch (IOException e) { 9249 Slog.e(TAG, "Copying native libraries failed", e); 9250 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9251 } finally { 9252 IoUtils.closeQuietly(handle); 9253 } 9254 9255 return ret; 9256 } 9257 9258 int doPreInstall(int status) { 9259 if (status != PackageManager.INSTALL_SUCCEEDED) { 9260 cleanUp(); 9261 } 9262 return status; 9263 } 9264 9265 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9266 if (status != PackageManager.INSTALL_SUCCEEDED) { 9267 cleanUp(); 9268 return false; 9269 } else { 9270 final File beforeCodeFile = codeFile; 9271 final File afterCodeFile = getNextCodePath(pkg.packageName); 9272 9273 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 9274 try { 9275 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 9276 } catch (ErrnoException e) { 9277 Slog.d(TAG, "Failed to rename", e); 9278 return false; 9279 } 9280 9281 if (!SELinux.restoreconRecursive(afterCodeFile)) { 9282 Slog.d(TAG, "Failed to restorecon"); 9283 return false; 9284 } 9285 9286 // Reflect the rename internally 9287 codeFile = afterCodeFile; 9288 resourceFile = afterCodeFile; 9289 9290 // Reflect the rename in scanned details 9291 pkg.codePath = afterCodeFile.getAbsolutePath(); 9292 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9293 pkg.baseCodePath); 9294 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9295 pkg.splitCodePaths); 9296 9297 // Reflect the rename in app info 9298 pkg.applicationInfo.setCodePath(pkg.codePath); 9299 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9300 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9301 pkg.applicationInfo.setResourcePath(pkg.codePath); 9302 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9303 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9304 9305 return true; 9306 } 9307 } 9308 9309 int doPostInstall(int status, int uid) { 9310 if (status != PackageManager.INSTALL_SUCCEEDED) { 9311 cleanUp(); 9312 } 9313 return status; 9314 } 9315 9316 @Override 9317 String getCodePath() { 9318 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 9319 } 9320 9321 @Override 9322 String getResourcePath() { 9323 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 9324 } 9325 9326 @Override 9327 String getLegacyNativeLibraryPath() { 9328 return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null; 9329 } 9330 9331 private boolean cleanUp() { 9332 if (codeFile == null || !codeFile.exists()) { 9333 return false; 9334 } 9335 9336 if (codeFile.isDirectory()) { 9337 FileUtils.deleteContents(codeFile); 9338 } 9339 codeFile.delete(); 9340 9341 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 9342 resourceFile.delete(); 9343 } 9344 9345 if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) { 9346 if (!FileUtils.deleteContents(legacyNativeLibraryPath)) { 9347 Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath); 9348 } 9349 legacyNativeLibraryPath.delete(); 9350 } 9351 9352 return true; 9353 } 9354 9355 void cleanUpResourcesLI() { 9356 // Try enumerating all code paths before deleting 9357 List<String> allCodePaths = Collections.EMPTY_LIST; 9358 if (codeFile != null && codeFile.exists()) { 9359 try { 9360 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9361 allCodePaths = pkg.getAllCodePaths(); 9362 } catch (PackageParserException e) { 9363 // Ignored; we tried our best 9364 } 9365 } 9366 9367 cleanUp(); 9368 9369 if (!allCodePaths.isEmpty()) { 9370 if (instructionSets == null) { 9371 throw new IllegalStateException("instructionSet == null"); 9372 } 9373 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9374 for (String codePath : allCodePaths) { 9375 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9376 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9377 if (retCode < 0) { 9378 Slog.w(TAG, "Couldn't remove dex file for package: " 9379 + " at location " + codePath + ", retcode=" + retCode); 9380 // we don't consider this to be a failure of the core package deletion 9381 } 9382 } 9383 } 9384 } 9385 } 9386 9387 boolean doPostDeleteLI(boolean delete) { 9388 // XXX err, shouldn't we respect the delete flag? 9389 cleanUpResourcesLI(); 9390 return true; 9391 } 9392 } 9393 9394 private boolean isAsecExternal(String cid) { 9395 final String asecPath = PackageHelper.getSdFilesystem(cid); 9396 return !asecPath.startsWith(mAsecInternalPath); 9397 } 9398 9399 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 9400 PackageManagerException { 9401 if (copyRet < 0) { 9402 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 9403 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 9404 throw new PackageManagerException(copyRet, message); 9405 } 9406 } 9407 } 9408 9409 /** 9410 * Extract the MountService "container ID" from the full code path of an 9411 * .apk. 9412 */ 9413 static String cidFromCodePath(String fullCodePath) { 9414 int eidx = fullCodePath.lastIndexOf("/"); 9415 String subStr1 = fullCodePath.substring(0, eidx); 9416 int sidx = subStr1.lastIndexOf("/"); 9417 return subStr1.substring(sidx+1, eidx); 9418 } 9419 9420 /** 9421 * Logic to handle installation of ASEC applications, including copying and 9422 * renaming logic. 9423 */ 9424 class AsecInstallArgs extends InstallArgs { 9425 static final String RES_FILE_NAME = "pkg.apk"; 9426 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 9427 9428 String cid; 9429 String packagePath; 9430 String resourcePath; 9431 String legacyNativeLibraryDir; 9432 9433 /** New install */ 9434 AsecInstallArgs(InstallParams params) { 9435 super(params.originFile, params.originStaged, params.observer, params.flags, 9436 params.installerPackageName, params.getManifestDigest(), 9437 params.getUser(), null /* instruction sets */, 9438 params.packageAbiOverride, params.multiArch); 9439 } 9440 9441 /** Existing install */ 9442 AsecInstallArgs(String fullCodePath, String[] instructionSets, 9443 boolean isExternal, boolean isForwardLocked, boolean isMultiArch) { 9444 super(null, false, null, (isExternal ? INSTALL_EXTERNAL : 0) 9445 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9446 instructionSets, null, isMultiArch); 9447 // Hackily pretend we're still looking at a full code path 9448 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 9449 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 9450 } 9451 9452 // Extract cid from fullCodePath 9453 int eidx = fullCodePath.lastIndexOf("/"); 9454 String subStr1 = fullCodePath.substring(0, eidx); 9455 int sidx = subStr1.lastIndexOf("/"); 9456 cid = subStr1.substring(sidx+1, eidx); 9457 setMountPath(subStr1); 9458 } 9459 9460 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked, 9461 boolean isMultiArch) { 9462 super(null, false, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 9463 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9464 instructionSets, null, isMultiArch); 9465 this.cid = cid; 9466 setMountPath(PackageHelper.getSdDir(cid)); 9467 } 9468 9469 /** New install from existing */ 9470 AsecInstallArgs(File originPackageFile, String cid, String[] instructionSets, 9471 boolean isExternal, boolean isForwardLocked, boolean isMultiArch) { 9472 super(originPackageFile, false, null, (isExternal ? INSTALL_EXTERNAL : 0) 9473 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9474 instructionSets, null, isMultiArch); 9475 this.cid = cid; 9476 } 9477 9478 void createCopyFile() { 9479 cid = mInstallerService.allocateExternalStageCidLegacy(); 9480 } 9481 9482 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9483 final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(), 9484 abiOverride); 9485 9486 final File target; 9487 if (isExternal()) { 9488 target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory(); 9489 } else { 9490 target = Environment.getDataDirectory(); 9491 } 9492 9493 final StorageManager storage = StorageManager.from(mContext); 9494 return (sizeBytes <= storage.getStorageBytesUntilLow(target)); 9495 } 9496 9497 private final boolean isExternal() { 9498 return (flags & PackageManager.INSTALL_EXTERNAL) != 0; 9499 } 9500 9501 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9502 // TODO: if already staged, we only need to extract native code 9503 if (temp) { 9504 createCopyFile(); 9505 } else { 9506 /* 9507 * Pre-emptively destroy the container since it's destroyed if 9508 * copying fails due to it existing anyway. 9509 */ 9510 PackageHelper.destroySdDir(cid); 9511 } 9512 9513 final String newMountPath = imcs.copyPackageToContainer( 9514 originFile.getAbsolutePath(), cid, getEncryptKey(), isExternal(), 9515 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 9516 9517 if (newMountPath != null) { 9518 setMountPath(newMountPath); 9519 return PackageManager.INSTALL_SUCCEEDED; 9520 } else { 9521 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9522 } 9523 } 9524 9525 @Override 9526 String getCodePath() { 9527 return packagePath; 9528 } 9529 9530 @Override 9531 String getResourcePath() { 9532 return resourcePath; 9533 } 9534 9535 @Override 9536 String getLegacyNativeLibraryPath() { 9537 return legacyNativeLibraryDir; 9538 } 9539 9540 int doPreInstall(int status) { 9541 if (status != PackageManager.INSTALL_SUCCEEDED) { 9542 // Destroy container 9543 PackageHelper.destroySdDir(cid); 9544 } else { 9545 boolean mounted = PackageHelper.isContainerMounted(cid); 9546 if (!mounted) { 9547 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 9548 Process.SYSTEM_UID); 9549 if (newMountPath != null) { 9550 setMountPath(newMountPath); 9551 } else { 9552 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9553 } 9554 } 9555 } 9556 return status; 9557 } 9558 9559 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9560 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 9561 String newMountPath = null; 9562 if (PackageHelper.isContainerMounted(cid)) { 9563 // Unmount the container 9564 if (!PackageHelper.unMountSdDir(cid)) { 9565 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9566 return false; 9567 } 9568 } 9569 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9570 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9571 " which might be stale. Will try to clean up."); 9572 // Clean up the stale container and proceed to recreate. 9573 if (!PackageHelper.destroySdDir(newCacheId)) { 9574 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9575 return false; 9576 } 9577 // Successfully cleaned up stale container. Try to rename again. 9578 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9579 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9580 + " inspite of cleaning it up."); 9581 return false; 9582 } 9583 } 9584 if (!PackageHelper.isContainerMounted(newCacheId)) { 9585 Slog.w(TAG, "Mounting container " + newCacheId); 9586 newMountPath = PackageHelper.mountSdDir(newCacheId, 9587 getEncryptKey(), Process.SYSTEM_UID); 9588 } else { 9589 newMountPath = PackageHelper.getSdDir(newCacheId); 9590 } 9591 if (newMountPath == null) { 9592 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9593 return false; 9594 } 9595 Log.i(TAG, "Succesfully renamed " + cid + 9596 " to " + newCacheId + 9597 " at new path: " + newMountPath); 9598 cid = newCacheId; 9599 9600 final File beforeCodeFile = new File(packagePath); 9601 setMountPath(newMountPath); 9602 final File afterCodeFile = new File(packagePath); 9603 9604 // Reflect the rename in scanned details 9605 pkg.codePath = afterCodeFile.getAbsolutePath(); 9606 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9607 pkg.baseCodePath); 9608 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9609 pkg.splitCodePaths); 9610 9611 // Reflect the rename in app info 9612 pkg.applicationInfo.setCodePath(pkg.codePath); 9613 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9614 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9615 pkg.applicationInfo.setResourcePath(pkg.codePath); 9616 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9617 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9618 9619 return true; 9620 } 9621 9622 private void setMountPath(String mountPath) { 9623 final File mountFile = new File(mountPath); 9624 9625 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 9626 if (monolithicFile.exists()) { 9627 packagePath = monolithicFile.getAbsolutePath(); 9628 if (isFwdLocked()) { 9629 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 9630 } else { 9631 resourcePath = packagePath; 9632 } 9633 } else { 9634 packagePath = mountFile.getAbsolutePath(); 9635 resourcePath = packagePath; 9636 } 9637 9638 legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath(); 9639 } 9640 9641 int doPostInstall(int status, int uid) { 9642 if (status != PackageManager.INSTALL_SUCCEEDED) { 9643 cleanUp(); 9644 } else { 9645 final int groupOwner; 9646 final String protectedFile; 9647 if (isFwdLocked()) { 9648 groupOwner = UserHandle.getSharedAppGid(uid); 9649 protectedFile = RES_FILE_NAME; 9650 } else { 9651 groupOwner = -1; 9652 protectedFile = null; 9653 } 9654 9655 if (uid < Process.FIRST_APPLICATION_UID 9656 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9657 Slog.e(TAG, "Failed to finalize " + cid); 9658 PackageHelper.destroySdDir(cid); 9659 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9660 } 9661 9662 boolean mounted = PackageHelper.isContainerMounted(cid); 9663 if (!mounted) { 9664 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9665 } 9666 } 9667 return status; 9668 } 9669 9670 private void cleanUp() { 9671 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9672 9673 // Destroy secure container 9674 PackageHelper.destroySdDir(cid); 9675 } 9676 9677 private List<String> getAllCodePaths() { 9678 final File codeFile = new File(getCodePath()); 9679 if (codeFile != null && codeFile.exists()) { 9680 try { 9681 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9682 return pkg.getAllCodePaths(); 9683 } catch (PackageParserException e) { 9684 // Ignored; we tried our best 9685 } 9686 } 9687 return Collections.EMPTY_LIST; 9688 } 9689 9690 void cleanUpResourcesLI() { 9691 // Enumerate all code paths before deleting 9692 cleanUpResourcesLI(getAllCodePaths()); 9693 } 9694 9695 private void cleanUpResourcesLI(List<String> allCodePaths) { 9696 cleanUp(); 9697 9698 if (!allCodePaths.isEmpty()) { 9699 if (instructionSets == null) { 9700 throw new IllegalStateException("instructionSet == null"); 9701 } 9702 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9703 for (String codePath : allCodePaths) { 9704 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9705 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9706 if (retCode < 0) { 9707 Slog.w(TAG, "Couldn't remove dex file for package: " 9708 + " at location " + codePath + ", retcode=" + retCode); 9709 // we don't consider this to be a failure of the core package deletion 9710 } 9711 } 9712 } 9713 } 9714 } 9715 9716 boolean matchContainer(String app) { 9717 if (cid.startsWith(app)) { 9718 return true; 9719 } 9720 return false; 9721 } 9722 9723 String getPackageName() { 9724 return getAsecPackageName(cid); 9725 } 9726 9727 boolean doPostDeleteLI(boolean delete) { 9728 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 9729 final List<String> allCodePaths = getAllCodePaths(); 9730 boolean mounted = PackageHelper.isContainerMounted(cid); 9731 if (mounted) { 9732 // Unmount first 9733 if (PackageHelper.unMountSdDir(cid)) { 9734 mounted = false; 9735 } 9736 } 9737 if (!mounted && delete) { 9738 cleanUpResourcesLI(allCodePaths); 9739 } 9740 return !mounted; 9741 } 9742 9743 @Override 9744 int doPreCopy() { 9745 if (isFwdLocked()) { 9746 if (!PackageHelper.fixSdPermissions(cid, 9747 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 9748 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9749 } 9750 } 9751 9752 return PackageManager.INSTALL_SUCCEEDED; 9753 } 9754 9755 @Override 9756 int doPostCopy(int uid) { 9757 if (isFwdLocked()) { 9758 if (uid < Process.FIRST_APPLICATION_UID 9759 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 9760 RES_FILE_NAME)) { 9761 Slog.e(TAG, "Failed to finalize " + cid); 9762 PackageHelper.destroySdDir(cid); 9763 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9764 } 9765 } 9766 9767 return PackageManager.INSTALL_SUCCEEDED; 9768 } 9769 } 9770 9771 static String getAsecPackageName(String packageCid) { 9772 int idx = packageCid.lastIndexOf("-"); 9773 if (idx == -1) { 9774 return packageCid; 9775 } 9776 return packageCid.substring(0, idx); 9777 } 9778 9779 // Utility method used to create code paths based on package name and available index. 9780 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 9781 String idxStr = ""; 9782 int idx = 1; 9783 // Fall back to default value of idx=1 if prefix is not 9784 // part of oldCodePath 9785 if (oldCodePath != null) { 9786 String subStr = oldCodePath; 9787 // Drop the suffix right away 9788 if (suffix != null && subStr.endsWith(suffix)) { 9789 subStr = subStr.substring(0, subStr.length() - suffix.length()); 9790 } 9791 // If oldCodePath already contains prefix find out the 9792 // ending index to either increment or decrement. 9793 int sidx = subStr.lastIndexOf(prefix); 9794 if (sidx != -1) { 9795 subStr = subStr.substring(sidx + prefix.length()); 9796 if (subStr != null) { 9797 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 9798 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 9799 } 9800 try { 9801 idx = Integer.parseInt(subStr); 9802 if (idx <= 1) { 9803 idx++; 9804 } else { 9805 idx--; 9806 } 9807 } catch(NumberFormatException e) { 9808 } 9809 } 9810 } 9811 } 9812 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 9813 return prefix + idxStr; 9814 } 9815 9816 private File getNextCodePath(String packageName) { 9817 int suffix = 1; 9818 File result; 9819 do { 9820 result = new File(mAppInstallDir, packageName + "-" + suffix); 9821 suffix++; 9822 } while (result.exists()); 9823 return result; 9824 } 9825 9826 // Utility method used to ignore ADD/REMOVE events 9827 // by directory observer. 9828 private static boolean ignoreCodePath(String fullPathStr) { 9829 String apkName = deriveCodePathName(fullPathStr); 9830 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 9831 if (idx != -1 && ((idx+1) < apkName.length())) { 9832 // Make sure the package ends with a numeral 9833 String version = apkName.substring(idx+1); 9834 try { 9835 Integer.parseInt(version); 9836 return true; 9837 } catch (NumberFormatException e) {} 9838 } 9839 return false; 9840 } 9841 9842 // Utility method that returns the relative package path with respect 9843 // to the installation directory. Like say for /data/data/com.test-1.apk 9844 // string com.test-1 is returned. 9845 static String deriveCodePathName(String codePath) { 9846 if (codePath == null) { 9847 return null; 9848 } 9849 final File codeFile = new File(codePath); 9850 final String name = codeFile.getName(); 9851 if (codeFile.isDirectory()) { 9852 return name; 9853 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 9854 final int lastDot = name.lastIndexOf('.'); 9855 return name.substring(0, lastDot); 9856 } else { 9857 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 9858 return null; 9859 } 9860 } 9861 9862 class PackageInstalledInfo { 9863 String name; 9864 int uid; 9865 // The set of users that originally had this package installed. 9866 int[] origUsers; 9867 // The set of users that now have this package installed. 9868 int[] newUsers; 9869 PackageParser.Package pkg; 9870 int returnCode; 9871 String returnMsg; 9872 PackageRemovedInfo removedInfo; 9873 9874 public void setError(int code, String msg) { 9875 returnCode = code; 9876 returnMsg = msg; 9877 Slog.w(TAG, msg); 9878 } 9879 9880 public void setError(String msg, PackageParserException e) { 9881 returnCode = e.error; 9882 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9883 Slog.w(TAG, msg, e); 9884 } 9885 9886 public void setError(String msg, PackageManagerException e) { 9887 returnCode = e.error; 9888 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9889 Slog.w(TAG, msg, e); 9890 } 9891 9892 // In some error cases we want to convey more info back to the observer 9893 String origPackage; 9894 String origPermission; 9895 } 9896 9897 /* 9898 * Install a non-existing package. 9899 */ 9900 private void installNewPackageLI(PackageParser.Package pkg, 9901 int parseFlags, int scanMode, UserHandle user, 9902 String installerPackageName, PackageInstalledInfo res) { 9903 // Remember this for later, in case we need to rollback this install 9904 String pkgName = pkg.packageName; 9905 9906 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 9907 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 9908 synchronized(mPackages) { 9909 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 9910 // A package with the same name is already installed, though 9911 // it has been renamed to an older name. The package we 9912 // are trying to install should be installed as an update to 9913 // the existing one, but that has not been requested, so bail. 9914 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9915 + " without first uninstalling package running as " 9916 + mSettings.mRenamedPackages.get(pkgName)); 9917 return; 9918 } 9919 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.codePath)) { 9920 // Don't allow installation over an existing package with the same name. 9921 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9922 + " without first uninstalling."); 9923 return; 9924 } 9925 } 9926 9927 try { 9928 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode, 9929 System.currentTimeMillis(), user); 9930 9931 updateSettingsLI(newPackage, installerPackageName, null, null, res); 9932 // delete the partially installed application. the data directory will have to be 9933 // restored if it was already existing 9934 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9935 // remove package from internal structures. Note that we want deletePackageX to 9936 // delete the package data and cache directories that it created in 9937 // scanPackageLocked, unless those directories existed before we even tried to 9938 // install. 9939 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 9940 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 9941 res.removedInfo, true); 9942 } 9943 9944 } catch (PackageManagerException e) { 9945 res.setError("Package couldn't be installed in " + pkg.codePath, e); 9946 } 9947 } 9948 9949 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 9950 // Upgrade keysets are being used. Determine if new package has a superset of the 9951 // required keys. 9952 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 9953 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9954 for (int i = 0; i < upgradeKeySets.length; i++) { 9955 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 9956 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 9957 return true; 9958 } 9959 } 9960 return false; 9961 } 9962 9963 private void replacePackageLI(PackageParser.Package pkg, 9964 int parseFlags, int scanMode, UserHandle user, 9965 String installerPackageName, PackageInstalledInfo res) { 9966 PackageParser.Package oldPackage; 9967 String pkgName = pkg.packageName; 9968 int[] allUsers; 9969 boolean[] perUserInstalled; 9970 9971 // First find the old package info and check signatures 9972 synchronized(mPackages) { 9973 oldPackage = mPackages.get(pkgName); 9974 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 9975 PackageSetting ps = mSettings.mPackages.get(pkgName); 9976 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 9977 // default to original signature matching 9978 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 9979 != PackageManager.SIGNATURE_MATCH) { 9980 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9981 "New package has a different signature: " + pkgName); 9982 return; 9983 } 9984 } else { 9985 if(!checkUpgradeKeySetLP(ps, pkg)) { 9986 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9987 "New package not signed by keys specified by upgrade-keysets: " 9988 + pkgName); 9989 return; 9990 } 9991 } 9992 9993 // In case of rollback, remember per-user/profile install state 9994 allUsers = sUserManager.getUserIds(); 9995 perUserInstalled = new boolean[allUsers.length]; 9996 for (int i = 0; i < allUsers.length; i++) { 9997 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 9998 } 9999 } 10000 10001 boolean sysPkg = (isSystemApp(oldPackage)); 10002 if (sysPkg) { 10003 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 10004 user, allUsers, perUserInstalled, installerPackageName, res); 10005 } else { 10006 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 10007 user, allUsers, perUserInstalled, installerPackageName, res); 10008 } 10009 } 10010 10011 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 10012 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 10013 int[] allUsers, boolean[] perUserInstalled, 10014 String installerPackageName, PackageInstalledInfo res) { 10015 String pkgName = deletedPackage.packageName; 10016 boolean deletedPkg = true; 10017 boolean updatedSettings = false; 10018 10019 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 10020 + deletedPackage); 10021 long origUpdateTime; 10022 if (pkg.mExtras != null) { 10023 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 10024 } else { 10025 origUpdateTime = 0; 10026 } 10027 10028 // First delete the existing package while retaining the data directory 10029 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 10030 res.removedInfo, true)) { 10031 // If the existing package wasn't successfully deleted 10032 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 10033 deletedPkg = false; 10034 } else { 10035 // Successfully deleted the old package. Now proceed with re-installation 10036 deleteCodeCacheDirsLI(pkgName); 10037 try { 10038 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 10039 scanMode | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 10040 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10041 updatedSettings = true; 10042 } catch (PackageManagerException e) { 10043 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10044 } 10045 } 10046 10047 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10048 // remove package from internal structures. Note that we want deletePackageX to 10049 // delete the package data and cache directories that it created in 10050 // scanPackageLocked, unless those directories existed before we even tried to 10051 // install. 10052 if(updatedSettings) { 10053 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 10054 deletePackageLI( 10055 pkgName, null, true, allUsers, perUserInstalled, 10056 PackageManager.DELETE_KEEP_DATA, 10057 res.removedInfo, true); 10058 } 10059 // Since we failed to install the new package we need to restore the old 10060 // package that we deleted. 10061 if (deletedPkg) { 10062 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 10063 File restoreFile = new File(deletedPackage.codePath); 10064 // Parse old package 10065 boolean oldOnSd = isExternal(deletedPackage); 10066 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 10067 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) | 10068 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 10069 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE 10070 | SCAN_UPDATE_TIME; 10071 try { 10072 scanPackageLI(restoreFile, oldParseFlags, oldScanMode, origUpdateTime, null); 10073 } catch (PackageManagerException e) { 10074 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 10075 + e.getMessage()); 10076 return; 10077 } 10078 // Restore of old package succeeded. Update permissions. 10079 // writer 10080 synchronized (mPackages) { 10081 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 10082 UPDATE_PERMISSIONS_ALL); 10083 // can downgrade to reader 10084 mSettings.writeLPr(); 10085 } 10086 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 10087 } 10088 } 10089 } 10090 10091 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 10092 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 10093 int[] allUsers, boolean[] perUserInstalled, 10094 String installerPackageName, PackageInstalledInfo res) { 10095 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 10096 + ", old=" + deletedPackage); 10097 boolean updatedSettings = false; 10098 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING | 10099 PackageParser.PARSE_IS_SYSTEM; 10100 if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) { 10101 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10102 } 10103 String packageName = deletedPackage.packageName; 10104 if (packageName == null) { 10105 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10106 "Attempt to delete null packageName."); 10107 return; 10108 } 10109 PackageParser.Package oldPkg; 10110 PackageSetting oldPkgSetting; 10111 // reader 10112 synchronized (mPackages) { 10113 oldPkg = mPackages.get(packageName); 10114 oldPkgSetting = mSettings.mPackages.get(packageName); 10115 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 10116 (oldPkgSetting == null)) { 10117 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10118 "Couldn't find package:" + packageName + " information"); 10119 return; 10120 } 10121 } 10122 10123 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 10124 10125 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10126 res.removedInfo.removedPackage = packageName; 10127 // Remove existing system package 10128 removePackageLI(oldPkgSetting, true); 10129 // writer 10130 synchronized (mPackages) { 10131 if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) { 10132 // We didn't need to disable the .apk as a current system package, 10133 // which means we are replacing another update that is already 10134 // installed. We need to make sure to delete the older one's .apk. 10135 res.removedInfo.args = createInstallArgsForExisting(0, 10136 deletedPackage.applicationInfo.getCodePath(), 10137 deletedPackage.applicationInfo.getResourcePath(), 10138 deletedPackage.applicationInfo.nativeLibraryRootDir, 10139 getAppDexInstructionSets(deletedPackage.applicationInfo), 10140 isMultiArch(deletedPackage.applicationInfo)); 10141 } else { 10142 res.removedInfo.args = null; 10143 } 10144 } 10145 10146 // Successfully disabled the old package. Now proceed with re-installation 10147 deleteCodeCacheDirsLI(packageName); 10148 10149 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10150 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10151 10152 PackageParser.Package newPackage = null; 10153 try { 10154 newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user); 10155 if (newPackage.mExtras != null) { 10156 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 10157 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10158 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10159 10160 // is the update attempting to change shared user? that isn't going to work... 10161 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10162 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 10163 "Forbidding shared user change from " + oldPkgSetting.sharedUser 10164 + " to " + newPkgSetting.sharedUser); 10165 updatedSettings = true; 10166 } 10167 } 10168 10169 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10170 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10171 updatedSettings = true; 10172 } 10173 10174 } catch (PackageManagerException e) { 10175 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10176 } 10177 10178 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10179 // Re installation failed. Restore old information 10180 // Remove new pkg information 10181 if (newPackage != null) { 10182 removeInstalledPackageLI(newPackage, true); 10183 } 10184 // Add back the old system package 10185 try { 10186 scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user); 10187 } catch (PackageManagerException e) { 10188 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 10189 } 10190 // Restore the old system information in Settings 10191 synchronized(mPackages) { 10192 if (updatedSettings) { 10193 mSettings.enableSystemPackageLPw(packageName); 10194 mSettings.setInstallerPackageName(packageName, 10195 oldPkgSetting.installerPackageName); 10196 } 10197 mSettings.writeLPr(); 10198 } 10199 } 10200 } 10201 10202 // Utility method used to move dex files during install. 10203 private int moveDexFilesLI(String oldCodePath, PackageParser.Package newPackage) { 10204 // TODO: extend to move split APK dex files 10205 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) { 10206 final String[] instructionSets = getAppDexInstructionSets(newPackage.applicationInfo); 10207 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 10208 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 10209 int retCode = mInstaller.movedex(oldCodePath, newPackage.baseCodePath, 10210 dexCodeInstructionSet); 10211 if (retCode != 0) { 10212 /* 10213 * Programs may be lazily run through dexopt, so the 10214 * source may not exist. However, something seems to 10215 * have gone wrong, so note that dexopt needs to be 10216 * run again and remove the source file. In addition, 10217 * remove the target to make sure there isn't a stale 10218 * file from a previous version of the package. 10219 */ 10220 newPackage.mDexOptPerformed.clear(); 10221 mInstaller.rmdex(oldCodePath, dexCodeInstructionSet); 10222 mInstaller.rmdex(newPackage.baseCodePath, dexCodeInstructionSet); 10223 } 10224 } 10225 } 10226 return PackageManager.INSTALL_SUCCEEDED; 10227 } 10228 10229 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10230 int[] allUsers, boolean[] perUserInstalled, 10231 PackageInstalledInfo res) { 10232 String pkgName = newPackage.packageName; 10233 synchronized (mPackages) { 10234 //write settings. the installStatus will be incomplete at this stage. 10235 //note that the new package setting would have already been 10236 //added to mPackages. It hasn't been persisted yet. 10237 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10238 mSettings.writeLPr(); 10239 } 10240 10241 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10242 10243 synchronized (mPackages) { 10244 updatePermissionsLPw(newPackage.packageName, newPackage, 10245 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10246 ? UPDATE_PERMISSIONS_ALL : 0)); 10247 // For system-bundled packages, we assume that installing an upgraded version 10248 // of the package implies that the user actually wants to run that new code, 10249 // so we enable the package. 10250 if (isSystemApp(newPackage)) { 10251 // NB: implicit assumption that system package upgrades apply to all users 10252 if (DEBUG_INSTALL) { 10253 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10254 } 10255 PackageSetting ps = mSettings.mPackages.get(pkgName); 10256 if (ps != null) { 10257 if (res.origUsers != null) { 10258 for (int userHandle : res.origUsers) { 10259 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10260 userHandle, installerPackageName); 10261 } 10262 } 10263 // Also convey the prior install/uninstall state 10264 if (allUsers != null && perUserInstalled != null) { 10265 for (int i = 0; i < allUsers.length; i++) { 10266 if (DEBUG_INSTALL) { 10267 Slog.d(TAG, " user " + allUsers[i] 10268 + " => " + perUserInstalled[i]); 10269 } 10270 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10271 } 10272 // these install state changes will be persisted in the 10273 // upcoming call to mSettings.writeLPr(). 10274 } 10275 } 10276 } 10277 res.name = pkgName; 10278 res.uid = newPackage.applicationInfo.uid; 10279 res.pkg = newPackage; 10280 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10281 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10282 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10283 //to update install status 10284 mSettings.writeLPr(); 10285 } 10286 } 10287 10288 private void installPackageLI(InstallArgs args, boolean newInstall, PackageInstalledInfo res) { 10289 int pFlags = args.flags; 10290 String installerPackageName = args.installerPackageName; 10291 File tmpPackageFile = new File(args.getCodePath()); 10292 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10293 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0); 10294 boolean replace = false; 10295 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE 10296 | (newInstall ? SCAN_NEW_INSTALL : 0); 10297 // Result object to be returned 10298 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10299 10300 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10301 // Retrieve PackageSettings and parse package 10302 int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10303 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10304 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 10305 PackageParser pp = new PackageParser(); 10306 pp.setSeparateProcesses(mSeparateProcesses); 10307 pp.setDisplayMetrics(mMetrics); 10308 10309 final PackageParser.Package pkg; 10310 try { 10311 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 10312 } catch (PackageParserException e) { 10313 res.setError("Failed parse during installPackageLI", e); 10314 return; 10315 } 10316 10317 // Mark that we have an install time CPU ABI override. 10318 pkg.cpuAbiOverride = args.abiOverride; 10319 10320 String pkgName = res.name = pkg.packageName; 10321 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 10322 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) { 10323 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 10324 return; 10325 } 10326 } 10327 10328 try { 10329 pp.collectCertificates(pkg, parseFlags); 10330 pp.collectManifestDigest(pkg); 10331 } catch (PackageParserException e) { 10332 res.setError("Failed collect during installPackageLI", e); 10333 return; 10334 } 10335 10336 /* If the installer passed in a manifest digest, compare it now. */ 10337 if (args.manifestDigest != null) { 10338 if (DEBUG_INSTALL) { 10339 final String parsedManifest = pkg.manifestDigest == null ? "null" 10340 : pkg.manifestDigest.toString(); 10341 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 10342 + parsedManifest); 10343 } 10344 10345 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 10346 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 10347 return; 10348 } 10349 } else if (DEBUG_INSTALL) { 10350 final String parsedManifest = pkg.manifestDigest == null 10351 ? "null" : pkg.manifestDigest.toString(); 10352 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 10353 } 10354 10355 // Get rid of all references to package scan path via parser. 10356 pp = null; 10357 String oldCodePath = null; 10358 boolean systemApp = false; 10359 synchronized (mPackages) { 10360 // Check whether the newly-scanned package wants to define an already-defined perm 10361 int N = pkg.permissions.size(); 10362 for (int i = N-1; i >= 0; i--) { 10363 PackageParser.Permission perm = pkg.permissions.get(i); 10364 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 10365 if (bp != null) { 10366 // If the defining package is signed with our cert, it's okay. This 10367 // also includes the "updating the same package" case, of course. 10368 if (compareSignatures(bp.packageSetting.signatures.mSignatures, 10369 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 10370 // If the owning package is the system itself, we log but allow 10371 // install to proceed; we fail the install on all other permission 10372 // redefinitions. 10373 if (!bp.sourcePackage.equals("android")) { 10374 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 10375 + pkg.packageName + " attempting to redeclare permission " 10376 + perm.info.name + " already owned by " + bp.sourcePackage); 10377 res.origPermission = perm.info.name; 10378 res.origPackage = bp.sourcePackage; 10379 return; 10380 } else { 10381 Slog.w(TAG, "Package " + pkg.packageName 10382 + " attempting to redeclare system permission " 10383 + perm.info.name + "; ignoring new declaration"); 10384 pkg.permissions.remove(i); 10385 } 10386 } 10387 } 10388 } 10389 10390 // Check if installing already existing package 10391 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10392 String oldName = mSettings.mRenamedPackages.get(pkgName); 10393 if (pkg.mOriginalPackages != null 10394 && pkg.mOriginalPackages.contains(oldName) 10395 && mPackages.containsKey(oldName)) { 10396 // This package is derived from an original package, 10397 // and this device has been updating from that original 10398 // name. We must continue using the original name, so 10399 // rename the new package here. 10400 pkg.setPackageName(oldName); 10401 pkgName = pkg.packageName; 10402 replace = true; 10403 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 10404 + oldName + " pkgName=" + pkgName); 10405 } else if (mPackages.containsKey(pkgName)) { 10406 // This package, under its official name, already exists 10407 // on the device; we should replace it. 10408 replace = true; 10409 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 10410 } 10411 } 10412 PackageSetting ps = mSettings.mPackages.get(pkgName); 10413 if (ps != null) { 10414 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 10415 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 10416 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 10417 systemApp = (ps.pkg.applicationInfo.flags & 10418 ApplicationInfo.FLAG_SYSTEM) != 0; 10419 } 10420 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10421 } 10422 } 10423 10424 if (systemApp && onSd) { 10425 // Disable updates to system apps on sdcard 10426 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 10427 "Cannot install updates to system apps on sdcard"); 10428 return; 10429 } 10430 10431 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 10432 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 10433 return; 10434 } 10435 10436 if (replace) { 10437 replacePackageLI(pkg, parseFlags, scanMode, args.user, 10438 installerPackageName, res); 10439 } else { 10440 installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user, 10441 installerPackageName, res); 10442 } 10443 synchronized (mPackages) { 10444 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10445 if (ps != null) { 10446 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10447 } 10448 } 10449 } 10450 10451 private static boolean isForwardLocked(PackageParser.Package pkg) { 10452 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10453 } 10454 10455 private static boolean isForwardLocked(ApplicationInfo info) { 10456 return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10457 } 10458 10459 private boolean isForwardLocked(PackageSetting ps) { 10460 return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10461 } 10462 10463 private static boolean isMultiArch(PackageSetting ps) { 10464 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10465 } 10466 10467 private static boolean isMultiArch(ApplicationInfo info) { 10468 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10469 } 10470 10471 private static boolean isExternal(PackageParser.Package pkg) { 10472 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10473 } 10474 10475 private static boolean isExternal(PackageSetting ps) { 10476 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10477 } 10478 10479 private static boolean isExternal(ApplicationInfo info) { 10480 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10481 } 10482 10483 private static boolean isSystemApp(PackageParser.Package pkg) { 10484 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10485 } 10486 10487 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 10488 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0; 10489 } 10490 10491 private static boolean isSystemApp(ApplicationInfo info) { 10492 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10493 } 10494 10495 private static boolean isSystemApp(PackageSetting ps) { 10496 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 10497 } 10498 10499 private static boolean isUpdatedSystemApp(PackageSetting ps) { 10500 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10501 } 10502 10503 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 10504 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10505 } 10506 10507 private static boolean isUpdatedSystemApp(ApplicationInfo info) { 10508 return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10509 } 10510 10511 private int packageFlagsToInstallFlags(PackageSetting ps) { 10512 int installFlags = 0; 10513 if (isExternal(ps)) { 10514 installFlags |= PackageManager.INSTALL_EXTERNAL; 10515 } 10516 if (isForwardLocked(ps)) { 10517 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 10518 } 10519 return installFlags; 10520 } 10521 10522 private void deleteTempPackageFiles() { 10523 final FilenameFilter filter = new FilenameFilter() { 10524 public boolean accept(File dir, String name) { 10525 return name.startsWith("vmdl") && name.endsWith(".tmp"); 10526 } 10527 }; 10528 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 10529 file.delete(); 10530 } 10531 } 10532 10533 @Override 10534 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 10535 int flags) { 10536 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 10537 flags); 10538 } 10539 10540 @Override 10541 public void deletePackage(final String packageName, 10542 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 10543 mContext.enforceCallingOrSelfPermission( 10544 android.Manifest.permission.DELETE_PACKAGES, null); 10545 final int uid = Binder.getCallingUid(); 10546 if (UserHandle.getUserId(uid) != userId) { 10547 mContext.enforceCallingPermission( 10548 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 10549 "deletePackage for user " + userId); 10550 } 10551 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 10552 try { 10553 observer.onPackageDeleted(packageName, 10554 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 10555 } catch (RemoteException re) { 10556 } 10557 return; 10558 } 10559 10560 boolean uninstallBlocked = false; 10561 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 10562 int[] users = sUserManager.getUserIds(); 10563 for (int i = 0; i < users.length; ++i) { 10564 if (getBlockUninstallForUser(packageName, users[i])) { 10565 uninstallBlocked = true; 10566 break; 10567 } 10568 } 10569 } else { 10570 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 10571 } 10572 if (uninstallBlocked) { 10573 try { 10574 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 10575 null); 10576 } catch (RemoteException re) { 10577 } 10578 return; 10579 } 10580 10581 if (DEBUG_REMOVE) { 10582 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 10583 } 10584 // Queue up an async operation since the package deletion may take a little while. 10585 mHandler.post(new Runnable() { 10586 public void run() { 10587 mHandler.removeCallbacks(this); 10588 final int returnCode = deletePackageX(packageName, userId, flags); 10589 if (observer != null) { 10590 try { 10591 observer.onPackageDeleted(packageName, returnCode, null); 10592 } catch (RemoteException e) { 10593 Log.i(TAG, "Observer no longer exists."); 10594 } //end catch 10595 } //end if 10596 } //end run 10597 }); 10598 } 10599 10600 private boolean isPackageDeviceAdmin(String packageName, int userId) { 10601 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 10602 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 10603 try { 10604 if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId) 10605 || dpm.isDeviceOwner(packageName))) { 10606 return true; 10607 } 10608 } catch (RemoteException e) { 10609 } 10610 return false; 10611 } 10612 10613 /** 10614 * This method is an internal method that could be get invoked either 10615 * to delete an installed package or to clean up a failed installation. 10616 * After deleting an installed package, a broadcast is sent to notify any 10617 * listeners that the package has been installed. For cleaning up a failed 10618 * installation, the broadcast is not necessary since the package's 10619 * installation wouldn't have sent the initial broadcast either 10620 * The key steps in deleting a package are 10621 * deleting the package information in internal structures like mPackages, 10622 * deleting the packages base directories through installd 10623 * updating mSettings to reflect current status 10624 * persisting settings for later use 10625 * sending a broadcast if necessary 10626 */ 10627 private int deletePackageX(String packageName, int userId, int flags) { 10628 final PackageRemovedInfo info = new PackageRemovedInfo(); 10629 final boolean res; 10630 10631 if (isPackageDeviceAdmin(packageName, userId)) { 10632 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 10633 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 10634 } 10635 10636 boolean removedForAllUsers = false; 10637 boolean systemUpdate = false; 10638 10639 // for the uninstall-updates case and restricted profiles, remember the per- 10640 // userhandle installed state 10641 int[] allUsers; 10642 boolean[] perUserInstalled; 10643 synchronized (mPackages) { 10644 PackageSetting ps = mSettings.mPackages.get(packageName); 10645 allUsers = sUserManager.getUserIds(); 10646 perUserInstalled = new boolean[allUsers.length]; 10647 for (int i = 0; i < allUsers.length; i++) { 10648 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10649 } 10650 } 10651 10652 synchronized (mInstallLock) { 10653 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 10654 res = deletePackageLI(packageName, 10655 (flags & PackageManager.DELETE_ALL_USERS) != 0 10656 ? UserHandle.ALL : new UserHandle(userId), 10657 true, allUsers, perUserInstalled, 10658 flags | REMOVE_CHATTY, info, true); 10659 systemUpdate = info.isRemovedPackageSystemUpdate; 10660 if (res && !systemUpdate && mPackages.get(packageName) == null) { 10661 removedForAllUsers = true; 10662 } 10663 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 10664 + " removedForAllUsers=" + removedForAllUsers); 10665 } 10666 10667 if (res) { 10668 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 10669 10670 // If the removed package was a system update, the old system package 10671 // was re-enabled; we need to broadcast this information 10672 if (systemUpdate) { 10673 Bundle extras = new Bundle(1); 10674 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 10675 ? info.removedAppId : info.uid); 10676 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10677 10678 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 10679 extras, null, null, null); 10680 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 10681 extras, null, null, null); 10682 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 10683 null, packageName, null, null); 10684 } 10685 } 10686 // Force a gc here. 10687 Runtime.getRuntime().gc(); 10688 // Delete the resources here after sending the broadcast to let 10689 // other processes clean up before deleting resources. 10690 if (info.args != null) { 10691 synchronized (mInstallLock) { 10692 info.args.doPostDeleteLI(true); 10693 } 10694 } 10695 10696 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10697 } 10698 10699 static class PackageRemovedInfo { 10700 String removedPackage; 10701 int uid = -1; 10702 int removedAppId = -1; 10703 int[] removedUsers = null; 10704 boolean isRemovedPackageSystemUpdate = false; 10705 // Clean up resources deleted packages. 10706 InstallArgs args = null; 10707 10708 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 10709 Bundle extras = new Bundle(1); 10710 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 10711 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 10712 if (replacing) { 10713 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10714 } 10715 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 10716 if (removedPackage != null) { 10717 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 10718 extras, null, null, removedUsers); 10719 if (fullRemove && !replacing) { 10720 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 10721 extras, null, null, removedUsers); 10722 } 10723 } 10724 if (removedAppId >= 0) { 10725 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 10726 removedUsers); 10727 } 10728 } 10729 } 10730 10731 /* 10732 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 10733 * flag is not set, the data directory is removed as well. 10734 * make sure this flag is set for partially installed apps. If not its meaningless to 10735 * delete a partially installed application. 10736 */ 10737 private void removePackageDataLI(PackageSetting ps, 10738 int[] allUserHandles, boolean[] perUserInstalled, 10739 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 10740 String packageName = ps.name; 10741 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 10742 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 10743 // Retrieve object to delete permissions for shared user later on 10744 final PackageSetting deletedPs; 10745 // reader 10746 synchronized (mPackages) { 10747 deletedPs = mSettings.mPackages.get(packageName); 10748 if (outInfo != null) { 10749 outInfo.removedPackage = packageName; 10750 outInfo.removedUsers = deletedPs != null 10751 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 10752 : null; 10753 } 10754 } 10755 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10756 removeDataDirsLI(packageName); 10757 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 10758 } 10759 // writer 10760 synchronized (mPackages) { 10761 if (deletedPs != null) { 10762 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10763 if (outInfo != null) { 10764 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 10765 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 10766 } 10767 if (deletedPs != null) { 10768 updatePermissionsLPw(deletedPs.name, null, 0); 10769 if (deletedPs.sharedUser != null) { 10770 // remove permissions associated with package 10771 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 10772 } 10773 } 10774 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 10775 } 10776 // make sure to preserve per-user disabled state if this removal was just 10777 // a downgrade of a system app to the factory package 10778 if (allUserHandles != null && perUserInstalled != null) { 10779 if (DEBUG_REMOVE) { 10780 Slog.d(TAG, "Propagating install state across downgrade"); 10781 } 10782 for (int i = 0; i < allUserHandles.length; i++) { 10783 if (DEBUG_REMOVE) { 10784 Slog.d(TAG, " user " + allUserHandles[i] 10785 + " => " + perUserInstalled[i]); 10786 } 10787 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10788 } 10789 } 10790 } 10791 // can downgrade to reader 10792 if (writeSettings) { 10793 // Save settings now 10794 mSettings.writeLPr(); 10795 } 10796 } 10797 if (outInfo != null) { 10798 // A user ID was deleted here. Go through all users and remove it 10799 // from KeyStore. 10800 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 10801 } 10802 } 10803 10804 static boolean locationIsPrivileged(File path) { 10805 try { 10806 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 10807 .getCanonicalPath(); 10808 return path.getCanonicalPath().startsWith(privilegedAppDir); 10809 } catch (IOException e) { 10810 Slog.e(TAG, "Unable to access code path " + path); 10811 } 10812 return false; 10813 } 10814 10815 /* 10816 * Tries to delete system package. 10817 */ 10818 private boolean deleteSystemPackageLI(PackageSetting newPs, 10819 int[] allUserHandles, boolean[] perUserInstalled, 10820 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 10821 final boolean applyUserRestrictions 10822 = (allUserHandles != null) && (perUserInstalled != null); 10823 PackageSetting disabledPs = null; 10824 // Confirm if the system package has been updated 10825 // An updated system app can be deleted. This will also have to restore 10826 // the system pkg from system partition 10827 // reader 10828 synchronized (mPackages) { 10829 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 10830 } 10831 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 10832 + " disabledPs=" + disabledPs); 10833 if (disabledPs == null) { 10834 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 10835 return false; 10836 } else if (DEBUG_REMOVE) { 10837 Slog.d(TAG, "Deleting system pkg from data partition"); 10838 } 10839 if (DEBUG_REMOVE) { 10840 if (applyUserRestrictions) { 10841 Slog.d(TAG, "Remembering install states:"); 10842 for (int i = 0; i < allUserHandles.length; i++) { 10843 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 10844 } 10845 } 10846 } 10847 // Delete the updated package 10848 outInfo.isRemovedPackageSystemUpdate = true; 10849 if (disabledPs.versionCode < newPs.versionCode) { 10850 // Delete data for downgrades 10851 flags &= ~PackageManager.DELETE_KEEP_DATA; 10852 } else { 10853 // Preserve data by setting flag 10854 flags |= PackageManager.DELETE_KEEP_DATA; 10855 } 10856 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 10857 allUserHandles, perUserInstalled, outInfo, writeSettings); 10858 if (!ret) { 10859 return false; 10860 } 10861 // writer 10862 synchronized (mPackages) { 10863 // Reinstate the old system package 10864 mSettings.enableSystemPackageLPw(newPs.name); 10865 // Remove any native libraries from the upgraded package. 10866 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 10867 } 10868 // Install the system package 10869 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 10870 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 10871 if (locationIsPrivileged(disabledPs.codePath)) { 10872 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10873 } 10874 10875 final PackageParser.Package newPkg; 10876 try { 10877 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, null); 10878 } catch (PackageManagerException e) { 10879 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 10880 return false; 10881 } 10882 10883 // writer 10884 synchronized (mPackages) { 10885 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 10886 updatePermissionsLPw(newPkg.packageName, newPkg, 10887 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 10888 if (applyUserRestrictions) { 10889 if (DEBUG_REMOVE) { 10890 Slog.d(TAG, "Propagating install state across reinstall"); 10891 } 10892 for (int i = 0; i < allUserHandles.length; i++) { 10893 if (DEBUG_REMOVE) { 10894 Slog.d(TAG, " user " + allUserHandles[i] 10895 + " => " + perUserInstalled[i]); 10896 } 10897 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10898 } 10899 // Regardless of writeSettings we need to ensure that this restriction 10900 // state propagation is persisted 10901 mSettings.writeAllUsersPackageRestrictionsLPr(); 10902 } 10903 // can downgrade to reader here 10904 if (writeSettings) { 10905 mSettings.writeLPr(); 10906 } 10907 } 10908 return true; 10909 } 10910 10911 private boolean deleteInstalledPackageLI(PackageSetting ps, 10912 boolean deleteCodeAndResources, int flags, 10913 int[] allUserHandles, boolean[] perUserInstalled, 10914 PackageRemovedInfo outInfo, boolean writeSettings) { 10915 if (outInfo != null) { 10916 outInfo.uid = ps.appId; 10917 } 10918 10919 // Delete package data from internal structures and also remove data if flag is set 10920 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 10921 10922 // Delete application code and resources 10923 if (deleteCodeAndResources && (outInfo != null)) { 10924 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 10925 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 10926 getAppDexInstructionSets(ps), isMultiArch(ps)); 10927 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 10928 } 10929 return true; 10930 } 10931 10932 @Override 10933 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 10934 int userId) { 10935 mContext.enforceCallingOrSelfPermission( 10936 android.Manifest.permission.DELETE_PACKAGES, null); 10937 synchronized (mPackages) { 10938 PackageSetting ps = mSettings.mPackages.get(packageName); 10939 if (ps == null) { 10940 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 10941 return false; 10942 } 10943 if (!ps.getInstalled(userId)) { 10944 // Can't block uninstall for an app that is not installed or enabled. 10945 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 10946 return false; 10947 } 10948 ps.setBlockUninstall(blockUninstall, userId); 10949 mSettings.writePackageRestrictionsLPr(userId); 10950 } 10951 return true; 10952 } 10953 10954 @Override 10955 public boolean getBlockUninstallForUser(String packageName, int userId) { 10956 synchronized (mPackages) { 10957 PackageSetting ps = mSettings.mPackages.get(packageName); 10958 if (ps == null) { 10959 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 10960 return false; 10961 } 10962 return ps.getBlockUninstall(userId); 10963 } 10964 } 10965 10966 /* 10967 * This method handles package deletion in general 10968 */ 10969 private boolean deletePackageLI(String packageName, UserHandle user, 10970 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 10971 int flags, PackageRemovedInfo outInfo, 10972 boolean writeSettings) { 10973 if (packageName == null) { 10974 Slog.w(TAG, "Attempt to delete null packageName."); 10975 return false; 10976 } 10977 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 10978 PackageSetting ps; 10979 boolean dataOnly = false; 10980 int removeUser = -1; 10981 int appId = -1; 10982 synchronized (mPackages) { 10983 ps = mSettings.mPackages.get(packageName); 10984 if (ps == null) { 10985 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 10986 return false; 10987 } 10988 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 10989 && user.getIdentifier() != UserHandle.USER_ALL) { 10990 // The caller is asking that the package only be deleted for a single 10991 // user. To do this, we just mark its uninstalled state and delete 10992 // its data. If this is a system app, we only allow this to happen if 10993 // they have set the special DELETE_SYSTEM_APP which requests different 10994 // semantics than normal for uninstalling system apps. 10995 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 10996 ps.setUserState(user.getIdentifier(), 10997 COMPONENT_ENABLED_STATE_DEFAULT, 10998 false, //installed 10999 true, //stopped 11000 true, //notLaunched 11001 false, //hidden 11002 null, null, null, 11003 false // blockUninstall 11004 ); 11005 if (!isSystemApp(ps)) { 11006 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 11007 // Other user still have this package installed, so all 11008 // we need to do is clear this user's data and save that 11009 // it is uninstalled. 11010 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 11011 removeUser = user.getIdentifier(); 11012 appId = ps.appId; 11013 mSettings.writePackageRestrictionsLPr(removeUser); 11014 } else { 11015 // We need to set it back to 'installed' so the uninstall 11016 // broadcasts will be sent correctly. 11017 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 11018 ps.setInstalled(true, user.getIdentifier()); 11019 } 11020 } else { 11021 // This is a system app, so we assume that the 11022 // other users still have this package installed, so all 11023 // we need to do is clear this user's data and save that 11024 // it is uninstalled. 11025 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 11026 removeUser = user.getIdentifier(); 11027 appId = ps.appId; 11028 mSettings.writePackageRestrictionsLPr(removeUser); 11029 } 11030 } 11031 } 11032 11033 if (removeUser >= 0) { 11034 // From above, we determined that we are deleting this only 11035 // for a single user. Continue the work here. 11036 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 11037 if (outInfo != null) { 11038 outInfo.removedPackage = packageName; 11039 outInfo.removedAppId = appId; 11040 outInfo.removedUsers = new int[] {removeUser}; 11041 } 11042 mInstaller.clearUserData(packageName, removeUser); 11043 removeKeystoreDataIfNeeded(removeUser, appId); 11044 schedulePackageCleaning(packageName, removeUser, false); 11045 return true; 11046 } 11047 11048 if (dataOnly) { 11049 // Delete application data first 11050 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 11051 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 11052 return true; 11053 } 11054 11055 boolean ret = false; 11056 if (isSystemApp(ps)) { 11057 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 11058 // When an updated system application is deleted we delete the existing resources as well and 11059 // fall back to existing code in system partition 11060 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 11061 flags, outInfo, writeSettings); 11062 } else { 11063 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 11064 // Kill application pre-emptively especially for apps on sd. 11065 killApplication(packageName, ps.appId, "uninstall pkg"); 11066 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 11067 allUserHandles, perUserInstalled, 11068 outInfo, writeSettings); 11069 } 11070 11071 return ret; 11072 } 11073 11074 private final class ClearStorageConnection implements ServiceConnection { 11075 IMediaContainerService mContainerService; 11076 11077 @Override 11078 public void onServiceConnected(ComponentName name, IBinder service) { 11079 synchronized (this) { 11080 mContainerService = IMediaContainerService.Stub.asInterface(service); 11081 notifyAll(); 11082 } 11083 } 11084 11085 @Override 11086 public void onServiceDisconnected(ComponentName name) { 11087 } 11088 } 11089 11090 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 11091 final boolean mounted; 11092 if (Environment.isExternalStorageEmulated()) { 11093 mounted = true; 11094 } else { 11095 final String status = Environment.getExternalStorageState(); 11096 11097 mounted = status.equals(Environment.MEDIA_MOUNTED) 11098 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 11099 } 11100 11101 if (!mounted) { 11102 return; 11103 } 11104 11105 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 11106 int[] users; 11107 if (userId == UserHandle.USER_ALL) { 11108 users = sUserManager.getUserIds(); 11109 } else { 11110 users = new int[] { userId }; 11111 } 11112 final ClearStorageConnection conn = new ClearStorageConnection(); 11113 if (mContext.bindServiceAsUser( 11114 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 11115 try { 11116 for (int curUser : users) { 11117 long timeout = SystemClock.uptimeMillis() + 5000; 11118 synchronized (conn) { 11119 long now = SystemClock.uptimeMillis(); 11120 while (conn.mContainerService == null && now < timeout) { 11121 try { 11122 conn.wait(timeout - now); 11123 } catch (InterruptedException e) { 11124 } 11125 } 11126 } 11127 if (conn.mContainerService == null) { 11128 return; 11129 } 11130 11131 final UserEnvironment userEnv = new UserEnvironment(curUser); 11132 clearDirectory(conn.mContainerService, 11133 userEnv.buildExternalStorageAppCacheDirs(packageName)); 11134 if (allData) { 11135 clearDirectory(conn.mContainerService, 11136 userEnv.buildExternalStorageAppDataDirs(packageName)); 11137 clearDirectory(conn.mContainerService, 11138 userEnv.buildExternalStorageAppMediaDirs(packageName)); 11139 } 11140 } 11141 } finally { 11142 mContext.unbindService(conn); 11143 } 11144 } 11145 } 11146 11147 @Override 11148 public void clearApplicationUserData(final String packageName, 11149 final IPackageDataObserver observer, final int userId) { 11150 mContext.enforceCallingOrSelfPermission( 11151 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 11152 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data"); 11153 // Queue up an async operation since the package deletion may take a little while. 11154 mHandler.post(new Runnable() { 11155 public void run() { 11156 mHandler.removeCallbacks(this); 11157 final boolean succeeded; 11158 synchronized (mInstallLock) { 11159 succeeded = clearApplicationUserDataLI(packageName, userId); 11160 } 11161 clearExternalStorageDataSync(packageName, userId, true); 11162 if (succeeded) { 11163 // invoke DeviceStorageMonitor's update method to clear any notifications 11164 DeviceStorageMonitorInternal 11165 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 11166 if (dsm != null) { 11167 dsm.checkMemory(); 11168 } 11169 } 11170 if(observer != null) { 11171 try { 11172 observer.onRemoveCompleted(packageName, succeeded); 11173 } catch (RemoteException e) { 11174 Log.i(TAG, "Observer no longer exists."); 11175 } 11176 } //end if observer 11177 } //end run 11178 }); 11179 } 11180 11181 private boolean clearApplicationUserDataLI(String packageName, int userId) { 11182 if (packageName == null) { 11183 Slog.w(TAG, "Attempt to delete null packageName."); 11184 return false; 11185 } 11186 PackageParser.Package p; 11187 boolean dataOnly = false; 11188 final int appId; 11189 synchronized (mPackages) { 11190 p = mPackages.get(packageName); 11191 if (p == null) { 11192 dataOnly = true; 11193 PackageSetting ps = mSettings.mPackages.get(packageName); 11194 if ((ps == null) || (ps.pkg == null)) { 11195 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11196 return false; 11197 } 11198 p = ps.pkg; 11199 } 11200 if (!dataOnly) { 11201 // need to check this only for fully installed applications 11202 if (p == null) { 11203 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11204 return false; 11205 } 11206 final ApplicationInfo applicationInfo = p.applicationInfo; 11207 if (applicationInfo == null) { 11208 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11209 return false; 11210 } 11211 } 11212 if (p != null && p.applicationInfo != null) { 11213 appId = p.applicationInfo.uid; 11214 } else { 11215 appId = -1; 11216 } 11217 } 11218 int retCode = mInstaller.clearUserData(packageName, userId); 11219 if (retCode < 0) { 11220 Slog.w(TAG, "Couldn't remove cache files for package: " 11221 + packageName); 11222 return false; 11223 } 11224 removeKeystoreDataIfNeeded(userId, appId); 11225 return true; 11226 } 11227 11228 /** 11229 * Remove entries from the keystore daemon. Will only remove it if the 11230 * {@code appId} is valid. 11231 */ 11232 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 11233 if (appId < 0) { 11234 return; 11235 } 11236 11237 final KeyStore keyStore = KeyStore.getInstance(); 11238 if (keyStore != null) { 11239 if (userId == UserHandle.USER_ALL) { 11240 for (final int individual : sUserManager.getUserIds()) { 11241 keyStore.clearUid(UserHandle.getUid(individual, appId)); 11242 } 11243 } else { 11244 keyStore.clearUid(UserHandle.getUid(userId, appId)); 11245 } 11246 } else { 11247 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 11248 } 11249 } 11250 11251 @Override 11252 public void deleteApplicationCacheFiles(final String packageName, 11253 final IPackageDataObserver observer) { 11254 mContext.enforceCallingOrSelfPermission( 11255 android.Manifest.permission.DELETE_CACHE_FILES, null); 11256 // Queue up an async operation since the package deletion may take a little while. 11257 final int userId = UserHandle.getCallingUserId(); 11258 mHandler.post(new Runnable() { 11259 public void run() { 11260 mHandler.removeCallbacks(this); 11261 final boolean succeded; 11262 synchronized (mInstallLock) { 11263 succeded = deleteApplicationCacheFilesLI(packageName, userId); 11264 } 11265 clearExternalStorageDataSync(packageName, userId, false); 11266 if(observer != null) { 11267 try { 11268 observer.onRemoveCompleted(packageName, succeded); 11269 } catch (RemoteException e) { 11270 Log.i(TAG, "Observer no longer exists."); 11271 } 11272 } //end if observer 11273 } //end run 11274 }); 11275 } 11276 11277 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 11278 if (packageName == null) { 11279 Slog.w(TAG, "Attempt to delete null packageName."); 11280 return false; 11281 } 11282 PackageParser.Package p; 11283 synchronized (mPackages) { 11284 p = mPackages.get(packageName); 11285 } 11286 if (p == null) { 11287 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11288 return false; 11289 } 11290 final ApplicationInfo applicationInfo = p.applicationInfo; 11291 if (applicationInfo == null) { 11292 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11293 return false; 11294 } 11295 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 11296 if (retCode < 0) { 11297 Slog.w(TAG, "Couldn't remove cache files for package: " 11298 + packageName + " u" + userId); 11299 return false; 11300 } 11301 return true; 11302 } 11303 11304 @Override 11305 public void getPackageSizeInfo(final String packageName, int userHandle, 11306 final IPackageStatsObserver observer) { 11307 mContext.enforceCallingOrSelfPermission( 11308 android.Manifest.permission.GET_PACKAGE_SIZE, null); 11309 if (packageName == null) { 11310 throw new IllegalArgumentException("Attempt to get size of null packageName"); 11311 } 11312 11313 PackageStats stats = new PackageStats(packageName, userHandle); 11314 11315 /* 11316 * Queue up an async operation since the package measurement may take a 11317 * little while. 11318 */ 11319 Message msg = mHandler.obtainMessage(INIT_COPY); 11320 msg.obj = new MeasureParams(stats, observer); 11321 mHandler.sendMessage(msg); 11322 } 11323 11324 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 11325 PackageStats pStats) { 11326 if (packageName == null) { 11327 Slog.w(TAG, "Attempt to get size of null packageName."); 11328 return false; 11329 } 11330 PackageParser.Package p; 11331 boolean dataOnly = false; 11332 String libDirRoot = null; 11333 String asecPath = null; 11334 PackageSetting ps = null; 11335 synchronized (mPackages) { 11336 p = mPackages.get(packageName); 11337 ps = mSettings.mPackages.get(packageName); 11338 if(p == null) { 11339 dataOnly = true; 11340 if((ps == null) || (ps.pkg == null)) { 11341 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11342 return false; 11343 } 11344 p = ps.pkg; 11345 } 11346 if (ps != null) { 11347 libDirRoot = ps.legacyNativeLibraryPathString; 11348 } 11349 if (p != null && (isExternal(p) || isForwardLocked(p))) { 11350 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 11351 if (secureContainerId != null) { 11352 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 11353 } 11354 } 11355 } 11356 String publicSrcDir = null; 11357 if(!dataOnly) { 11358 final ApplicationInfo applicationInfo = p.applicationInfo; 11359 if (applicationInfo == null) { 11360 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11361 return false; 11362 } 11363 if (isForwardLocked(p)) { 11364 publicSrcDir = applicationInfo.getBaseResourcePath(); 11365 } 11366 } 11367 // TODO: extend to measure size of split APKs 11368 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 11369 // not just the first level. 11370 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 11371 // just the primary. 11372 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 11373 int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot, 11374 publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 11375 if (res < 0) { 11376 return false; 11377 } 11378 11379 // Fix-up for forward-locked applications in ASEC containers. 11380 if (!isExternal(p)) { 11381 pStats.codeSize += pStats.externalCodeSize; 11382 pStats.externalCodeSize = 0L; 11383 } 11384 11385 return true; 11386 } 11387 11388 11389 @Override 11390 public void addPackageToPreferred(String packageName) { 11391 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 11392 } 11393 11394 @Override 11395 public void removePackageFromPreferred(String packageName) { 11396 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 11397 } 11398 11399 @Override 11400 public List<PackageInfo> getPreferredPackages(int flags) { 11401 return new ArrayList<PackageInfo>(); 11402 } 11403 11404 private int getUidTargetSdkVersionLockedLPr(int uid) { 11405 Object obj = mSettings.getUserIdLPr(uid); 11406 if (obj instanceof SharedUserSetting) { 11407 final SharedUserSetting sus = (SharedUserSetting) obj; 11408 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 11409 final Iterator<PackageSetting> it = sus.packages.iterator(); 11410 while (it.hasNext()) { 11411 final PackageSetting ps = it.next(); 11412 if (ps.pkg != null) { 11413 int v = ps.pkg.applicationInfo.targetSdkVersion; 11414 if (v < vers) vers = v; 11415 } 11416 } 11417 return vers; 11418 } else if (obj instanceof PackageSetting) { 11419 final PackageSetting ps = (PackageSetting) obj; 11420 if (ps.pkg != null) { 11421 return ps.pkg.applicationInfo.targetSdkVersion; 11422 } 11423 } 11424 return Build.VERSION_CODES.CUR_DEVELOPMENT; 11425 } 11426 11427 @Override 11428 public void addPreferredActivity(IntentFilter filter, int match, 11429 ComponentName[] set, ComponentName activity, int userId) { 11430 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11431 "Adding preferred"); 11432 } 11433 11434 private void addPreferredActivityInternal(IntentFilter filter, int match, 11435 ComponentName[] set, ComponentName activity, boolean always, int userId, 11436 String opname) { 11437 // writer 11438 int callingUid = Binder.getCallingUid(); 11439 enforceCrossUserPermission(callingUid, userId, true, "add preferred activity"); 11440 if (filter.countActions() == 0) { 11441 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11442 return; 11443 } 11444 synchronized (mPackages) { 11445 if (mContext.checkCallingOrSelfPermission( 11446 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11447 != PackageManager.PERMISSION_GRANTED) { 11448 if (getUidTargetSdkVersionLockedLPr(callingUid) 11449 < Build.VERSION_CODES.FROYO) { 11450 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 11451 + callingUid); 11452 return; 11453 } 11454 mContext.enforceCallingOrSelfPermission( 11455 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11456 } 11457 11458 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 11459 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 11460 + userId + ":"); 11461 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11462 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 11463 mSettings.writePackageRestrictionsLPr(userId); 11464 } 11465 } 11466 11467 @Override 11468 public void replacePreferredActivity(IntentFilter filter, int match, 11469 ComponentName[] set, ComponentName activity, int userId) { 11470 if (filter.countActions() != 1) { 11471 throw new IllegalArgumentException( 11472 "replacePreferredActivity expects filter to have only 1 action."); 11473 } 11474 if (filter.countDataAuthorities() != 0 11475 || filter.countDataPaths() != 0 11476 || filter.countDataSchemes() > 1 11477 || filter.countDataTypes() != 0) { 11478 throw new IllegalArgumentException( 11479 "replacePreferredActivity expects filter to have no data authorities, " + 11480 "paths, or types; and at most one scheme."); 11481 } 11482 11483 final int callingUid = Binder.getCallingUid(); 11484 enforceCrossUserPermission(callingUid, userId, true, "replace preferred activity"); 11485 synchronized (mPackages) { 11486 if (mContext.checkCallingOrSelfPermission( 11487 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11488 != PackageManager.PERMISSION_GRANTED) { 11489 if (getUidTargetSdkVersionLockedLPr(callingUid) 11490 < Build.VERSION_CODES.FROYO) { 11491 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 11492 + Binder.getCallingUid()); 11493 return; 11494 } 11495 mContext.enforceCallingOrSelfPermission( 11496 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11497 } 11498 11499 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11500 if (pir != null) { 11501 // Get all of the existing entries that exactly match this filter. 11502 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 11503 if (existing != null && existing.size() == 1) { 11504 PreferredActivity cur = existing.get(0); 11505 if (DEBUG_PREFERRED) { 11506 Slog.i(TAG, "Checking replace of preferred:"); 11507 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11508 if (!cur.mPref.mAlways) { 11509 Slog.i(TAG, " -- CUR; not mAlways!"); 11510 } else { 11511 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 11512 Slog.i(TAG, " -- CUR: mSet=" 11513 + Arrays.toString(cur.mPref.mSetComponents)); 11514 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 11515 Slog.i(TAG, " -- NEW: mMatch=" 11516 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 11517 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 11518 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 11519 } 11520 } 11521 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 11522 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 11523 && cur.mPref.sameSet(set)) { 11524 if (DEBUG_PREFERRED) { 11525 Slog.i(TAG, "Replacing with same preferred activity " 11526 + cur.mPref.mShortComponent + " for user " 11527 + userId + ":"); 11528 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11529 } else { 11530 Slog.i(TAG, "Replacing with same preferred activity " 11531 + cur.mPref.mShortComponent + " for user " 11532 + userId); 11533 } 11534 return; 11535 } 11536 } 11537 11538 if (existing != null) { 11539 if (DEBUG_PREFERRED) { 11540 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 11541 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11542 } 11543 for (int i = 0; i < existing.size(); i++) { 11544 PreferredActivity pa = existing.get(i); 11545 if (DEBUG_PREFERRED) { 11546 Slog.i(TAG, "Removing existing preferred activity " 11547 + pa.mPref.mComponent + ":"); 11548 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 11549 } 11550 pir.removeFilter(pa); 11551 } 11552 } 11553 } 11554 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11555 "Replacing preferred"); 11556 } 11557 } 11558 11559 @Override 11560 public void clearPackagePreferredActivities(String packageName) { 11561 final int uid = Binder.getCallingUid(); 11562 // writer 11563 synchronized (mPackages) { 11564 PackageParser.Package pkg = mPackages.get(packageName); 11565 if (pkg == null || pkg.applicationInfo.uid != uid) { 11566 if (mContext.checkCallingOrSelfPermission( 11567 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11568 != PackageManager.PERMISSION_GRANTED) { 11569 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11570 < Build.VERSION_CODES.FROYO) { 11571 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 11572 + Binder.getCallingUid()); 11573 return; 11574 } 11575 mContext.enforceCallingOrSelfPermission( 11576 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11577 } 11578 } 11579 11580 int user = UserHandle.getCallingUserId(); 11581 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 11582 mSettings.writePackageRestrictionsLPr(user); 11583 scheduleWriteSettingsLocked(); 11584 } 11585 } 11586 } 11587 11588 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 11589 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 11590 ArrayList<PreferredActivity> removed = null; 11591 boolean changed = false; 11592 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11593 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 11594 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11595 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 11596 continue; 11597 } 11598 Iterator<PreferredActivity> it = pir.filterIterator(); 11599 while (it.hasNext()) { 11600 PreferredActivity pa = it.next(); 11601 // Mark entry for removal only if it matches the package name 11602 // and the entry is of type "always". 11603 if (packageName == null || 11604 (pa.mPref.mComponent.getPackageName().equals(packageName) 11605 && pa.mPref.mAlways)) { 11606 if (removed == null) { 11607 removed = new ArrayList<PreferredActivity>(); 11608 } 11609 removed.add(pa); 11610 } 11611 } 11612 if (removed != null) { 11613 for (int j=0; j<removed.size(); j++) { 11614 PreferredActivity pa = removed.get(j); 11615 pir.removeFilter(pa); 11616 } 11617 changed = true; 11618 } 11619 } 11620 return changed; 11621 } 11622 11623 @Override 11624 public void resetPreferredActivities(int userId) { 11625 mContext.enforceCallingOrSelfPermission( 11626 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11627 // writer 11628 synchronized (mPackages) { 11629 int user = UserHandle.getCallingUserId(); 11630 clearPackagePreferredActivitiesLPw(null, user); 11631 mSettings.readDefaultPreferredAppsLPw(this, user); 11632 mSettings.writePackageRestrictionsLPr(user); 11633 scheduleWriteSettingsLocked(); 11634 } 11635 } 11636 11637 @Override 11638 public int getPreferredActivities(List<IntentFilter> outFilters, 11639 List<ComponentName> outActivities, String packageName) { 11640 11641 int num = 0; 11642 final int userId = UserHandle.getCallingUserId(); 11643 // reader 11644 synchronized (mPackages) { 11645 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11646 if (pir != null) { 11647 final Iterator<PreferredActivity> it = pir.filterIterator(); 11648 while (it.hasNext()) { 11649 final PreferredActivity pa = it.next(); 11650 if (packageName == null 11651 || (pa.mPref.mComponent.getPackageName().equals(packageName) 11652 && pa.mPref.mAlways)) { 11653 if (outFilters != null) { 11654 outFilters.add(new IntentFilter(pa)); 11655 } 11656 if (outActivities != null) { 11657 outActivities.add(pa.mPref.mComponent); 11658 } 11659 } 11660 } 11661 } 11662 } 11663 11664 return num; 11665 } 11666 11667 @Override 11668 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 11669 int userId) { 11670 int callingUid = Binder.getCallingUid(); 11671 if (callingUid != Process.SYSTEM_UID) { 11672 throw new SecurityException( 11673 "addPersistentPreferredActivity can only be run by the system"); 11674 } 11675 if (filter.countActions() == 0) { 11676 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11677 return; 11678 } 11679 synchronized (mPackages) { 11680 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 11681 " :"); 11682 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11683 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 11684 new PersistentPreferredActivity(filter, activity)); 11685 mSettings.writePackageRestrictionsLPr(userId); 11686 } 11687 } 11688 11689 @Override 11690 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 11691 int callingUid = Binder.getCallingUid(); 11692 if (callingUid != Process.SYSTEM_UID) { 11693 throw new SecurityException( 11694 "clearPackagePersistentPreferredActivities can only be run by the system"); 11695 } 11696 ArrayList<PersistentPreferredActivity> removed = null; 11697 boolean changed = false; 11698 synchronized (mPackages) { 11699 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 11700 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 11701 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 11702 .valueAt(i); 11703 if (userId != thisUserId) { 11704 continue; 11705 } 11706 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 11707 while (it.hasNext()) { 11708 PersistentPreferredActivity ppa = it.next(); 11709 // Mark entry for removal only if it matches the package name. 11710 if (ppa.mComponent.getPackageName().equals(packageName)) { 11711 if (removed == null) { 11712 removed = new ArrayList<PersistentPreferredActivity>(); 11713 } 11714 removed.add(ppa); 11715 } 11716 } 11717 if (removed != null) { 11718 for (int j=0; j<removed.size(); j++) { 11719 PersistentPreferredActivity ppa = removed.get(j); 11720 ppir.removeFilter(ppa); 11721 } 11722 changed = true; 11723 } 11724 } 11725 11726 if (changed) { 11727 mSettings.writePackageRestrictionsLPr(userId); 11728 } 11729 } 11730 } 11731 11732 @Override 11733 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 11734 int ownerUserId, int sourceUserId, int targetUserId, int flags) { 11735 mContext.enforceCallingOrSelfPermission( 11736 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11737 int callingUid = Binder.getCallingUid(); 11738 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11739 if (intentFilter.countActions() == 0) { 11740 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 11741 return; 11742 } 11743 synchronized (mPackages) { 11744 CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter, 11745 ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags); 11746 mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter); 11747 mSettings.writePackageRestrictionsLPr(sourceUserId); 11748 } 11749 } 11750 11751 @Override 11752 public void addCrossProfileIntentsForPackage(String packageName, 11753 int sourceUserId, int targetUserId) { 11754 mContext.enforceCallingOrSelfPermission( 11755 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11756 mSettings.addCrossProfilePackage(packageName, sourceUserId, targetUserId); 11757 mSettings.writePackageRestrictionsLPr(sourceUserId); 11758 } 11759 11760 @Override 11761 public void removeCrossProfileIntentsForPackage(String packageName, 11762 int sourceUserId, int targetUserId) { 11763 mContext.enforceCallingOrSelfPermission( 11764 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11765 mSettings.removeCrossProfilePackage(packageName, sourceUserId, targetUserId); 11766 mSettings.writePackageRestrictionsLPr(sourceUserId); 11767 } 11768 11769 @Override 11770 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage, 11771 int ownerUserId) { 11772 mContext.enforceCallingOrSelfPermission( 11773 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11774 int callingUid = Binder.getCallingUid(); 11775 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11776 int callingUserId = UserHandle.getUserId(callingUid); 11777 synchronized (mPackages) { 11778 CrossProfileIntentResolver resolver = 11779 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11780 HashSet<CrossProfileIntentFilter> set = 11781 new HashSet<CrossProfileIntentFilter>(resolver.filterSet()); 11782 for (CrossProfileIntentFilter filter : set) { 11783 if (filter.getOwnerPackage().equals(ownerPackage) 11784 && filter.getOwnerUserId() == callingUserId) { 11785 resolver.removeFilter(filter); 11786 } 11787 } 11788 mSettings.writePackageRestrictionsLPr(sourceUserId); 11789 } 11790 } 11791 11792 // Enforcing that callingUid is owning pkg on userId 11793 private void enforceOwnerRights(String pkg, int userId, int callingUid) { 11794 // The system owns everything. 11795 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 11796 return; 11797 } 11798 int callingUserId = UserHandle.getUserId(callingUid); 11799 if (callingUserId != userId) { 11800 throw new SecurityException("calling uid " + callingUid 11801 + " pretends to own " + pkg + " on user " + userId + " but belongs to user " 11802 + callingUserId); 11803 } 11804 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 11805 if (pi == null) { 11806 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 11807 + callingUserId); 11808 } 11809 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 11810 throw new SecurityException("Calling uid " + callingUid 11811 + " does not own package " + pkg); 11812 } 11813 } 11814 11815 @Override 11816 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 11817 Intent intent = new Intent(Intent.ACTION_MAIN); 11818 intent.addCategory(Intent.CATEGORY_HOME); 11819 11820 final int callingUserId = UserHandle.getCallingUserId(); 11821 List<ResolveInfo> list = queryIntentActivities(intent, null, 11822 PackageManager.GET_META_DATA, callingUserId); 11823 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 11824 true, false, false, callingUserId); 11825 11826 allHomeCandidates.clear(); 11827 if (list != null) { 11828 for (ResolveInfo ri : list) { 11829 allHomeCandidates.add(ri); 11830 } 11831 } 11832 return (preferred == null || preferred.activityInfo == null) 11833 ? null 11834 : new ComponentName(preferred.activityInfo.packageName, 11835 preferred.activityInfo.name); 11836 } 11837 11838 /** 11839 * Check if calling UID is the current home app. This handles both the case 11840 * where the user has selected a specific home app, and where there is only 11841 * one home app. 11842 */ 11843 public boolean checkCallerIsHomeApp() { 11844 final Intent intent = new Intent(Intent.ACTION_MAIN); 11845 intent.addCategory(Intent.CATEGORY_HOME); 11846 11847 final int callingUid = Binder.getCallingUid(); 11848 final int callingUserId = UserHandle.getCallingUserId(); 11849 final List<ResolveInfo> allHomes = queryIntentActivities(intent, null, 0, callingUserId); 11850 final ResolveInfo preferredHome = findPreferredActivity(intent, null, 0, allHomes, 0, true, 11851 false, false, callingUserId); 11852 11853 if (preferredHome != null) { 11854 if (callingUid == preferredHome.activityInfo.applicationInfo.uid) { 11855 return true; 11856 } 11857 } else { 11858 for (ResolveInfo info : allHomes) { 11859 if (callingUid == info.activityInfo.applicationInfo.uid) { 11860 return true; 11861 } 11862 } 11863 } 11864 11865 return false; 11866 } 11867 11868 /** 11869 * Enforce that calling UID is the current home app. This handles both the 11870 * case where the user has selected a specific home app, and where there is 11871 * only one home app. 11872 */ 11873 public void enforceCallerIsHomeApp() { 11874 if (!checkCallerIsHomeApp()) { 11875 throw new SecurityException("Caller is not currently selected home app"); 11876 } 11877 } 11878 11879 @Override 11880 public void setApplicationEnabledSetting(String appPackageName, 11881 int newState, int flags, int userId, String callingPackage) { 11882 if (!sUserManager.exists(userId)) return; 11883 if (callingPackage == null) { 11884 callingPackage = Integer.toString(Binder.getCallingUid()); 11885 } 11886 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 11887 } 11888 11889 @Override 11890 public void setComponentEnabledSetting(ComponentName componentName, 11891 int newState, int flags, int userId) { 11892 if (!sUserManager.exists(userId)) return; 11893 setEnabledSetting(componentName.getPackageName(), 11894 componentName.getClassName(), newState, flags, userId, null); 11895 } 11896 11897 private void setEnabledSetting(final String packageName, String className, int newState, 11898 final int flags, int userId, String callingPackage) { 11899 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 11900 || newState == COMPONENT_ENABLED_STATE_ENABLED 11901 || newState == COMPONENT_ENABLED_STATE_DISABLED 11902 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 11903 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 11904 throw new IllegalArgumentException("Invalid new component state: " 11905 + newState); 11906 } 11907 PackageSetting pkgSetting; 11908 final int uid = Binder.getCallingUid(); 11909 final int permission = mContext.checkCallingOrSelfPermission( 11910 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11911 enforceCrossUserPermission(uid, userId, false, "set enabled"); 11912 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11913 boolean sendNow = false; 11914 boolean isApp = (className == null); 11915 String componentName = isApp ? packageName : className; 11916 int packageUid = -1; 11917 ArrayList<String> components; 11918 11919 // writer 11920 synchronized (mPackages) { 11921 pkgSetting = mSettings.mPackages.get(packageName); 11922 if (pkgSetting == null) { 11923 if (className == null) { 11924 throw new IllegalArgumentException( 11925 "Unknown package: " + packageName); 11926 } 11927 throw new IllegalArgumentException( 11928 "Unknown component: " + packageName 11929 + "/" + className); 11930 } 11931 // Allow root and verify that userId is not being specified by a different user 11932 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 11933 throw new SecurityException( 11934 "Permission Denial: attempt to change component state from pid=" 11935 + Binder.getCallingPid() 11936 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 11937 } 11938 if (className == null) { 11939 // We're dealing with an application/package level state change 11940 if (pkgSetting.getEnabled(userId) == newState) { 11941 // Nothing to do 11942 return; 11943 } 11944 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 11945 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 11946 // Don't care about who enables an app. 11947 callingPackage = null; 11948 } 11949 pkgSetting.setEnabled(newState, userId, callingPackage); 11950 // pkgSetting.pkg.mSetEnabled = newState; 11951 } else { 11952 // We're dealing with a component level state change 11953 // First, verify that this is a valid class name. 11954 PackageParser.Package pkg = pkgSetting.pkg; 11955 if (pkg == null || !pkg.hasComponentClassName(className)) { 11956 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 11957 throw new IllegalArgumentException("Component class " + className 11958 + " does not exist in " + packageName); 11959 } else { 11960 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 11961 + className + " does not exist in " + packageName); 11962 } 11963 } 11964 switch (newState) { 11965 case COMPONENT_ENABLED_STATE_ENABLED: 11966 if (!pkgSetting.enableComponentLPw(className, userId)) { 11967 return; 11968 } 11969 break; 11970 case COMPONENT_ENABLED_STATE_DISABLED: 11971 if (!pkgSetting.disableComponentLPw(className, userId)) { 11972 return; 11973 } 11974 break; 11975 case COMPONENT_ENABLED_STATE_DEFAULT: 11976 if (!pkgSetting.restoreComponentLPw(className, userId)) { 11977 return; 11978 } 11979 break; 11980 default: 11981 Slog.e(TAG, "Invalid new component state: " + newState); 11982 return; 11983 } 11984 } 11985 mSettings.writePackageRestrictionsLPr(userId); 11986 components = mPendingBroadcasts.get(userId, packageName); 11987 final boolean newPackage = components == null; 11988 if (newPackage) { 11989 components = new ArrayList<String>(); 11990 } 11991 if (!components.contains(componentName)) { 11992 components.add(componentName); 11993 } 11994 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 11995 sendNow = true; 11996 // Purge entry from pending broadcast list if another one exists already 11997 // since we are sending one right away. 11998 mPendingBroadcasts.remove(userId, packageName); 11999 } else { 12000 if (newPackage) { 12001 mPendingBroadcasts.put(userId, packageName, components); 12002 } 12003 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 12004 // Schedule a message 12005 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 12006 } 12007 } 12008 } 12009 12010 long callingId = Binder.clearCallingIdentity(); 12011 try { 12012 if (sendNow) { 12013 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 12014 sendPackageChangedBroadcast(packageName, 12015 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 12016 } 12017 } finally { 12018 Binder.restoreCallingIdentity(callingId); 12019 } 12020 } 12021 12022 private void sendPackageChangedBroadcast(String packageName, 12023 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 12024 if (DEBUG_INSTALL) 12025 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 12026 + componentNames); 12027 Bundle extras = new Bundle(4); 12028 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 12029 String nameList[] = new String[componentNames.size()]; 12030 componentNames.toArray(nameList); 12031 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 12032 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 12033 extras.putInt(Intent.EXTRA_UID, packageUid); 12034 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 12035 new int[] {UserHandle.getUserId(packageUid)}); 12036 } 12037 12038 @Override 12039 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 12040 if (!sUserManager.exists(userId)) return; 12041 final int uid = Binder.getCallingUid(); 12042 final int permission = mContext.checkCallingOrSelfPermission( 12043 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 12044 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 12045 enforceCrossUserPermission(uid, userId, true, "stop package"); 12046 // writer 12047 synchronized (mPackages) { 12048 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 12049 uid, userId)) { 12050 scheduleWritePackageRestrictionsLocked(userId); 12051 } 12052 } 12053 } 12054 12055 @Override 12056 public String getInstallerPackageName(String packageName) { 12057 // reader 12058 synchronized (mPackages) { 12059 return mSettings.getInstallerPackageNameLPr(packageName); 12060 } 12061 } 12062 12063 @Override 12064 public int getApplicationEnabledSetting(String packageName, int userId) { 12065 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12066 int uid = Binder.getCallingUid(); 12067 enforceCrossUserPermission(uid, userId, false, "get enabled"); 12068 // reader 12069 synchronized (mPackages) { 12070 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 12071 } 12072 } 12073 12074 @Override 12075 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 12076 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12077 int uid = Binder.getCallingUid(); 12078 enforceCrossUserPermission(uid, userId, false, "get component enabled"); 12079 // reader 12080 synchronized (mPackages) { 12081 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 12082 } 12083 } 12084 12085 @Override 12086 public void enterSafeMode() { 12087 enforceSystemOrRoot("Only the system can request entering safe mode"); 12088 12089 if (!mSystemReady) { 12090 mSafeMode = true; 12091 } 12092 } 12093 12094 @Override 12095 public void systemReady() { 12096 mSystemReady = true; 12097 12098 // Read the compatibilty setting when the system is ready. 12099 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 12100 mContext.getContentResolver(), 12101 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 12102 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 12103 if (DEBUG_SETTINGS) { 12104 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 12105 } 12106 12107 synchronized (mPackages) { 12108 // Verify that all of the preferred activity components actually 12109 // exist. It is possible for applications to be updated and at 12110 // that point remove a previously declared activity component that 12111 // had been set as a preferred activity. We try to clean this up 12112 // the next time we encounter that preferred activity, but it is 12113 // possible for the user flow to never be able to return to that 12114 // situation so here we do a sanity check to make sure we haven't 12115 // left any junk around. 12116 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 12117 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12118 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12119 removed.clear(); 12120 for (PreferredActivity pa : pir.filterSet()) { 12121 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 12122 removed.add(pa); 12123 } 12124 } 12125 if (removed.size() > 0) { 12126 for (int r=0; r<removed.size(); r++) { 12127 PreferredActivity pa = removed.get(r); 12128 Slog.w(TAG, "Removing dangling preferred activity: " 12129 + pa.mPref.mComponent); 12130 pir.removeFilter(pa); 12131 } 12132 mSettings.writePackageRestrictionsLPr( 12133 mSettings.mPreferredActivities.keyAt(i)); 12134 } 12135 } 12136 } 12137 sUserManager.systemReady(); 12138 } 12139 12140 @Override 12141 public boolean isSafeMode() { 12142 return mSafeMode; 12143 } 12144 12145 @Override 12146 public boolean hasSystemUidErrors() { 12147 return mHasSystemUidErrors; 12148 } 12149 12150 static String arrayToString(int[] array) { 12151 StringBuffer buf = new StringBuffer(128); 12152 buf.append('['); 12153 if (array != null) { 12154 for (int i=0; i<array.length; i++) { 12155 if (i > 0) buf.append(", "); 12156 buf.append(array[i]); 12157 } 12158 } 12159 buf.append(']'); 12160 return buf.toString(); 12161 } 12162 12163 static class DumpState { 12164 public static final int DUMP_LIBS = 1 << 0; 12165 public static final int DUMP_FEATURES = 1 << 1; 12166 public static final int DUMP_RESOLVERS = 1 << 2; 12167 public static final int DUMP_PERMISSIONS = 1 << 3; 12168 public static final int DUMP_PACKAGES = 1 << 4; 12169 public static final int DUMP_SHARED_USERS = 1 << 5; 12170 public static final int DUMP_MESSAGES = 1 << 6; 12171 public static final int DUMP_PROVIDERS = 1 << 7; 12172 public static final int DUMP_VERIFIERS = 1 << 8; 12173 public static final int DUMP_PREFERRED = 1 << 9; 12174 public static final int DUMP_PREFERRED_XML = 1 << 10; 12175 public static final int DUMP_KEYSETS = 1 << 11; 12176 public static final int DUMP_VERSION = 1 << 12; 12177 public static final int DUMP_INSTALLS = 1 << 13; 12178 12179 public static final int OPTION_SHOW_FILTERS = 1 << 0; 12180 12181 private int mTypes; 12182 12183 private int mOptions; 12184 12185 private boolean mTitlePrinted; 12186 12187 private SharedUserSetting mSharedUser; 12188 12189 public boolean isDumping(int type) { 12190 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 12191 return true; 12192 } 12193 12194 return (mTypes & type) != 0; 12195 } 12196 12197 public void setDump(int type) { 12198 mTypes |= type; 12199 } 12200 12201 public boolean isOptionEnabled(int option) { 12202 return (mOptions & option) != 0; 12203 } 12204 12205 public void setOptionEnabled(int option) { 12206 mOptions |= option; 12207 } 12208 12209 public boolean onTitlePrinted() { 12210 final boolean printed = mTitlePrinted; 12211 mTitlePrinted = true; 12212 return printed; 12213 } 12214 12215 public boolean getTitlePrinted() { 12216 return mTitlePrinted; 12217 } 12218 12219 public void setTitlePrinted(boolean enabled) { 12220 mTitlePrinted = enabled; 12221 } 12222 12223 public SharedUserSetting getSharedUser() { 12224 return mSharedUser; 12225 } 12226 12227 public void setSharedUser(SharedUserSetting user) { 12228 mSharedUser = user; 12229 } 12230 } 12231 12232 @Override 12233 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 12234 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 12235 != PackageManager.PERMISSION_GRANTED) { 12236 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 12237 + Binder.getCallingPid() 12238 + ", uid=" + Binder.getCallingUid() 12239 + " without permission " 12240 + android.Manifest.permission.DUMP); 12241 return; 12242 } 12243 12244 DumpState dumpState = new DumpState(); 12245 boolean fullPreferred = false; 12246 boolean checkin = false; 12247 12248 String packageName = null; 12249 12250 int opti = 0; 12251 while (opti < args.length) { 12252 String opt = args[opti]; 12253 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 12254 break; 12255 } 12256 opti++; 12257 if ("-a".equals(opt)) { 12258 // Right now we only know how to print all. 12259 } else if ("-h".equals(opt)) { 12260 pw.println("Package manager dump options:"); 12261 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 12262 pw.println(" --checkin: dump for a checkin"); 12263 pw.println(" -f: print details of intent filters"); 12264 pw.println(" -h: print this help"); 12265 pw.println(" cmd may be one of:"); 12266 pw.println(" l[ibraries]: list known shared libraries"); 12267 pw.println(" f[ibraries]: list device features"); 12268 pw.println(" k[eysets]: print known keysets"); 12269 pw.println(" r[esolvers]: dump intent resolvers"); 12270 pw.println(" perm[issions]: dump permissions"); 12271 pw.println(" pref[erred]: print preferred package settings"); 12272 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 12273 pw.println(" prov[iders]: dump content providers"); 12274 pw.println(" p[ackages]: dump installed packages"); 12275 pw.println(" s[hared-users]: dump shared user IDs"); 12276 pw.println(" m[essages]: print collected runtime messages"); 12277 pw.println(" v[erifiers]: print package verifier info"); 12278 pw.println(" version: print database version info"); 12279 pw.println(" write: write current settings now"); 12280 pw.println(" <package.name>: info about given package"); 12281 pw.println(" installs: details about install sessions"); 12282 return; 12283 } else if ("--checkin".equals(opt)) { 12284 checkin = true; 12285 } else if ("-f".equals(opt)) { 12286 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12287 } else { 12288 pw.println("Unknown argument: " + opt + "; use -h for help"); 12289 } 12290 } 12291 12292 // Is the caller requesting to dump a particular piece of data? 12293 if (opti < args.length) { 12294 String cmd = args[opti]; 12295 opti++; 12296 // Is this a package name? 12297 if ("android".equals(cmd) || cmd.contains(".")) { 12298 packageName = cmd; 12299 // When dumping a single package, we always dump all of its 12300 // filter information since the amount of data will be reasonable. 12301 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12302 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 12303 dumpState.setDump(DumpState.DUMP_LIBS); 12304 } else if ("f".equals(cmd) || "features".equals(cmd)) { 12305 dumpState.setDump(DumpState.DUMP_FEATURES); 12306 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 12307 dumpState.setDump(DumpState.DUMP_RESOLVERS); 12308 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 12309 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 12310 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 12311 dumpState.setDump(DumpState.DUMP_PREFERRED); 12312 } else if ("preferred-xml".equals(cmd)) { 12313 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 12314 if (opti < args.length && "--full".equals(args[opti])) { 12315 fullPreferred = true; 12316 opti++; 12317 } 12318 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 12319 dumpState.setDump(DumpState.DUMP_PACKAGES); 12320 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 12321 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 12322 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 12323 dumpState.setDump(DumpState.DUMP_PROVIDERS); 12324 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 12325 dumpState.setDump(DumpState.DUMP_MESSAGES); 12326 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 12327 dumpState.setDump(DumpState.DUMP_VERIFIERS); 12328 } else if ("version".equals(cmd)) { 12329 dumpState.setDump(DumpState.DUMP_VERSION); 12330 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 12331 dumpState.setDump(DumpState.DUMP_KEYSETS); 12332 } else if ("write".equals(cmd)) { 12333 synchronized (mPackages) { 12334 mSettings.writeLPr(); 12335 pw.println("Settings written."); 12336 return; 12337 } 12338 } else if ("installs".equals(cmd)) { 12339 dumpState.setDump(DumpState.DUMP_INSTALLS); 12340 } 12341 } 12342 12343 if (checkin) { 12344 pw.println("vers,1"); 12345 } 12346 12347 // reader 12348 synchronized (mPackages) { 12349 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 12350 if (!checkin) { 12351 if (dumpState.onTitlePrinted()) 12352 pw.println(); 12353 pw.println("Database versions:"); 12354 pw.print(" SDK Version:"); 12355 pw.print(" internal="); 12356 pw.print(mSettings.mInternalSdkPlatform); 12357 pw.print(" external="); 12358 pw.println(mSettings.mExternalSdkPlatform); 12359 pw.print(" DB Version:"); 12360 pw.print(" internal="); 12361 pw.print(mSettings.mInternalDatabaseVersion); 12362 pw.print(" external="); 12363 pw.println(mSettings.mExternalDatabaseVersion); 12364 } 12365 } 12366 12367 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 12368 if (!checkin) { 12369 if (dumpState.onTitlePrinted()) 12370 pw.println(); 12371 pw.println("Verifiers:"); 12372 pw.print(" Required: "); 12373 pw.print(mRequiredVerifierPackage); 12374 pw.print(" (uid="); 12375 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 12376 pw.println(")"); 12377 } else if (mRequiredVerifierPackage != null) { 12378 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 12379 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 12380 } 12381 } 12382 12383 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 12384 boolean printedHeader = false; 12385 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 12386 while (it.hasNext()) { 12387 String name = it.next(); 12388 SharedLibraryEntry ent = mSharedLibraries.get(name); 12389 if (!checkin) { 12390 if (!printedHeader) { 12391 if (dumpState.onTitlePrinted()) 12392 pw.println(); 12393 pw.println("Libraries:"); 12394 printedHeader = true; 12395 } 12396 pw.print(" "); 12397 } else { 12398 pw.print("lib,"); 12399 } 12400 pw.print(name); 12401 if (!checkin) { 12402 pw.print(" -> "); 12403 } 12404 if (ent.path != null) { 12405 if (!checkin) { 12406 pw.print("(jar) "); 12407 pw.print(ent.path); 12408 } else { 12409 pw.print(",jar,"); 12410 pw.print(ent.path); 12411 } 12412 } else { 12413 if (!checkin) { 12414 pw.print("(apk) "); 12415 pw.print(ent.apk); 12416 } else { 12417 pw.print(",apk,"); 12418 pw.print(ent.apk); 12419 } 12420 } 12421 pw.println(); 12422 } 12423 } 12424 12425 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 12426 if (dumpState.onTitlePrinted()) 12427 pw.println(); 12428 if (!checkin) { 12429 pw.println("Features:"); 12430 } 12431 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 12432 while (it.hasNext()) { 12433 String name = it.next(); 12434 if (!checkin) { 12435 pw.print(" "); 12436 } else { 12437 pw.print("feat,"); 12438 } 12439 pw.println(name); 12440 } 12441 } 12442 12443 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 12444 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 12445 : "Activity Resolver Table:", " ", packageName, 12446 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12447 dumpState.setTitlePrinted(true); 12448 } 12449 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 12450 : "Receiver Resolver Table:", " ", packageName, 12451 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12452 dumpState.setTitlePrinted(true); 12453 } 12454 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 12455 : "Service Resolver Table:", " ", packageName, 12456 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12457 dumpState.setTitlePrinted(true); 12458 } 12459 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 12460 : "Provider Resolver Table:", " ", packageName, 12461 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12462 dumpState.setTitlePrinted(true); 12463 } 12464 } 12465 12466 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 12467 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12468 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12469 int user = mSettings.mPreferredActivities.keyAt(i); 12470 if (pir.dump(pw, 12471 dumpState.getTitlePrinted() 12472 ? "\nPreferred Activities User " + user + ":" 12473 : "Preferred Activities User " + user + ":", " ", 12474 packageName, true)) { 12475 dumpState.setTitlePrinted(true); 12476 } 12477 } 12478 } 12479 12480 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 12481 pw.flush(); 12482 FileOutputStream fout = new FileOutputStream(fd); 12483 BufferedOutputStream str = new BufferedOutputStream(fout); 12484 XmlSerializer serializer = new FastXmlSerializer(); 12485 try { 12486 serializer.setOutput(str, "utf-8"); 12487 serializer.startDocument(null, true); 12488 serializer.setFeature( 12489 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 12490 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 12491 serializer.endDocument(); 12492 serializer.flush(); 12493 } catch (IllegalArgumentException e) { 12494 pw.println("Failed writing: " + e); 12495 } catch (IllegalStateException e) { 12496 pw.println("Failed writing: " + e); 12497 } catch (IOException e) { 12498 pw.println("Failed writing: " + e); 12499 } 12500 } 12501 12502 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 12503 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 12504 if (packageName == null) { 12505 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 12506 if (iperm == 0) { 12507 if (dumpState.onTitlePrinted()) 12508 pw.println(); 12509 pw.println("AppOp Permissions:"); 12510 } 12511 pw.print(" AppOp Permission "); 12512 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 12513 pw.println(":"); 12514 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 12515 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 12516 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 12517 } 12518 } 12519 } 12520 } 12521 12522 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 12523 boolean printedSomething = false; 12524 for (PackageParser.Provider p : mProviders.mProviders.values()) { 12525 if (packageName != null && !packageName.equals(p.info.packageName)) { 12526 continue; 12527 } 12528 if (!printedSomething) { 12529 if (dumpState.onTitlePrinted()) 12530 pw.println(); 12531 pw.println("Registered ContentProviders:"); 12532 printedSomething = true; 12533 } 12534 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 12535 pw.print(" "); pw.println(p.toString()); 12536 } 12537 printedSomething = false; 12538 for (Map.Entry<String, PackageParser.Provider> entry : 12539 mProvidersByAuthority.entrySet()) { 12540 PackageParser.Provider p = entry.getValue(); 12541 if (packageName != null && !packageName.equals(p.info.packageName)) { 12542 continue; 12543 } 12544 if (!printedSomething) { 12545 if (dumpState.onTitlePrinted()) 12546 pw.println(); 12547 pw.println("ContentProvider Authorities:"); 12548 printedSomething = true; 12549 } 12550 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 12551 pw.print(" "); pw.println(p.toString()); 12552 if (p.info != null && p.info.applicationInfo != null) { 12553 final String appInfo = p.info.applicationInfo.toString(); 12554 pw.print(" applicationInfo="); pw.println(appInfo); 12555 } 12556 } 12557 } 12558 12559 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 12560 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 12561 } 12562 12563 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 12564 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 12565 } 12566 12567 if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 12568 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState); 12569 } 12570 12571 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS)) { 12572 if (dumpState.onTitlePrinted()) pw.println(); 12573 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 12574 } 12575 12576 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 12577 if (dumpState.onTitlePrinted()) pw.println(); 12578 mSettings.dumpReadMessagesLPr(pw, dumpState); 12579 12580 pw.println(); 12581 pw.println("Package warning messages:"); 12582 final File fname = getSettingsProblemFile(); 12583 FileInputStream in = null; 12584 try { 12585 in = new FileInputStream(fname); 12586 final int avail = in.available(); 12587 final byte[] data = new byte[avail]; 12588 in.read(data); 12589 pw.print(new String(data)); 12590 } catch (FileNotFoundException e) { 12591 } catch (IOException e) { 12592 } finally { 12593 if (in != null) { 12594 try { 12595 in.close(); 12596 } catch (IOException e) { 12597 } 12598 } 12599 } 12600 } 12601 } 12602 } 12603 12604 // ------- apps on sdcard specific code ------- 12605 static final boolean DEBUG_SD_INSTALL = false; 12606 12607 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 12608 12609 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 12610 12611 private boolean mMediaMounted = false; 12612 12613 static String getEncryptKey() { 12614 try { 12615 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 12616 SD_ENCRYPTION_KEYSTORE_NAME); 12617 if (sdEncKey == null) { 12618 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 12619 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 12620 if (sdEncKey == null) { 12621 Slog.e(TAG, "Failed to create encryption keys"); 12622 return null; 12623 } 12624 } 12625 return sdEncKey; 12626 } catch (NoSuchAlgorithmException nsae) { 12627 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 12628 return null; 12629 } catch (IOException ioe) { 12630 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 12631 return null; 12632 } 12633 } 12634 12635 /* 12636 * Update media status on PackageManager. 12637 */ 12638 @Override 12639 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 12640 int callingUid = Binder.getCallingUid(); 12641 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 12642 throw new SecurityException("Media status can only be updated by the system"); 12643 } 12644 // reader; this apparently protects mMediaMounted, but should probably 12645 // be a different lock in that case. 12646 synchronized (mPackages) { 12647 Log.i(TAG, "Updating external media status from " 12648 + (mMediaMounted ? "mounted" : "unmounted") + " to " 12649 + (mediaStatus ? "mounted" : "unmounted")); 12650 if (DEBUG_SD_INSTALL) 12651 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 12652 + ", mMediaMounted=" + mMediaMounted); 12653 if (mediaStatus == mMediaMounted) { 12654 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 12655 : 0, -1); 12656 mHandler.sendMessage(msg); 12657 return; 12658 } 12659 mMediaMounted = mediaStatus; 12660 } 12661 // Queue up an async operation since the package installation may take a 12662 // little while. 12663 mHandler.post(new Runnable() { 12664 public void run() { 12665 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 12666 } 12667 }); 12668 } 12669 12670 /** 12671 * Called by MountService when the initial ASECs to scan are available. 12672 * Should block until all the ASEC containers are finished being scanned. 12673 */ 12674 public void scanAvailableAsecs() { 12675 updateExternalMediaStatusInner(true, false, false); 12676 if (mShouldRestoreconData) { 12677 SELinuxMMAC.setRestoreconDone(); 12678 mShouldRestoreconData = false; 12679 } 12680 } 12681 12682 /* 12683 * Collect information of applications on external media, map them against 12684 * existing containers and update information based on current mount status. 12685 * Please note that we always have to report status if reportStatus has been 12686 * set to true especially when unloading packages. 12687 */ 12688 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 12689 boolean externalStorage) { 12690 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 12691 int[] uidArr = EmptyArray.INT; 12692 12693 final String[] list = PackageHelper.getSecureContainerList(); 12694 if (ArrayUtils.isEmpty(list)) { 12695 Log.i(TAG, "No secure containers found"); 12696 } else { 12697 // Process list of secure containers and categorize them 12698 // as active or stale based on their package internal state. 12699 12700 // reader 12701 synchronized (mPackages) { 12702 for (String cid : list) { 12703 // Leave stages untouched for now; installer service owns them 12704 if (PackageInstallerService.isStageName(cid)) continue; 12705 12706 if (DEBUG_SD_INSTALL) 12707 Log.i(TAG, "Processing container " + cid); 12708 String pkgName = getAsecPackageName(cid); 12709 if (pkgName == null) { 12710 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 12711 continue; 12712 } 12713 if (DEBUG_SD_INSTALL) 12714 Log.i(TAG, "Looking for pkg : " + pkgName); 12715 12716 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12717 if (ps == null) { 12718 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 12719 continue; 12720 } 12721 12722 /* 12723 * Skip packages that are not external if we're unmounting 12724 * external storage. 12725 */ 12726 if (externalStorage && !isMounted && !isExternal(ps)) { 12727 continue; 12728 } 12729 12730 final AsecInstallArgs args = new AsecInstallArgs(cid, 12731 getAppDexInstructionSets(ps), isForwardLocked(ps), isMultiArch(ps)); 12732 // The package status is changed only if the code path 12733 // matches between settings and the container id. 12734 if (ps.codePathString != null 12735 && ps.codePathString.startsWith(args.getCodePath())) { 12736 if (DEBUG_SD_INSTALL) { 12737 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 12738 + " at code path: " + ps.codePathString); 12739 } 12740 12741 // We do have a valid package installed on sdcard 12742 processCids.put(args, ps.codePathString); 12743 final int uid = ps.appId; 12744 if (uid != -1) { 12745 uidArr = ArrayUtils.appendInt(uidArr, uid); 12746 } 12747 } else { 12748 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 12749 + ps.codePathString); 12750 } 12751 } 12752 } 12753 12754 Arrays.sort(uidArr); 12755 } 12756 12757 // Process packages with valid entries. 12758 if (isMounted) { 12759 if (DEBUG_SD_INSTALL) 12760 Log.i(TAG, "Loading packages"); 12761 loadMediaPackages(processCids, uidArr); 12762 startCleaningPackages(); 12763 mInstallerService.onSecureContainersAvailable(); 12764 } else { 12765 if (DEBUG_SD_INSTALL) 12766 Log.i(TAG, "Unloading packages"); 12767 unloadMediaPackages(processCids, uidArr, reportStatus); 12768 } 12769 } 12770 12771 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 12772 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 12773 int size = pkgList.size(); 12774 if (size > 0) { 12775 // Send broadcasts here 12776 Bundle extras = new Bundle(); 12777 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 12778 .toArray(new String[size])); 12779 if (uidArr != null) { 12780 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 12781 } 12782 if (replacing) { 12783 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 12784 } 12785 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 12786 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 12787 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 12788 } 12789 } 12790 12791 /* 12792 * Look at potentially valid container ids from processCids If package 12793 * information doesn't match the one on record or package scanning fails, 12794 * the cid is added to list of removeCids. We currently don't delete stale 12795 * containers. 12796 */ 12797 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 12798 ArrayList<String> pkgList = new ArrayList<String>(); 12799 Set<AsecInstallArgs> keys = processCids.keySet(); 12800 12801 for (AsecInstallArgs args : keys) { 12802 String codePath = processCids.get(args); 12803 if (DEBUG_SD_INSTALL) 12804 Log.i(TAG, "Loading container : " + args.cid); 12805 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12806 try { 12807 // Make sure there are no container errors first. 12808 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 12809 Slog.e(TAG, "Failed to mount cid : " + args.cid 12810 + " when installing from sdcard"); 12811 continue; 12812 } 12813 // Check code path here. 12814 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 12815 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 12816 + " does not match one in settings " + codePath); 12817 continue; 12818 } 12819 // Parse package 12820 int parseFlags = mDefParseFlags; 12821 if (args.isExternal()) { 12822 parseFlags |= PackageParser.PARSE_ON_SDCARD; 12823 } 12824 if (args.isFwdLocked()) { 12825 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 12826 } 12827 12828 synchronized (mInstallLock) { 12829 PackageParser.Package pkg = null; 12830 try { 12831 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 12832 } catch (PackageManagerException e) { 12833 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 12834 } 12835 // Scan the package 12836 if (pkg != null) { 12837 /* 12838 * TODO why is the lock being held? doPostInstall is 12839 * called in other places without the lock. This needs 12840 * to be straightened out. 12841 */ 12842 // writer 12843 synchronized (mPackages) { 12844 retCode = PackageManager.INSTALL_SUCCEEDED; 12845 pkgList.add(pkg.packageName); 12846 // Post process args 12847 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 12848 pkg.applicationInfo.uid); 12849 } 12850 } else { 12851 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 12852 } 12853 } 12854 12855 } finally { 12856 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 12857 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 12858 } 12859 } 12860 } 12861 // writer 12862 synchronized (mPackages) { 12863 // If the platform SDK has changed since the last time we booted, 12864 // we need to re-grant app permission to catch any new ones that 12865 // appear. This is really a hack, and means that apps can in some 12866 // cases get permissions that the user didn't initially explicitly 12867 // allow... it would be nice to have some better way to handle 12868 // this situation. 12869 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 12870 if (regrantPermissions) 12871 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 12872 + mSdkVersion + "; regranting permissions for external storage"); 12873 mSettings.mExternalSdkPlatform = mSdkVersion; 12874 12875 // Make sure group IDs have been assigned, and any permission 12876 // changes in other apps are accounted for 12877 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 12878 | (regrantPermissions 12879 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 12880 : 0)); 12881 12882 mSettings.updateExternalDatabaseVersion(); 12883 12884 // can downgrade to reader 12885 // Persist settings 12886 mSettings.writeLPr(); 12887 } 12888 // Send a broadcast to let everyone know we are done processing 12889 if (pkgList.size() > 0) { 12890 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12891 } 12892 } 12893 12894 /* 12895 * Utility method to unload a list of specified containers 12896 */ 12897 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 12898 // Just unmount all valid containers. 12899 for (AsecInstallArgs arg : cidArgs) { 12900 synchronized (mInstallLock) { 12901 arg.doPostDeleteLI(false); 12902 } 12903 } 12904 } 12905 12906 /* 12907 * Unload packages mounted on external media. This involves deleting package 12908 * data from internal structures, sending broadcasts about diabled packages, 12909 * gc'ing to free up references, unmounting all secure containers 12910 * corresponding to packages on external media, and posting a 12911 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 12912 * that we always have to post this message if status has been requested no 12913 * matter what. 12914 */ 12915 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 12916 final boolean reportStatus) { 12917 if (DEBUG_SD_INSTALL) 12918 Log.i(TAG, "unloading media packages"); 12919 ArrayList<String> pkgList = new ArrayList<String>(); 12920 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 12921 final Set<AsecInstallArgs> keys = processCids.keySet(); 12922 for (AsecInstallArgs args : keys) { 12923 String pkgName = args.getPackageName(); 12924 if (DEBUG_SD_INSTALL) 12925 Log.i(TAG, "Trying to unload pkg : " + pkgName); 12926 // Delete package internally 12927 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 12928 synchronized (mInstallLock) { 12929 boolean res = deletePackageLI(pkgName, null, false, null, null, 12930 PackageManager.DELETE_KEEP_DATA, outInfo, false); 12931 if (res) { 12932 pkgList.add(pkgName); 12933 } else { 12934 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 12935 failedList.add(args); 12936 } 12937 } 12938 } 12939 12940 // reader 12941 synchronized (mPackages) { 12942 // We didn't update the settings after removing each package; 12943 // write them now for all packages. 12944 mSettings.writeLPr(); 12945 } 12946 12947 // We have to absolutely send UPDATED_MEDIA_STATUS only 12948 // after confirming that all the receivers processed the ordered 12949 // broadcast when packages get disabled, force a gc to clean things up. 12950 // and unload all the containers. 12951 if (pkgList.size() > 0) { 12952 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 12953 new IIntentReceiver.Stub() { 12954 public void performReceive(Intent intent, int resultCode, String data, 12955 Bundle extras, boolean ordered, boolean sticky, 12956 int sendingUser) throws RemoteException { 12957 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 12958 reportStatus ? 1 : 0, 1, keys); 12959 mHandler.sendMessage(msg); 12960 } 12961 }); 12962 } else { 12963 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 12964 keys); 12965 mHandler.sendMessage(msg); 12966 } 12967 } 12968 12969 /** Binder call */ 12970 @Override 12971 public void movePackage(final String packageName, final IPackageMoveObserver observer, 12972 final int flags) { 12973 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 12974 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 12975 int returnCode = PackageManager.MOVE_SUCCEEDED; 12976 int currFlags = 0; 12977 int newFlags = 0; 12978 // reader 12979 synchronized (mPackages) { 12980 PackageParser.Package pkg = mPackages.get(packageName); 12981 if (pkg == null) { 12982 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12983 } else { 12984 // Disable moving fwd locked apps and system packages 12985 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 12986 Slog.w(TAG, "Cannot move system application"); 12987 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 12988 } else if (pkg.mOperationPending) { 12989 Slog.w(TAG, "Attempt to move package which has pending operations"); 12990 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 12991 } else { 12992 // Find install location first 12993 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 12994 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 12995 Slog.w(TAG, "Ambigous flags specified for move location."); 12996 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12997 } else { 12998 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL 12999 : PackageManager.INSTALL_INTERNAL; 13000 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL 13001 : PackageManager.INSTALL_INTERNAL; 13002 13003 if (newFlags == currFlags) { 13004 Slog.w(TAG, "No move required. Trying to move to same location"); 13005 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 13006 } else { 13007 if (isForwardLocked(pkg)) { 13008 currFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13009 newFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13010 } 13011 } 13012 } 13013 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13014 pkg.mOperationPending = true; 13015 } 13016 } 13017 } 13018 13019 /* 13020 * TODO this next block probably shouldn't be inside the lock. We 13021 * can't guarantee these won't change after this is fired off 13022 * anyway. 13023 */ 13024 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 13025 processPendingMove(new MoveParams(null, observer, 0, packageName, null, -1, user, false), 13026 returnCode); 13027 } else { 13028 Message msg = mHandler.obtainMessage(INIT_COPY); 13029 final String[] instructionSets = getAppDexInstructionSets(pkg.applicationInfo); 13030 final boolean multiArch = isMultiArch(pkg.applicationInfo); 13031 InstallArgs srcArgs = createInstallArgsForExisting(currFlags, 13032 pkg.applicationInfo.getCodePath(), pkg.applicationInfo.getResourcePath(), 13033 pkg.applicationInfo.nativeLibraryRootDir, instructionSets, multiArch); 13034 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName, 13035 instructionSets, pkg.applicationInfo.uid, user, multiArch); 13036 msg.obj = mp; 13037 mHandler.sendMessage(msg); 13038 } 13039 } 13040 } 13041 13042 private void processPendingMove(final MoveParams mp, final int currentStatus) { 13043 // Queue up an async operation since the package deletion may take a 13044 // little while. 13045 mHandler.post(new Runnable() { 13046 public void run() { 13047 // TODO fix this; this does nothing. 13048 mHandler.removeCallbacks(this); 13049 int returnCode = currentStatus; 13050 if (currentStatus == PackageManager.MOVE_SUCCEEDED) { 13051 int uidArr[] = null; 13052 ArrayList<String> pkgList = null; 13053 synchronized (mPackages) { 13054 PackageParser.Package pkg = mPackages.get(mp.packageName); 13055 if (pkg == null) { 13056 Slog.w(TAG, " Package " + mp.packageName 13057 + " doesn't exist. Aborting move"); 13058 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 13059 } else if (!mp.srcArgs.getCodePath().equals( 13060 pkg.applicationInfo.getCodePath())) { 13061 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " 13062 + mp.srcArgs.getCodePath() + " to " 13063 + pkg.applicationInfo.getCodePath() 13064 + " Aborting move and returning error"); 13065 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 13066 } else { 13067 uidArr = new int[] { 13068 pkg.applicationInfo.uid 13069 }; 13070 pkgList = new ArrayList<String>(); 13071 pkgList.add(mp.packageName); 13072 } 13073 } 13074 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13075 // Send resources unavailable broadcast 13076 sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null); 13077 // Update package code and resource paths 13078 synchronized (mInstallLock) { 13079 synchronized (mPackages) { 13080 PackageParser.Package pkg = mPackages.get(mp.packageName); 13081 // Recheck for package again. 13082 if (pkg == null) { 13083 Slog.w(TAG, " Package " + mp.packageName 13084 + " doesn't exist. Aborting move"); 13085 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 13086 } else if (!mp.srcArgs.getCodePath().equals( 13087 pkg.applicationInfo.getCodePath())) { 13088 Slog.w(TAG, "Package " + mp.packageName 13089 + " code path changed from " + mp.srcArgs.getCodePath() 13090 + " to " + pkg.applicationInfo.getCodePath() 13091 + " Aborting move and returning error"); 13092 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 13093 } else { 13094 final String oldCodePath = pkg.codePath; 13095 final String newCodePath = mp.targetArgs.getCodePath(); 13096 final String newResPath = mp.targetArgs.getResourcePath(); 13097 // TODO: This assumes the new style of installation. 13098 // should we look at legacyNativeLibraryPath ? 13099 final String newNativeRoot = new File(pkg.codePath, LIB_DIR_NAME).getAbsolutePath(); 13100 final File newNativeDir = new File(newNativeRoot); 13101 13102 if (!isForwardLocked(pkg) && !isExternal(pkg)) { 13103 // TODO(multiArch): Fix this so that it looks at the existing 13104 // recorded CPU abis from the package. There's no need for a separate 13105 // round of ABI scanning here. 13106 NativeLibraryHelper.Handle handle = null; 13107 try { 13108 handle = NativeLibraryHelper.Handle.create( 13109 new File(newCodePath)); 13110 final int abi = NativeLibraryHelper.findSupportedAbi( 13111 handle, Build.SUPPORTED_ABIS); 13112 if (abi >= 0) { 13113 NativeLibraryHelper.copyNativeBinariesIfNeededLI( 13114 handle, newNativeDir, Build.SUPPORTED_ABIS[abi]); 13115 } 13116 } catch (IOException ioe) { 13117 Slog.w(TAG, "Unable to extract native libs for package :" 13118 + mp.packageName, ioe); 13119 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 13120 } finally { 13121 IoUtils.closeQuietly(handle); 13122 } 13123 } 13124 13125 final int[] users = sUserManager.getUserIds(); 13126 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13127 for (int user : users) { 13128 // TODO(multiArch): Fix this so that it links to the 13129 // correct directory. We're currently pointing to root. but we 13130 // must point to the arch specific subdirectory (if applicable). 13131 // 13132 // TODO(multiArch): Bogus reference to nativeLibraryDir. 13133 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, 13134 newNativeRoot, user) < 0) { 13135 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 13136 } 13137 } 13138 } 13139 13140 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13141 pkg.codePath = newCodePath; 13142 pkg.baseCodePath = newCodePath; 13143 // Move dex files around 13144 if (moveDexFilesLI(oldCodePath, pkg) != PackageManager.INSTALL_SUCCEEDED) { 13145 // Moving of dex files failed. Set 13146 // error code and abort move. 13147 pkg.codePath = oldCodePath; 13148 pkg.baseCodePath = oldCodePath; 13149 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 13150 } 13151 } 13152 13153 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13154 pkg.applicationInfo.setCodePath(newCodePath); 13155 pkg.applicationInfo.setBaseCodePath(newCodePath); 13156 pkg.applicationInfo.setSplitCodePaths(null); 13157 pkg.applicationInfo.setResourcePath(newResPath); 13158 pkg.applicationInfo.setBaseResourcePath(newResPath); 13159 pkg.applicationInfo.setSplitResourcePaths(null); 13160 13161 PackageSetting ps = (PackageSetting) pkg.mExtras; 13162 ps.codePath = new File(pkg.applicationInfo.getCodePath()); 13163 ps.codePathString = ps.codePath.getPath(); 13164 ps.resourcePath = new File(pkg.applicationInfo.getResourcePath()); 13165 ps.resourcePathString = ps.resourcePath.getPath(); 13166 13167 // Note that we don't have to recalculate the primary and secondary 13168 // CPU ABIs because they must already have been calculated during the 13169 // initial install of the app. 13170 ps.legacyNativeLibraryPathString = null; 13171 13172 // Set the application info flag 13173 // correctly. 13174 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) { 13175 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE; 13176 } else { 13177 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE; 13178 } 13179 ps.setFlags(pkg.applicationInfo.flags); 13180 mAppDirs.remove(oldCodePath); 13181 mAppDirs.put(newCodePath, pkg); 13182 // Persist settings 13183 mSettings.writeLPr(); 13184 } 13185 } 13186 } 13187 } 13188 // Send resources available broadcast 13189 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 13190 } 13191 } 13192 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 13193 // Clean up failed installation 13194 if (mp.targetArgs != null) { 13195 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR, 13196 -1); 13197 } 13198 } else { 13199 // Force a gc to clear things up. 13200 Runtime.getRuntime().gc(); 13201 // Delete older code 13202 synchronized (mInstallLock) { 13203 mp.srcArgs.doPostDeleteLI(true); 13204 } 13205 } 13206 13207 // Allow more operations on this file if we didn't fail because 13208 // an operation was already pending for this package. 13209 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) { 13210 synchronized (mPackages) { 13211 PackageParser.Package pkg = mPackages.get(mp.packageName); 13212 if (pkg != null) { 13213 pkg.mOperationPending = false; 13214 } 13215 } 13216 } 13217 13218 IPackageMoveObserver observer = mp.observer; 13219 if (observer != null) { 13220 try { 13221 observer.packageMoved(mp.packageName, returnCode); 13222 } catch (RemoteException e) { 13223 Log.i(TAG, "Observer no longer exists."); 13224 } 13225 } 13226 } 13227 }); 13228 } 13229 13230 @Override 13231 public boolean setInstallLocation(int loc) { 13232 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 13233 null); 13234 if (getInstallLocation() == loc) { 13235 return true; 13236 } 13237 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 13238 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 13239 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 13240 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 13241 return true; 13242 } 13243 return false; 13244 } 13245 13246 @Override 13247 public int getInstallLocation() { 13248 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13249 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 13250 PackageHelper.APP_INSTALL_AUTO); 13251 } 13252 13253 /** Called by UserManagerService */ 13254 void cleanUpUserLILPw(int userHandle) { 13255 mDirtyUsers.remove(userHandle); 13256 mSettings.removeUserLPw(userHandle); 13257 mPendingBroadcasts.remove(userHandle); 13258 if (mInstaller != null) { 13259 // Technically, we shouldn't be doing this with the package lock 13260 // held. However, this is very rare, and there is already so much 13261 // other disk I/O going on, that we'll let it slide for now. 13262 mInstaller.removeUserDataDirs(userHandle); 13263 } 13264 mUserNeedsBadging.delete(userHandle); 13265 } 13266 13267 /** Called by UserManagerService */ 13268 void createNewUserLILPw(int userHandle, File path) { 13269 if (mInstaller != null) { 13270 mInstaller.createUserConfig(userHandle); 13271 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 13272 } 13273 } 13274 13275 @Override 13276 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 13277 mContext.enforceCallingOrSelfPermission( 13278 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13279 "Only package verification agents can read the verifier device identity"); 13280 13281 synchronized (mPackages) { 13282 return mSettings.getVerifierDeviceIdentityLPw(); 13283 } 13284 } 13285 13286 @Override 13287 public void setPermissionEnforced(String permission, boolean enforced) { 13288 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 13289 if (READ_EXTERNAL_STORAGE.equals(permission)) { 13290 synchronized (mPackages) { 13291 if (mSettings.mReadExternalStorageEnforced == null 13292 || mSettings.mReadExternalStorageEnforced != enforced) { 13293 mSettings.mReadExternalStorageEnforced = enforced; 13294 mSettings.writeLPr(); 13295 } 13296 } 13297 // kill any non-foreground processes so we restart them and 13298 // grant/revoke the GID. 13299 final IActivityManager am = ActivityManagerNative.getDefault(); 13300 if (am != null) { 13301 final long token = Binder.clearCallingIdentity(); 13302 try { 13303 am.killProcessesBelowForeground("setPermissionEnforcement"); 13304 } catch (RemoteException e) { 13305 } finally { 13306 Binder.restoreCallingIdentity(token); 13307 } 13308 } 13309 } else { 13310 throw new IllegalArgumentException("No selective enforcement for " + permission); 13311 } 13312 } 13313 13314 @Override 13315 @Deprecated 13316 public boolean isPermissionEnforced(String permission) { 13317 return true; 13318 } 13319 13320 @Override 13321 public boolean isStorageLow() { 13322 final long token = Binder.clearCallingIdentity(); 13323 try { 13324 final DeviceStorageMonitorInternal 13325 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13326 if (dsm != null) { 13327 return dsm.isMemoryLow(); 13328 } else { 13329 return false; 13330 } 13331 } finally { 13332 Binder.restoreCallingIdentity(token); 13333 } 13334 } 13335 13336 @Override 13337 public IPackageInstaller getPackageInstaller() { 13338 return mInstallerService; 13339 } 13340 13341 private boolean userNeedsBadging(int userId) { 13342 int index = mUserNeedsBadging.indexOfKey(userId); 13343 if (index < 0) { 13344 final UserInfo userInfo; 13345 final long token = Binder.clearCallingIdentity(); 13346 try { 13347 userInfo = sUserManager.getUserInfo(userId); 13348 } finally { 13349 Binder.restoreCallingIdentity(token); 13350 } 13351 final boolean b; 13352 if (userInfo != null && userInfo.isManagedProfile()) { 13353 b = true; 13354 } else { 13355 b = false; 13356 } 13357 mUserNeedsBadging.put(userId, b); 13358 return b; 13359 } 13360 return mUserNeedsBadging.valueAt(index); 13361 } 13362 13363 @Override 13364 public KeySetHandle getKeySetByAlias(String packageName, String alias) { 13365 if (packageName == null || alias == null) { 13366 return null; 13367 } 13368 synchronized(mPackages) { 13369 final PackageParser.Package pkg = mPackages.get(packageName); 13370 if (pkg == null) { 13371 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13372 throw new IllegalArgumentException("Unknown package: " + packageName); 13373 } 13374 if (pkg.applicationInfo.uid != Binder.getCallingUid() 13375 && Process.SYSTEM_UID != Binder.getCallingUid()) { 13376 throw new SecurityException("May not access KeySets defined by" 13377 + " aliases in other applications."); 13378 } 13379 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13380 return ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias); 13381 } 13382 } 13383 13384 @Override 13385 public KeySetHandle getSigningKeySet(String packageName) { 13386 if (packageName == null) { 13387 return null; 13388 } 13389 synchronized(mPackages) { 13390 final PackageParser.Package pkg = mPackages.get(packageName); 13391 if (pkg == null) { 13392 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13393 throw new IllegalArgumentException("Unknown package: " + packageName); 13394 } 13395 if (pkg.applicationInfo.uid != Binder.getCallingUid() 13396 && Process.SYSTEM_UID != Binder.getCallingUid()) { 13397 throw new SecurityException("May not access signing KeySet of other apps."); 13398 } 13399 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13400 return ksms.getSigningKeySetByPackageNameLPr(packageName); 13401 } 13402 } 13403 13404 @Override 13405 public boolean isPackageSignedByKeySet(String packageName, IBinder ks) { 13406 if (packageName == null || ks == null) { 13407 return false; 13408 } 13409 synchronized(mPackages) { 13410 final PackageParser.Package pkg = mPackages.get(packageName); 13411 if (pkg == null) { 13412 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13413 throw new IllegalArgumentException("Unknown package: " + packageName); 13414 } 13415 if (ks instanceof KeySetHandle) { 13416 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13417 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ks); 13418 } 13419 return false; 13420 } 13421 } 13422 13423 @Override 13424 public boolean isPackageSignedByKeySetExactly(String packageName, IBinder ks) { 13425 if (packageName == null || ks == null) { 13426 return false; 13427 } 13428 synchronized(mPackages) { 13429 final PackageParser.Package pkg = mPackages.get(packageName); 13430 if (pkg == null) { 13431 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13432 throw new IllegalArgumentException("Unknown package: " + packageName); 13433 } 13434 if (ks instanceof KeySetHandle) { 13435 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13436 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ks); 13437 } 13438 return false; 13439 } 13440 } 13441} 13442