PackageManagerService.java revision d382be9b220d8f68d095cd5df56c0b900af44f9a
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS; 20import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 21import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 26import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 27import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 28import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 29import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 30import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 32import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 33import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 34import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 36import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 37import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 38import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 39import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 41import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 42import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 44import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 45import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 46import static android.content.pm.PackageParser.isApkFile; 47import static android.os.Process.PACKAGE_INFO_GID; 48import static android.os.Process.SYSTEM_UID; 49import static android.system.OsConstants.O_CREAT; 50import static android.system.OsConstants.O_RDWR; 51import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 52import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 53import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 54import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 55import static com.android.internal.util.ArrayUtils.appendInt; 56import static com.android.internal.util.ArrayUtils.removeInt; 57 58import android.util.ArrayMap; 59 60import com.android.internal.R; 61import com.android.internal.app.IMediaContainerService; 62import com.android.internal.app.ResolverActivity; 63import com.android.internal.content.NativeLibraryHelper; 64import com.android.internal.content.PackageHelper; 65import com.android.internal.os.IParcelFileDescriptorFactory; 66import com.android.internal.util.ArrayUtils; 67import com.android.internal.util.FastPrintWriter; 68import com.android.internal.util.FastXmlSerializer; 69import com.android.internal.util.IndentingPrintWriter; 70import com.android.server.EventLogTags; 71import com.android.server.IntentResolver; 72import com.android.server.LocalServices; 73import com.android.server.ServiceThread; 74import com.android.server.SystemConfig; 75import com.android.server.Watchdog; 76import com.android.server.pm.Settings.DatabaseVersion; 77import com.android.server.storage.DeviceStorageMonitorInternal; 78 79import org.xmlpull.v1.XmlSerializer; 80 81import android.app.ActivityManager; 82import android.app.ActivityManagerNative; 83import android.app.IActivityManager; 84import android.app.admin.IDevicePolicyManager; 85import android.app.backup.IBackupManager; 86import android.content.BroadcastReceiver; 87import android.content.ComponentName; 88import android.content.Context; 89import android.content.IIntentReceiver; 90import android.content.Intent; 91import android.content.IntentFilter; 92import android.content.IntentSender; 93import android.content.IntentSender.SendIntentException; 94import android.content.ServiceConnection; 95import android.content.pm.ActivityInfo; 96import android.content.pm.ApplicationInfo; 97import android.content.pm.FeatureInfo; 98import android.content.pm.IPackageDataObserver; 99import android.content.pm.IPackageDeleteObserver; 100import android.content.pm.IPackageDeleteObserver2; 101import android.content.pm.IPackageInstallObserver2; 102import android.content.pm.IPackageInstaller; 103import android.content.pm.IPackageManager; 104import android.content.pm.IPackageMoveObserver; 105import android.content.pm.IPackageStatsObserver; 106import android.content.pm.InstrumentationInfo; 107import android.content.pm.KeySet; 108import android.content.pm.ManifestDigest; 109import android.content.pm.PackageCleanItem; 110import android.content.pm.PackageInfo; 111import android.content.pm.PackageInfoLite; 112import android.content.pm.PackageInstaller; 113import android.content.pm.PackageManager; 114import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 115import android.content.pm.PackageParser.ActivityIntentInfo; 116import android.content.pm.PackageParser.PackageLite; 117import android.content.pm.PackageParser.PackageParserException; 118import android.content.pm.PackageParser; 119import android.content.pm.PackageStats; 120import android.content.pm.PackageUserState; 121import android.content.pm.ParceledListSlice; 122import android.content.pm.PermissionGroupInfo; 123import android.content.pm.PermissionInfo; 124import android.content.pm.ProviderInfo; 125import android.content.pm.ResolveInfo; 126import android.content.pm.ServiceInfo; 127import android.content.pm.Signature; 128import android.content.pm.UserInfo; 129import android.content.pm.VerificationParams; 130import android.content.pm.VerifierDeviceIdentity; 131import android.content.pm.VerifierInfo; 132import android.content.res.Resources; 133import android.hardware.display.DisplayManager; 134import android.net.Uri; 135import android.os.Binder; 136import android.os.Build; 137import android.os.Bundle; 138import android.os.Environment; 139import android.os.Environment.UserEnvironment; 140import android.os.storage.StorageManager; 141import android.os.FileUtils; 142import android.os.Handler; 143import android.os.IBinder; 144import android.os.Looper; 145import android.os.Message; 146import android.os.Parcel; 147import android.os.ParcelFileDescriptor; 148import android.os.Process; 149import android.os.RemoteException; 150import android.os.SELinux; 151import android.os.ServiceManager; 152import android.os.SystemClock; 153import android.os.SystemProperties; 154import android.os.UserHandle; 155import android.os.UserManager; 156import android.security.KeyStore; 157import android.security.SystemKeyStore; 158import android.system.ErrnoException; 159import android.system.Os; 160import android.system.StructStat; 161import android.text.TextUtils; 162import android.util.ArraySet; 163import android.util.AtomicFile; 164import android.util.DisplayMetrics; 165import android.util.EventLog; 166import android.util.ExceptionUtils; 167import android.util.Log; 168import android.util.LogPrinter; 169import android.util.PrintStreamPrinter; 170import android.util.Slog; 171import android.util.SparseArray; 172import android.util.SparseBooleanArray; 173import android.view.Display; 174 175import java.io.BufferedInputStream; 176import java.io.BufferedOutputStream; 177import java.io.File; 178import java.io.FileDescriptor; 179import java.io.FileInputStream; 180import java.io.FileNotFoundException; 181import java.io.FileOutputStream; 182import java.io.FilenameFilter; 183import java.io.IOException; 184import java.io.InputStream; 185import java.io.PrintWriter; 186import java.nio.charset.StandardCharsets; 187import java.security.NoSuchAlgorithmException; 188import java.security.PublicKey; 189import java.security.cert.CertificateEncodingException; 190import java.security.cert.CertificateException; 191import java.text.SimpleDateFormat; 192import java.util.ArrayList; 193import java.util.Arrays; 194import java.util.Collection; 195import java.util.Collections; 196import java.util.Comparator; 197import java.util.Date; 198import java.util.HashMap; 199import java.util.HashSet; 200import java.util.Iterator; 201import java.util.List; 202import java.util.Map; 203import java.util.Set; 204import java.util.concurrent.atomic.AtomicBoolean; 205import java.util.concurrent.atomic.AtomicLong; 206 207import dalvik.system.DexFile; 208import dalvik.system.StaleDexCacheError; 209import dalvik.system.VMRuntime; 210 211import libcore.io.IoUtils; 212import libcore.util.EmptyArray; 213 214/** 215 * Keep track of all those .apks everywhere. 216 * 217 * This is very central to the platform's security; please run the unit 218 * tests whenever making modifications here: 219 * 220mmm frameworks/base/tests/AndroidTests 221adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 222adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 223 * 224 * {@hide} 225 */ 226public class PackageManagerService extends IPackageManager.Stub { 227 static final String TAG = "PackageManager"; 228 static final boolean DEBUG_SETTINGS = false; 229 static final boolean DEBUG_PREFERRED = false; 230 static final boolean DEBUG_UPGRADE = false; 231 private static final boolean DEBUG_INSTALL = false; 232 private static final boolean DEBUG_REMOVE = false; 233 private static final boolean DEBUG_BROADCASTS = false; 234 private static final boolean DEBUG_SHOW_INFO = false; 235 private static final boolean DEBUG_PACKAGE_INFO = false; 236 private static final boolean DEBUG_INTENT_MATCHING = false; 237 private static final boolean DEBUG_PACKAGE_SCANNING = false; 238 private static final boolean DEBUG_VERIFY = false; 239 private static final boolean DEBUG_DEXOPT = false; 240 private static final boolean DEBUG_ABI_SELECTION = false; 241 242 private static final int RADIO_UID = Process.PHONE_UID; 243 private static final int LOG_UID = Process.LOG_UID; 244 private static final int NFC_UID = Process.NFC_UID; 245 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 246 private static final int SHELL_UID = Process.SHELL_UID; 247 248 // Cap the size of permission trees that 3rd party apps can define 249 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 250 251 // Suffix used during package installation when copying/moving 252 // package apks to install directory. 253 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 254 255 static final int SCAN_NO_DEX = 1<<1; 256 static final int SCAN_FORCE_DEX = 1<<2; 257 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 258 static final int SCAN_NEW_INSTALL = 1<<4; 259 static final int SCAN_NO_PATHS = 1<<5; 260 static final int SCAN_UPDATE_TIME = 1<<6; 261 static final int SCAN_DEFER_DEX = 1<<7; 262 static final int SCAN_BOOTING = 1<<8; 263 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 264 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 265 static final int SCAN_REPLACING = 1<<11; 266 267 static final int REMOVE_CHATTY = 1<<16; 268 269 /** 270 * Timeout (in milliseconds) after which the watchdog should declare that 271 * our handler thread is wedged. The usual default for such things is one 272 * minute but we sometimes do very lengthy I/O operations on this thread, 273 * such as installing multi-gigabyte applications, so ours needs to be longer. 274 */ 275 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 276 277 /** 278 * Whether verification is enabled by default. 279 */ 280 private static final boolean DEFAULT_VERIFY_ENABLE = true; 281 282 /** 283 * The default maximum time to wait for the verification agent to return in 284 * milliseconds. 285 */ 286 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 287 288 /** 289 * The default response for package verification timeout. 290 * 291 * This can be either PackageManager.VERIFICATION_ALLOW or 292 * PackageManager.VERIFICATION_REJECT. 293 */ 294 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 295 296 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 297 298 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 299 DEFAULT_CONTAINER_PACKAGE, 300 "com.android.defcontainer.DefaultContainerService"); 301 302 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 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 boolean mLazyDexOpt; 321 final DisplayMetrics mMetrics; 322 final int mDefParseFlags; 323 final String[] mSeparateProcesses; 324 325 // This is where all application persistent data goes. 326 final File mAppDataDir; 327 328 // This is where all application persistent data goes for secondary users. 329 final File mUserAppDataDir; 330 331 /** The location for ASEC container files on internal storage. */ 332 final String mAsecInternalPath; 333 334 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 335 // LOCK HELD. Can be called with mInstallLock held. 336 final Installer mInstaller; 337 338 /** Directory where installed third-party apps stored */ 339 final File mAppInstallDir; 340 341 /** 342 * Directory to which applications installed internally have their 343 * 32 bit native libraries copied. 344 */ 345 private File mAppLib32InstallDir; 346 347 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 348 // apps. 349 final File mDrmAppPrivateInstallDir; 350 351 // ---------------------------------------------------------------- 352 353 // Lock for state used when installing and doing other long running 354 // operations. Methods that must be called with this lock held have 355 // the suffix "LI". 356 final Object mInstallLock = new Object(); 357 358 // ---------------------------------------------------------------- 359 360 // Keys are String (package name), values are Package. This also serves 361 // as the lock for the global state. Methods that must be called with 362 // this lock held have the prefix "LP". 363 final HashMap<String, PackageParser.Package> mPackages = 364 new HashMap<String, PackageParser.Package>(); 365 366 // Tracks available target package names -> overlay package paths. 367 final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays = 368 new HashMap<String, HashMap<String, PackageParser.Package>>(); 369 370 final Settings mSettings; 371 boolean mRestoredSettings; 372 373 // System configuration read by SystemConfig. 374 final int[] mGlobalGids; 375 final SparseArray<HashSet<String>> mSystemPermissions; 376 final HashMap<String, FeatureInfo> mAvailableFeatures; 377 378 // If mac_permissions.xml was found for seinfo labeling. 379 boolean mFoundPolicyFile; 380 381 // If a recursive restorecon of /data/data/<pkg> is needed. 382 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 383 384 public static final class SharedLibraryEntry { 385 public final String path; 386 public final String apk; 387 388 SharedLibraryEntry(String _path, String _apk) { 389 path = _path; 390 apk = _apk; 391 } 392 } 393 394 // Currently known shared libraries. 395 final HashMap<String, SharedLibraryEntry> mSharedLibraries = 396 new HashMap<String, SharedLibraryEntry>(); 397 398 // All available activities, for your resolving pleasure. 399 final ActivityIntentResolver mActivities = 400 new ActivityIntentResolver(); 401 402 // All available receivers, for your resolving pleasure. 403 final ActivityIntentResolver mReceivers = 404 new ActivityIntentResolver(); 405 406 // All available services, for your resolving pleasure. 407 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 408 409 // All available providers, for your resolving pleasure. 410 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 411 412 // Mapping from provider base names (first directory in content URI codePath) 413 // to the provider information. 414 final HashMap<String, PackageParser.Provider> mProvidersByAuthority = 415 new HashMap<String, PackageParser.Provider>(); 416 417 // Mapping from instrumentation class names to info about them. 418 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 419 new HashMap<ComponentName, PackageParser.Instrumentation>(); 420 421 // Mapping from permission names to info about them. 422 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups = 423 new HashMap<String, PackageParser.PermissionGroup>(); 424 425 // Packages whose data we have transfered into another package, thus 426 // should no longer exist. 427 final HashSet<String> mTransferedPackages = new HashSet<String>(); 428 429 // Broadcast actions that are only available to the system. 430 final HashSet<String> mProtectedBroadcasts = new HashSet<String>(); 431 432 /** List of packages waiting for verification. */ 433 final SparseArray<PackageVerificationState> mPendingVerification 434 = new SparseArray<PackageVerificationState>(); 435 436 /** Set of packages associated with each app op permission. */ 437 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 438 439 final PackageInstallerService mInstallerService; 440 441 HashSet<PackageParser.Package> mDeferredDexOpt = null; 442 443 // Cache of users who need badging. 444 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 445 446 /** Token for keys in mPendingVerification. */ 447 private int mPendingVerificationToken = 0; 448 449 boolean mSystemReady; 450 boolean mSafeMode; 451 boolean mHasSystemUidErrors; 452 453 ApplicationInfo mAndroidApplication; 454 final ActivityInfo mResolveActivity = new ActivityInfo(); 455 final ResolveInfo mResolveInfo = new ResolveInfo(); 456 ComponentName mResolveComponentName; 457 PackageParser.Package mPlatformPackage; 458 ComponentName mCustomResolverComponentName; 459 460 boolean mResolverReplaced = false; 461 462 // Set of pending broadcasts for aggregating enable/disable of components. 463 static class PendingPackageBroadcasts { 464 // for each user id, a map of <package name -> components within that package> 465 final SparseArray<HashMap<String, ArrayList<String>>> mUidMap; 466 467 public PendingPackageBroadcasts() { 468 mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2); 469 } 470 471 public ArrayList<String> get(int userId, String packageName) { 472 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 473 return packages.get(packageName); 474 } 475 476 public void put(int userId, String packageName, ArrayList<String> components) { 477 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 478 packages.put(packageName, components); 479 } 480 481 public void remove(int userId, String packageName) { 482 HashMap<String, ArrayList<String>> packages = mUidMap.get(userId); 483 if (packages != null) { 484 packages.remove(packageName); 485 } 486 } 487 488 public void remove(int userId) { 489 mUidMap.remove(userId); 490 } 491 492 public int userIdCount() { 493 return mUidMap.size(); 494 } 495 496 public int userIdAt(int n) { 497 return mUidMap.keyAt(n); 498 } 499 500 public HashMap<String, ArrayList<String>> packagesForUserId(int userId) { 501 return mUidMap.get(userId); 502 } 503 504 public int size() { 505 // total number of pending broadcast entries across all userIds 506 int num = 0; 507 for (int i = 0; i< mUidMap.size(); i++) { 508 num += mUidMap.valueAt(i).size(); 509 } 510 return num; 511 } 512 513 public void clear() { 514 mUidMap.clear(); 515 } 516 517 private HashMap<String, ArrayList<String>> getOrAllocate(int userId) { 518 HashMap<String, ArrayList<String>> map = mUidMap.get(userId); 519 if (map == null) { 520 map = new HashMap<String, ArrayList<String>>(); 521 mUidMap.put(userId, map); 522 } 523 return map; 524 } 525 } 526 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 527 528 // Service Connection to remote media container service to copy 529 // package uri's from external media onto secure containers 530 // or internal storage. 531 private IMediaContainerService mContainerService = null; 532 533 static final int SEND_PENDING_BROADCAST = 1; 534 static final int MCS_BOUND = 3; 535 static final int END_COPY = 4; 536 static final int INIT_COPY = 5; 537 static final int MCS_UNBIND = 6; 538 static final int START_CLEANING_PACKAGE = 7; 539 static final int FIND_INSTALL_LOC = 8; 540 static final int POST_INSTALL = 9; 541 static final int MCS_RECONNECT = 10; 542 static final int MCS_GIVE_UP = 11; 543 static final int UPDATED_MEDIA_STATUS = 12; 544 static final int WRITE_SETTINGS = 13; 545 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 546 static final int PACKAGE_VERIFIED = 15; 547 static final int CHECK_PENDING_VERIFICATION = 16; 548 549 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 550 551 // Delay time in millisecs 552 static final int BROADCAST_DELAY = 10 * 1000; 553 554 static UserManagerService sUserManager; 555 556 // Stores a list of users whose package restrictions file needs to be updated 557 private HashSet<Integer> mDirtyUsers = new HashSet<Integer>(); 558 559 final private DefaultContainerConnection mDefContainerConn = 560 new DefaultContainerConnection(); 561 class DefaultContainerConnection implements ServiceConnection { 562 public void onServiceConnected(ComponentName name, IBinder service) { 563 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 564 IMediaContainerService imcs = 565 IMediaContainerService.Stub.asInterface(service); 566 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 567 } 568 569 public void onServiceDisconnected(ComponentName name) { 570 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 571 } 572 }; 573 574 // Recordkeeping of restore-after-install operations that are currently in flight 575 // between the Package Manager and the Backup Manager 576 class PostInstallData { 577 public InstallArgs args; 578 public PackageInstalledInfo res; 579 580 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 581 args = _a; 582 res = _r; 583 } 584 }; 585 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 586 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 587 588 private final String mRequiredVerifierPackage; 589 590 private final PackageUsage mPackageUsage = new PackageUsage(); 591 592 private class PackageUsage { 593 private static final int WRITE_INTERVAL 594 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 595 596 private final Object mFileLock = new Object(); 597 private final AtomicLong mLastWritten = new AtomicLong(0); 598 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 599 600 private boolean mIsHistoricalPackageUsageAvailable = true; 601 602 boolean isHistoricalPackageUsageAvailable() { 603 return mIsHistoricalPackageUsageAvailable; 604 } 605 606 void write(boolean force) { 607 if (force) { 608 writeInternal(); 609 return; 610 } 611 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 612 && !DEBUG_DEXOPT) { 613 return; 614 } 615 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 616 new Thread("PackageUsage_DiskWriter") { 617 @Override 618 public void run() { 619 try { 620 writeInternal(); 621 } finally { 622 mBackgroundWriteRunning.set(false); 623 } 624 } 625 }.start(); 626 } 627 } 628 629 private void writeInternal() { 630 synchronized (mPackages) { 631 synchronized (mFileLock) { 632 AtomicFile file = getFile(); 633 FileOutputStream f = null; 634 try { 635 f = file.startWrite(); 636 BufferedOutputStream out = new BufferedOutputStream(f); 637 FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID); 638 StringBuilder sb = new StringBuilder(); 639 for (PackageParser.Package pkg : mPackages.values()) { 640 if (pkg.mLastPackageUsageTimeInMills == 0) { 641 continue; 642 } 643 sb.setLength(0); 644 sb.append(pkg.packageName); 645 sb.append(' '); 646 sb.append((long)pkg.mLastPackageUsageTimeInMills); 647 sb.append('\n'); 648 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 649 } 650 out.flush(); 651 file.finishWrite(f); 652 } catch (IOException e) { 653 if (f != null) { 654 file.failWrite(f); 655 } 656 Log.e(TAG, "Failed to write package usage times", e); 657 } 658 } 659 } 660 mLastWritten.set(SystemClock.elapsedRealtime()); 661 } 662 663 void readLP() { 664 synchronized (mFileLock) { 665 AtomicFile file = getFile(); 666 BufferedInputStream in = null; 667 try { 668 in = new BufferedInputStream(file.openRead()); 669 StringBuffer sb = new StringBuffer(); 670 while (true) { 671 String packageName = readToken(in, sb, ' '); 672 if (packageName == null) { 673 break; 674 } 675 String timeInMillisString = readToken(in, sb, '\n'); 676 if (timeInMillisString == null) { 677 throw new IOException("Failed to find last usage time for package " 678 + packageName); 679 } 680 PackageParser.Package pkg = mPackages.get(packageName); 681 if (pkg == null) { 682 continue; 683 } 684 long timeInMillis; 685 try { 686 timeInMillis = Long.parseLong(timeInMillisString.toString()); 687 } catch (NumberFormatException e) { 688 throw new IOException("Failed to parse " + timeInMillisString 689 + " as a long.", e); 690 } 691 pkg.mLastPackageUsageTimeInMills = timeInMillis; 692 } 693 } catch (FileNotFoundException expected) { 694 mIsHistoricalPackageUsageAvailable = false; 695 } catch (IOException e) { 696 Log.w(TAG, "Failed to read package usage times", e); 697 } finally { 698 IoUtils.closeQuietly(in); 699 } 700 } 701 mLastWritten.set(SystemClock.elapsedRealtime()); 702 } 703 704 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 705 throws IOException { 706 sb.setLength(0); 707 while (true) { 708 int ch = in.read(); 709 if (ch == -1) { 710 if (sb.length() == 0) { 711 return null; 712 } 713 throw new IOException("Unexpected EOF"); 714 } 715 if (ch == endOfToken) { 716 return sb.toString(); 717 } 718 sb.append((char)ch); 719 } 720 } 721 722 private AtomicFile getFile() { 723 File dataDir = Environment.getDataDirectory(); 724 File systemDir = new File(dataDir, "system"); 725 File fname = new File(systemDir, "package-usage.list"); 726 return new AtomicFile(fname); 727 } 728 } 729 730 class PackageHandler extends Handler { 731 private boolean mBound = false; 732 final ArrayList<HandlerParams> mPendingInstalls = 733 new ArrayList<HandlerParams>(); 734 735 private boolean connectToService() { 736 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 737 " DefaultContainerService"); 738 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 739 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 740 if (mContext.bindServiceAsUser(service, mDefContainerConn, 741 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 742 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 743 mBound = true; 744 return true; 745 } 746 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 747 return false; 748 } 749 750 private void disconnectService() { 751 mContainerService = null; 752 mBound = false; 753 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 754 mContext.unbindService(mDefContainerConn); 755 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 756 } 757 758 PackageHandler(Looper looper) { 759 super(looper); 760 } 761 762 public void handleMessage(Message msg) { 763 try { 764 doHandleMessage(msg); 765 } finally { 766 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 767 } 768 } 769 770 void doHandleMessage(Message msg) { 771 switch (msg.what) { 772 case INIT_COPY: { 773 HandlerParams params = (HandlerParams) msg.obj; 774 int idx = mPendingInstalls.size(); 775 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 776 // If a bind was already initiated we dont really 777 // need to do anything. The pending install 778 // will be processed later on. 779 if (!mBound) { 780 // If this is the only one pending we might 781 // have to bind to the service again. 782 if (!connectToService()) { 783 Slog.e(TAG, "Failed to bind to media container service"); 784 params.serviceError(); 785 return; 786 } else { 787 // Once we bind to the service, the first 788 // pending request will be processed. 789 mPendingInstalls.add(idx, params); 790 } 791 } else { 792 mPendingInstalls.add(idx, params); 793 // Already bound to the service. Just make 794 // sure we trigger off processing the first request. 795 if (idx == 0) { 796 mHandler.sendEmptyMessage(MCS_BOUND); 797 } 798 } 799 break; 800 } 801 case MCS_BOUND: { 802 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 803 if (msg.obj != null) { 804 mContainerService = (IMediaContainerService) msg.obj; 805 } 806 if (mContainerService == null) { 807 // Something seriously wrong. Bail out 808 Slog.e(TAG, "Cannot bind to media container service"); 809 for (HandlerParams params : mPendingInstalls) { 810 // Indicate service bind error 811 params.serviceError(); 812 } 813 mPendingInstalls.clear(); 814 } else if (mPendingInstalls.size() > 0) { 815 HandlerParams params = mPendingInstalls.get(0); 816 if (params != null) { 817 if (params.startCopy()) { 818 // We are done... look for more work or to 819 // go idle. 820 if (DEBUG_SD_INSTALL) Log.i(TAG, 821 "Checking for more work or unbind..."); 822 // Delete pending install 823 if (mPendingInstalls.size() > 0) { 824 mPendingInstalls.remove(0); 825 } 826 if (mPendingInstalls.size() == 0) { 827 if (mBound) { 828 if (DEBUG_SD_INSTALL) Log.i(TAG, 829 "Posting delayed MCS_UNBIND"); 830 removeMessages(MCS_UNBIND); 831 Message ubmsg = obtainMessage(MCS_UNBIND); 832 // Unbind after a little delay, to avoid 833 // continual thrashing. 834 sendMessageDelayed(ubmsg, 10000); 835 } 836 } else { 837 // There are more pending requests in queue. 838 // Just post MCS_BOUND message to trigger processing 839 // of next pending install. 840 if (DEBUG_SD_INSTALL) Log.i(TAG, 841 "Posting MCS_BOUND for next work"); 842 mHandler.sendEmptyMessage(MCS_BOUND); 843 } 844 } 845 } 846 } else { 847 // Should never happen ideally. 848 Slog.w(TAG, "Empty queue"); 849 } 850 break; 851 } 852 case MCS_RECONNECT: { 853 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 854 if (mPendingInstalls.size() > 0) { 855 if (mBound) { 856 disconnectService(); 857 } 858 if (!connectToService()) { 859 Slog.e(TAG, "Failed to bind to media container service"); 860 for (HandlerParams params : mPendingInstalls) { 861 // Indicate service bind error 862 params.serviceError(); 863 } 864 mPendingInstalls.clear(); 865 } 866 } 867 break; 868 } 869 case MCS_UNBIND: { 870 // If there is no actual work left, then time to unbind. 871 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 872 873 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 874 if (mBound) { 875 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 876 877 disconnectService(); 878 } 879 } else if (mPendingInstalls.size() > 0) { 880 // There are more pending requests in queue. 881 // Just post MCS_BOUND message to trigger processing 882 // of next pending install. 883 mHandler.sendEmptyMessage(MCS_BOUND); 884 } 885 886 break; 887 } 888 case MCS_GIVE_UP: { 889 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 890 mPendingInstalls.remove(0); 891 break; 892 } 893 case SEND_PENDING_BROADCAST: { 894 String packages[]; 895 ArrayList<String> components[]; 896 int size = 0; 897 int uids[]; 898 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 899 synchronized (mPackages) { 900 if (mPendingBroadcasts == null) { 901 return; 902 } 903 size = mPendingBroadcasts.size(); 904 if (size <= 0) { 905 // Nothing to be done. Just return 906 return; 907 } 908 packages = new String[size]; 909 components = new ArrayList[size]; 910 uids = new int[size]; 911 int i = 0; // filling out the above arrays 912 913 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 914 int packageUserId = mPendingBroadcasts.userIdAt(n); 915 Iterator<Map.Entry<String, ArrayList<String>>> it 916 = mPendingBroadcasts.packagesForUserId(packageUserId) 917 .entrySet().iterator(); 918 while (it.hasNext() && i < size) { 919 Map.Entry<String, ArrayList<String>> ent = it.next(); 920 packages[i] = ent.getKey(); 921 components[i] = ent.getValue(); 922 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 923 uids[i] = (ps != null) 924 ? UserHandle.getUid(packageUserId, ps.appId) 925 : -1; 926 i++; 927 } 928 } 929 size = i; 930 mPendingBroadcasts.clear(); 931 } 932 // Send broadcasts 933 for (int i = 0; i < size; i++) { 934 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 935 } 936 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 937 break; 938 } 939 case START_CLEANING_PACKAGE: { 940 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 941 final String packageName = (String)msg.obj; 942 final int userId = msg.arg1; 943 final boolean andCode = msg.arg2 != 0; 944 synchronized (mPackages) { 945 if (userId == UserHandle.USER_ALL) { 946 int[] users = sUserManager.getUserIds(); 947 for (int user : users) { 948 mSettings.addPackageToCleanLPw( 949 new PackageCleanItem(user, packageName, andCode)); 950 } 951 } else { 952 mSettings.addPackageToCleanLPw( 953 new PackageCleanItem(userId, packageName, andCode)); 954 } 955 } 956 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 957 startCleaningPackages(); 958 } break; 959 case POST_INSTALL: { 960 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 961 PostInstallData data = mRunningInstalls.get(msg.arg1); 962 mRunningInstalls.delete(msg.arg1); 963 boolean deleteOld = false; 964 965 if (data != null) { 966 InstallArgs args = data.args; 967 PackageInstalledInfo res = data.res; 968 969 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 970 res.removedInfo.sendBroadcast(false, true, false); 971 Bundle extras = new Bundle(1); 972 extras.putInt(Intent.EXTRA_UID, res.uid); 973 // Determine the set of users who are adding this 974 // package for the first time vs. those who are seeing 975 // an update. 976 int[] firstUsers; 977 int[] updateUsers = new int[0]; 978 if (res.origUsers == null || res.origUsers.length == 0) { 979 firstUsers = res.newUsers; 980 } else { 981 firstUsers = new int[0]; 982 for (int i=0; i<res.newUsers.length; i++) { 983 int user = res.newUsers[i]; 984 boolean isNew = true; 985 for (int j=0; j<res.origUsers.length; j++) { 986 if (res.origUsers[j] == user) { 987 isNew = false; 988 break; 989 } 990 } 991 if (isNew) { 992 int[] newFirst = new int[firstUsers.length+1]; 993 System.arraycopy(firstUsers, 0, newFirst, 0, 994 firstUsers.length); 995 newFirst[firstUsers.length] = user; 996 firstUsers = newFirst; 997 } else { 998 int[] newUpdate = new int[updateUsers.length+1]; 999 System.arraycopy(updateUsers, 0, newUpdate, 0, 1000 updateUsers.length); 1001 newUpdate[updateUsers.length] = user; 1002 updateUsers = newUpdate; 1003 } 1004 } 1005 } 1006 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1007 res.pkg.applicationInfo.packageName, 1008 extras, null, null, firstUsers); 1009 final boolean update = res.removedInfo.removedPackage != null; 1010 if (update) { 1011 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1012 } 1013 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1014 res.pkg.applicationInfo.packageName, 1015 extras, null, null, updateUsers); 1016 if (update) { 1017 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1018 res.pkg.applicationInfo.packageName, 1019 extras, null, null, updateUsers); 1020 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1021 null, null, 1022 res.pkg.applicationInfo.packageName, null, updateUsers); 1023 1024 // treat asec-hosted packages like removable media on upgrade 1025 if (isForwardLocked(res.pkg) || isExternal(res.pkg)) { 1026 if (DEBUG_INSTALL) { 1027 Slog.i(TAG, "upgrading pkg " + res.pkg 1028 + " is ASEC-hosted -> AVAILABLE"); 1029 } 1030 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1031 ArrayList<String> pkgList = new ArrayList<String>(1); 1032 pkgList.add(res.pkg.applicationInfo.packageName); 1033 sendResourcesChangedBroadcast(true, true, 1034 pkgList,uidArray, null); 1035 } 1036 } 1037 if (res.removedInfo.args != null) { 1038 // Remove the replaced package's older resources safely now 1039 deleteOld = true; 1040 } 1041 1042 // Log current value of "unknown sources" setting 1043 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1044 getUnknownSourcesSettings()); 1045 } 1046 // Force a gc to clear up things 1047 Runtime.getRuntime().gc(); 1048 // We delete after a gc for applications on sdcard. 1049 if (deleteOld) { 1050 synchronized (mInstallLock) { 1051 res.removedInfo.args.doPostDeleteLI(true); 1052 } 1053 } 1054 if (args.observer != null) { 1055 try { 1056 Bundle extras = extrasForInstallResult(res); 1057 args.observer.onPackageInstalled(res.name, res.returnCode, 1058 res.returnMsg, extras); 1059 } catch (RemoteException e) { 1060 Slog.i(TAG, "Observer no longer exists."); 1061 } 1062 } 1063 } else { 1064 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1065 } 1066 } break; 1067 case UPDATED_MEDIA_STATUS: { 1068 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1069 boolean reportStatus = msg.arg1 == 1; 1070 boolean doGc = msg.arg2 == 1; 1071 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1072 if (doGc) { 1073 // Force a gc to clear up stale containers. 1074 Runtime.getRuntime().gc(); 1075 } 1076 if (msg.obj != null) { 1077 @SuppressWarnings("unchecked") 1078 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1079 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1080 // Unload containers 1081 unloadAllContainers(args); 1082 } 1083 if (reportStatus) { 1084 try { 1085 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1086 PackageHelper.getMountService().finishMediaUpdate(); 1087 } catch (RemoteException e) { 1088 Log.e(TAG, "MountService not running?"); 1089 } 1090 } 1091 } break; 1092 case WRITE_SETTINGS: { 1093 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1094 synchronized (mPackages) { 1095 removeMessages(WRITE_SETTINGS); 1096 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1097 mSettings.writeLPr(); 1098 mDirtyUsers.clear(); 1099 } 1100 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1101 } break; 1102 case WRITE_PACKAGE_RESTRICTIONS: { 1103 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1104 synchronized (mPackages) { 1105 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1106 for (int userId : mDirtyUsers) { 1107 mSettings.writePackageRestrictionsLPr(userId); 1108 } 1109 mDirtyUsers.clear(); 1110 } 1111 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1112 } break; 1113 case CHECK_PENDING_VERIFICATION: { 1114 final int verificationId = msg.arg1; 1115 final PackageVerificationState state = mPendingVerification.get(verificationId); 1116 1117 if ((state != null) && !state.timeoutExtended()) { 1118 final InstallArgs args = state.getInstallArgs(); 1119 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1120 1121 Slog.i(TAG, "Verification timed out for " + originUri); 1122 mPendingVerification.remove(verificationId); 1123 1124 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1125 1126 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1127 Slog.i(TAG, "Continuing with installation of " + originUri); 1128 state.setVerifierResponse(Binder.getCallingUid(), 1129 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1130 broadcastPackageVerified(verificationId, originUri, 1131 PackageManager.VERIFICATION_ALLOW, 1132 state.getInstallArgs().getUser()); 1133 try { 1134 ret = args.copyApk(mContainerService, true); 1135 } catch (RemoteException e) { 1136 Slog.e(TAG, "Could not contact the ContainerService"); 1137 } 1138 } else { 1139 broadcastPackageVerified(verificationId, originUri, 1140 PackageManager.VERIFICATION_REJECT, 1141 state.getInstallArgs().getUser()); 1142 } 1143 1144 processPendingInstall(args, ret); 1145 mHandler.sendEmptyMessage(MCS_UNBIND); 1146 } 1147 break; 1148 } 1149 case PACKAGE_VERIFIED: { 1150 final int verificationId = msg.arg1; 1151 1152 final PackageVerificationState state = mPendingVerification.get(verificationId); 1153 if (state == null) { 1154 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1155 break; 1156 } 1157 1158 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1159 1160 state.setVerifierResponse(response.callerUid, response.code); 1161 1162 if (state.isVerificationComplete()) { 1163 mPendingVerification.remove(verificationId); 1164 1165 final InstallArgs args = state.getInstallArgs(); 1166 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1167 1168 int ret; 1169 if (state.isInstallAllowed()) { 1170 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1171 broadcastPackageVerified(verificationId, originUri, 1172 response.code, state.getInstallArgs().getUser()); 1173 try { 1174 ret = args.copyApk(mContainerService, true); 1175 } catch (RemoteException e) { 1176 Slog.e(TAG, "Could not contact the ContainerService"); 1177 } 1178 } else { 1179 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1180 } 1181 1182 processPendingInstall(args, ret); 1183 1184 mHandler.sendEmptyMessage(MCS_UNBIND); 1185 } 1186 1187 break; 1188 } 1189 } 1190 } 1191 } 1192 1193 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1194 Bundle extras = null; 1195 switch (res.returnCode) { 1196 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1197 extras = new Bundle(); 1198 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1199 res.origPermission); 1200 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1201 res.origPackage); 1202 break; 1203 } 1204 } 1205 return extras; 1206 } 1207 1208 void scheduleWriteSettingsLocked() { 1209 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1210 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1211 } 1212 } 1213 1214 void scheduleWritePackageRestrictionsLocked(int userId) { 1215 if (!sUserManager.exists(userId)) return; 1216 mDirtyUsers.add(userId); 1217 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1218 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1219 } 1220 } 1221 1222 public static final PackageManagerService main(Context context, Installer installer, 1223 boolean factoryTest, boolean onlyCore) { 1224 PackageManagerService m = new PackageManagerService(context, installer, 1225 factoryTest, onlyCore); 1226 ServiceManager.addService("package", m); 1227 return m; 1228 } 1229 1230 static String[] splitString(String str, char sep) { 1231 int count = 1; 1232 int i = 0; 1233 while ((i=str.indexOf(sep, i)) >= 0) { 1234 count++; 1235 i++; 1236 } 1237 1238 String[] res = new String[count]; 1239 i=0; 1240 count = 0; 1241 int lastI=0; 1242 while ((i=str.indexOf(sep, i)) >= 0) { 1243 res[count] = str.substring(lastI, i); 1244 count++; 1245 i++; 1246 lastI = i; 1247 } 1248 res[count] = str.substring(lastI, str.length()); 1249 return res; 1250 } 1251 1252 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1253 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1254 Context.DISPLAY_SERVICE); 1255 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1256 } 1257 1258 public PackageManagerService(Context context, Installer installer, 1259 boolean factoryTest, boolean onlyCore) { 1260 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1261 SystemClock.uptimeMillis()); 1262 1263 if (mSdkVersion <= 0) { 1264 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1265 } 1266 1267 mContext = context; 1268 mFactoryTest = factoryTest; 1269 mOnlyCore = onlyCore; 1270 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1271 mMetrics = new DisplayMetrics(); 1272 mSettings = new Settings(context); 1273 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1274 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1275 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1276 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1277 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1278 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1279 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1280 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1281 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1282 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1283 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1284 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1285 1286 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1287 if (separateProcesses != null && separateProcesses.length() > 0) { 1288 if ("*".equals(separateProcesses)) { 1289 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1290 mSeparateProcesses = null; 1291 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1292 } else { 1293 mDefParseFlags = 0; 1294 mSeparateProcesses = separateProcesses.split(","); 1295 Slog.w(TAG, "Running with debug.separate_processes: " 1296 + separateProcesses); 1297 } 1298 } else { 1299 mDefParseFlags = 0; 1300 mSeparateProcesses = null; 1301 } 1302 1303 mInstaller = installer; 1304 1305 getDefaultDisplayMetrics(context, mMetrics); 1306 1307 SystemConfig systemConfig = SystemConfig.getInstance(); 1308 mGlobalGids = systemConfig.getGlobalGids(); 1309 mSystemPermissions = systemConfig.getSystemPermissions(); 1310 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1311 1312 synchronized (mInstallLock) { 1313 // writer 1314 synchronized (mPackages) { 1315 mHandlerThread = new ServiceThread(TAG, 1316 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1317 mHandlerThread.start(); 1318 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1319 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1320 1321 File dataDir = Environment.getDataDirectory(); 1322 mAppDataDir = new File(dataDir, "data"); 1323 mAppInstallDir = new File(dataDir, "app"); 1324 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1325 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1326 mUserAppDataDir = new File(dataDir, "user"); 1327 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1328 1329 sUserManager = new UserManagerService(context, this, 1330 mInstallLock, mPackages); 1331 1332 // Propagate permission configuration in to package manager. 1333 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1334 = systemConfig.getPermissions(); 1335 for (int i=0; i<permConfig.size(); i++) { 1336 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1337 BasePermission bp = mSettings.mPermissions.get(perm.name); 1338 if (bp == null) { 1339 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1340 mSettings.mPermissions.put(perm.name, bp); 1341 } 1342 if (perm.gids != null) { 1343 bp.gids = appendInts(bp.gids, perm.gids); 1344 } 1345 } 1346 1347 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1348 for (int i=0; i<libConfig.size(); i++) { 1349 mSharedLibraries.put(libConfig.keyAt(i), 1350 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1351 } 1352 1353 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1354 1355 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1356 mSdkVersion, mOnlyCore); 1357 1358 String customResolverActivity = Resources.getSystem().getString( 1359 R.string.config_customResolverActivity); 1360 if (TextUtils.isEmpty(customResolverActivity)) { 1361 customResolverActivity = null; 1362 } else { 1363 mCustomResolverComponentName = ComponentName.unflattenFromString( 1364 customResolverActivity); 1365 } 1366 1367 long startTime = SystemClock.uptimeMillis(); 1368 1369 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1370 startTime); 1371 1372 // Set flag to monitor and not change apk file paths when 1373 // scanning install directories. 1374 int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1375 1376 final HashSet<String> alreadyDexOpted = new HashSet<String>(); 1377 1378 /** 1379 * Add everything in the in the boot class path to the 1380 * list of process files because dexopt will have been run 1381 * if necessary during zygote startup. 1382 */ 1383 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1384 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1385 1386 if (bootClassPath != null) { 1387 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1388 for (String element : bootClassPathElements) { 1389 alreadyDexOpted.add(element); 1390 } 1391 } else { 1392 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1393 } 1394 1395 if (systemServerClassPath != null) { 1396 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1397 for (String element : systemServerClassPathElements) { 1398 alreadyDexOpted.add(element); 1399 } 1400 } else { 1401 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1402 } 1403 1404 boolean didDexOptLibraryOrTool = false; 1405 1406 final List<String> allInstructionSets = getAllInstructionSets(); 1407 final String[] dexCodeInstructionSets = 1408 getDexCodeInstructionSets(allInstructionSets.toArray(new String[allInstructionSets.size()])); 1409 1410 /** 1411 * Ensure all external libraries have had dexopt run on them. 1412 */ 1413 if (mSharedLibraries.size() > 0) { 1414 // NOTE: For now, we're compiling these system "shared libraries" 1415 // (and framework jars) into all available architectures. It's possible 1416 // to compile them only when we come across an app that uses them (there's 1417 // already logic for that in scanPackageLI) but that adds some complexity. 1418 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1419 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1420 final String lib = libEntry.path; 1421 if (lib == null) { 1422 continue; 1423 } 1424 1425 try { 1426 byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null, 1427 dexCodeInstructionSet, 1428 false); 1429 if (dexoptRequired != DexFile.UP_TO_DATE) { 1430 alreadyDexOpted.add(lib); 1431 1432 // The list of "shared libraries" we have at this point is 1433 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1434 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1435 } else { 1436 mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1437 } 1438 didDexOptLibraryOrTool = true; 1439 } 1440 } catch (FileNotFoundException e) { 1441 Slog.w(TAG, "Library not found: " + lib); 1442 } catch (IOException e) { 1443 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1444 + e.getMessage()); 1445 } 1446 } 1447 } 1448 } 1449 1450 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1451 1452 // Gross hack for now: we know this file doesn't contain any 1453 // code, so don't dexopt it to avoid the resulting log spew. 1454 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1455 1456 // Gross hack for now: we know this file is only part of 1457 // the boot class path for art, so don't dexopt it to 1458 // avoid the resulting log spew. 1459 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1460 1461 /** 1462 * And there are a number of commands implemented in Java, which 1463 * we currently need to do the dexopt on so that they can be 1464 * run from a non-root shell. 1465 */ 1466 String[] frameworkFiles = frameworkDir.list(); 1467 if (frameworkFiles != null) { 1468 // TODO: We could compile these only for the most preferred ABI. We should 1469 // first double check that the dex files for these commands are not referenced 1470 // by other system apps. 1471 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1472 for (int i=0; i<frameworkFiles.length; i++) { 1473 File libPath = new File(frameworkDir, frameworkFiles[i]); 1474 String path = libPath.getPath(); 1475 // Skip the file if we already did it. 1476 if (alreadyDexOpted.contains(path)) { 1477 continue; 1478 } 1479 // Skip the file if it is not a type we want to dexopt. 1480 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1481 continue; 1482 } 1483 try { 1484 byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null, 1485 dexCodeInstructionSet, 1486 false); 1487 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1488 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1489 didDexOptLibraryOrTool = true; 1490 } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) { 1491 mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1492 didDexOptLibraryOrTool = true; 1493 } 1494 } catch (FileNotFoundException e) { 1495 Slog.w(TAG, "Jar not found: " + path); 1496 } catch (IOException e) { 1497 Slog.w(TAG, "Exception reading jar: " + path, e); 1498 } 1499 } 1500 } 1501 } 1502 1503 // Collect vendor overlay packages. 1504 // (Do this before scanning any apps.) 1505 // For security and version matching reason, only consider 1506 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1507 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1508 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1509 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1510 1511 // Find base frameworks (resource packages without code). 1512 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1513 | PackageParser.PARSE_IS_SYSTEM_DIR 1514 | PackageParser.PARSE_IS_PRIVILEGED, 1515 scanFlags | SCAN_NO_DEX, 0); 1516 1517 // Collected privileged system packages. 1518 File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1519 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1520 | PackageParser.PARSE_IS_SYSTEM_DIR 1521 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1522 1523 // Collect ordinary system packages. 1524 File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1525 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1526 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1527 1528 // Collect all vendor packages. 1529 File vendorAppDir = new File("/vendor/app"); 1530 try { 1531 vendorAppDir = vendorAppDir.getCanonicalFile(); 1532 } catch (IOException e) { 1533 // failed to look up canonical path, continue with original one 1534 } 1535 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1536 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1537 1538 // Collect all OEM packages. 1539 File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1540 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1541 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1542 1543 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1544 mInstaller.moveFiles(); 1545 1546 // Prune any system packages that no longer exist. 1547 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1548 if (!mOnlyCore) { 1549 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1550 while (psit.hasNext()) { 1551 PackageSetting ps = psit.next(); 1552 1553 /* 1554 * If this is not a system app, it can't be a 1555 * disable system app. 1556 */ 1557 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1558 continue; 1559 } 1560 1561 /* 1562 * If the package is scanned, it's not erased. 1563 */ 1564 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1565 if (scannedPkg != null) { 1566 /* 1567 * If the system app is both scanned and in the 1568 * disabled packages list, then it must have been 1569 * added via OTA. Remove it from the currently 1570 * scanned package so the previously user-installed 1571 * application can be scanned. 1572 */ 1573 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1574 Slog.i(TAG, "Expecting better updatd system app for " + ps.name 1575 + "; removing system app"); 1576 removePackageLI(ps, true); 1577 } 1578 1579 continue; 1580 } 1581 1582 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1583 psit.remove(); 1584 String msg = "System package " + ps.name 1585 + " no longer exists; wiping its data"; 1586 reportSettingsProblem(Log.WARN, msg); 1587 removeDataDirsLI(ps.name); 1588 } else { 1589 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1590 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1591 possiblyDeletedUpdatedSystemApps.add(ps.name); 1592 } 1593 } 1594 } 1595 } 1596 1597 //look for any incomplete package installations 1598 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1599 //clean up list 1600 for(int i = 0; i < deletePkgsList.size(); i++) { 1601 //clean up here 1602 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1603 } 1604 //delete tmp files 1605 deleteTempPackageFiles(); 1606 1607 // Remove any shared userIDs that have no associated packages 1608 mSettings.pruneSharedUsersLPw(); 1609 1610 if (!mOnlyCore) { 1611 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 1612 SystemClock.uptimeMillis()); 1613 scanDirLI(mAppInstallDir, 0, scanFlags, 0); 1614 1615 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 1616 scanFlags, 0); 1617 1618 /** 1619 * Remove disable package settings for any updated system 1620 * apps that were removed via an OTA. If they're not a 1621 * previously-updated app, remove them completely. 1622 * Otherwise, just revoke their system-level permissions. 1623 */ 1624 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 1625 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 1626 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 1627 1628 String msg; 1629 if (deletedPkg == null) { 1630 msg = "Updated system package " + deletedAppName 1631 + " no longer exists; wiping its data"; 1632 removeDataDirsLI(deletedAppName); 1633 } else { 1634 msg = "Updated system app + " + deletedAppName 1635 + " no longer present; removing system privileges for " 1636 + deletedAppName; 1637 1638 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 1639 1640 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 1641 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 1642 } 1643 reportSettingsProblem(Log.WARN, msg); 1644 } 1645 } 1646 1647 // Now that we know all of the shared libraries, update all clients to have 1648 // the correct library paths. 1649 updateAllSharedLibrariesLPw(); 1650 1651 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 1652 // NOTE: We ignore potential failures here during a system scan (like 1653 // the rest of the commands above) because there's precious little we 1654 // can do about it. A settings error is reported, though. 1655 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 1656 false /* force dexopt */, false /* defer dexopt */); 1657 } 1658 1659 // Now that we know all the packages we are keeping, 1660 // read and update their last usage times. 1661 mPackageUsage.readLP(); 1662 1663 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 1664 SystemClock.uptimeMillis()); 1665 Slog.i(TAG, "Time to scan packages: " 1666 + ((SystemClock.uptimeMillis()-startTime)/1000f) 1667 + " seconds"); 1668 1669 // If the platform SDK has changed since the last time we booted, 1670 // we need to re-grant app permission to catch any new ones that 1671 // appear. This is really a hack, and means that apps can in some 1672 // cases get permissions that the user didn't initially explicitly 1673 // allow... it would be nice to have some better way to handle 1674 // this situation. 1675 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 1676 != mSdkVersion; 1677 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 1678 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 1679 + "; regranting permissions for internal storage"); 1680 mSettings.mInternalSdkPlatform = mSdkVersion; 1681 1682 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 1683 | (regrantPermissions 1684 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 1685 : 0)); 1686 1687 // If this is the first boot, and it is a normal boot, then 1688 // we need to initialize the default preferred apps. 1689 if (!mRestoredSettings && !onlyCore) { 1690 mSettings.readDefaultPreferredAppsLPw(this, 0); 1691 } 1692 1693 // If this is first boot after an OTA, and a normal boot, then 1694 // we need to clear code cache directories. 1695 if (!Build.FINGERPRINT.equals(mSettings.mFingerprint) && !onlyCore) { 1696 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 1697 for (String pkgName : mSettings.mPackages.keySet()) { 1698 deleteCodeCacheDirsLI(pkgName); 1699 } 1700 mSettings.mFingerprint = Build.FINGERPRINT; 1701 } 1702 1703 // All the changes are done during package scanning. 1704 mSettings.updateInternalDatabaseVersion(); 1705 1706 // can downgrade to reader 1707 mSettings.writeLPr(); 1708 1709 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 1710 SystemClock.uptimeMillis()); 1711 1712 1713 mRequiredVerifierPackage = getRequiredVerifierLPr(); 1714 } // synchronized (mPackages) 1715 } // synchronized (mInstallLock) 1716 1717 mInstallerService = new PackageInstallerService(context, this, mAppInstallDir); 1718 1719 // Now after opening every single application zip, make sure they 1720 // are all flushed. Not really needed, but keeps things nice and 1721 // tidy. 1722 Runtime.getRuntime().gc(); 1723 } 1724 1725 @Override 1726 public boolean isFirstBoot() { 1727 return !mRestoredSettings; 1728 } 1729 1730 @Override 1731 public boolean isOnlyCoreApps() { 1732 return mOnlyCore; 1733 } 1734 1735 private String getRequiredVerifierLPr() { 1736 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 1737 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 1738 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 1739 1740 String requiredVerifier = null; 1741 1742 final int N = receivers.size(); 1743 for (int i = 0; i < N; i++) { 1744 final ResolveInfo info = receivers.get(i); 1745 1746 if (info.activityInfo == null) { 1747 continue; 1748 } 1749 1750 final String packageName = info.activityInfo.packageName; 1751 1752 final PackageSetting ps = mSettings.mPackages.get(packageName); 1753 if (ps == null) { 1754 continue; 1755 } 1756 1757 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1758 if (!gp.grantedPermissions 1759 .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) { 1760 continue; 1761 } 1762 1763 if (requiredVerifier != null) { 1764 throw new RuntimeException("There can be only one required verifier"); 1765 } 1766 1767 requiredVerifier = packageName; 1768 } 1769 1770 return requiredVerifier; 1771 } 1772 1773 @Override 1774 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 1775 throws RemoteException { 1776 try { 1777 return super.onTransact(code, data, reply, flags); 1778 } catch (RuntimeException e) { 1779 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 1780 Slog.wtf(TAG, "Package Manager Crash", e); 1781 } 1782 throw e; 1783 } 1784 } 1785 1786 void cleanupInstallFailedPackage(PackageSetting ps) { 1787 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name); 1788 removeDataDirsLI(ps.name); 1789 1790 // TODO: try cleaning up codePath directory contents first, since it 1791 // might be a cluster 1792 1793 if (ps.codePath != null) { 1794 if (!ps.codePath.delete()) { 1795 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath); 1796 } 1797 } 1798 if (ps.resourcePath != null) { 1799 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) { 1800 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath); 1801 } 1802 } 1803 mSettings.removePackageLPw(ps.name); 1804 } 1805 1806 static int[] appendInts(int[] cur, int[] add) { 1807 if (add == null) return cur; 1808 if (cur == null) return add; 1809 final int N = add.length; 1810 for (int i=0; i<N; i++) { 1811 cur = appendInt(cur, add[i]); 1812 } 1813 return cur; 1814 } 1815 1816 static int[] removeInts(int[] cur, int[] rem) { 1817 if (rem == null) return cur; 1818 if (cur == null) return cur; 1819 final int N = rem.length; 1820 for (int i=0; i<N; i++) { 1821 cur = removeInt(cur, rem[i]); 1822 } 1823 return cur; 1824 } 1825 1826 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 1827 if (!sUserManager.exists(userId)) return null; 1828 final PackageSetting ps = (PackageSetting) p.mExtras; 1829 if (ps == null) { 1830 return null; 1831 } 1832 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1833 final PackageUserState state = ps.readUserState(userId); 1834 return PackageParser.generatePackageInfo(p, gp.gids, flags, 1835 ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions, 1836 state, userId); 1837 } 1838 1839 @Override 1840 public boolean isPackageAvailable(String packageName, int userId) { 1841 if (!sUserManager.exists(userId)) return false; 1842 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available"); 1843 synchronized (mPackages) { 1844 PackageParser.Package p = mPackages.get(packageName); 1845 if (p != null) { 1846 final PackageSetting ps = (PackageSetting) p.mExtras; 1847 if (ps != null) { 1848 final PackageUserState state = ps.readUserState(userId); 1849 if (state != null) { 1850 return PackageParser.isAvailable(state); 1851 } 1852 } 1853 } 1854 } 1855 return false; 1856 } 1857 1858 @Override 1859 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 1860 if (!sUserManager.exists(userId)) return null; 1861 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info"); 1862 // reader 1863 synchronized (mPackages) { 1864 PackageParser.Package p = mPackages.get(packageName); 1865 if (DEBUG_PACKAGE_INFO) 1866 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 1867 if (p != null) { 1868 return generatePackageInfo(p, flags, userId); 1869 } 1870 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 1871 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 1872 } 1873 } 1874 return null; 1875 } 1876 1877 @Override 1878 public String[] currentToCanonicalPackageNames(String[] names) { 1879 String[] out = new String[names.length]; 1880 // reader 1881 synchronized (mPackages) { 1882 for (int i=names.length-1; i>=0; i--) { 1883 PackageSetting ps = mSettings.mPackages.get(names[i]); 1884 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 1885 } 1886 } 1887 return out; 1888 } 1889 1890 @Override 1891 public String[] canonicalToCurrentPackageNames(String[] names) { 1892 String[] out = new String[names.length]; 1893 // reader 1894 synchronized (mPackages) { 1895 for (int i=names.length-1; i>=0; i--) { 1896 String cur = mSettings.mRenamedPackages.get(names[i]); 1897 out[i] = cur != null ? cur : names[i]; 1898 } 1899 } 1900 return out; 1901 } 1902 1903 @Override 1904 public int getPackageUid(String packageName, int userId) { 1905 if (!sUserManager.exists(userId)) return -1; 1906 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid"); 1907 // reader 1908 synchronized (mPackages) { 1909 PackageParser.Package p = mPackages.get(packageName); 1910 if(p != null) { 1911 return UserHandle.getUid(userId, p.applicationInfo.uid); 1912 } 1913 PackageSetting ps = mSettings.mPackages.get(packageName); 1914 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 1915 return -1; 1916 } 1917 p = ps.pkg; 1918 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 1919 } 1920 } 1921 1922 @Override 1923 public int[] getPackageGids(String packageName) { 1924 // reader 1925 synchronized (mPackages) { 1926 PackageParser.Package p = mPackages.get(packageName); 1927 if (DEBUG_PACKAGE_INFO) 1928 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 1929 if (p != null) { 1930 final PackageSetting ps = (PackageSetting)p.mExtras; 1931 return ps.getGids(); 1932 } 1933 } 1934 // stupid thing to indicate an error. 1935 return new int[0]; 1936 } 1937 1938 static final PermissionInfo generatePermissionInfo( 1939 BasePermission bp, int flags) { 1940 if (bp.perm != null) { 1941 return PackageParser.generatePermissionInfo(bp.perm, flags); 1942 } 1943 PermissionInfo pi = new PermissionInfo(); 1944 pi.name = bp.name; 1945 pi.packageName = bp.sourcePackage; 1946 pi.nonLocalizedLabel = bp.name; 1947 pi.protectionLevel = bp.protectionLevel; 1948 return pi; 1949 } 1950 1951 @Override 1952 public PermissionInfo getPermissionInfo(String name, int flags) { 1953 // reader 1954 synchronized (mPackages) { 1955 final BasePermission p = mSettings.mPermissions.get(name); 1956 if (p != null) { 1957 return generatePermissionInfo(p, flags); 1958 } 1959 return null; 1960 } 1961 } 1962 1963 @Override 1964 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 1965 // reader 1966 synchronized (mPackages) { 1967 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 1968 for (BasePermission p : mSettings.mPermissions.values()) { 1969 if (group == null) { 1970 if (p.perm == null || p.perm.info.group == null) { 1971 out.add(generatePermissionInfo(p, flags)); 1972 } 1973 } else { 1974 if (p.perm != null && group.equals(p.perm.info.group)) { 1975 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 1976 } 1977 } 1978 } 1979 1980 if (out.size() > 0) { 1981 return out; 1982 } 1983 return mPermissionGroups.containsKey(group) ? out : null; 1984 } 1985 } 1986 1987 @Override 1988 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 1989 // reader 1990 synchronized (mPackages) { 1991 return PackageParser.generatePermissionGroupInfo( 1992 mPermissionGroups.get(name), flags); 1993 } 1994 } 1995 1996 @Override 1997 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 1998 // reader 1999 synchronized (mPackages) { 2000 final int N = mPermissionGroups.size(); 2001 ArrayList<PermissionGroupInfo> out 2002 = new ArrayList<PermissionGroupInfo>(N); 2003 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2004 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2005 } 2006 return out; 2007 } 2008 } 2009 2010 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2011 int userId) { 2012 if (!sUserManager.exists(userId)) return null; 2013 PackageSetting ps = mSettings.mPackages.get(packageName); 2014 if (ps != null) { 2015 if (ps.pkg == null) { 2016 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2017 flags, userId); 2018 if (pInfo != null) { 2019 return pInfo.applicationInfo; 2020 } 2021 return null; 2022 } 2023 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2024 ps.readUserState(userId), userId); 2025 } 2026 return null; 2027 } 2028 2029 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2030 int userId) { 2031 if (!sUserManager.exists(userId)) return null; 2032 PackageSetting ps = mSettings.mPackages.get(packageName); 2033 if (ps != null) { 2034 PackageParser.Package pkg = ps.pkg; 2035 if (pkg == null) { 2036 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2037 return null; 2038 } 2039 // Only data remains, so we aren't worried about code paths 2040 pkg = new PackageParser.Package(packageName); 2041 pkg.applicationInfo.packageName = packageName; 2042 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2043 pkg.applicationInfo.dataDir = 2044 getDataPathForPackage(packageName, 0).getPath(); 2045 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2046 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2047 } 2048 return generatePackageInfo(pkg, flags, userId); 2049 } 2050 return null; 2051 } 2052 2053 @Override 2054 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2055 if (!sUserManager.exists(userId)) return null; 2056 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info"); 2057 // writer 2058 synchronized (mPackages) { 2059 PackageParser.Package p = mPackages.get(packageName); 2060 if (DEBUG_PACKAGE_INFO) Log.v( 2061 TAG, "getApplicationInfo " + packageName 2062 + ": " + p); 2063 if (p != null) { 2064 PackageSetting ps = mSettings.mPackages.get(packageName); 2065 if (ps == null) return null; 2066 // Note: isEnabledLP() does not apply here - always return info 2067 return PackageParser.generateApplicationInfo( 2068 p, flags, ps.readUserState(userId), userId); 2069 } 2070 if ("android".equals(packageName)||"system".equals(packageName)) { 2071 return mAndroidApplication; 2072 } 2073 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2074 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2075 } 2076 } 2077 return null; 2078 } 2079 2080 2081 @Override 2082 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2083 mContext.enforceCallingOrSelfPermission( 2084 android.Manifest.permission.CLEAR_APP_CACHE, null); 2085 // Queue up an async operation since clearing cache may take a little while. 2086 mHandler.post(new Runnable() { 2087 public void run() { 2088 mHandler.removeCallbacks(this); 2089 int retCode = -1; 2090 synchronized (mInstallLock) { 2091 retCode = mInstaller.freeCache(freeStorageSize); 2092 if (retCode < 0) { 2093 Slog.w(TAG, "Couldn't clear application caches"); 2094 } 2095 } 2096 if (observer != null) { 2097 try { 2098 observer.onRemoveCompleted(null, (retCode >= 0)); 2099 } catch (RemoteException e) { 2100 Slog.w(TAG, "RemoveException when invoking call back"); 2101 } 2102 } 2103 } 2104 }); 2105 } 2106 2107 @Override 2108 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2109 mContext.enforceCallingOrSelfPermission( 2110 android.Manifest.permission.CLEAR_APP_CACHE, null); 2111 // Queue up an async operation since clearing cache may take a little while. 2112 mHandler.post(new Runnable() { 2113 public void run() { 2114 mHandler.removeCallbacks(this); 2115 int retCode = -1; 2116 synchronized (mInstallLock) { 2117 retCode = mInstaller.freeCache(freeStorageSize); 2118 if (retCode < 0) { 2119 Slog.w(TAG, "Couldn't clear application caches"); 2120 } 2121 } 2122 if(pi != null) { 2123 try { 2124 // Callback via pending intent 2125 int code = (retCode >= 0) ? 1 : 0; 2126 pi.sendIntent(null, code, null, 2127 null, null); 2128 } catch (SendIntentException e1) { 2129 Slog.i(TAG, "Failed to send pending intent"); 2130 } 2131 } 2132 } 2133 }); 2134 } 2135 2136 void freeStorage(long freeStorageSize) throws IOException { 2137 synchronized (mInstallLock) { 2138 if (mInstaller.freeCache(freeStorageSize) < 0) { 2139 throw new IOException("Failed to free enough space"); 2140 } 2141 } 2142 } 2143 2144 @Override 2145 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2146 if (!sUserManager.exists(userId)) return null; 2147 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info"); 2148 synchronized (mPackages) { 2149 PackageParser.Activity a = mActivities.mActivities.get(component); 2150 2151 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2152 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2153 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2154 if (ps == null) return null; 2155 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2156 userId); 2157 } 2158 if (mResolveComponentName.equals(component)) { 2159 return mResolveActivity; 2160 } 2161 } 2162 return null; 2163 } 2164 2165 @Override 2166 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2167 String resolvedType) { 2168 synchronized (mPackages) { 2169 PackageParser.Activity a = mActivities.mActivities.get(component); 2170 if (a == null) { 2171 return false; 2172 } 2173 for (int i=0; i<a.intents.size(); i++) { 2174 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2175 intent.getData(), intent.getCategories(), TAG) >= 0) { 2176 return true; 2177 } 2178 } 2179 return false; 2180 } 2181 } 2182 2183 @Override 2184 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2185 if (!sUserManager.exists(userId)) return null; 2186 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info"); 2187 synchronized (mPackages) { 2188 PackageParser.Activity a = mReceivers.mActivities.get(component); 2189 if (DEBUG_PACKAGE_INFO) Log.v( 2190 TAG, "getReceiverInfo " + component + ": " + a); 2191 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2192 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2193 if (ps == null) return null; 2194 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2195 userId); 2196 } 2197 } 2198 return null; 2199 } 2200 2201 @Override 2202 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2203 if (!sUserManager.exists(userId)) return null; 2204 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info"); 2205 synchronized (mPackages) { 2206 PackageParser.Service s = mServices.mServices.get(component); 2207 if (DEBUG_PACKAGE_INFO) Log.v( 2208 TAG, "getServiceInfo " + component + ": " + s); 2209 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2210 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2211 if (ps == null) return null; 2212 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2213 userId); 2214 } 2215 } 2216 return null; 2217 } 2218 2219 @Override 2220 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2221 if (!sUserManager.exists(userId)) return null; 2222 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info"); 2223 synchronized (mPackages) { 2224 PackageParser.Provider p = mProviders.mProviders.get(component); 2225 if (DEBUG_PACKAGE_INFO) Log.v( 2226 TAG, "getProviderInfo " + component + ": " + p); 2227 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2228 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2229 if (ps == null) return null; 2230 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2231 userId); 2232 } 2233 } 2234 return null; 2235 } 2236 2237 @Override 2238 public String[] getSystemSharedLibraryNames() { 2239 Set<String> libSet; 2240 synchronized (mPackages) { 2241 libSet = mSharedLibraries.keySet(); 2242 int size = libSet.size(); 2243 if (size > 0) { 2244 String[] libs = new String[size]; 2245 libSet.toArray(libs); 2246 return libs; 2247 } 2248 } 2249 return null; 2250 } 2251 2252 @Override 2253 public FeatureInfo[] getSystemAvailableFeatures() { 2254 Collection<FeatureInfo> featSet; 2255 synchronized (mPackages) { 2256 featSet = mAvailableFeatures.values(); 2257 int size = featSet.size(); 2258 if (size > 0) { 2259 FeatureInfo[] features = new FeatureInfo[size+1]; 2260 featSet.toArray(features); 2261 FeatureInfo fi = new FeatureInfo(); 2262 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2263 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2264 features[size] = fi; 2265 return features; 2266 } 2267 } 2268 return null; 2269 } 2270 2271 @Override 2272 public boolean hasSystemFeature(String name) { 2273 synchronized (mPackages) { 2274 return mAvailableFeatures.containsKey(name); 2275 } 2276 } 2277 2278 private void checkValidCaller(int uid, int userId) { 2279 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2280 return; 2281 2282 throw new SecurityException("Caller uid=" + uid 2283 + " is not privileged to communicate with user=" + userId); 2284 } 2285 2286 @Override 2287 public int checkPermission(String permName, String pkgName) { 2288 synchronized (mPackages) { 2289 PackageParser.Package p = mPackages.get(pkgName); 2290 if (p != null && p.mExtras != null) { 2291 PackageSetting ps = (PackageSetting)p.mExtras; 2292 if (ps.sharedUser != null) { 2293 if (ps.sharedUser.grantedPermissions.contains(permName)) { 2294 return PackageManager.PERMISSION_GRANTED; 2295 } 2296 } else if (ps.grantedPermissions.contains(permName)) { 2297 return PackageManager.PERMISSION_GRANTED; 2298 } 2299 } 2300 } 2301 return PackageManager.PERMISSION_DENIED; 2302 } 2303 2304 @Override 2305 public int checkUidPermission(String permName, int uid) { 2306 synchronized (mPackages) { 2307 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2308 if (obj != null) { 2309 GrantedPermissions gp = (GrantedPermissions)obj; 2310 if (gp.grantedPermissions.contains(permName)) { 2311 return PackageManager.PERMISSION_GRANTED; 2312 } 2313 } else { 2314 HashSet<String> perms = mSystemPermissions.get(uid); 2315 if (perms != null && perms.contains(permName)) { 2316 return PackageManager.PERMISSION_GRANTED; 2317 } 2318 } 2319 } 2320 return PackageManager.PERMISSION_DENIED; 2321 } 2322 2323 /** 2324 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2325 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2326 * @param message the message to log on security exception 2327 */ 2328 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2329 String message) { 2330 if (userId < 0) { 2331 throw new IllegalArgumentException("Invalid userId " + userId); 2332 } 2333 if (userId == UserHandle.getUserId(callingUid)) return; 2334 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2335 if (requireFullPermission) { 2336 mContext.enforceCallingOrSelfPermission( 2337 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2338 } else { 2339 try { 2340 mContext.enforceCallingOrSelfPermission( 2341 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2342 } catch (SecurityException se) { 2343 mContext.enforceCallingOrSelfPermission( 2344 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2345 } 2346 } 2347 } 2348 } 2349 2350 private BasePermission findPermissionTreeLP(String permName) { 2351 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2352 if (permName.startsWith(bp.name) && 2353 permName.length() > bp.name.length() && 2354 permName.charAt(bp.name.length()) == '.') { 2355 return bp; 2356 } 2357 } 2358 return null; 2359 } 2360 2361 private BasePermission checkPermissionTreeLP(String permName) { 2362 if (permName != null) { 2363 BasePermission bp = findPermissionTreeLP(permName); 2364 if (bp != null) { 2365 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2366 return bp; 2367 } 2368 throw new SecurityException("Calling uid " 2369 + Binder.getCallingUid() 2370 + " is not allowed to add to permission tree " 2371 + bp.name + " owned by uid " + bp.uid); 2372 } 2373 } 2374 throw new SecurityException("No permission tree found for " + permName); 2375 } 2376 2377 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2378 if (s1 == null) { 2379 return s2 == null; 2380 } 2381 if (s2 == null) { 2382 return false; 2383 } 2384 if (s1.getClass() != s2.getClass()) { 2385 return false; 2386 } 2387 return s1.equals(s2); 2388 } 2389 2390 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2391 if (pi1.icon != pi2.icon) return false; 2392 if (pi1.logo != pi2.logo) return false; 2393 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2394 if (!compareStrings(pi1.name, pi2.name)) return false; 2395 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2396 // We'll take care of setting this one. 2397 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2398 // These are not currently stored in settings. 2399 //if (!compareStrings(pi1.group, pi2.group)) return false; 2400 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2401 //if (pi1.labelRes != pi2.labelRes) return false; 2402 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2403 return true; 2404 } 2405 2406 int permissionInfoFootprint(PermissionInfo info) { 2407 int size = info.name.length(); 2408 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2409 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2410 return size; 2411 } 2412 2413 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2414 int size = 0; 2415 for (BasePermission perm : mSettings.mPermissions.values()) { 2416 if (perm.uid == tree.uid) { 2417 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2418 } 2419 } 2420 return size; 2421 } 2422 2423 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2424 // We calculate the max size of permissions defined by this uid and throw 2425 // if that plus the size of 'info' would exceed our stated maximum. 2426 if (tree.uid != Process.SYSTEM_UID) { 2427 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2428 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2429 throw new SecurityException("Permission tree size cap exceeded"); 2430 } 2431 } 2432 } 2433 2434 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2435 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2436 throw new SecurityException("Label must be specified in permission"); 2437 } 2438 BasePermission tree = checkPermissionTreeLP(info.name); 2439 BasePermission bp = mSettings.mPermissions.get(info.name); 2440 boolean added = bp == null; 2441 boolean changed = true; 2442 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2443 if (added) { 2444 enforcePermissionCapLocked(info, tree); 2445 bp = new BasePermission(info.name, tree.sourcePackage, 2446 BasePermission.TYPE_DYNAMIC); 2447 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2448 throw new SecurityException( 2449 "Not allowed to modify non-dynamic permission " 2450 + info.name); 2451 } else { 2452 if (bp.protectionLevel == fixedLevel 2453 && bp.perm.owner.equals(tree.perm.owner) 2454 && bp.uid == tree.uid 2455 && comparePermissionInfos(bp.perm.info, info)) { 2456 changed = false; 2457 } 2458 } 2459 bp.protectionLevel = fixedLevel; 2460 info = new PermissionInfo(info); 2461 info.protectionLevel = fixedLevel; 2462 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 2463 bp.perm.info.packageName = tree.perm.info.packageName; 2464 bp.uid = tree.uid; 2465 if (added) { 2466 mSettings.mPermissions.put(info.name, bp); 2467 } 2468 if (changed) { 2469 if (!async) { 2470 mSettings.writeLPr(); 2471 } else { 2472 scheduleWriteSettingsLocked(); 2473 } 2474 } 2475 return added; 2476 } 2477 2478 @Override 2479 public boolean addPermission(PermissionInfo info) { 2480 synchronized (mPackages) { 2481 return addPermissionLocked(info, false); 2482 } 2483 } 2484 2485 @Override 2486 public boolean addPermissionAsync(PermissionInfo info) { 2487 synchronized (mPackages) { 2488 return addPermissionLocked(info, true); 2489 } 2490 } 2491 2492 @Override 2493 public void removePermission(String name) { 2494 synchronized (mPackages) { 2495 checkPermissionTreeLP(name); 2496 BasePermission bp = mSettings.mPermissions.get(name); 2497 if (bp != null) { 2498 if (bp.type != BasePermission.TYPE_DYNAMIC) { 2499 throw new SecurityException( 2500 "Not allowed to modify non-dynamic permission " 2501 + name); 2502 } 2503 mSettings.mPermissions.remove(name); 2504 mSettings.writeLPr(); 2505 } 2506 } 2507 } 2508 2509 private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) { 2510 int index = pkg.requestedPermissions.indexOf(bp.name); 2511 if (index == -1) { 2512 throw new SecurityException("Package " + pkg.packageName 2513 + " has not requested permission " + bp.name); 2514 } 2515 boolean isNormal = 2516 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2517 == PermissionInfo.PROTECTION_NORMAL); 2518 boolean isDangerous = 2519 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2520 == PermissionInfo.PROTECTION_DANGEROUS); 2521 boolean isDevelopment = 2522 ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0); 2523 2524 if (!isNormal && !isDangerous && !isDevelopment) { 2525 throw new SecurityException("Permission " + bp.name 2526 + " is not a changeable permission type"); 2527 } 2528 2529 if (isNormal || isDangerous) { 2530 if (pkg.requestedPermissionsRequired.get(index)) { 2531 throw new SecurityException("Can't change " + bp.name 2532 + ". It is required by the application"); 2533 } 2534 } 2535 } 2536 2537 @Override 2538 public void grantPermission(String packageName, String permissionName) { 2539 mContext.enforceCallingOrSelfPermission( 2540 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2541 synchronized (mPackages) { 2542 final PackageParser.Package pkg = mPackages.get(packageName); 2543 if (pkg == null) { 2544 throw new IllegalArgumentException("Unknown package: " + packageName); 2545 } 2546 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2547 if (bp == null) { 2548 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2549 } 2550 2551 checkGrantRevokePermissions(pkg, bp); 2552 2553 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2554 if (ps == null) { 2555 return; 2556 } 2557 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2558 if (gp.grantedPermissions.add(permissionName)) { 2559 if (ps.haveGids) { 2560 gp.gids = appendInts(gp.gids, bp.gids); 2561 } 2562 mSettings.writeLPr(); 2563 } 2564 } 2565 } 2566 2567 @Override 2568 public void revokePermission(String packageName, String permissionName) { 2569 int changedAppId = -1; 2570 2571 synchronized (mPackages) { 2572 final PackageParser.Package pkg = mPackages.get(packageName); 2573 if (pkg == null) { 2574 throw new IllegalArgumentException("Unknown package: " + packageName); 2575 } 2576 if (pkg.applicationInfo.uid != Binder.getCallingUid()) { 2577 mContext.enforceCallingOrSelfPermission( 2578 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2579 } 2580 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2581 if (bp == null) { 2582 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2583 } 2584 2585 checkGrantRevokePermissions(pkg, bp); 2586 2587 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2588 if (ps == null) { 2589 return; 2590 } 2591 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2592 if (gp.grantedPermissions.remove(permissionName)) { 2593 gp.grantedPermissions.remove(permissionName); 2594 if (ps.haveGids) { 2595 gp.gids = removeInts(gp.gids, bp.gids); 2596 } 2597 mSettings.writeLPr(); 2598 changedAppId = ps.appId; 2599 } 2600 } 2601 2602 if (changedAppId >= 0) { 2603 // We changed the perm on someone, kill its processes. 2604 IActivityManager am = ActivityManagerNative.getDefault(); 2605 if (am != null) { 2606 final int callingUserId = UserHandle.getCallingUserId(); 2607 final long ident = Binder.clearCallingIdentity(); 2608 try { 2609 //XXX we should only revoke for the calling user's app permissions, 2610 // but for now we impact all users. 2611 //am.killUid(UserHandle.getUid(callingUserId, changedAppId), 2612 // "revoke " + permissionName); 2613 int[] users = sUserManager.getUserIds(); 2614 for (int user : users) { 2615 am.killUid(UserHandle.getUid(user, changedAppId), 2616 "revoke " + permissionName); 2617 } 2618 } catch (RemoteException e) { 2619 } finally { 2620 Binder.restoreCallingIdentity(ident); 2621 } 2622 } 2623 } 2624 } 2625 2626 @Override 2627 public boolean isProtectedBroadcast(String actionName) { 2628 synchronized (mPackages) { 2629 return mProtectedBroadcasts.contains(actionName); 2630 } 2631 } 2632 2633 @Override 2634 public int checkSignatures(String pkg1, String pkg2) { 2635 synchronized (mPackages) { 2636 final PackageParser.Package p1 = mPackages.get(pkg1); 2637 final PackageParser.Package p2 = mPackages.get(pkg2); 2638 if (p1 == null || p1.mExtras == null 2639 || p2 == null || p2.mExtras == null) { 2640 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2641 } 2642 return compareSignatures(p1.mSignatures, p2.mSignatures); 2643 } 2644 } 2645 2646 @Override 2647 public int checkUidSignatures(int uid1, int uid2) { 2648 // Map to base uids. 2649 uid1 = UserHandle.getAppId(uid1); 2650 uid2 = UserHandle.getAppId(uid2); 2651 // reader 2652 synchronized (mPackages) { 2653 Signature[] s1; 2654 Signature[] s2; 2655 Object obj = mSettings.getUserIdLPr(uid1); 2656 if (obj != null) { 2657 if (obj instanceof SharedUserSetting) { 2658 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 2659 } else if (obj instanceof PackageSetting) { 2660 s1 = ((PackageSetting)obj).signatures.mSignatures; 2661 } else { 2662 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2663 } 2664 } else { 2665 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2666 } 2667 obj = mSettings.getUserIdLPr(uid2); 2668 if (obj != null) { 2669 if (obj instanceof SharedUserSetting) { 2670 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 2671 } else if (obj instanceof PackageSetting) { 2672 s2 = ((PackageSetting)obj).signatures.mSignatures; 2673 } else { 2674 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2675 } 2676 } else { 2677 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2678 } 2679 return compareSignatures(s1, s2); 2680 } 2681 } 2682 2683 /** 2684 * Compares two sets of signatures. Returns: 2685 * <br /> 2686 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 2687 * <br /> 2688 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 2689 * <br /> 2690 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 2691 * <br /> 2692 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 2693 * <br /> 2694 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 2695 */ 2696 static int compareSignatures(Signature[] s1, Signature[] s2) { 2697 if (s1 == null) { 2698 return s2 == null 2699 ? PackageManager.SIGNATURE_NEITHER_SIGNED 2700 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 2701 } 2702 2703 if (s2 == null) { 2704 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 2705 } 2706 2707 if (s1.length != s2.length) { 2708 return PackageManager.SIGNATURE_NO_MATCH; 2709 } 2710 2711 // Since both signature sets are of size 1, we can compare without HashSets. 2712 if (s1.length == 1) { 2713 return s1[0].equals(s2[0]) ? 2714 PackageManager.SIGNATURE_MATCH : 2715 PackageManager.SIGNATURE_NO_MATCH; 2716 } 2717 2718 HashSet<Signature> set1 = new HashSet<Signature>(); 2719 for (Signature sig : s1) { 2720 set1.add(sig); 2721 } 2722 HashSet<Signature> set2 = new HashSet<Signature>(); 2723 for (Signature sig : s2) { 2724 set2.add(sig); 2725 } 2726 // Make sure s2 contains all signatures in s1. 2727 if (set1.equals(set2)) { 2728 return PackageManager.SIGNATURE_MATCH; 2729 } 2730 return PackageManager.SIGNATURE_NO_MATCH; 2731 } 2732 2733 /** 2734 * If the database version for this type of package (internal storage or 2735 * external storage) is less than the version where package signatures 2736 * were updated, return true. 2737 */ 2738 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2739 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 2740 DatabaseVersion.SIGNATURE_END_ENTITY)) 2741 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 2742 DatabaseVersion.SIGNATURE_END_ENTITY)); 2743 } 2744 2745 /** 2746 * Used for backward compatibility to make sure any packages with 2747 * certificate chains get upgraded to the new style. {@code existingSigs} 2748 * will be in the old format (since they were stored on disk from before the 2749 * system upgrade) and {@code scannedSigs} will be in the newer format. 2750 */ 2751 private int compareSignaturesCompat(PackageSignatures existingSigs, 2752 PackageParser.Package scannedPkg) { 2753 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 2754 return PackageManager.SIGNATURE_NO_MATCH; 2755 } 2756 2757 HashSet<Signature> existingSet = new HashSet<Signature>(); 2758 for (Signature sig : existingSigs.mSignatures) { 2759 existingSet.add(sig); 2760 } 2761 HashSet<Signature> scannedCompatSet = new HashSet<Signature>(); 2762 for (Signature sig : scannedPkg.mSignatures) { 2763 try { 2764 Signature[] chainSignatures = sig.getChainSignatures(); 2765 for (Signature chainSig : chainSignatures) { 2766 scannedCompatSet.add(chainSig); 2767 } 2768 } catch (CertificateEncodingException e) { 2769 scannedCompatSet.add(sig); 2770 } 2771 } 2772 /* 2773 * Make sure the expanded scanned set contains all signatures in the 2774 * existing one. 2775 */ 2776 if (scannedCompatSet.equals(existingSet)) { 2777 // Migrate the old signatures to the new scheme. 2778 existingSigs.assignSignatures(scannedPkg.mSignatures); 2779 // The new KeySets will be re-added later in the scanning process. 2780 synchronized (mPackages) { 2781 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 2782 } 2783 return PackageManager.SIGNATURE_MATCH; 2784 } 2785 return PackageManager.SIGNATURE_NO_MATCH; 2786 } 2787 2788 @Override 2789 public String[] getPackagesForUid(int uid) { 2790 uid = UserHandle.getAppId(uid); 2791 // reader 2792 synchronized (mPackages) { 2793 Object obj = mSettings.getUserIdLPr(uid); 2794 if (obj instanceof SharedUserSetting) { 2795 final SharedUserSetting sus = (SharedUserSetting) obj; 2796 final int N = sus.packages.size(); 2797 final String[] res = new String[N]; 2798 final Iterator<PackageSetting> it = sus.packages.iterator(); 2799 int i = 0; 2800 while (it.hasNext()) { 2801 res[i++] = it.next().name; 2802 } 2803 return res; 2804 } else if (obj instanceof PackageSetting) { 2805 final PackageSetting ps = (PackageSetting) obj; 2806 return new String[] { ps.name }; 2807 } 2808 } 2809 return null; 2810 } 2811 2812 @Override 2813 public String getNameForUid(int uid) { 2814 // reader 2815 synchronized (mPackages) { 2816 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2817 if (obj instanceof SharedUserSetting) { 2818 final SharedUserSetting sus = (SharedUserSetting) obj; 2819 return sus.name + ":" + sus.userId; 2820 } else if (obj instanceof PackageSetting) { 2821 final PackageSetting ps = (PackageSetting) obj; 2822 return ps.name; 2823 } 2824 } 2825 return null; 2826 } 2827 2828 @Override 2829 public int getUidForSharedUser(String sharedUserName) { 2830 if(sharedUserName == null) { 2831 return -1; 2832 } 2833 // reader 2834 synchronized (mPackages) { 2835 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false); 2836 if (suid == null) { 2837 return -1; 2838 } 2839 return suid.userId; 2840 } 2841 } 2842 2843 @Override 2844 public int getFlagsForUid(int uid) { 2845 synchronized (mPackages) { 2846 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2847 if (obj instanceof SharedUserSetting) { 2848 final SharedUserSetting sus = (SharedUserSetting) obj; 2849 return sus.pkgFlags; 2850 } else if (obj instanceof PackageSetting) { 2851 final PackageSetting ps = (PackageSetting) obj; 2852 return ps.pkgFlags; 2853 } 2854 } 2855 return 0; 2856 } 2857 2858 @Override 2859 public String[] getAppOpPermissionPackages(String permissionName) { 2860 synchronized (mPackages) { 2861 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 2862 if (pkgs == null) { 2863 return null; 2864 } 2865 return pkgs.toArray(new String[pkgs.size()]); 2866 } 2867 } 2868 2869 @Override 2870 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 2871 int flags, int userId) { 2872 if (!sUserManager.exists(userId)) return null; 2873 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent"); 2874 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2875 return chooseBestActivity(intent, resolvedType, flags, query, userId); 2876 } 2877 2878 @Override 2879 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 2880 IntentFilter filter, int match, ComponentName activity) { 2881 final int userId = UserHandle.getCallingUserId(); 2882 if (DEBUG_PREFERRED) { 2883 Log.v(TAG, "setLastChosenActivity intent=" + intent 2884 + " resolvedType=" + resolvedType 2885 + " flags=" + flags 2886 + " filter=" + filter 2887 + " match=" + match 2888 + " activity=" + activity); 2889 filter.dump(new PrintStreamPrinter(System.out), " "); 2890 } 2891 intent.setComponent(null); 2892 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2893 // Find any earlier preferred or last chosen entries and nuke them 2894 findPreferredActivity(intent, resolvedType, 2895 flags, query, 0, false, true, false, userId); 2896 // Add the new activity as the last chosen for this filter 2897 addPreferredActivityInternal(filter, match, null, activity, false, userId, 2898 "Setting last chosen"); 2899 } 2900 2901 @Override 2902 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 2903 final int userId = UserHandle.getCallingUserId(); 2904 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 2905 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2906 return findPreferredActivity(intent, resolvedType, flags, query, 0, 2907 false, false, false, userId); 2908 } 2909 2910 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 2911 int flags, List<ResolveInfo> query, int userId) { 2912 if (query != null) { 2913 final int N = query.size(); 2914 if (N == 1) { 2915 return query.get(0); 2916 } else if (N > 1) { 2917 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 2918 // If there is more than one activity with the same priority, 2919 // then let the user decide between them. 2920 ResolveInfo r0 = query.get(0); 2921 ResolveInfo r1 = query.get(1); 2922 if (DEBUG_INTENT_MATCHING || debug) { 2923 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 2924 + r1.activityInfo.name + "=" + r1.priority); 2925 } 2926 // If the first activity has a higher priority, or a different 2927 // default, then it is always desireable to pick it. 2928 if (r0.priority != r1.priority 2929 || r0.preferredOrder != r1.preferredOrder 2930 || r0.isDefault != r1.isDefault) { 2931 return query.get(0); 2932 } 2933 // If we have saved a preference for a preferred activity for 2934 // this Intent, use that. 2935 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 2936 flags, query, r0.priority, true, false, debug, userId); 2937 if (ri != null) { 2938 return ri; 2939 } 2940 if (userId != 0) { 2941 ri = new ResolveInfo(mResolveInfo); 2942 ri.activityInfo = new ActivityInfo(ri.activityInfo); 2943 ri.activityInfo.applicationInfo = new ApplicationInfo( 2944 ri.activityInfo.applicationInfo); 2945 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 2946 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 2947 return ri; 2948 } 2949 return mResolveInfo; 2950 } 2951 } 2952 return null; 2953 } 2954 2955 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 2956 int flags, List<ResolveInfo> query, boolean debug, int userId) { 2957 final int N = query.size(); 2958 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 2959 .get(userId); 2960 // Get the list of persistent preferred activities that handle the intent 2961 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 2962 List<PersistentPreferredActivity> pprefs = ppir != null 2963 ? ppir.queryIntent(intent, resolvedType, 2964 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 2965 : null; 2966 if (pprefs != null && pprefs.size() > 0) { 2967 final int M = pprefs.size(); 2968 for (int i=0; i<M; i++) { 2969 final PersistentPreferredActivity ppa = pprefs.get(i); 2970 if (DEBUG_PREFERRED || debug) { 2971 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 2972 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 2973 + "\n component=" + ppa.mComponent); 2974 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 2975 } 2976 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 2977 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 2978 if (DEBUG_PREFERRED || debug) { 2979 Slog.v(TAG, "Found persistent preferred activity:"); 2980 if (ai != null) { 2981 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 2982 } else { 2983 Slog.v(TAG, " null"); 2984 } 2985 } 2986 if (ai == null) { 2987 // This previously registered persistent preferred activity 2988 // component is no longer known. Ignore it and do NOT remove it. 2989 continue; 2990 } 2991 for (int j=0; j<N; j++) { 2992 final ResolveInfo ri = query.get(j); 2993 if (!ri.activityInfo.applicationInfo.packageName 2994 .equals(ai.applicationInfo.packageName)) { 2995 continue; 2996 } 2997 if (!ri.activityInfo.name.equals(ai.name)) { 2998 continue; 2999 } 3000 // Found a persistent preference that can handle the intent. 3001 if (DEBUG_PREFERRED || debug) { 3002 Slog.v(TAG, "Returning persistent preferred activity: " + 3003 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3004 } 3005 return ri; 3006 } 3007 } 3008 } 3009 return null; 3010 } 3011 3012 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3013 List<ResolveInfo> query, int priority, boolean always, 3014 boolean removeMatches, boolean debug, int userId) { 3015 if (!sUserManager.exists(userId)) return null; 3016 // writer 3017 synchronized (mPackages) { 3018 if (intent.getSelector() != null) { 3019 intent = intent.getSelector(); 3020 } 3021 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3022 3023 // Try to find a matching persistent preferred activity. 3024 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3025 debug, userId); 3026 3027 // If a persistent preferred activity matched, use it. 3028 if (pri != null) { 3029 return pri; 3030 } 3031 3032 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3033 // Get the list of preferred activities that handle the intent 3034 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3035 List<PreferredActivity> prefs = pir != null 3036 ? pir.queryIntent(intent, resolvedType, 3037 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3038 : null; 3039 if (prefs != null && prefs.size() > 0) { 3040 boolean changed = false; 3041 try { 3042 // First figure out how good the original match set is. 3043 // We will only allow preferred activities that came 3044 // from the same match quality. 3045 int match = 0; 3046 3047 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3048 3049 final int N = query.size(); 3050 for (int j=0; j<N; j++) { 3051 final ResolveInfo ri = query.get(j); 3052 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3053 + ": 0x" + Integer.toHexString(match)); 3054 if (ri.match > match) { 3055 match = ri.match; 3056 } 3057 } 3058 3059 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3060 + Integer.toHexString(match)); 3061 3062 match &= IntentFilter.MATCH_CATEGORY_MASK; 3063 final int M = prefs.size(); 3064 for (int i=0; i<M; i++) { 3065 final PreferredActivity pa = prefs.get(i); 3066 if (DEBUG_PREFERRED || debug) { 3067 Slog.v(TAG, "Checking PreferredActivity ds=" 3068 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3069 + "\n component=" + pa.mPref.mComponent); 3070 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3071 } 3072 if (pa.mPref.mMatch != match) { 3073 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3074 + Integer.toHexString(pa.mPref.mMatch)); 3075 continue; 3076 } 3077 // If it's not an "always" type preferred activity and that's what we're 3078 // looking for, skip it. 3079 if (always && !pa.mPref.mAlways) { 3080 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3081 continue; 3082 } 3083 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3084 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3085 if (DEBUG_PREFERRED || debug) { 3086 Slog.v(TAG, "Found preferred activity:"); 3087 if (ai != null) { 3088 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3089 } else { 3090 Slog.v(TAG, " null"); 3091 } 3092 } 3093 if (ai == null) { 3094 // This previously registered preferred activity 3095 // component is no longer known. Most likely an update 3096 // to the app was installed and in the new version this 3097 // component no longer exists. Clean it up by removing 3098 // it from the preferred activities list, and skip it. 3099 Slog.w(TAG, "Removing dangling preferred activity: " 3100 + pa.mPref.mComponent); 3101 pir.removeFilter(pa); 3102 changed = true; 3103 continue; 3104 } 3105 for (int j=0; j<N; j++) { 3106 final ResolveInfo ri = query.get(j); 3107 if (!ri.activityInfo.applicationInfo.packageName 3108 .equals(ai.applicationInfo.packageName)) { 3109 continue; 3110 } 3111 if (!ri.activityInfo.name.equals(ai.name)) { 3112 continue; 3113 } 3114 3115 if (removeMatches) { 3116 pir.removeFilter(pa); 3117 changed = true; 3118 if (DEBUG_PREFERRED) { 3119 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3120 } 3121 break; 3122 } 3123 3124 // Okay we found a previously set preferred or last chosen app. 3125 // If the result set is different from when this 3126 // was created, we need to clear it and re-ask the 3127 // user their preference, if we're looking for an "always" type entry. 3128 if (always && !pa.mPref.sameSet(query, priority)) { 3129 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3130 + intent + " type " + resolvedType); 3131 if (DEBUG_PREFERRED) { 3132 Slog.v(TAG, "Removing preferred activity since set changed " 3133 + pa.mPref.mComponent); 3134 } 3135 pir.removeFilter(pa); 3136 // Re-add the filter as a "last chosen" entry (!always) 3137 PreferredActivity lastChosen = new PreferredActivity( 3138 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3139 pir.addFilter(lastChosen); 3140 changed = true; 3141 return null; 3142 } 3143 3144 // Yay! Either the set matched or we're looking for the last chosen 3145 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3146 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3147 return ri; 3148 } 3149 } 3150 } finally { 3151 if (changed) { 3152 if (DEBUG_PREFERRED) { 3153 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 3154 } 3155 mSettings.writePackageRestrictionsLPr(userId); 3156 } 3157 } 3158 } 3159 } 3160 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3161 return null; 3162 } 3163 3164 /* 3165 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3166 */ 3167 @Override 3168 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3169 int targetUserId) { 3170 mContext.enforceCallingOrSelfPermission( 3171 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3172 List<CrossProfileIntentFilter> matches = 3173 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3174 if (matches != null) { 3175 int size = matches.size(); 3176 for (int i = 0; i < size; i++) { 3177 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3178 } 3179 } 3180 ArrayList<String> packageNames = null; 3181 SparseArray<ArrayList<String>> fromSource = 3182 mSettings.mCrossProfilePackageInfo.get(sourceUserId); 3183 if (fromSource != null) { 3184 packageNames = fromSource.get(targetUserId); 3185 if (packageNames != null) { 3186 // We need the package name, so we try to resolve with the loosest flags possible 3187 List<ResolveInfo> resolveInfos = mActivities.queryIntent(intent, resolvedType, 3188 PackageManager.GET_UNINSTALLED_PACKAGES, targetUserId); 3189 int count = resolveInfos.size(); 3190 for (int i = 0; i < count; i++) { 3191 ResolveInfo resolveInfo = resolveInfos.get(i); 3192 if (packageNames.contains(resolveInfo.activityInfo.packageName)) { 3193 return true; 3194 } 3195 } 3196 } 3197 } 3198 return false; 3199 } 3200 3201 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3202 String resolvedType, int userId) { 3203 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3204 if (resolver != null) { 3205 return resolver.queryIntent(intent, resolvedType, false, userId); 3206 } 3207 return null; 3208 } 3209 3210 @Override 3211 public List<ResolveInfo> queryIntentActivities(Intent intent, 3212 String resolvedType, int flags, int userId) { 3213 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3214 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities"); 3215 ComponentName comp = intent.getComponent(); 3216 if (comp == null) { 3217 if (intent.getSelector() != null) { 3218 intent = intent.getSelector(); 3219 comp = intent.getComponent(); 3220 } 3221 } 3222 3223 if (comp != null) { 3224 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3225 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3226 if (ai != null) { 3227 final ResolveInfo ri = new ResolveInfo(); 3228 ri.activityInfo = ai; 3229 list.add(ri); 3230 } 3231 return list; 3232 } 3233 3234 // reader 3235 synchronized (mPackages) { 3236 final String pkgName = intent.getPackage(); 3237 boolean queryCrossProfile = (flags & PackageManager.NO_CROSS_PROFILE) == 0; 3238 if (pkgName == null) { 3239 ResolveInfo resolveInfo = null; 3240 if (queryCrossProfile) { 3241 // Check if the intent needs to be forwarded to another user for this package 3242 ArrayList<ResolveInfo> crossProfileResult = 3243 queryIntentActivitiesCrossProfilePackage( 3244 intent, resolvedType, flags, userId); 3245 if (!crossProfileResult.isEmpty()) { 3246 // Skip the current profile 3247 return crossProfileResult; 3248 } 3249 List<CrossProfileIntentFilter> matchingFilters = 3250 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3251 // Check for results that need to skip the current profile. 3252 resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3253 resolvedType, flags, userId); 3254 if (resolveInfo != null) { 3255 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3256 result.add(resolveInfo); 3257 return result; 3258 } 3259 // Check for cross profile results. 3260 resolveInfo = queryCrossProfileIntents( 3261 matchingFilters, intent, resolvedType, flags, userId); 3262 } 3263 // Check for results in the current profile. 3264 List<ResolveInfo> result = mActivities.queryIntent( 3265 intent, resolvedType, flags, userId); 3266 if (resolveInfo != null) { 3267 result.add(resolveInfo); 3268 Collections.sort(result, mResolvePrioritySorter); 3269 } 3270 return result; 3271 } 3272 final PackageParser.Package pkg = mPackages.get(pkgName); 3273 if (pkg != null) { 3274 if (queryCrossProfile) { 3275 ArrayList<ResolveInfo> crossProfileResult = 3276 queryIntentActivitiesCrossProfilePackage( 3277 intent, resolvedType, flags, userId, pkg, pkgName); 3278 if (!crossProfileResult.isEmpty()) { 3279 // Skip the current profile 3280 return crossProfileResult; 3281 } 3282 } 3283 return mActivities.queryIntentForPackage(intent, resolvedType, flags, 3284 pkg.activities, userId); 3285 } 3286 return new ArrayList<ResolveInfo>(); 3287 } 3288 } 3289 3290 private ResolveInfo querySkipCurrentProfileIntents( 3291 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3292 int flags, int sourceUserId) { 3293 if (matchingFilters != null) { 3294 int size = matchingFilters.size(); 3295 for (int i = 0; i < size; i ++) { 3296 CrossProfileIntentFilter filter = matchingFilters.get(i); 3297 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 3298 // Checking if there are activities in the target user that can handle the 3299 // intent. 3300 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3301 flags, sourceUserId); 3302 if (resolveInfo != null) { 3303 return resolveInfo; 3304 } 3305 } 3306 } 3307 } 3308 return null; 3309 } 3310 3311 private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage( 3312 Intent intent, String resolvedType, int flags, int userId) { 3313 ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>(); 3314 SparseArray<ArrayList<String>> sourceForwardingInfo = 3315 mSettings.mCrossProfilePackageInfo.get(userId); 3316 if (sourceForwardingInfo != null) { 3317 int NI = sourceForwardingInfo.size(); 3318 for (int i = 0; i < NI; i++) { 3319 int targetUserId = sourceForwardingInfo.keyAt(i); 3320 ArrayList<String> packageNames = sourceForwardingInfo.valueAt(i); 3321 List<ResolveInfo> resolveInfos = mActivities.queryIntent( 3322 intent, resolvedType, flags, targetUserId); 3323 int NJ = resolveInfos.size(); 3324 for (int j = 0; j < NJ; j++) { 3325 ResolveInfo resolveInfo = resolveInfos.get(j); 3326 if (packageNames.contains(resolveInfo.activityInfo.packageName)) { 3327 matchingResolveInfos.add(createForwardingResolveInfo( 3328 resolveInfo.filter, userId, targetUserId)); 3329 } 3330 } 3331 } 3332 } 3333 return matchingResolveInfos; 3334 } 3335 3336 private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage( 3337 Intent intent, String resolvedType, int flags, int userId, PackageParser.Package pkg, 3338 String packageName) { 3339 ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>(); 3340 SparseArray<ArrayList<String>> sourceForwardingInfo = 3341 mSettings.mCrossProfilePackageInfo.get(userId); 3342 if (sourceForwardingInfo != null) { 3343 int NI = sourceForwardingInfo.size(); 3344 for (int i = 0; i < NI; i++) { 3345 int targetUserId = sourceForwardingInfo.keyAt(i); 3346 if (sourceForwardingInfo.valueAt(i).contains(packageName)) { 3347 List<ResolveInfo> resolveInfos = mActivities.queryIntentForPackage( 3348 intent, resolvedType, flags, pkg.activities, targetUserId); 3349 int NJ = resolveInfos.size(); 3350 for (int j = 0; j < NJ; j++) { 3351 ResolveInfo resolveInfo = resolveInfos.get(j); 3352 matchingResolveInfos.add(createForwardingResolveInfo( 3353 resolveInfo.filter, userId, targetUserId)); 3354 } 3355 } 3356 } 3357 } 3358 return matchingResolveInfos; 3359 } 3360 3361 // Return matching ResolveInfo if any for skip current profile intent filters. 3362 private ResolveInfo queryCrossProfileIntents( 3363 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3364 int flags, int sourceUserId) { 3365 if (matchingFilters != null) { 3366 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 3367 // match the same intent. For performance reasons, it is better not to 3368 // run queryIntent twice for the same userId 3369 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 3370 int size = matchingFilters.size(); 3371 for (int i = 0; i < size; i++) { 3372 CrossProfileIntentFilter filter = matchingFilters.get(i); 3373 int targetUserId = filter.getTargetUserId(); 3374 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 3375 && !alreadyTriedUserIds.get(targetUserId)) { 3376 // Checking if there are activities in the target user that can handle the 3377 // intent. 3378 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3379 flags, sourceUserId); 3380 if (resolveInfo != null) return resolveInfo; 3381 alreadyTriedUserIds.put(targetUserId, true); 3382 } 3383 } 3384 } 3385 return null; 3386 } 3387 3388 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 3389 String resolvedType, int flags, int sourceUserId) { 3390 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 3391 resolvedType, flags, filter.getTargetUserId()); 3392 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 3393 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 3394 } 3395 return null; 3396 } 3397 3398 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 3399 int sourceUserId, int targetUserId) { 3400 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 3401 String className; 3402 if (targetUserId == UserHandle.USER_OWNER) { 3403 className = FORWARD_INTENT_TO_USER_OWNER; 3404 } else { 3405 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 3406 } 3407 ComponentName forwardingActivityComponentName = new ComponentName( 3408 mAndroidApplication.packageName, className); 3409 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 3410 sourceUserId); 3411 if (targetUserId == UserHandle.USER_OWNER) { 3412 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 3413 forwardingResolveInfo.noResourceId = true; 3414 } 3415 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 3416 forwardingResolveInfo.priority = 0; 3417 forwardingResolveInfo.preferredOrder = 0; 3418 forwardingResolveInfo.match = 0; 3419 forwardingResolveInfo.isDefault = true; 3420 forwardingResolveInfo.filter = filter; 3421 forwardingResolveInfo.targetUserId = targetUserId; 3422 return forwardingResolveInfo; 3423 } 3424 3425 @Override 3426 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 3427 Intent[] specifics, String[] specificTypes, Intent intent, 3428 String resolvedType, int flags, int userId) { 3429 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3430 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 3431 "query intent activity options"); 3432 final String resultsAction = intent.getAction(); 3433 3434 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 3435 | PackageManager.GET_RESOLVED_FILTER, userId); 3436 3437 if (DEBUG_INTENT_MATCHING) { 3438 Log.v(TAG, "Query " + intent + ": " + results); 3439 } 3440 3441 int specificsPos = 0; 3442 int N; 3443 3444 // todo: note that the algorithm used here is O(N^2). This 3445 // isn't a problem in our current environment, but if we start running 3446 // into situations where we have more than 5 or 10 matches then this 3447 // should probably be changed to something smarter... 3448 3449 // First we go through and resolve each of the specific items 3450 // that were supplied, taking care of removing any corresponding 3451 // duplicate items in the generic resolve list. 3452 if (specifics != null) { 3453 for (int i=0; i<specifics.length; i++) { 3454 final Intent sintent = specifics[i]; 3455 if (sintent == null) { 3456 continue; 3457 } 3458 3459 if (DEBUG_INTENT_MATCHING) { 3460 Log.v(TAG, "Specific #" + i + ": " + sintent); 3461 } 3462 3463 String action = sintent.getAction(); 3464 if (resultsAction != null && resultsAction.equals(action)) { 3465 // If this action was explicitly requested, then don't 3466 // remove things that have it. 3467 action = null; 3468 } 3469 3470 ResolveInfo ri = null; 3471 ActivityInfo ai = null; 3472 3473 ComponentName comp = sintent.getComponent(); 3474 if (comp == null) { 3475 ri = resolveIntent( 3476 sintent, 3477 specificTypes != null ? specificTypes[i] : null, 3478 flags, userId); 3479 if (ri == null) { 3480 continue; 3481 } 3482 if (ri == mResolveInfo) { 3483 // ACK! Must do something better with this. 3484 } 3485 ai = ri.activityInfo; 3486 comp = new ComponentName(ai.applicationInfo.packageName, 3487 ai.name); 3488 } else { 3489 ai = getActivityInfo(comp, flags, userId); 3490 if (ai == null) { 3491 continue; 3492 } 3493 } 3494 3495 // Look for any generic query activities that are duplicates 3496 // of this specific one, and remove them from the results. 3497 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 3498 N = results.size(); 3499 int j; 3500 for (j=specificsPos; j<N; j++) { 3501 ResolveInfo sri = results.get(j); 3502 if ((sri.activityInfo.name.equals(comp.getClassName()) 3503 && sri.activityInfo.applicationInfo.packageName.equals( 3504 comp.getPackageName())) 3505 || (action != null && sri.filter.matchAction(action))) { 3506 results.remove(j); 3507 if (DEBUG_INTENT_MATCHING) Log.v( 3508 TAG, "Removing duplicate item from " + j 3509 + " due to specific " + specificsPos); 3510 if (ri == null) { 3511 ri = sri; 3512 } 3513 j--; 3514 N--; 3515 } 3516 } 3517 3518 // Add this specific item to its proper place. 3519 if (ri == null) { 3520 ri = new ResolveInfo(); 3521 ri.activityInfo = ai; 3522 } 3523 results.add(specificsPos, ri); 3524 ri.specificIndex = i; 3525 specificsPos++; 3526 } 3527 } 3528 3529 // Now we go through the remaining generic results and remove any 3530 // duplicate actions that are found here. 3531 N = results.size(); 3532 for (int i=specificsPos; i<N-1; i++) { 3533 final ResolveInfo rii = results.get(i); 3534 if (rii.filter == null) { 3535 continue; 3536 } 3537 3538 // Iterate over all of the actions of this result's intent 3539 // filter... typically this should be just one. 3540 final Iterator<String> it = rii.filter.actionsIterator(); 3541 if (it == null) { 3542 continue; 3543 } 3544 while (it.hasNext()) { 3545 final String action = it.next(); 3546 if (resultsAction != null && resultsAction.equals(action)) { 3547 // If this action was explicitly requested, then don't 3548 // remove things that have it. 3549 continue; 3550 } 3551 for (int j=i+1; j<N; j++) { 3552 final ResolveInfo rij = results.get(j); 3553 if (rij.filter != null && rij.filter.hasAction(action)) { 3554 results.remove(j); 3555 if (DEBUG_INTENT_MATCHING) Log.v( 3556 TAG, "Removing duplicate item from " + j 3557 + " due to action " + action + " at " + i); 3558 j--; 3559 N--; 3560 } 3561 } 3562 } 3563 3564 // If the caller didn't request filter information, drop it now 3565 // so we don't have to marshall/unmarshall it. 3566 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3567 rii.filter = null; 3568 } 3569 } 3570 3571 // Filter out the caller activity if so requested. 3572 if (caller != null) { 3573 N = results.size(); 3574 for (int i=0; i<N; i++) { 3575 ActivityInfo ainfo = results.get(i).activityInfo; 3576 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 3577 && caller.getClassName().equals(ainfo.name)) { 3578 results.remove(i); 3579 break; 3580 } 3581 } 3582 } 3583 3584 // If the caller didn't request filter information, 3585 // drop them now so we don't have to 3586 // marshall/unmarshall it. 3587 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3588 N = results.size(); 3589 for (int i=0; i<N; i++) { 3590 results.get(i).filter = null; 3591 } 3592 } 3593 3594 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 3595 return results; 3596 } 3597 3598 @Override 3599 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 3600 int userId) { 3601 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3602 ComponentName comp = intent.getComponent(); 3603 if (comp == null) { 3604 if (intent.getSelector() != null) { 3605 intent = intent.getSelector(); 3606 comp = intent.getComponent(); 3607 } 3608 } 3609 if (comp != null) { 3610 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3611 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 3612 if (ai != null) { 3613 ResolveInfo ri = new ResolveInfo(); 3614 ri.activityInfo = ai; 3615 list.add(ri); 3616 } 3617 return list; 3618 } 3619 3620 // reader 3621 synchronized (mPackages) { 3622 String pkgName = intent.getPackage(); 3623 if (pkgName == null) { 3624 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 3625 } 3626 final PackageParser.Package pkg = mPackages.get(pkgName); 3627 if (pkg != null) { 3628 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 3629 userId); 3630 } 3631 return null; 3632 } 3633 } 3634 3635 @Override 3636 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 3637 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 3638 if (!sUserManager.exists(userId)) return null; 3639 if (query != null) { 3640 if (query.size() >= 1) { 3641 // If there is more than one service with the same priority, 3642 // just arbitrarily pick the first one. 3643 return query.get(0); 3644 } 3645 } 3646 return null; 3647 } 3648 3649 @Override 3650 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 3651 int userId) { 3652 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3653 ComponentName comp = intent.getComponent(); 3654 if (comp == null) { 3655 if (intent.getSelector() != null) { 3656 intent = intent.getSelector(); 3657 comp = intent.getComponent(); 3658 } 3659 } 3660 if (comp != null) { 3661 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3662 final ServiceInfo si = getServiceInfo(comp, flags, userId); 3663 if (si != null) { 3664 final ResolveInfo ri = new ResolveInfo(); 3665 ri.serviceInfo = si; 3666 list.add(ri); 3667 } 3668 return list; 3669 } 3670 3671 // reader 3672 synchronized (mPackages) { 3673 String pkgName = intent.getPackage(); 3674 if (pkgName == null) { 3675 return mServices.queryIntent(intent, resolvedType, flags, userId); 3676 } 3677 final PackageParser.Package pkg = mPackages.get(pkgName); 3678 if (pkg != null) { 3679 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 3680 userId); 3681 } 3682 return null; 3683 } 3684 } 3685 3686 @Override 3687 public List<ResolveInfo> queryIntentContentProviders( 3688 Intent intent, String resolvedType, int flags, int userId) { 3689 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3690 ComponentName comp = intent.getComponent(); 3691 if (comp == null) { 3692 if (intent.getSelector() != null) { 3693 intent = intent.getSelector(); 3694 comp = intent.getComponent(); 3695 } 3696 } 3697 if (comp != null) { 3698 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3699 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 3700 if (pi != null) { 3701 final ResolveInfo ri = new ResolveInfo(); 3702 ri.providerInfo = pi; 3703 list.add(ri); 3704 } 3705 return list; 3706 } 3707 3708 // reader 3709 synchronized (mPackages) { 3710 String pkgName = intent.getPackage(); 3711 if (pkgName == null) { 3712 return mProviders.queryIntent(intent, resolvedType, flags, userId); 3713 } 3714 final PackageParser.Package pkg = mPackages.get(pkgName); 3715 if (pkg != null) { 3716 return mProviders.queryIntentForPackage( 3717 intent, resolvedType, flags, pkg.providers, userId); 3718 } 3719 return null; 3720 } 3721 } 3722 3723 @Override 3724 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 3725 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3726 3727 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages"); 3728 3729 // writer 3730 synchronized (mPackages) { 3731 ArrayList<PackageInfo> list; 3732 if (listUninstalled) { 3733 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 3734 for (PackageSetting ps : mSettings.mPackages.values()) { 3735 PackageInfo pi; 3736 if (ps.pkg != null) { 3737 pi = generatePackageInfo(ps.pkg, flags, userId); 3738 } else { 3739 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3740 } 3741 if (pi != null) { 3742 list.add(pi); 3743 } 3744 } 3745 } else { 3746 list = new ArrayList<PackageInfo>(mPackages.size()); 3747 for (PackageParser.Package p : mPackages.values()) { 3748 PackageInfo pi = generatePackageInfo(p, flags, userId); 3749 if (pi != null) { 3750 list.add(pi); 3751 } 3752 } 3753 } 3754 3755 return new ParceledListSlice<PackageInfo>(list); 3756 } 3757 } 3758 3759 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 3760 String[] permissions, boolean[] tmp, int flags, int userId) { 3761 int numMatch = 0; 3762 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 3763 for (int i=0; i<permissions.length; i++) { 3764 if (gp.grantedPermissions.contains(permissions[i])) { 3765 tmp[i] = true; 3766 numMatch++; 3767 } else { 3768 tmp[i] = false; 3769 } 3770 } 3771 if (numMatch == 0) { 3772 return; 3773 } 3774 PackageInfo pi; 3775 if (ps.pkg != null) { 3776 pi = generatePackageInfo(ps.pkg, flags, userId); 3777 } else { 3778 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3779 } 3780 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 3781 if (numMatch == permissions.length) { 3782 pi.requestedPermissions = permissions; 3783 } else { 3784 pi.requestedPermissions = new String[numMatch]; 3785 numMatch = 0; 3786 for (int i=0; i<permissions.length; i++) { 3787 if (tmp[i]) { 3788 pi.requestedPermissions[numMatch] = permissions[i]; 3789 numMatch++; 3790 } 3791 } 3792 } 3793 } 3794 list.add(pi); 3795 } 3796 3797 @Override 3798 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 3799 String[] permissions, int flags, int userId) { 3800 if (!sUserManager.exists(userId)) return null; 3801 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3802 3803 // writer 3804 synchronized (mPackages) { 3805 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 3806 boolean[] tmpBools = new boolean[permissions.length]; 3807 if (listUninstalled) { 3808 for (PackageSetting ps : mSettings.mPackages.values()) { 3809 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 3810 } 3811 } else { 3812 for (PackageParser.Package pkg : mPackages.values()) { 3813 PackageSetting ps = (PackageSetting)pkg.mExtras; 3814 if (ps != null) { 3815 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 3816 userId); 3817 } 3818 } 3819 } 3820 3821 return new ParceledListSlice<PackageInfo>(list); 3822 } 3823 } 3824 3825 @Override 3826 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 3827 if (!sUserManager.exists(userId)) return null; 3828 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3829 3830 // writer 3831 synchronized (mPackages) { 3832 ArrayList<ApplicationInfo> list; 3833 if (listUninstalled) { 3834 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 3835 for (PackageSetting ps : mSettings.mPackages.values()) { 3836 ApplicationInfo ai; 3837 if (ps.pkg != null) { 3838 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3839 ps.readUserState(userId), userId); 3840 } else { 3841 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 3842 } 3843 if (ai != null) { 3844 list.add(ai); 3845 } 3846 } 3847 } else { 3848 list = new ArrayList<ApplicationInfo>(mPackages.size()); 3849 for (PackageParser.Package p : mPackages.values()) { 3850 if (p.mExtras != null) { 3851 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3852 ((PackageSetting)p.mExtras).readUserState(userId), userId); 3853 if (ai != null) { 3854 list.add(ai); 3855 } 3856 } 3857 } 3858 } 3859 3860 return new ParceledListSlice<ApplicationInfo>(list); 3861 } 3862 } 3863 3864 public List<ApplicationInfo> getPersistentApplications(int flags) { 3865 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 3866 3867 // reader 3868 synchronized (mPackages) { 3869 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 3870 final int userId = UserHandle.getCallingUserId(); 3871 while (i.hasNext()) { 3872 final PackageParser.Package p = i.next(); 3873 if (p.applicationInfo != null 3874 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 3875 && (!mSafeMode || isSystemApp(p))) { 3876 PackageSetting ps = mSettings.mPackages.get(p.packageName); 3877 if (ps != null) { 3878 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3879 ps.readUserState(userId), userId); 3880 if (ai != null) { 3881 finalList.add(ai); 3882 } 3883 } 3884 } 3885 } 3886 } 3887 3888 return finalList; 3889 } 3890 3891 @Override 3892 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 3893 if (!sUserManager.exists(userId)) return null; 3894 // reader 3895 synchronized (mPackages) { 3896 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 3897 PackageSetting ps = provider != null 3898 ? mSettings.mPackages.get(provider.owner.packageName) 3899 : null; 3900 return ps != null 3901 && mSettings.isEnabledLPr(provider.info, flags, userId) 3902 && (!mSafeMode || (provider.info.applicationInfo.flags 3903 &ApplicationInfo.FLAG_SYSTEM) != 0) 3904 ? PackageParser.generateProviderInfo(provider, flags, 3905 ps.readUserState(userId), userId) 3906 : null; 3907 } 3908 } 3909 3910 /** 3911 * @deprecated 3912 */ 3913 @Deprecated 3914 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 3915 // reader 3916 synchronized (mPackages) { 3917 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 3918 .entrySet().iterator(); 3919 final int userId = UserHandle.getCallingUserId(); 3920 while (i.hasNext()) { 3921 Map.Entry<String, PackageParser.Provider> entry = i.next(); 3922 PackageParser.Provider p = entry.getValue(); 3923 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3924 3925 if (ps != null && p.syncable 3926 && (!mSafeMode || (p.info.applicationInfo.flags 3927 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 3928 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 3929 ps.readUserState(userId), userId); 3930 if (info != null) { 3931 outNames.add(entry.getKey()); 3932 outInfo.add(info); 3933 } 3934 } 3935 } 3936 } 3937 } 3938 3939 @Override 3940 public List<ProviderInfo> queryContentProviders(String processName, 3941 int uid, int flags) { 3942 ArrayList<ProviderInfo> finalList = null; 3943 // reader 3944 synchronized (mPackages) { 3945 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 3946 final int userId = processName != null ? 3947 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 3948 while (i.hasNext()) { 3949 final PackageParser.Provider p = i.next(); 3950 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3951 if (ps != null && p.info.authority != null 3952 && (processName == null 3953 || (p.info.processName.equals(processName) 3954 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 3955 && mSettings.isEnabledLPr(p.info, flags, userId) 3956 && (!mSafeMode 3957 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 3958 if (finalList == null) { 3959 finalList = new ArrayList<ProviderInfo>(3); 3960 } 3961 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 3962 ps.readUserState(userId), userId); 3963 if (info != null) { 3964 finalList.add(info); 3965 } 3966 } 3967 } 3968 } 3969 3970 if (finalList != null) { 3971 Collections.sort(finalList, mProviderInitOrderSorter); 3972 } 3973 3974 return finalList; 3975 } 3976 3977 @Override 3978 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 3979 int flags) { 3980 // reader 3981 synchronized (mPackages) { 3982 final PackageParser.Instrumentation i = mInstrumentation.get(name); 3983 return PackageParser.generateInstrumentationInfo(i, flags); 3984 } 3985 } 3986 3987 @Override 3988 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 3989 int flags) { 3990 ArrayList<InstrumentationInfo> finalList = 3991 new ArrayList<InstrumentationInfo>(); 3992 3993 // reader 3994 synchronized (mPackages) { 3995 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 3996 while (i.hasNext()) { 3997 final PackageParser.Instrumentation p = i.next(); 3998 if (targetPackage == null 3999 || targetPackage.equals(p.info.targetPackage)) { 4000 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4001 flags); 4002 if (ii != null) { 4003 finalList.add(ii); 4004 } 4005 } 4006 } 4007 } 4008 4009 return finalList; 4010 } 4011 4012 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4013 HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4014 if (overlays == null) { 4015 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4016 return; 4017 } 4018 for (PackageParser.Package opkg : overlays.values()) { 4019 // Not much to do if idmap fails: we already logged the error 4020 // and we certainly don't want to abort installation of pkg simply 4021 // because an overlay didn't fit properly. For these reasons, 4022 // ignore the return value of createIdmapForPackagePairLI. 4023 createIdmapForPackagePairLI(pkg, opkg); 4024 } 4025 } 4026 4027 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4028 PackageParser.Package opkg) { 4029 if (!opkg.mTrustedOverlay) { 4030 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4031 opkg.baseCodePath + ": overlay not trusted"); 4032 return false; 4033 } 4034 HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4035 if (overlaySet == null) { 4036 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4037 opkg.baseCodePath + " but target package has no known overlays"); 4038 return false; 4039 } 4040 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4041 // TODO: generate idmap for split APKs 4042 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4043 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4044 + opkg.baseCodePath); 4045 return false; 4046 } 4047 PackageParser.Package[] overlayArray = 4048 overlaySet.values().toArray(new PackageParser.Package[0]); 4049 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4050 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4051 return p1.mOverlayPriority - p2.mOverlayPriority; 4052 } 4053 }; 4054 Arrays.sort(overlayArray, cmp); 4055 4056 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4057 int i = 0; 4058 for (PackageParser.Package p : overlayArray) { 4059 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4060 } 4061 return true; 4062 } 4063 4064 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 4065 final File[] files = dir.listFiles(); 4066 if (ArrayUtils.isEmpty(files)) { 4067 Log.d(TAG, "No files in app dir " + dir); 4068 return; 4069 } 4070 4071 if (DEBUG_PACKAGE_SCANNING) { 4072 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 4073 + " flags=0x" + Integer.toHexString(parseFlags)); 4074 } 4075 4076 for (File file : files) { 4077 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 4078 && !PackageInstallerService.isStageName(file.getName()); 4079 if (!isPackage) { 4080 // Ignore entries which are not packages 4081 continue; 4082 } 4083 try { 4084 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 4085 scanFlags, currentTime, null); 4086 } catch (PackageManagerException e) { 4087 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4088 4089 // Delete invalid userdata apps 4090 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4091 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4092 Slog.w(TAG, "Deleting invalid package at " + file); 4093 if (file.isDirectory()) { 4094 FileUtils.deleteContents(file); 4095 } 4096 file.delete(); 4097 } 4098 } 4099 } 4100 } 4101 4102 private static File getSettingsProblemFile() { 4103 File dataDir = Environment.getDataDirectory(); 4104 File systemDir = new File(dataDir, "system"); 4105 File fname = new File(systemDir, "uiderrors.txt"); 4106 return fname; 4107 } 4108 4109 static void reportSettingsProblem(int priority, String msg) { 4110 try { 4111 File fname = getSettingsProblemFile(); 4112 FileOutputStream out = new FileOutputStream(fname, true); 4113 PrintWriter pw = new FastPrintWriter(out); 4114 SimpleDateFormat formatter = new SimpleDateFormat(); 4115 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4116 pw.println(dateString + ": " + msg); 4117 pw.close(); 4118 FileUtils.setPermissions( 4119 fname.toString(), 4120 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4121 -1, -1); 4122 } catch (java.io.IOException e) { 4123 } 4124 Slog.println(priority, TAG, msg); 4125 } 4126 4127 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 4128 PackageParser.Package pkg, File srcFile, int parseFlags) 4129 throws PackageManagerException { 4130 if (ps != null 4131 && ps.codePath.equals(srcFile) 4132 && ps.timeStamp == srcFile.lastModified() 4133 && !isCompatSignatureUpdateNeeded(pkg)) { 4134 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4135 if (ps.signatures.mSignatures != null 4136 && ps.signatures.mSignatures.length != 0 4137 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4138 // Optimization: reuse the existing cached certificates 4139 // if the package appears to be unchanged. 4140 pkg.mSignatures = ps.signatures.mSignatures; 4141 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4142 synchronized (mPackages) { 4143 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 4144 } 4145 return; 4146 } 4147 4148 Slog.w(TAG, "PackageSetting for " + ps.name 4149 + " is missing signatures. Collecting certs again to recover them."); 4150 } else { 4151 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4152 } 4153 4154 try { 4155 pp.collectCertificates(pkg, parseFlags); 4156 pp.collectManifestDigest(pkg); 4157 } catch (PackageParserException e) { 4158 throw new PackageManagerException(e.error, "Failed to collect certificates for " 4159 + pkg.packageName + ": " + e.getMessage()); 4160 } 4161 } 4162 4163 /* 4164 * Scan a package and return the newly parsed package. 4165 * Returns null in case of errors and the error code is stored in mLastScanError 4166 */ 4167 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 4168 long currentTime, UserHandle user) throws PackageManagerException { 4169 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4170 parseFlags |= mDefParseFlags; 4171 PackageParser pp = new PackageParser(); 4172 pp.setSeparateProcesses(mSeparateProcesses); 4173 pp.setOnlyCoreApps(mOnlyCore); 4174 pp.setDisplayMetrics(mMetrics); 4175 4176 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 4177 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4178 } 4179 4180 final PackageParser.Package pkg; 4181 try { 4182 pkg = pp.parsePackage(scanFile, parseFlags); 4183 } catch (PackageParserException e) { 4184 throw new PackageManagerException(e.error, 4185 "Failed to scan " + scanFile + ": " + e.getMessage()); 4186 } 4187 4188 PackageSetting ps = null; 4189 PackageSetting updatedPkg; 4190 // reader 4191 synchronized (mPackages) { 4192 // Look to see if we already know about this package. 4193 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4194 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4195 // This package has been renamed to its original name. Let's 4196 // use that. 4197 ps = mSettings.peekPackageLPr(oldName); 4198 } 4199 // If there was no original package, see one for the real package name. 4200 if (ps == null) { 4201 ps = mSettings.peekPackageLPr(pkg.packageName); 4202 } 4203 // Check to see if this package could be hiding/updating a system 4204 // package. Must look for it either under the original or real 4205 // package name depending on our state. 4206 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4207 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4208 } 4209 boolean updatedPkgBetter = false; 4210 // First check if this is a system package that may involve an update 4211 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4212 if (ps != null && !ps.codePath.equals(scanFile)) { 4213 // The path has changed from what was last scanned... check the 4214 // version of the new path against what we have stored to determine 4215 // what to do. 4216 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4217 if (pkg.mVersionCode < ps.versionCode) { 4218 // The system package has been updated and the code path does not match 4219 // Ignore entry. Skip it. 4220 Log.i(TAG, "Package " + ps.name + " at " + scanFile 4221 + " ignored: updated version " + ps.versionCode 4222 + " better than this " + pkg.mVersionCode); 4223 if (!updatedPkg.codePath.equals(scanFile)) { 4224 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4225 + ps.name + " changing from " + updatedPkg.codePathString 4226 + " to " + scanFile); 4227 updatedPkg.codePath = scanFile; 4228 updatedPkg.codePathString = scanFile.toString(); 4229 // This is the point at which we know that the system-disk APK 4230 // for this package has moved during a reboot (e.g. due to an OTA), 4231 // so we need to reevaluate it for privilege policy. 4232 if (locationIsPrivileged(scanFile)) { 4233 updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED; 4234 } 4235 } 4236 updatedPkg.pkg = pkg; 4237 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 4238 } else { 4239 // The current app on the system partition is better than 4240 // what we have updated to on the data partition; switch 4241 // back to the system partition version. 4242 // At this point, its safely assumed that package installation for 4243 // apps in system partition will go through. If not there won't be a working 4244 // version of the app 4245 // writer 4246 synchronized (mPackages) { 4247 // Just remove the loaded entries from package lists. 4248 mPackages.remove(ps.name); 4249 } 4250 Slog.w(TAG, "Package " + ps.name + " at " + scanFile 4251 + "reverting from " + ps.codePathString 4252 + ": new version " + pkg.mVersionCode 4253 + " better than installed " + ps.versionCode); 4254 4255 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4256 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4257 getAppDexInstructionSets(ps)); 4258 synchronized (mInstallLock) { 4259 args.cleanUpResourcesLI(); 4260 } 4261 synchronized (mPackages) { 4262 mSettings.enableSystemPackageLPw(ps.name); 4263 } 4264 updatedPkgBetter = true; 4265 } 4266 } 4267 } 4268 4269 if (updatedPkg != null) { 4270 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4271 // initially 4272 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4273 4274 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4275 // flag set initially 4276 if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) { 4277 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4278 } 4279 } 4280 4281 // Verify certificates against what was last scanned 4282 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 4283 4284 /* 4285 * A new system app appeared, but we already had a non-system one of the 4286 * same name installed earlier. 4287 */ 4288 boolean shouldHideSystemApp = false; 4289 if (updatedPkg == null && ps != null 4290 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4291 /* 4292 * Check to make sure the signatures match first. If they don't, 4293 * wipe the installed application and its data. 4294 */ 4295 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4296 != PackageManager.SIGNATURE_MATCH) { 4297 if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!"); 4298 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4299 ps = null; 4300 } else { 4301 /* 4302 * If the newly-added system app is an older version than the 4303 * already installed version, hide it. It will be scanned later 4304 * and re-added like an update. 4305 */ 4306 if (pkg.mVersionCode < ps.versionCode) { 4307 shouldHideSystemApp = true; 4308 } else { 4309 /* 4310 * The newly found system app is a newer version that the 4311 * one previously installed. Simply remove the 4312 * already-installed application and replace it with our own 4313 * while keeping the application data. 4314 */ 4315 Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from " 4316 + ps.codePathString + ": new version " + pkg.mVersionCode 4317 + " better than installed " + ps.versionCode); 4318 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4319 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4320 getAppDexInstructionSets(ps)); 4321 synchronized (mInstallLock) { 4322 args.cleanUpResourcesLI(); 4323 } 4324 } 4325 } 4326 } 4327 4328 // The apk is forward locked (not public) if its code and resources 4329 // are kept in different files. (except for app in either system or 4330 // vendor path). 4331 // TODO grab this value from PackageSettings 4332 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4333 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4334 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 4335 } 4336 } 4337 4338 // TODO: extend to support forward-locked splits 4339 String resourcePath = null; 4340 String baseResourcePath = null; 4341 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 4342 if (ps != null && ps.resourcePathString != null) { 4343 resourcePath = ps.resourcePathString; 4344 baseResourcePath = ps.resourcePathString; 4345 } else { 4346 // Should not happen at all. Just log an error. 4347 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 4348 } 4349 } else { 4350 resourcePath = pkg.codePath; 4351 baseResourcePath = pkg.baseCodePath; 4352 } 4353 4354 // Set application objects path explicitly. 4355 pkg.applicationInfo.setCodePath(pkg.codePath); 4356 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 4357 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 4358 pkg.applicationInfo.setResourcePath(resourcePath); 4359 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 4360 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 4361 4362 // Note that we invoke the following method only if we are about to unpack an application 4363 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 4364 | SCAN_UPDATE_SIGNATURE, currentTime, user); 4365 4366 /* 4367 * If the system app should be overridden by a previously installed 4368 * data, hide the system app now and let the /data/app scan pick it up 4369 * again. 4370 */ 4371 if (shouldHideSystemApp) { 4372 synchronized (mPackages) { 4373 /* 4374 * We have to grant systems permissions before we hide, because 4375 * grantPermissions will assume the package update is trying to 4376 * expand its permissions. 4377 */ 4378 grantPermissionsLPw(pkg, true); 4379 mSettings.disableSystemPackageLPw(pkg.packageName); 4380 } 4381 } 4382 4383 return scannedPkg; 4384 } 4385 4386 private static String fixProcessName(String defProcessName, 4387 String processName, int uid) { 4388 if (processName == null) { 4389 return defProcessName; 4390 } 4391 return processName; 4392 } 4393 4394 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 4395 throws PackageManagerException { 4396 if (pkgSetting.signatures.mSignatures != null) { 4397 // Already existing package. Make sure signatures match 4398 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 4399 == PackageManager.SIGNATURE_MATCH; 4400 if (!match) { 4401 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 4402 == PackageManager.SIGNATURE_MATCH; 4403 } 4404 if (!match) { 4405 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 4406 + pkg.packageName + " signatures do not match the " 4407 + "previously installed version; ignoring!"); 4408 } 4409 } 4410 4411 // Check for shared user signatures 4412 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 4413 // Already existing package. Make sure signatures match 4414 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4415 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 4416 if (!match) { 4417 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 4418 == PackageManager.SIGNATURE_MATCH; 4419 } 4420 if (!match) { 4421 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 4422 "Package " + pkg.packageName 4423 + " has no signatures that match those in shared user " 4424 + pkgSetting.sharedUser.name + "; ignoring!"); 4425 } 4426 } 4427 } 4428 4429 /** 4430 * Enforces that only the system UID or root's UID can call a method exposed 4431 * via Binder. 4432 * 4433 * @param message used as message if SecurityException is thrown 4434 * @throws SecurityException if the caller is not system or root 4435 */ 4436 private static final void enforceSystemOrRoot(String message) { 4437 final int uid = Binder.getCallingUid(); 4438 if (uid != Process.SYSTEM_UID && uid != 0) { 4439 throw new SecurityException(message); 4440 } 4441 } 4442 4443 @Override 4444 public void performBootDexOpt() { 4445 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4446 4447 final HashSet<PackageParser.Package> pkgs; 4448 synchronized (mPackages) { 4449 pkgs = mDeferredDexOpt; 4450 mDeferredDexOpt = null; 4451 } 4452 4453 if (pkgs != null) { 4454 // Filter out packages that aren't recently used. 4455 // 4456 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 4457 // should do a full dexopt. 4458 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 4459 // TODO: add a property to control this? 4460 long dexOptLRUThresholdInMinutes; 4461 if (mLazyDexOpt) { 4462 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 4463 } else { 4464 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 4465 } 4466 long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 4467 4468 int total = pkgs.size(); 4469 int skipped = 0; 4470 long now = System.currentTimeMillis(); 4471 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 4472 PackageParser.Package pkg = i.next(); 4473 long then = pkg.mLastPackageUsageTimeInMills; 4474 if (then + dexOptLRUThresholdInMills < now) { 4475 if (DEBUG_DEXOPT) { 4476 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 4477 ((then == 0) ? "never" : new Date(then))); 4478 } 4479 i.remove(); 4480 skipped++; 4481 } 4482 } 4483 if (DEBUG_DEXOPT) { 4484 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 4485 } 4486 } 4487 4488 int i = 0; 4489 for (PackageParser.Package pkg : pkgs) { 4490 i++; 4491 if (DEBUG_DEXOPT) { 4492 Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size() 4493 + ": " + pkg.packageName); 4494 } 4495 if (!isFirstBoot()) { 4496 try { 4497 ActivityManagerNative.getDefault().showBootMessage( 4498 mContext.getResources().getString( 4499 R.string.android_upgrading_apk, 4500 i, pkgs.size()), true); 4501 } catch (RemoteException e) { 4502 } 4503 } 4504 PackageParser.Package p = pkg; 4505 synchronized (mInstallLock) { 4506 performDexOptLI(p, null /* instruction sets */, false /* force dex */, false /* defer */, 4507 true /* include dependencies */); 4508 } 4509 } 4510 } 4511 } 4512 4513 @Override 4514 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 4515 return performDexOpt(packageName, instructionSet, false); 4516 } 4517 4518 private static String getPrimaryInstructionSet(ApplicationInfo info) { 4519 if (info.primaryCpuAbi == null) { 4520 return getPreferredInstructionSet(); 4521 } 4522 4523 return VMRuntime.getInstructionSet(info.primaryCpuAbi); 4524 } 4525 4526 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 4527 boolean dexopt = mLazyDexOpt || backgroundDexopt; 4528 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 4529 if (!dexopt && !updateUsage) { 4530 // We aren't going to dexopt or update usage, so bail early. 4531 return false; 4532 } 4533 PackageParser.Package p; 4534 final String targetInstructionSet; 4535 synchronized (mPackages) { 4536 p = mPackages.get(packageName); 4537 if (p == null) { 4538 return false; 4539 } 4540 if (updateUsage) { 4541 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 4542 } 4543 mPackageUsage.write(false); 4544 if (!dexopt) { 4545 // We aren't going to dexopt, so bail early. 4546 return false; 4547 } 4548 4549 targetInstructionSet = instructionSet != null ? instructionSet : 4550 getPrimaryInstructionSet(p.applicationInfo); 4551 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 4552 return false; 4553 } 4554 } 4555 4556 synchronized (mInstallLock) { 4557 final String[] instructionSets = new String[] { targetInstructionSet }; 4558 return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */, 4559 true /* include dependencies */) == DEX_OPT_PERFORMED; 4560 } 4561 } 4562 4563 public HashSet<String> getPackagesThatNeedDexOpt() { 4564 HashSet<String> pkgs = null; 4565 synchronized (mPackages) { 4566 for (PackageParser.Package p : mPackages.values()) { 4567 if (DEBUG_DEXOPT) { 4568 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 4569 } 4570 if (!p.mDexOptPerformed.isEmpty()) { 4571 continue; 4572 } 4573 if (pkgs == null) { 4574 pkgs = new HashSet<String>(); 4575 } 4576 pkgs.add(p.packageName); 4577 } 4578 } 4579 return pkgs; 4580 } 4581 4582 public void shutdown() { 4583 mPackageUsage.write(true); 4584 } 4585 4586 private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets, 4587 boolean forceDex, boolean defer, HashSet<String> done) { 4588 for (int i=0; i<libs.size(); i++) { 4589 PackageParser.Package libPkg; 4590 String libName; 4591 synchronized (mPackages) { 4592 libName = libs.get(i); 4593 SharedLibraryEntry lib = mSharedLibraries.get(libName); 4594 if (lib != null && lib.apk != null) { 4595 libPkg = mPackages.get(lib.apk); 4596 } else { 4597 libPkg = null; 4598 } 4599 } 4600 if (libPkg != null && !done.contains(libName)) { 4601 performDexOptLI(libPkg, instructionSets, forceDex, defer, done); 4602 } 4603 } 4604 } 4605 4606 static final int DEX_OPT_SKIPPED = 0; 4607 static final int DEX_OPT_PERFORMED = 1; 4608 static final int DEX_OPT_DEFERRED = 2; 4609 static final int DEX_OPT_FAILED = -1; 4610 4611 private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets, 4612 boolean forceDex, boolean defer, HashSet<String> done) { 4613 final String[] instructionSets = targetInstructionSets != null ? 4614 targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo); 4615 4616 if (done != null) { 4617 done.add(pkg.packageName); 4618 if (pkg.usesLibraries != null) { 4619 performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done); 4620 } 4621 if (pkg.usesOptionalLibraries != null) { 4622 performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done); 4623 } 4624 } 4625 4626 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) { 4627 return DEX_OPT_SKIPPED; 4628 } 4629 4630 final boolean vmSafeMode = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0; 4631 4632 final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly(); 4633 boolean performedDexOpt = false; 4634 // There are three basic cases here: 4635 // 1.) we need to dexopt, either because we are forced or it is needed 4636 // 2.) we are defering a needed dexopt 4637 // 3.) we are skipping an unneeded dexopt 4638 final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 4639 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 4640 if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) { 4641 continue; 4642 } 4643 4644 for (String path : paths) { 4645 try { 4646 // This will return DEXOPT_NEEDED if we either cannot find any odex file for this 4647 // patckage or the one we find does not match the image checksum (i.e. it was 4648 // compiled against an old image). It will return PATCHOAT_NEEDED if we can find a 4649 // odex file and it matches the checksum of the image but not its base address, 4650 // meaning we need to move it. 4651 final byte isDexOptNeeded = DexFile.isDexOptNeededInternal(path, 4652 pkg.packageName, dexCodeInstructionSet, defer); 4653 if (forceDex || (!defer && isDexOptNeeded == DexFile.DEXOPT_NEEDED)) { 4654 Log.i(TAG, "Running dexopt on: " + path + " pkg=" 4655 + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet 4656 + " vmSafeMode=" + vmSafeMode); 4657 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4658 final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg), 4659 pkg.packageName, dexCodeInstructionSet, vmSafeMode); 4660 4661 if (ret < 0) { 4662 // Don't bother running dexopt again if we failed, it will probably 4663 // just result in an error again. Also, don't bother dexopting for other 4664 // paths & ISAs. 4665 return DEX_OPT_FAILED; 4666 } 4667 4668 performedDexOpt = true; 4669 } else if (!defer && isDexOptNeeded == DexFile.PATCHOAT_NEEDED) { 4670 Log.i(TAG, "Running patchoat on: " + pkg.applicationInfo.packageName); 4671 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4672 final int ret = mInstaller.patchoat(path, sharedGid, !isForwardLocked(pkg), 4673 pkg.packageName, dexCodeInstructionSet); 4674 4675 if (ret < 0) { 4676 // Don't bother running patchoat again if we failed, it will probably 4677 // just result in an error again. Also, don't bother dexopting for other 4678 // paths & ISAs. 4679 return DEX_OPT_FAILED; 4680 } 4681 4682 performedDexOpt = true; 4683 } 4684 4685 // We're deciding to defer a needed dexopt. Don't bother dexopting for other 4686 // paths and instruction sets. We'll deal with them all together when we process 4687 // our list of deferred dexopts. 4688 if (defer && isDexOptNeeded != DexFile.UP_TO_DATE) { 4689 if (mDeferredDexOpt == null) { 4690 mDeferredDexOpt = new HashSet<PackageParser.Package>(); 4691 } 4692 mDeferredDexOpt.add(pkg); 4693 return DEX_OPT_DEFERRED; 4694 } 4695 } catch (FileNotFoundException e) { 4696 Slog.w(TAG, "Apk not found for dexopt: " + path); 4697 return DEX_OPT_FAILED; 4698 } catch (IOException e) { 4699 Slog.w(TAG, "IOException reading apk: " + path, e); 4700 return DEX_OPT_FAILED; 4701 } catch (StaleDexCacheError e) { 4702 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e); 4703 return DEX_OPT_FAILED; 4704 } catch (Exception e) { 4705 Slog.w(TAG, "Exception when doing dexopt : ", e); 4706 return DEX_OPT_FAILED; 4707 } 4708 } 4709 4710 // At this point we haven't failed dexopt and we haven't deferred dexopt. We must 4711 // either have either succeeded dexopt, or have had isDexOptNeededInternal tell us 4712 // it isn't required. We therefore mark that this package doesn't need dexopt unless 4713 // it's forced. performedDexOpt will tell us whether we performed dex-opt or skipped 4714 // it. 4715 pkg.mDexOptPerformed.add(dexCodeInstructionSet); 4716 } 4717 4718 // If we've gotten here, we're sure that no error occurred and that we haven't 4719 // deferred dex-opt. We've either dex-opted one more paths or instruction sets or 4720 // we've skipped all of them because they are up to date. In both cases this 4721 // package doesn't need dexopt any longer. 4722 return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED; 4723 } 4724 4725 private static String[] getAppDexInstructionSets(ApplicationInfo info) { 4726 if (info.primaryCpuAbi != null) { 4727 if (info.secondaryCpuAbi != null) { 4728 return new String[] { 4729 VMRuntime.getInstructionSet(info.primaryCpuAbi), 4730 VMRuntime.getInstructionSet(info.secondaryCpuAbi) }; 4731 } else { 4732 return new String[] { 4733 VMRuntime.getInstructionSet(info.primaryCpuAbi) }; 4734 } 4735 } 4736 4737 return new String[] { getPreferredInstructionSet() }; 4738 } 4739 4740 private static String[] getAppDexInstructionSets(PackageSetting ps) { 4741 if (ps.primaryCpuAbiString != null) { 4742 if (ps.secondaryCpuAbiString != null) { 4743 return new String[] { 4744 VMRuntime.getInstructionSet(ps.primaryCpuAbiString), 4745 VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) }; 4746 } else { 4747 return new String[] { 4748 VMRuntime.getInstructionSet(ps.primaryCpuAbiString) }; 4749 } 4750 } 4751 4752 return new String[] { getPreferredInstructionSet() }; 4753 } 4754 4755 private static String getPreferredInstructionSet() { 4756 if (sPreferredInstructionSet == null) { 4757 sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]); 4758 } 4759 4760 return sPreferredInstructionSet; 4761 } 4762 4763 private static List<String> getAllInstructionSets() { 4764 final String[] allAbis = Build.SUPPORTED_ABIS; 4765 final List<String> allInstructionSets = new ArrayList<String>(allAbis.length); 4766 4767 for (String abi : allAbis) { 4768 final String instructionSet = VMRuntime.getInstructionSet(abi); 4769 if (!allInstructionSets.contains(instructionSet)) { 4770 allInstructionSets.add(instructionSet); 4771 } 4772 } 4773 4774 return allInstructionSets; 4775 } 4776 4777 /** 4778 * Returns the instruction set that should be used to compile dex code. In the presence of 4779 * a native bridge this might be different than the one shared libraries use. 4780 */ 4781 private static String getDexCodeInstructionSet(String sharedLibraryIsa) { 4782 String dexCodeIsa = SystemProperties.get("ro.dalvik.vm.isa." + sharedLibraryIsa); 4783 return (dexCodeIsa.isEmpty() ? sharedLibraryIsa : dexCodeIsa); 4784 } 4785 4786 private static String[] getDexCodeInstructionSets(String[] instructionSets) { 4787 HashSet<String> dexCodeInstructionSets = new HashSet<String>(instructionSets.length); 4788 for (String instructionSet : instructionSets) { 4789 dexCodeInstructionSets.add(getDexCodeInstructionSet(instructionSet)); 4790 } 4791 return dexCodeInstructionSets.toArray(new String[dexCodeInstructionSets.size()]); 4792 } 4793 4794 @Override 4795 public void forceDexOpt(String packageName) { 4796 enforceSystemOrRoot("forceDexOpt"); 4797 4798 PackageParser.Package pkg; 4799 synchronized (mPackages) { 4800 pkg = mPackages.get(packageName); 4801 if (pkg == null) { 4802 throw new IllegalArgumentException("Missing package: " + packageName); 4803 } 4804 } 4805 4806 synchronized (mInstallLock) { 4807 final String[] instructionSets = new String[] { 4808 getPrimaryInstructionSet(pkg.applicationInfo) }; 4809 final int res = performDexOptLI(pkg, instructionSets, true, false, true); 4810 if (res != DEX_OPT_PERFORMED) { 4811 throw new IllegalStateException("Failed to dexopt: " + res); 4812 } 4813 } 4814 } 4815 4816 private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets, 4817 boolean forceDex, boolean defer, boolean inclDependencies) { 4818 HashSet<String> done; 4819 if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) { 4820 done = new HashSet<String>(); 4821 done.add(pkg.packageName); 4822 } else { 4823 done = null; 4824 } 4825 return performDexOptLI(pkg, instructionSets, forceDex, defer, done); 4826 } 4827 4828 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 4829 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 4830 Slog.w(TAG, "Unable to update from " + oldPkg.name 4831 + " to " + newPkg.packageName 4832 + ": old package not in system partition"); 4833 return false; 4834 } else if (mPackages.get(oldPkg.name) != null) { 4835 Slog.w(TAG, "Unable to update from " + oldPkg.name 4836 + " to " + newPkg.packageName 4837 + ": old package still exists"); 4838 return false; 4839 } 4840 return true; 4841 } 4842 4843 File getDataPathForUser(int userId) { 4844 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId); 4845 } 4846 4847 private File getDataPathForPackage(String packageName, int userId) { 4848 /* 4849 * Until we fully support multiple users, return the directory we 4850 * previously would have. The PackageManagerTests will need to be 4851 * revised when this is changed back.. 4852 */ 4853 if (userId == 0) { 4854 return new File(mAppDataDir, packageName); 4855 } else { 4856 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 4857 + File.separator + packageName); 4858 } 4859 } 4860 4861 private int createDataDirsLI(String packageName, int uid, String seinfo) { 4862 int[] users = sUserManager.getUserIds(); 4863 int res = mInstaller.install(packageName, uid, uid, seinfo); 4864 if (res < 0) { 4865 return res; 4866 } 4867 for (int user : users) { 4868 if (user != 0) { 4869 res = mInstaller.createUserData(packageName, 4870 UserHandle.getUid(user, uid), user, seinfo); 4871 if (res < 0) { 4872 return res; 4873 } 4874 } 4875 } 4876 return res; 4877 } 4878 4879 private int removeDataDirsLI(String packageName) { 4880 int[] users = sUserManager.getUserIds(); 4881 int res = 0; 4882 for (int user : users) { 4883 int resInner = mInstaller.remove(packageName, user); 4884 if (resInner < 0) { 4885 res = resInner; 4886 } 4887 } 4888 4889 return res; 4890 } 4891 4892 private int deleteCodeCacheDirsLI(String packageName) { 4893 int[] users = sUserManager.getUserIds(); 4894 int res = 0; 4895 for (int user : users) { 4896 int resInner = mInstaller.deleteCodeCacheFiles(packageName, user); 4897 if (resInner < 0) { 4898 res = resInner; 4899 } 4900 } 4901 return res; 4902 } 4903 4904 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 4905 PackageParser.Package changingLib) { 4906 if (file.path != null) { 4907 usesLibraryFiles.add(file.path); 4908 return; 4909 } 4910 PackageParser.Package p = mPackages.get(file.apk); 4911 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 4912 // If we are doing this while in the middle of updating a library apk, 4913 // then we need to make sure to use that new apk for determining the 4914 // dependencies here. (We haven't yet finished committing the new apk 4915 // to the package manager state.) 4916 if (p == null || p.packageName.equals(changingLib.packageName)) { 4917 p = changingLib; 4918 } 4919 } 4920 if (p != null) { 4921 usesLibraryFiles.addAll(p.getAllCodePaths()); 4922 } 4923 } 4924 4925 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 4926 PackageParser.Package changingLib) throws PackageManagerException { 4927 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 4928 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 4929 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 4930 for (int i=0; i<N; i++) { 4931 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 4932 if (file == null) { 4933 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 4934 "Package " + pkg.packageName + " requires unavailable shared library " 4935 + pkg.usesLibraries.get(i) + "; failing!"); 4936 } 4937 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4938 } 4939 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 4940 for (int i=0; i<N; i++) { 4941 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 4942 if (file == null) { 4943 Slog.w(TAG, "Package " + pkg.packageName 4944 + " desires unavailable shared library " 4945 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 4946 } else { 4947 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4948 } 4949 } 4950 N = usesLibraryFiles.size(); 4951 if (N > 0) { 4952 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 4953 } else { 4954 pkg.usesLibraryFiles = null; 4955 } 4956 } 4957 } 4958 4959 private static boolean hasString(List<String> list, List<String> which) { 4960 if (list == null) { 4961 return false; 4962 } 4963 for (int i=list.size()-1; i>=0; i--) { 4964 for (int j=which.size()-1; j>=0; j--) { 4965 if (which.get(j).equals(list.get(i))) { 4966 return true; 4967 } 4968 } 4969 } 4970 return false; 4971 } 4972 4973 private void updateAllSharedLibrariesLPw() { 4974 for (PackageParser.Package pkg : mPackages.values()) { 4975 try { 4976 updateSharedLibrariesLPw(pkg, null); 4977 } catch (PackageManagerException e) { 4978 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 4979 } 4980 } 4981 } 4982 4983 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 4984 PackageParser.Package changingPkg) { 4985 ArrayList<PackageParser.Package> res = null; 4986 for (PackageParser.Package pkg : mPackages.values()) { 4987 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 4988 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 4989 if (res == null) { 4990 res = new ArrayList<PackageParser.Package>(); 4991 } 4992 res.add(pkg); 4993 try { 4994 updateSharedLibrariesLPw(pkg, changingPkg); 4995 } catch (PackageManagerException e) { 4996 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 4997 } 4998 } 4999 } 5000 return res; 5001 } 5002 5003 /** 5004 * Derive the value of the {@code cpuAbiOverride} based on the provided 5005 * value and an optional stored value from the package settings. 5006 */ 5007 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5008 String cpuAbiOverride = null; 5009 5010 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5011 cpuAbiOverride = null; 5012 } else if (abiOverride != null) { 5013 cpuAbiOverride = abiOverride; 5014 } else if (settings != null) { 5015 cpuAbiOverride = settings.cpuAbiOverrideString; 5016 } 5017 5018 return cpuAbiOverride; 5019 } 5020 5021 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5022 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5023 final File scanFile = new File(pkg.codePath); 5024 if (pkg.applicationInfo.getCodePath() == null || 5025 pkg.applicationInfo.getResourcePath() == null) { 5026 // Bail out. The resource and code paths haven't been set. 5027 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5028 "Code and resource paths haven't been set correctly"); 5029 } 5030 5031 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5032 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5033 } 5034 5035 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5036 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED; 5037 } 5038 5039 if (mCustomResolverComponentName != null && 5040 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5041 setUpCustomResolverActivity(pkg); 5042 } 5043 5044 if (pkg.packageName.equals("android")) { 5045 synchronized (mPackages) { 5046 if (mAndroidApplication != null) { 5047 Slog.w(TAG, "*************************************************"); 5048 Slog.w(TAG, "Core android package being redefined. Skipping."); 5049 Slog.w(TAG, " file=" + scanFile); 5050 Slog.w(TAG, "*************************************************"); 5051 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5052 "Core android package being redefined. Skipping."); 5053 } 5054 5055 // Set up information for our fall-back user intent resolution activity. 5056 mPlatformPackage = pkg; 5057 pkg.mVersionCode = mSdkVersion; 5058 mAndroidApplication = pkg.applicationInfo; 5059 5060 if (!mResolverReplaced) { 5061 mResolveActivity.applicationInfo = mAndroidApplication; 5062 mResolveActivity.name = ResolverActivity.class.getName(); 5063 mResolveActivity.packageName = mAndroidApplication.packageName; 5064 mResolveActivity.processName = "system:ui"; 5065 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5066 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5067 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5068 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5069 mResolveActivity.exported = true; 5070 mResolveActivity.enabled = true; 5071 mResolveInfo.activityInfo = mResolveActivity; 5072 mResolveInfo.priority = 0; 5073 mResolveInfo.preferredOrder = 0; 5074 mResolveInfo.match = 0; 5075 mResolveComponentName = new ComponentName( 5076 mAndroidApplication.packageName, mResolveActivity.name); 5077 } 5078 } 5079 } 5080 5081 if (DEBUG_PACKAGE_SCANNING) { 5082 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5083 Log.d(TAG, "Scanning package " + pkg.packageName); 5084 } 5085 5086 if (mPackages.containsKey(pkg.packageName) 5087 || mSharedLibraries.containsKey(pkg.packageName)) { 5088 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5089 "Application package " + pkg.packageName 5090 + " already installed. Skipping duplicate."); 5091 } 5092 5093 // Initialize package source and resource directories 5094 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5095 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5096 5097 SharedUserSetting suid = null; 5098 PackageSetting pkgSetting = null; 5099 5100 if (!isSystemApp(pkg)) { 5101 // Only system apps can use these features. 5102 pkg.mOriginalPackages = null; 5103 pkg.mRealPackage = null; 5104 pkg.mAdoptPermissions = null; 5105 } 5106 5107 // writer 5108 synchronized (mPackages) { 5109 if (pkg.mSharedUserId != null) { 5110 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true); 5111 if (suid == null) { 5112 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5113 "Creating application package " + pkg.packageName 5114 + " for shared user failed"); 5115 } 5116 if (DEBUG_PACKAGE_SCANNING) { 5117 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5118 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5119 + "): packages=" + suid.packages); 5120 } 5121 } 5122 5123 // Check if we are renaming from an original package name. 5124 PackageSetting origPackage = null; 5125 String realName = null; 5126 if (pkg.mOriginalPackages != null) { 5127 // This package may need to be renamed to a previously 5128 // installed name. Let's check on that... 5129 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5130 if (pkg.mOriginalPackages.contains(renamed)) { 5131 // This package had originally been installed as the 5132 // original name, and we have already taken care of 5133 // transitioning to the new one. Just update the new 5134 // one to continue using the old name. 5135 realName = pkg.mRealPackage; 5136 if (!pkg.packageName.equals(renamed)) { 5137 // Callers into this function may have already taken 5138 // care of renaming the package; only do it here if 5139 // it is not already done. 5140 pkg.setPackageName(renamed); 5141 } 5142 5143 } else { 5144 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5145 if ((origPackage = mSettings.peekPackageLPr( 5146 pkg.mOriginalPackages.get(i))) != null) { 5147 // We do have the package already installed under its 5148 // original name... should we use it? 5149 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5150 // New package is not compatible with original. 5151 origPackage = null; 5152 continue; 5153 } else if (origPackage.sharedUser != null) { 5154 // Make sure uid is compatible between packages. 5155 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5156 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5157 + " to " + pkg.packageName + ": old uid " 5158 + origPackage.sharedUser.name 5159 + " differs from " + pkg.mSharedUserId); 5160 origPackage = null; 5161 continue; 5162 } 5163 } else { 5164 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5165 + pkg.packageName + " to old name " + origPackage.name); 5166 } 5167 break; 5168 } 5169 } 5170 } 5171 } 5172 5173 if (mTransferedPackages.contains(pkg.packageName)) { 5174 Slog.w(TAG, "Package " + pkg.packageName 5175 + " was transferred to another, but its .apk remains"); 5176 } 5177 5178 // Just create the setting, don't add it yet. For already existing packages 5179 // the PkgSetting exists already and doesn't have to be created. 5180 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5181 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 5182 pkg.applicationInfo.primaryCpuAbi, 5183 pkg.applicationInfo.secondaryCpuAbi, 5184 pkg.applicationInfo.flags, user, false); 5185 if (pkgSetting == null) { 5186 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5187 "Creating application package " + pkg.packageName + " failed"); 5188 } 5189 5190 if (pkgSetting.origPackage != null) { 5191 // If we are first transitioning from an original package, 5192 // fix up the new package's name now. We need to do this after 5193 // looking up the package under its new name, so getPackageLP 5194 // can take care of fiddling things correctly. 5195 pkg.setPackageName(origPackage.name); 5196 5197 // File a report about this. 5198 String msg = "New package " + pkgSetting.realName 5199 + " renamed to replace old package " + pkgSetting.name; 5200 reportSettingsProblem(Log.WARN, msg); 5201 5202 // Make a note of it. 5203 mTransferedPackages.add(origPackage.name); 5204 5205 // No longer need to retain this. 5206 pkgSetting.origPackage = null; 5207 } 5208 5209 if (realName != null) { 5210 // Make a note of it. 5211 mTransferedPackages.add(pkg.packageName); 5212 } 5213 5214 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5215 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5216 } 5217 5218 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5219 // Check all shared libraries and map to their actual file path. 5220 // We only do this here for apps not on a system dir, because those 5221 // are the only ones that can fail an install due to this. We 5222 // will take care of the system apps by updating all of their 5223 // library paths after the scan is done. 5224 updateSharedLibrariesLPw(pkg, null); 5225 } 5226 5227 if (mFoundPolicyFile) { 5228 SELinuxMMAC.assignSeinfoValue(pkg); 5229 } 5230 5231 pkg.applicationInfo.uid = pkgSetting.appId; 5232 pkg.mExtras = pkgSetting; 5233 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5234 try { 5235 verifySignaturesLP(pkgSetting, pkg); 5236 } catch (PackageManagerException e) { 5237 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5238 throw e; 5239 } 5240 // The signature has changed, but this package is in the system 5241 // image... let's recover! 5242 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5243 // However... if this package is part of a shared user, but it 5244 // doesn't match the signature of the shared user, let's fail. 5245 // What this means is that you can't change the signatures 5246 // associated with an overall shared user, which doesn't seem all 5247 // that unreasonable. 5248 if (pkgSetting.sharedUser != null) { 5249 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5250 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5251 throw new PackageManagerException( 5252 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 5253 "Signature mismatch for shared user : " 5254 + pkgSetting.sharedUser); 5255 } 5256 } 5257 // File a report about this. 5258 String msg = "System package " + pkg.packageName 5259 + " signature changed; retaining data."; 5260 reportSettingsProblem(Log.WARN, msg); 5261 } 5262 } else { 5263 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 5264 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5265 + pkg.packageName + " upgrade keys do not match the " 5266 + "previously installed version"); 5267 } else { 5268 // signatures may have changed as result of upgrade 5269 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5270 } 5271 } 5272 // Verify that this new package doesn't have any content providers 5273 // that conflict with existing packages. Only do this if the 5274 // package isn't already installed, since we don't want to break 5275 // things that are installed. 5276 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 5277 final int N = pkg.providers.size(); 5278 int i; 5279 for (i=0; i<N; i++) { 5280 PackageParser.Provider p = pkg.providers.get(i); 5281 if (p.info.authority != null) { 5282 String names[] = p.info.authority.split(";"); 5283 for (int j = 0; j < names.length; j++) { 5284 if (mProvidersByAuthority.containsKey(names[j])) { 5285 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5286 final String otherPackageName = 5287 ((other != null && other.getComponentName() != null) ? 5288 other.getComponentName().getPackageName() : "?"); 5289 throw new PackageManagerException( 5290 INSTALL_FAILED_CONFLICTING_PROVIDER, 5291 "Can't install because provider name " + names[j] 5292 + " (in package " + pkg.applicationInfo.packageName 5293 + ") is already used by " + otherPackageName); 5294 } 5295 } 5296 } 5297 } 5298 } 5299 5300 if (pkg.mAdoptPermissions != null) { 5301 // This package wants to adopt ownership of permissions from 5302 // another package. 5303 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 5304 final String origName = pkg.mAdoptPermissions.get(i); 5305 final PackageSetting orig = mSettings.peekPackageLPr(origName); 5306 if (orig != null) { 5307 if (verifyPackageUpdateLPr(orig, pkg)) { 5308 Slog.i(TAG, "Adopting permissions from " + origName + " to " 5309 + pkg.packageName); 5310 mSettings.transferPermissionsLPw(origName, pkg.packageName); 5311 } 5312 } 5313 } 5314 } 5315 } 5316 5317 final String pkgName = pkg.packageName; 5318 5319 final long scanFileTime = scanFile.lastModified(); 5320 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 5321 pkg.applicationInfo.processName = fixProcessName( 5322 pkg.applicationInfo.packageName, 5323 pkg.applicationInfo.processName, 5324 pkg.applicationInfo.uid); 5325 5326 File dataPath; 5327 if (mPlatformPackage == pkg) { 5328 // The system package is special. 5329 dataPath = new File (Environment.getDataDirectory(), "system"); 5330 pkg.applicationInfo.dataDir = dataPath.getPath(); 5331 5332 } else { 5333 // This is a normal package, need to make its data directory. 5334 dataPath = getDataPathForPackage(pkg.packageName, 0); 5335 5336 boolean uidError = false; 5337 5338 if (dataPath.exists()) { 5339 int currentUid = 0; 5340 try { 5341 StructStat stat = Os.stat(dataPath.getPath()); 5342 currentUid = stat.st_uid; 5343 } catch (ErrnoException e) { 5344 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 5345 } 5346 5347 // If we have mismatched owners for the data path, we have a problem. 5348 if (currentUid != pkg.applicationInfo.uid) { 5349 boolean recovered = false; 5350 if (currentUid == 0) { 5351 // The directory somehow became owned by root. Wow. 5352 // This is probably because the system was stopped while 5353 // installd was in the middle of messing with its libs 5354 // directory. Ask installd to fix that. 5355 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 5356 pkg.applicationInfo.uid); 5357 if (ret >= 0) { 5358 recovered = true; 5359 String msg = "Package " + pkg.packageName 5360 + " unexpectedly changed to uid 0; recovered to " + 5361 + pkg.applicationInfo.uid; 5362 reportSettingsProblem(Log.WARN, msg); 5363 } 5364 } 5365 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5366 || (scanFlags&SCAN_BOOTING) != 0)) { 5367 // If this is a system app, we can at least delete its 5368 // current data so the application will still work. 5369 int ret = removeDataDirsLI(pkgName); 5370 if (ret >= 0) { 5371 // TODO: Kill the processes first 5372 // Old data gone! 5373 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5374 ? "System package " : "Third party package "; 5375 String msg = prefix + pkg.packageName 5376 + " has changed from uid: " 5377 + currentUid + " to " 5378 + pkg.applicationInfo.uid + "; old data erased"; 5379 reportSettingsProblem(Log.WARN, msg); 5380 recovered = true; 5381 5382 // And now re-install the app. 5383 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5384 pkg.applicationInfo.seinfo); 5385 if (ret == -1) { 5386 // Ack should not happen! 5387 msg = prefix + pkg.packageName 5388 + " could not have data directory re-created after delete."; 5389 reportSettingsProblem(Log.WARN, msg); 5390 throw new PackageManagerException( 5391 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 5392 } 5393 } 5394 if (!recovered) { 5395 mHasSystemUidErrors = true; 5396 } 5397 } else if (!recovered) { 5398 // If we allow this install to proceed, we will be broken. 5399 // Abort, abort! 5400 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 5401 "scanPackageLI"); 5402 } 5403 if (!recovered) { 5404 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 5405 + pkg.applicationInfo.uid + "/fs_" 5406 + currentUid; 5407 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 5408 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 5409 String msg = "Package " + pkg.packageName 5410 + " has mismatched uid: " 5411 + currentUid + " on disk, " 5412 + pkg.applicationInfo.uid + " in settings"; 5413 // writer 5414 synchronized (mPackages) { 5415 mSettings.mReadMessages.append(msg); 5416 mSettings.mReadMessages.append('\n'); 5417 uidError = true; 5418 if (!pkgSetting.uidError) { 5419 reportSettingsProblem(Log.ERROR, msg); 5420 } 5421 } 5422 } 5423 } 5424 pkg.applicationInfo.dataDir = dataPath.getPath(); 5425 if (mShouldRestoreconData) { 5426 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 5427 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 5428 pkg.applicationInfo.uid); 5429 } 5430 } else { 5431 if (DEBUG_PACKAGE_SCANNING) { 5432 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5433 Log.v(TAG, "Want this data dir: " + dataPath); 5434 } 5435 //invoke installer to do the actual installation 5436 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5437 pkg.applicationInfo.seinfo); 5438 if (ret < 0) { 5439 // Error from installer 5440 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5441 "Unable to create data dirs [errorCode=" + ret + "]"); 5442 } 5443 5444 if (dataPath.exists()) { 5445 pkg.applicationInfo.dataDir = dataPath.getPath(); 5446 } else { 5447 Slog.w(TAG, "Unable to create data directory: " + dataPath); 5448 pkg.applicationInfo.dataDir = null; 5449 } 5450 } 5451 5452 pkgSetting.uidError = uidError; 5453 } 5454 5455 final String path = scanFile.getPath(); 5456 final String codePath = pkg.applicationInfo.getCodePath(); 5457 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 5458 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 5459 setBundledAppAbisAndRoots(pkg, pkgSetting); 5460 5461 // If we haven't found any native libraries for the app, check if it has 5462 // renderscript code. We'll need to force the app to 32 bit if it has 5463 // renderscript bitcode. 5464 if (pkg.applicationInfo.primaryCpuAbi == null 5465 && pkg.applicationInfo.secondaryCpuAbi == null 5466 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5467 NativeLibraryHelper.Handle handle = null; 5468 try { 5469 handle = NativeLibraryHelper.Handle.create(scanFile); 5470 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5471 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 5472 } 5473 } catch (IOException ioe) { 5474 Slog.w(TAG, "Error scanning system app : " + ioe); 5475 } finally { 5476 IoUtils.closeQuietly(handle); 5477 } 5478 } 5479 5480 setNativeLibraryPaths(pkg); 5481 } else { 5482 // TODO: We can probably be smarter about this stuff. For installed apps, 5483 // we can calculate this information at install time once and for all. For 5484 // system apps, we can probably assume that this information doesn't change 5485 // after the first boot scan. As things stand, we do lots of unnecessary work. 5486 5487 // Give ourselves some initial paths; we'll come back for another 5488 // pass once we've determined ABI below. 5489 setNativeLibraryPaths(pkg); 5490 5491 final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg); 5492 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 5493 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 5494 5495 NativeLibraryHelper.Handle handle = null; 5496 try { 5497 handle = NativeLibraryHelper.Handle.create(scanFile); 5498 // TODO(multiArch): This can be null for apps that didn't go through the 5499 // usual installation process. We can calculate it again, like we 5500 // do during install time. 5501 // 5502 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 5503 // unnecessary. 5504 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 5505 5506 // Null out the abis so that they can be recalculated. 5507 pkg.applicationInfo.primaryCpuAbi = null; 5508 pkg.applicationInfo.secondaryCpuAbi = null; 5509 if (isMultiArch(pkg.applicationInfo)) { 5510 // Warn if we've set an abiOverride for multi-lib packages.. 5511 // By definition, we need to copy both 32 and 64 bit libraries for 5512 // such packages. 5513 if (pkg.cpuAbiOverride != null 5514 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 5515 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 5516 } 5517 5518 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 5519 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 5520 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 5521 if (isAsec) { 5522 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 5523 } else { 5524 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5525 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 5526 useIsaSpecificSubdirs); 5527 } 5528 } 5529 5530 maybeThrowExceptionForMultiArchCopy( 5531 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 5532 5533 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5534 if (isAsec) { 5535 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 5536 } else { 5537 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5538 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 5539 useIsaSpecificSubdirs); 5540 } 5541 } 5542 5543 maybeThrowExceptionForMultiArchCopy( 5544 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 5545 5546 if (abi64 >= 0) { 5547 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 5548 } 5549 5550 if (abi32 >= 0) { 5551 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 5552 if (abi64 >= 0) { 5553 pkg.applicationInfo.secondaryCpuAbi = abi; 5554 } else { 5555 pkg.applicationInfo.primaryCpuAbi = abi; 5556 } 5557 } 5558 } else { 5559 String[] abiList = (cpuAbiOverride != null) ? 5560 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 5561 5562 // Enable gross and lame hacks for apps that are built with old 5563 // SDK tools. We must scan their APKs for renderscript bitcode and 5564 // not launch them if it's present. Don't bother checking on devices 5565 // that don't have 64 bit support. 5566 boolean needsRenderScriptOverride = false; 5567 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 5568 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5569 abiList = Build.SUPPORTED_32_BIT_ABIS; 5570 needsRenderScriptOverride = true; 5571 } 5572 5573 final int copyRet; 5574 if (isAsec) { 5575 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 5576 } else { 5577 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5578 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 5579 } 5580 5581 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5582 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5583 "Error unpackaging native libs for app, errorCode=" + copyRet); 5584 } 5585 5586 if (copyRet >= 0) { 5587 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 5588 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 5589 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 5590 } else if (needsRenderScriptOverride) { 5591 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 5592 } 5593 } 5594 } catch (IOException ioe) { 5595 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 5596 } finally { 5597 IoUtils.closeQuietly(handle); 5598 } 5599 5600 // Now that we've calculated the ABIs and determined if it's an internal app, 5601 // we will go ahead and populate the nativeLibraryPath. 5602 setNativeLibraryPaths(pkg); 5603 5604 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 5605 final int[] userIds = sUserManager.getUserIds(); 5606 synchronized (mInstallLock) { 5607 // Create a native library symlink only if we have native libraries 5608 // and if the native libraries are 32 bit libraries. We do not provide 5609 // this symlink for 64 bit libraries. 5610 if (pkg.applicationInfo.primaryCpuAbi != null && 5611 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 5612 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 5613 for (int userId : userIds) { 5614 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 5615 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5616 "Failed linking native library dir (user=" + userId + ")"); 5617 } 5618 } 5619 } 5620 } 5621 } 5622 5623 // This is a special case for the "system" package, where the ABI is 5624 // dictated by the zygote configuration (and init.rc). We should keep track 5625 // of this ABI so that we can deal with "normal" applications that run under 5626 // the same UID correctly. 5627 if (mPlatformPackage == pkg) { 5628 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 5629 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 5630 } 5631 5632 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 5633 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 5634 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 5635 // Copy the derived override back to the parsed package, so that we can 5636 // update the package settings accordingly. 5637 pkg.cpuAbiOverride = cpuAbiOverride; 5638 5639 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 5640 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 5641 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 5642 5643 // Push the derived path down into PackageSettings so we know what to 5644 // clean up at uninstall time. 5645 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 5646 5647 if (DEBUG_ABI_SELECTION) { 5648 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 5649 " primary=" + pkg.applicationInfo.primaryCpuAbi + 5650 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 5651 } 5652 5653 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 5654 // We don't do this here during boot because we can do it all 5655 // at once after scanning all existing packages. 5656 // 5657 // We also do this *before* we perform dexopt on this package, so that 5658 // we can avoid redundant dexopts, and also to make sure we've got the 5659 // code and package path correct. 5660 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 5661 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 5662 } 5663 5664 if ((scanFlags&SCAN_NO_DEX) == 0) { 5665 if (performDexOptLI(pkg, null /* instruction sets */, forceDex, (scanFlags&SCAN_DEFER_DEX) != 0, false) 5666 == DEX_OPT_FAILED) { 5667 if ((scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5668 removeDataDirsLI(pkg.packageName); 5669 } 5670 5671 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 5672 } 5673 } 5674 5675 if (mFactoryTest && pkg.requestedPermissions.contains( 5676 android.Manifest.permission.FACTORY_TEST)) { 5677 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 5678 } 5679 5680 ArrayList<PackageParser.Package> clientLibPkgs = null; 5681 5682 // writer 5683 synchronized (mPackages) { 5684 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5685 // Only system apps can add new shared libraries. 5686 if (pkg.libraryNames != null) { 5687 for (int i=0; i<pkg.libraryNames.size(); i++) { 5688 String name = pkg.libraryNames.get(i); 5689 boolean allowed = false; 5690 if (isUpdatedSystemApp(pkg)) { 5691 // New library entries can only be added through the 5692 // system image. This is important to get rid of a lot 5693 // of nasty edge cases: for example if we allowed a non- 5694 // system update of the app to add a library, then uninstalling 5695 // the update would make the library go away, and assumptions 5696 // we made such as through app install filtering would now 5697 // have allowed apps on the device which aren't compatible 5698 // with it. Better to just have the restriction here, be 5699 // conservative, and create many fewer cases that can negatively 5700 // impact the user experience. 5701 final PackageSetting sysPs = mSettings 5702 .getDisabledSystemPkgLPr(pkg.packageName); 5703 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 5704 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 5705 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 5706 allowed = true; 5707 allowed = true; 5708 break; 5709 } 5710 } 5711 } 5712 } else { 5713 allowed = true; 5714 } 5715 if (allowed) { 5716 if (!mSharedLibraries.containsKey(name)) { 5717 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 5718 } else if (!name.equals(pkg.packageName)) { 5719 Slog.w(TAG, "Package " + pkg.packageName + " library " 5720 + name + " already exists; skipping"); 5721 } 5722 } else { 5723 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 5724 + name + " that is not declared on system image; skipping"); 5725 } 5726 } 5727 if ((scanFlags&SCAN_BOOTING) == 0) { 5728 // If we are not booting, we need to update any applications 5729 // that are clients of our shared library. If we are booting, 5730 // this will all be done once the scan is complete. 5731 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 5732 } 5733 } 5734 } 5735 } 5736 5737 // We also need to dexopt any apps that are dependent on this library. Note that 5738 // if these fail, we should abort the install since installing the library will 5739 // result in some apps being broken. 5740 if (clientLibPkgs != null) { 5741 if ((scanFlags&SCAN_NO_DEX) == 0) { 5742 for (int i=0; i<clientLibPkgs.size(); i++) { 5743 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5744 if (performDexOptLI(clientPkg, null /* instruction sets */, 5745 forceDex, (scanFlags&SCAN_DEFER_DEX) != 0, false) 5746 == DEX_OPT_FAILED) { 5747 if ((scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5748 removeDataDirsLI(pkg.packageName); 5749 } 5750 5751 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 5752 "scanPackageLI failed to dexopt clientLibPkgs"); 5753 } 5754 } 5755 } 5756 } 5757 5758 // Request the ActivityManager to kill the process(only for existing packages) 5759 // so that we do not end up in a confused state while the user is still using the older 5760 // version of the application while the new one gets installed. 5761 if ((scanFlags & SCAN_REPLACING) != 0) { 5762 killApplication(pkg.applicationInfo.packageName, 5763 pkg.applicationInfo.uid, "update pkg"); 5764 } 5765 5766 // Also need to kill any apps that are dependent on the library. 5767 if (clientLibPkgs != null) { 5768 for (int i=0; i<clientLibPkgs.size(); i++) { 5769 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5770 killApplication(clientPkg.applicationInfo.packageName, 5771 clientPkg.applicationInfo.uid, "update lib"); 5772 } 5773 } 5774 5775 // writer 5776 synchronized (mPackages) { 5777 // We don't expect installation to fail beyond this point 5778 5779 // Add the new setting to mSettings 5780 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 5781 // Add the new setting to mPackages 5782 mPackages.put(pkg.applicationInfo.packageName, pkg); 5783 // Make sure we don't accidentally delete its data. 5784 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 5785 while (iter.hasNext()) { 5786 PackageCleanItem item = iter.next(); 5787 if (pkgName.equals(item.packageName)) { 5788 iter.remove(); 5789 } 5790 } 5791 5792 // Take care of first install / last update times. 5793 if (currentTime != 0) { 5794 if (pkgSetting.firstInstallTime == 0) { 5795 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 5796 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 5797 pkgSetting.lastUpdateTime = currentTime; 5798 } 5799 } else if (pkgSetting.firstInstallTime == 0) { 5800 // We need *something*. Take time time stamp of the file. 5801 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 5802 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 5803 if (scanFileTime != pkgSetting.timeStamp) { 5804 // A package on the system image has changed; consider this 5805 // to be an update. 5806 pkgSetting.lastUpdateTime = scanFileTime; 5807 } 5808 } 5809 5810 // Add the package's KeySets to the global KeySetManagerService 5811 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5812 try { 5813 // Old KeySetData no longer valid. 5814 ksms.removeAppKeySetDataLPw(pkg.packageName); 5815 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 5816 if (pkg.mKeySetMapping != null) { 5817 for (Map.Entry<String, ArraySet<PublicKey>> entry : 5818 pkg.mKeySetMapping.entrySet()) { 5819 if (entry.getValue() != null) { 5820 ksms.addDefinedKeySetToPackageLPw(pkg.packageName, 5821 entry.getValue(), entry.getKey()); 5822 } 5823 } 5824 if (pkg.mUpgradeKeySets != null) { 5825 for (String upgradeAlias : pkg.mUpgradeKeySets) { 5826 ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias); 5827 } 5828 } 5829 } 5830 } catch (NullPointerException e) { 5831 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 5832 } catch (IllegalArgumentException e) { 5833 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 5834 } 5835 5836 int N = pkg.providers.size(); 5837 StringBuilder r = null; 5838 int i; 5839 for (i=0; i<N; i++) { 5840 PackageParser.Provider p = pkg.providers.get(i); 5841 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 5842 p.info.processName, pkg.applicationInfo.uid); 5843 mProviders.addProvider(p); 5844 p.syncable = p.info.isSyncable; 5845 if (p.info.authority != null) { 5846 String names[] = p.info.authority.split(";"); 5847 p.info.authority = null; 5848 for (int j = 0; j < names.length; j++) { 5849 if (j == 1 && p.syncable) { 5850 // We only want the first authority for a provider to possibly be 5851 // syncable, so if we already added this provider using a different 5852 // authority clear the syncable flag. We copy the provider before 5853 // changing it because the mProviders object contains a reference 5854 // to a provider that we don't want to change. 5855 // Only do this for the second authority since the resulting provider 5856 // object can be the same for all future authorities for this provider. 5857 p = new PackageParser.Provider(p); 5858 p.syncable = false; 5859 } 5860 if (!mProvidersByAuthority.containsKey(names[j])) { 5861 mProvidersByAuthority.put(names[j], p); 5862 if (p.info.authority == null) { 5863 p.info.authority = names[j]; 5864 } else { 5865 p.info.authority = p.info.authority + ";" + names[j]; 5866 } 5867 if (DEBUG_PACKAGE_SCANNING) { 5868 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5869 Log.d(TAG, "Registered content provider: " + names[j] 5870 + ", className = " + p.info.name + ", isSyncable = " 5871 + p.info.isSyncable); 5872 } 5873 } else { 5874 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5875 Slog.w(TAG, "Skipping provider name " + names[j] + 5876 " (in package " + pkg.applicationInfo.packageName + 5877 "): name already used by " 5878 + ((other != null && other.getComponentName() != null) 5879 ? other.getComponentName().getPackageName() : "?")); 5880 } 5881 } 5882 } 5883 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5884 if (r == null) { 5885 r = new StringBuilder(256); 5886 } else { 5887 r.append(' '); 5888 } 5889 r.append(p.info.name); 5890 } 5891 } 5892 if (r != null) { 5893 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 5894 } 5895 5896 N = pkg.services.size(); 5897 r = null; 5898 for (i=0; i<N; i++) { 5899 PackageParser.Service s = pkg.services.get(i); 5900 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 5901 s.info.processName, pkg.applicationInfo.uid); 5902 mServices.addService(s); 5903 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5904 if (r == null) { 5905 r = new StringBuilder(256); 5906 } else { 5907 r.append(' '); 5908 } 5909 r.append(s.info.name); 5910 } 5911 } 5912 if (r != null) { 5913 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 5914 } 5915 5916 N = pkg.receivers.size(); 5917 r = null; 5918 for (i=0; i<N; i++) { 5919 PackageParser.Activity a = pkg.receivers.get(i); 5920 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5921 a.info.processName, pkg.applicationInfo.uid); 5922 mReceivers.addActivity(a, "receiver"); 5923 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5924 if (r == null) { 5925 r = new StringBuilder(256); 5926 } else { 5927 r.append(' '); 5928 } 5929 r.append(a.info.name); 5930 } 5931 } 5932 if (r != null) { 5933 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 5934 } 5935 5936 N = pkg.activities.size(); 5937 r = null; 5938 for (i=0; i<N; i++) { 5939 PackageParser.Activity a = pkg.activities.get(i); 5940 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5941 a.info.processName, pkg.applicationInfo.uid); 5942 mActivities.addActivity(a, "activity"); 5943 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5944 if (r == null) { 5945 r = new StringBuilder(256); 5946 } else { 5947 r.append(' '); 5948 } 5949 r.append(a.info.name); 5950 } 5951 } 5952 if (r != null) { 5953 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 5954 } 5955 5956 N = pkg.permissionGroups.size(); 5957 r = null; 5958 for (i=0; i<N; i++) { 5959 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 5960 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 5961 if (cur == null) { 5962 mPermissionGroups.put(pg.info.name, pg); 5963 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5964 if (r == null) { 5965 r = new StringBuilder(256); 5966 } else { 5967 r.append(' '); 5968 } 5969 r.append(pg.info.name); 5970 } 5971 } else { 5972 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 5973 + pg.info.packageName + " ignored: original from " 5974 + cur.info.packageName); 5975 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5976 if (r == null) { 5977 r = new StringBuilder(256); 5978 } else { 5979 r.append(' '); 5980 } 5981 r.append("DUP:"); 5982 r.append(pg.info.name); 5983 } 5984 } 5985 } 5986 if (r != null) { 5987 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 5988 } 5989 5990 N = pkg.permissions.size(); 5991 r = null; 5992 for (i=0; i<N; i++) { 5993 PackageParser.Permission p = pkg.permissions.get(i); 5994 HashMap<String, BasePermission> permissionMap = 5995 p.tree ? mSettings.mPermissionTrees 5996 : mSettings.mPermissions; 5997 p.group = mPermissionGroups.get(p.info.group); 5998 if (p.info.group == null || p.group != null) { 5999 BasePermission bp = permissionMap.get(p.info.name); 6000 if (bp == null) { 6001 bp = new BasePermission(p.info.name, p.info.packageName, 6002 BasePermission.TYPE_NORMAL); 6003 permissionMap.put(p.info.name, bp); 6004 } 6005 if (bp.perm == null) { 6006 if (bp.sourcePackage != null 6007 && !bp.sourcePackage.equals(p.info.packageName)) { 6008 // If this is a permission that was formerly defined by a non-system 6009 // app, but is now defined by a system app (following an upgrade), 6010 // discard the previous declaration and consider the system's to be 6011 // canonical. 6012 if (isSystemApp(p.owner)) { 6013 String msg = "New decl " + p.owner + " of permission " 6014 + p.info.name + " is system"; 6015 reportSettingsProblem(Log.WARN, msg); 6016 bp.sourcePackage = null; 6017 } 6018 } 6019 if (bp.sourcePackage == null 6020 || bp.sourcePackage.equals(p.info.packageName)) { 6021 BasePermission tree = findPermissionTreeLP(p.info.name); 6022 if (tree == null 6023 || tree.sourcePackage.equals(p.info.packageName)) { 6024 bp.packageSetting = pkgSetting; 6025 bp.perm = p; 6026 bp.uid = pkg.applicationInfo.uid; 6027 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6028 if (r == null) { 6029 r = new StringBuilder(256); 6030 } else { 6031 r.append(' '); 6032 } 6033 r.append(p.info.name); 6034 } 6035 } else { 6036 Slog.w(TAG, "Permission " + p.info.name + " from package " 6037 + p.info.packageName + " ignored: base tree " 6038 + tree.name + " is from package " 6039 + tree.sourcePackage); 6040 } 6041 } else { 6042 Slog.w(TAG, "Permission " + p.info.name + " from package " 6043 + p.info.packageName + " ignored: original from " 6044 + bp.sourcePackage); 6045 } 6046 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6047 if (r == null) { 6048 r = new StringBuilder(256); 6049 } else { 6050 r.append(' '); 6051 } 6052 r.append("DUP:"); 6053 r.append(p.info.name); 6054 } 6055 if (bp.perm == p) { 6056 bp.protectionLevel = p.info.protectionLevel; 6057 } 6058 } else { 6059 Slog.w(TAG, "Permission " + p.info.name + " from package " 6060 + p.info.packageName + " ignored: no group " 6061 + p.group); 6062 } 6063 } 6064 if (r != null) { 6065 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6066 } 6067 6068 N = pkg.instrumentation.size(); 6069 r = null; 6070 for (i=0; i<N; i++) { 6071 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6072 a.info.packageName = pkg.applicationInfo.packageName; 6073 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6074 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6075 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6076 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6077 a.info.dataDir = pkg.applicationInfo.dataDir; 6078 6079 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6080 // need other information about the application, like the ABI and what not ? 6081 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6082 mInstrumentation.put(a.getComponentName(), a); 6083 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6084 if (r == null) { 6085 r = new StringBuilder(256); 6086 } else { 6087 r.append(' '); 6088 } 6089 r.append(a.info.name); 6090 } 6091 } 6092 if (r != null) { 6093 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6094 } 6095 6096 if (pkg.protectedBroadcasts != null) { 6097 N = pkg.protectedBroadcasts.size(); 6098 for (i=0; i<N; i++) { 6099 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6100 } 6101 } 6102 6103 pkgSetting.setTimeStamp(scanFileTime); 6104 6105 // Create idmap files for pairs of (packages, overlay packages). 6106 // Note: "android", ie framework-res.apk, is handled by native layers. 6107 if (pkg.mOverlayTarget != null) { 6108 // This is an overlay package. 6109 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6110 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6111 mOverlays.put(pkg.mOverlayTarget, 6112 new HashMap<String, PackageParser.Package>()); 6113 } 6114 HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6115 map.put(pkg.packageName, pkg); 6116 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6117 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6118 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6119 "scanPackageLI failed to createIdmap"); 6120 } 6121 } 6122 } else if (mOverlays.containsKey(pkg.packageName) && 6123 !pkg.packageName.equals("android")) { 6124 // This is a regular package, with one or more known overlay packages. 6125 createIdmapsForPackageLI(pkg); 6126 } 6127 } 6128 6129 return pkg; 6130 } 6131 6132 /** 6133 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6134 * i.e, so that all packages can be run inside a single process if required. 6135 * 6136 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6137 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6138 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6139 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6140 * updating a package that belongs to a shared user. 6141 * 6142 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6143 * adds unnecessary complexity. 6144 */ 6145 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6146 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6147 String requiredInstructionSet = null; 6148 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6149 requiredInstructionSet = VMRuntime.getInstructionSet( 6150 scannedPackage.applicationInfo.primaryCpuAbi); 6151 } 6152 6153 PackageSetting requirer = null; 6154 for (PackageSetting ps : packagesForUser) { 6155 // If packagesForUser contains scannedPackage, we skip it. This will happen 6156 // when scannedPackage is an update of an existing package. Without this check, 6157 // we will never be able to change the ABI of any package belonging to a shared 6158 // user, even if it's compatible with other packages. 6159 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6160 if (ps.primaryCpuAbiString == null) { 6161 continue; 6162 } 6163 6164 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6165 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6166 // We have a mismatch between instruction sets (say arm vs arm64) warn about 6167 // this but there's not much we can do. 6168 String errorMessage = "Instruction set mismatch, " 6169 + ((requirer == null) ? "[caller]" : requirer) 6170 + " requires " + requiredInstructionSet + " whereas " + ps 6171 + " requires " + instructionSet; 6172 Slog.w(TAG, errorMessage); 6173 } 6174 6175 if (requiredInstructionSet == null) { 6176 requiredInstructionSet = instructionSet; 6177 requirer = ps; 6178 } 6179 } 6180 } 6181 6182 if (requiredInstructionSet != null) { 6183 String adjustedAbi; 6184 if (requirer != null) { 6185 // requirer != null implies that either scannedPackage was null or that scannedPackage 6186 // did not require an ABI, in which case we have to adjust scannedPackage to match 6187 // the ABI of the set (which is the same as requirer's ABI) 6188 adjustedAbi = requirer.primaryCpuAbiString; 6189 if (scannedPackage != null) { 6190 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6191 } 6192 } else { 6193 // requirer == null implies that we're updating all ABIs in the set to 6194 // match scannedPackage. 6195 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6196 } 6197 6198 for (PackageSetting ps : packagesForUser) { 6199 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6200 if (ps.primaryCpuAbiString != null) { 6201 continue; 6202 } 6203 6204 ps.primaryCpuAbiString = adjustedAbi; 6205 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6206 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6207 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6208 6209 if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt, 6210 deferDexOpt, true) == DEX_OPT_FAILED) { 6211 ps.primaryCpuAbiString = null; 6212 ps.pkg.applicationInfo.primaryCpuAbi = null; 6213 return; 6214 } else { 6215 mInstaller.rmdex(ps.codePathString, 6216 getDexCodeInstructionSet(getPreferredInstructionSet())); 6217 } 6218 } 6219 } 6220 } 6221 } 6222 } 6223 6224 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6225 synchronized (mPackages) { 6226 mResolverReplaced = true; 6227 // Set up information for custom user intent resolution activity. 6228 mResolveActivity.applicationInfo = pkg.applicationInfo; 6229 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6230 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6231 mResolveActivity.processName = null; 6232 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6233 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6234 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6235 mResolveActivity.theme = 0; 6236 mResolveActivity.exported = true; 6237 mResolveActivity.enabled = true; 6238 mResolveInfo.activityInfo = mResolveActivity; 6239 mResolveInfo.priority = 0; 6240 mResolveInfo.preferredOrder = 0; 6241 mResolveInfo.match = 0; 6242 mResolveComponentName = mCustomResolverComponentName; 6243 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6244 mResolveComponentName); 6245 } 6246 } 6247 6248 private static String calculateBundledApkRoot(final String codePathString) { 6249 final File codePath = new File(codePathString); 6250 final File codeRoot; 6251 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6252 codeRoot = Environment.getRootDirectory(); 6253 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6254 codeRoot = Environment.getOemDirectory(); 6255 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6256 codeRoot = Environment.getVendorDirectory(); 6257 } else { 6258 // Unrecognized code path; take its top real segment as the apk root: 6259 // e.g. /something/app/blah.apk => /something 6260 try { 6261 File f = codePath.getCanonicalFile(); 6262 File parent = f.getParentFile(); // non-null because codePath is a file 6263 File tmp; 6264 while ((tmp = parent.getParentFile()) != null) { 6265 f = parent; 6266 parent = tmp; 6267 } 6268 codeRoot = f; 6269 Slog.w(TAG, "Unrecognized code path " 6270 + codePath + " - using " + codeRoot); 6271 } catch (IOException e) { 6272 // Can't canonicalize the code path -- shenanigans? 6273 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6274 return Environment.getRootDirectory().getPath(); 6275 } 6276 } 6277 return codeRoot.getPath(); 6278 } 6279 6280 /** 6281 * Derive and set the location of native libraries for the given package, 6282 * which varies depending on where and how the package was installed. 6283 */ 6284 private void setNativeLibraryPaths(PackageParser.Package pkg) { 6285 final ApplicationInfo info = pkg.applicationInfo; 6286 final String codePath = pkg.codePath; 6287 final File codeFile = new File(codePath); 6288 final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info); 6289 final boolean asecApp = isForwardLocked(info) || isExternal(info); 6290 6291 info.nativeLibraryRootDir = null; 6292 info.nativeLibraryRootRequiresIsa = false; 6293 info.nativeLibraryDir = null; 6294 info.secondaryNativeLibraryDir = null; 6295 6296 if (isApkFile(codeFile)) { 6297 // Monolithic install 6298 if (bundledApp) { 6299 // If "/system/lib64/apkname" exists, assume that is the per-package 6300 // native library directory to use; otherwise use "/system/lib/apkname". 6301 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 6302 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 6303 getPrimaryInstructionSet(info)); 6304 6305 // This is a bundled system app so choose the path based on the ABI. 6306 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 6307 // is just the default path. 6308 final String apkName = deriveCodePathName(codePath); 6309 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 6310 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 6311 apkName).getAbsolutePath(); 6312 6313 if (info.secondaryCpuAbi != null) { 6314 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 6315 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 6316 secondaryLibDir, apkName).getAbsolutePath(); 6317 } 6318 } else if (asecApp) { 6319 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 6320 .getAbsolutePath(); 6321 } else { 6322 final String apkName = deriveCodePathName(codePath); 6323 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 6324 .getAbsolutePath(); 6325 } 6326 6327 info.nativeLibraryRootRequiresIsa = false; 6328 info.nativeLibraryDir = info.nativeLibraryRootDir; 6329 } else { 6330 // Cluster install 6331 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 6332 info.nativeLibraryRootRequiresIsa = true; 6333 6334 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 6335 getPrimaryInstructionSet(info)).getAbsolutePath(); 6336 6337 if (info.secondaryCpuAbi != null) { 6338 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 6339 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 6340 } 6341 } 6342 } 6343 6344 /** 6345 * Calculate the abis and roots for a bundled app. These can uniquely 6346 * be determined from the contents of the system partition, i.e whether 6347 * it contains 64 or 32 bit shared libraries etc. We do not validate any 6348 * of this information, and instead assume that the system was built 6349 * sensibly. 6350 */ 6351 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 6352 PackageSetting pkgSetting) { 6353 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 6354 6355 // If "/system/lib64/apkname" exists, assume that is the per-package 6356 // native library directory to use; otherwise use "/system/lib/apkname". 6357 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 6358 setBundledAppAbi(pkg, apkRoot, apkName); 6359 // pkgSetting might be null during rescan following uninstall of updates 6360 // to a bundled app, so accommodate that possibility. The settings in 6361 // that case will be established later from the parsed package. 6362 // 6363 // If the settings aren't null, sync them up with what we've just derived. 6364 // note that apkRoot isn't stored in the package settings. 6365 if (pkgSetting != null) { 6366 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6367 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6368 } 6369 } 6370 6371 /** 6372 * Deduces the ABI of a bundled app and sets the relevant fields on the 6373 * parsed pkg object. 6374 * 6375 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 6376 * under which system libraries are installed. 6377 * @param apkName the name of the installed package. 6378 */ 6379 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 6380 final File codeFile = new File(pkg.codePath); 6381 6382 final boolean has64BitLibs; 6383 final boolean has32BitLibs; 6384 if (isApkFile(codeFile)) { 6385 // Monolithic install 6386 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 6387 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 6388 } else { 6389 // Cluster install 6390 final File rootDir = new File(codeFile, LIB_DIR_NAME); 6391 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 6392 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 6393 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 6394 has64BitLibs = (new File(rootDir, isa)).exists(); 6395 } else { 6396 has64BitLibs = false; 6397 } 6398 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 6399 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 6400 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 6401 has32BitLibs = (new File(rootDir, isa)).exists(); 6402 } else { 6403 has32BitLibs = false; 6404 } 6405 } 6406 6407 if (has64BitLibs && !has32BitLibs) { 6408 // The package has 64 bit libs, but not 32 bit libs. Its primary 6409 // ABI should be 64 bit. We can safely assume here that the bundled 6410 // native libraries correspond to the most preferred ABI in the list. 6411 6412 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6413 pkg.applicationInfo.secondaryCpuAbi = null; 6414 } else if (has32BitLibs && !has64BitLibs) { 6415 // The package has 32 bit libs but not 64 bit libs. Its primary 6416 // ABI should be 32 bit. 6417 6418 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6419 pkg.applicationInfo.secondaryCpuAbi = null; 6420 } else if (has32BitLibs && has64BitLibs) { 6421 // The application has both 64 and 32 bit bundled libraries. We check 6422 // here that the app declares multiArch support, and warn if it doesn't. 6423 // 6424 // We will be lenient here and record both ABIs. The primary will be the 6425 // ABI that's higher on the list, i.e, a device that's configured to prefer 6426 // 64 bit apps will see a 64 bit primary ABI, 6427 6428 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 6429 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 6430 } 6431 6432 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 6433 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6434 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6435 } else { 6436 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6437 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6438 } 6439 } else { 6440 pkg.applicationInfo.primaryCpuAbi = null; 6441 pkg.applicationInfo.secondaryCpuAbi = null; 6442 } 6443 } 6444 6445 private void killApplication(String pkgName, int appId, String reason) { 6446 // Request the ActivityManager to kill the process(only for existing packages) 6447 // so that we do not end up in a confused state while the user is still using the older 6448 // version of the application while the new one gets installed. 6449 IActivityManager am = ActivityManagerNative.getDefault(); 6450 if (am != null) { 6451 try { 6452 am.killApplicationWithAppId(pkgName, appId, reason); 6453 } catch (RemoteException e) { 6454 } 6455 } 6456 } 6457 6458 void removePackageLI(PackageSetting ps, boolean chatty) { 6459 if (DEBUG_INSTALL) { 6460 if (chatty) 6461 Log.d(TAG, "Removing package " + ps.name); 6462 } 6463 6464 // writer 6465 synchronized (mPackages) { 6466 mPackages.remove(ps.name); 6467 final PackageParser.Package pkg = ps.pkg; 6468 if (pkg != null) { 6469 cleanPackageDataStructuresLILPw(pkg, chatty); 6470 } 6471 } 6472 } 6473 6474 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 6475 if (DEBUG_INSTALL) { 6476 if (chatty) 6477 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 6478 } 6479 6480 // writer 6481 synchronized (mPackages) { 6482 mPackages.remove(pkg.applicationInfo.packageName); 6483 cleanPackageDataStructuresLILPw(pkg, chatty); 6484 } 6485 } 6486 6487 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 6488 int N = pkg.providers.size(); 6489 StringBuilder r = null; 6490 int i; 6491 for (i=0; i<N; i++) { 6492 PackageParser.Provider p = pkg.providers.get(i); 6493 mProviders.removeProvider(p); 6494 if (p.info.authority == null) { 6495 6496 /* There was another ContentProvider with this authority when 6497 * this app was installed so this authority is null, 6498 * Ignore it as we don't have to unregister the provider. 6499 */ 6500 continue; 6501 } 6502 String names[] = p.info.authority.split(";"); 6503 for (int j = 0; j < names.length; j++) { 6504 if (mProvidersByAuthority.get(names[j]) == p) { 6505 mProvidersByAuthority.remove(names[j]); 6506 if (DEBUG_REMOVE) { 6507 if (chatty) 6508 Log.d(TAG, "Unregistered content provider: " + names[j] 6509 + ", className = " + p.info.name + ", isSyncable = " 6510 + p.info.isSyncable); 6511 } 6512 } 6513 } 6514 if (DEBUG_REMOVE && chatty) { 6515 if (r == null) { 6516 r = new StringBuilder(256); 6517 } else { 6518 r.append(' '); 6519 } 6520 r.append(p.info.name); 6521 } 6522 } 6523 if (r != null) { 6524 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 6525 } 6526 6527 N = pkg.services.size(); 6528 r = null; 6529 for (i=0; i<N; i++) { 6530 PackageParser.Service s = pkg.services.get(i); 6531 mServices.removeService(s); 6532 if (chatty) { 6533 if (r == null) { 6534 r = new StringBuilder(256); 6535 } else { 6536 r.append(' '); 6537 } 6538 r.append(s.info.name); 6539 } 6540 } 6541 if (r != null) { 6542 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 6543 } 6544 6545 N = pkg.receivers.size(); 6546 r = null; 6547 for (i=0; i<N; i++) { 6548 PackageParser.Activity a = pkg.receivers.get(i); 6549 mReceivers.removeActivity(a, "receiver"); 6550 if (DEBUG_REMOVE && chatty) { 6551 if (r == null) { 6552 r = new StringBuilder(256); 6553 } else { 6554 r.append(' '); 6555 } 6556 r.append(a.info.name); 6557 } 6558 } 6559 if (r != null) { 6560 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 6561 } 6562 6563 N = pkg.activities.size(); 6564 r = null; 6565 for (i=0; i<N; i++) { 6566 PackageParser.Activity a = pkg.activities.get(i); 6567 mActivities.removeActivity(a, "activity"); 6568 if (DEBUG_REMOVE && chatty) { 6569 if (r == null) { 6570 r = new StringBuilder(256); 6571 } else { 6572 r.append(' '); 6573 } 6574 r.append(a.info.name); 6575 } 6576 } 6577 if (r != null) { 6578 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 6579 } 6580 6581 N = pkg.permissions.size(); 6582 r = null; 6583 for (i=0; i<N; i++) { 6584 PackageParser.Permission p = pkg.permissions.get(i); 6585 BasePermission bp = mSettings.mPermissions.get(p.info.name); 6586 if (bp == null) { 6587 bp = mSettings.mPermissionTrees.get(p.info.name); 6588 } 6589 if (bp != null && bp.perm == p) { 6590 bp.perm = null; 6591 if (DEBUG_REMOVE && chatty) { 6592 if (r == null) { 6593 r = new StringBuilder(256); 6594 } else { 6595 r.append(' '); 6596 } 6597 r.append(p.info.name); 6598 } 6599 } 6600 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6601 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 6602 if (appOpPerms != null) { 6603 appOpPerms.remove(pkg.packageName); 6604 } 6605 } 6606 } 6607 if (r != null) { 6608 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6609 } 6610 6611 N = pkg.requestedPermissions.size(); 6612 r = null; 6613 for (i=0; i<N; i++) { 6614 String perm = pkg.requestedPermissions.get(i); 6615 BasePermission bp = mSettings.mPermissions.get(perm); 6616 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6617 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 6618 if (appOpPerms != null) { 6619 appOpPerms.remove(pkg.packageName); 6620 if (appOpPerms.isEmpty()) { 6621 mAppOpPermissionPackages.remove(perm); 6622 } 6623 } 6624 } 6625 } 6626 if (r != null) { 6627 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6628 } 6629 6630 N = pkg.instrumentation.size(); 6631 r = null; 6632 for (i=0; i<N; i++) { 6633 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6634 mInstrumentation.remove(a.getComponentName()); 6635 if (DEBUG_REMOVE && chatty) { 6636 if (r == null) { 6637 r = new StringBuilder(256); 6638 } else { 6639 r.append(' '); 6640 } 6641 r.append(a.info.name); 6642 } 6643 } 6644 if (r != null) { 6645 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 6646 } 6647 6648 r = null; 6649 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6650 // Only system apps can hold shared libraries. 6651 if (pkg.libraryNames != null) { 6652 for (i=0; i<pkg.libraryNames.size(); i++) { 6653 String name = pkg.libraryNames.get(i); 6654 SharedLibraryEntry cur = mSharedLibraries.get(name); 6655 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 6656 mSharedLibraries.remove(name); 6657 if (DEBUG_REMOVE && chatty) { 6658 if (r == null) { 6659 r = new StringBuilder(256); 6660 } else { 6661 r.append(' '); 6662 } 6663 r.append(name); 6664 } 6665 } 6666 } 6667 } 6668 } 6669 if (r != null) { 6670 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 6671 } 6672 } 6673 6674 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 6675 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 6676 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 6677 return true; 6678 } 6679 } 6680 return false; 6681 } 6682 6683 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 6684 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 6685 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 6686 6687 private void updatePermissionsLPw(String changingPkg, 6688 PackageParser.Package pkgInfo, int flags) { 6689 // Make sure there are no dangling permission trees. 6690 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 6691 while (it.hasNext()) { 6692 final BasePermission bp = it.next(); 6693 if (bp.packageSetting == null) { 6694 // We may not yet have parsed the package, so just see if 6695 // we still know about its settings. 6696 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6697 } 6698 if (bp.packageSetting == null) { 6699 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 6700 + " from package " + bp.sourcePackage); 6701 it.remove(); 6702 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6703 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6704 Slog.i(TAG, "Removing old permission tree: " + bp.name 6705 + " from package " + bp.sourcePackage); 6706 flags |= UPDATE_PERMISSIONS_ALL; 6707 it.remove(); 6708 } 6709 } 6710 } 6711 6712 // Make sure all dynamic permissions have been assigned to a package, 6713 // and make sure there are no dangling permissions. 6714 it = mSettings.mPermissions.values().iterator(); 6715 while (it.hasNext()) { 6716 final BasePermission bp = it.next(); 6717 if (bp.type == BasePermission.TYPE_DYNAMIC) { 6718 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 6719 + bp.name + " pkg=" + bp.sourcePackage 6720 + " info=" + bp.pendingInfo); 6721 if (bp.packageSetting == null && bp.pendingInfo != null) { 6722 final BasePermission tree = findPermissionTreeLP(bp.name); 6723 if (tree != null && tree.perm != null) { 6724 bp.packageSetting = tree.packageSetting; 6725 bp.perm = new PackageParser.Permission(tree.perm.owner, 6726 new PermissionInfo(bp.pendingInfo)); 6727 bp.perm.info.packageName = tree.perm.info.packageName; 6728 bp.perm.info.name = bp.name; 6729 bp.uid = tree.uid; 6730 } 6731 } 6732 } 6733 if (bp.packageSetting == null) { 6734 // We may not yet have parsed the package, so just see if 6735 // we still know about its settings. 6736 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6737 } 6738 if (bp.packageSetting == null) { 6739 Slog.w(TAG, "Removing dangling permission: " + bp.name 6740 + " from package " + bp.sourcePackage); 6741 it.remove(); 6742 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6743 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6744 Slog.i(TAG, "Removing old permission: " + bp.name 6745 + " from package " + bp.sourcePackage); 6746 flags |= UPDATE_PERMISSIONS_ALL; 6747 it.remove(); 6748 } 6749 } 6750 } 6751 6752 // Now update the permissions for all packages, in particular 6753 // replace the granted permissions of the system packages. 6754 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 6755 for (PackageParser.Package pkg : mPackages.values()) { 6756 if (pkg != pkgInfo) { 6757 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0); 6758 } 6759 } 6760 } 6761 6762 if (pkgInfo != null) { 6763 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0); 6764 } 6765 } 6766 6767 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) { 6768 final PackageSetting ps = (PackageSetting) pkg.mExtras; 6769 if (ps == null) { 6770 return; 6771 } 6772 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 6773 HashSet<String> origPermissions = gp.grantedPermissions; 6774 boolean changedPermission = false; 6775 6776 if (replace) { 6777 ps.permissionsFixed = false; 6778 if (gp == ps) { 6779 origPermissions = new HashSet<String>(gp.grantedPermissions); 6780 gp.grantedPermissions.clear(); 6781 gp.gids = mGlobalGids; 6782 } 6783 } 6784 6785 if (gp.gids == null) { 6786 gp.gids = mGlobalGids; 6787 } 6788 6789 final int N = pkg.requestedPermissions.size(); 6790 for (int i=0; i<N; i++) { 6791 final String name = pkg.requestedPermissions.get(i); 6792 final boolean required = pkg.requestedPermissionsRequired.get(i); 6793 final BasePermission bp = mSettings.mPermissions.get(name); 6794 if (DEBUG_INSTALL) { 6795 if (gp != ps) { 6796 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 6797 } 6798 } 6799 6800 if (bp == null || bp.packageSetting == null) { 6801 Slog.w(TAG, "Unknown permission " + name 6802 + " in package " + pkg.packageName); 6803 continue; 6804 } 6805 6806 final String perm = bp.name; 6807 boolean allowed; 6808 boolean allowedSig = false; 6809 if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6810 // Keep track of app op permissions. 6811 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 6812 if (pkgs == null) { 6813 pkgs = new ArraySet<>(); 6814 mAppOpPermissionPackages.put(bp.name, pkgs); 6815 } 6816 pkgs.add(pkg.packageName); 6817 } 6818 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 6819 if (level == PermissionInfo.PROTECTION_NORMAL 6820 || level == PermissionInfo.PROTECTION_DANGEROUS) { 6821 // We grant a normal or dangerous permission if any of the following 6822 // are true: 6823 // 1) The permission is required 6824 // 2) The permission is optional, but was granted in the past 6825 // 3) The permission is optional, but was requested by an 6826 // app in /system (not /data) 6827 // 6828 // Otherwise, reject the permission. 6829 allowed = (required || origPermissions.contains(perm) 6830 || (isSystemApp(ps) && !isUpdatedSystemApp(ps))); 6831 } else if (bp.packageSetting == null) { 6832 // This permission is invalid; skip it. 6833 allowed = false; 6834 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 6835 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions); 6836 if (allowed) { 6837 allowedSig = true; 6838 } 6839 } else { 6840 allowed = false; 6841 } 6842 if (DEBUG_INSTALL) { 6843 if (gp != ps) { 6844 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 6845 } 6846 } 6847 if (allowed) { 6848 if (!isSystemApp(ps) && ps.permissionsFixed) { 6849 // If this is an existing, non-system package, then 6850 // we can't add any new permissions to it. 6851 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 6852 // Except... if this is a permission that was added 6853 // to the platform (note: need to only do this when 6854 // updating the platform). 6855 allowed = isNewPlatformPermissionForPackage(perm, pkg); 6856 } 6857 } 6858 if (allowed) { 6859 if (!gp.grantedPermissions.contains(perm)) { 6860 changedPermission = true; 6861 gp.grantedPermissions.add(perm); 6862 gp.gids = appendInts(gp.gids, bp.gids); 6863 } else if (!ps.haveGids) { 6864 gp.gids = appendInts(gp.gids, bp.gids); 6865 } 6866 } else { 6867 Slog.w(TAG, "Not granting permission " + perm 6868 + " to package " + pkg.packageName 6869 + " because it was previously installed without"); 6870 } 6871 } else { 6872 if (gp.grantedPermissions.remove(perm)) { 6873 changedPermission = true; 6874 gp.gids = removeInts(gp.gids, bp.gids); 6875 Slog.i(TAG, "Un-granting permission " + perm 6876 + " from package " + pkg.packageName 6877 + " (protectionLevel=" + bp.protectionLevel 6878 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6879 + ")"); 6880 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 6881 // Don't print warning for app op permissions, since it is fine for them 6882 // not to be granted, there is a UI for the user to decide. 6883 Slog.w(TAG, "Not granting permission " + perm 6884 + " to package " + pkg.packageName 6885 + " (protectionLevel=" + bp.protectionLevel 6886 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6887 + ")"); 6888 } 6889 } 6890 } 6891 6892 if ((changedPermission || replace) && !ps.permissionsFixed && 6893 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 6894 // This is the first that we have heard about this package, so the 6895 // permissions we have now selected are fixed until explicitly 6896 // changed. 6897 ps.permissionsFixed = true; 6898 } 6899 ps.haveGids = true; 6900 } 6901 6902 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 6903 boolean allowed = false; 6904 final int NP = PackageParser.NEW_PERMISSIONS.length; 6905 for (int ip=0; ip<NP; ip++) { 6906 final PackageParser.NewPermissionInfo npi 6907 = PackageParser.NEW_PERMISSIONS[ip]; 6908 if (npi.name.equals(perm) 6909 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 6910 allowed = true; 6911 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 6912 + pkg.packageName); 6913 break; 6914 } 6915 } 6916 return allowed; 6917 } 6918 6919 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 6920 BasePermission bp, HashSet<String> origPermissions) { 6921 boolean allowed; 6922 allowed = (compareSignatures( 6923 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 6924 == PackageManager.SIGNATURE_MATCH) 6925 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 6926 == PackageManager.SIGNATURE_MATCH); 6927 if (!allowed && (bp.protectionLevel 6928 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 6929 if (isSystemApp(pkg)) { 6930 // For updated system applications, a system permission 6931 // is granted only if it had been defined by the original application. 6932 if (isUpdatedSystemApp(pkg)) { 6933 final PackageSetting sysPs = mSettings 6934 .getDisabledSystemPkgLPr(pkg.packageName); 6935 final GrantedPermissions origGp = sysPs.sharedUser != null 6936 ? sysPs.sharedUser : sysPs; 6937 6938 if (origGp.grantedPermissions.contains(perm)) { 6939 // If the original was granted this permission, we take 6940 // that grant decision as read and propagate it to the 6941 // update. 6942 allowed = true; 6943 } else { 6944 // The system apk may have been updated with an older 6945 // version of the one on the data partition, but which 6946 // granted a new system permission that it didn't have 6947 // before. In this case we do want to allow the app to 6948 // now get the new permission if the ancestral apk is 6949 // privileged to get it. 6950 if (sysPs.pkg != null && sysPs.isPrivileged()) { 6951 for (int j=0; 6952 j<sysPs.pkg.requestedPermissions.size(); j++) { 6953 if (perm.equals( 6954 sysPs.pkg.requestedPermissions.get(j))) { 6955 allowed = true; 6956 break; 6957 } 6958 } 6959 } 6960 } 6961 } else { 6962 allowed = isPrivilegedApp(pkg); 6963 } 6964 } 6965 } 6966 if (!allowed && (bp.protectionLevel 6967 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 6968 // For development permissions, a development permission 6969 // is granted only if it was already granted. 6970 allowed = origPermissions.contains(perm); 6971 } 6972 return allowed; 6973 } 6974 6975 final class ActivityIntentResolver 6976 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 6977 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 6978 boolean defaultOnly, int userId) { 6979 if (!sUserManager.exists(userId)) return null; 6980 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 6981 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 6982 } 6983 6984 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 6985 int userId) { 6986 if (!sUserManager.exists(userId)) return null; 6987 mFlags = flags; 6988 return super.queryIntent(intent, resolvedType, 6989 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 6990 } 6991 6992 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 6993 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 6994 if (!sUserManager.exists(userId)) return null; 6995 if (packageActivities == null) { 6996 return null; 6997 } 6998 mFlags = flags; 6999 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7000 final int N = packageActivities.size(); 7001 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 7002 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 7003 7004 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 7005 for (int i = 0; i < N; ++i) { 7006 intentFilters = packageActivities.get(i).intents; 7007 if (intentFilters != null && intentFilters.size() > 0) { 7008 PackageParser.ActivityIntentInfo[] array = 7009 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 7010 intentFilters.toArray(array); 7011 listCut.add(array); 7012 } 7013 } 7014 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7015 } 7016 7017 public final void addActivity(PackageParser.Activity a, String type) { 7018 final boolean systemApp = isSystemApp(a.info.applicationInfo); 7019 mActivities.put(a.getComponentName(), a); 7020 if (DEBUG_SHOW_INFO) 7021 Log.v( 7022 TAG, " " + type + " " + 7023 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 7024 if (DEBUG_SHOW_INFO) 7025 Log.v(TAG, " Class=" + a.info.name); 7026 final int NI = a.intents.size(); 7027 for (int j=0; j<NI; j++) { 7028 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7029 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 7030 intent.setPriority(0); 7031 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 7032 + a.className + " with priority > 0, forcing to 0"); 7033 } 7034 if (DEBUG_SHOW_INFO) { 7035 Log.v(TAG, " IntentFilter:"); 7036 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7037 } 7038 if (!intent.debugCheck()) { 7039 Log.w(TAG, "==> For Activity " + a.info.name); 7040 } 7041 addFilter(intent); 7042 } 7043 } 7044 7045 public final void removeActivity(PackageParser.Activity a, String type) { 7046 mActivities.remove(a.getComponentName()); 7047 if (DEBUG_SHOW_INFO) { 7048 Log.v(TAG, " " + type + " " 7049 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 7050 : a.info.name) + ":"); 7051 Log.v(TAG, " Class=" + a.info.name); 7052 } 7053 final int NI = a.intents.size(); 7054 for (int j=0; j<NI; j++) { 7055 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7056 if (DEBUG_SHOW_INFO) { 7057 Log.v(TAG, " IntentFilter:"); 7058 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7059 } 7060 removeFilter(intent); 7061 } 7062 } 7063 7064 @Override 7065 protected boolean allowFilterResult( 7066 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 7067 ActivityInfo filterAi = filter.activity.info; 7068 for (int i=dest.size()-1; i>=0; i--) { 7069 ActivityInfo destAi = dest.get(i).activityInfo; 7070 if (destAi.name == filterAi.name 7071 && destAi.packageName == filterAi.packageName) { 7072 return false; 7073 } 7074 } 7075 return true; 7076 } 7077 7078 @Override 7079 protected ActivityIntentInfo[] newArray(int size) { 7080 return new ActivityIntentInfo[size]; 7081 } 7082 7083 @Override 7084 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 7085 if (!sUserManager.exists(userId)) return true; 7086 PackageParser.Package p = filter.activity.owner; 7087 if (p != null) { 7088 PackageSetting ps = (PackageSetting)p.mExtras; 7089 if (ps != null) { 7090 // System apps are never considered stopped for purposes of 7091 // filtering, because there may be no way for the user to 7092 // actually re-launch them. 7093 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 7094 && ps.getStopped(userId); 7095 } 7096 } 7097 return false; 7098 } 7099 7100 @Override 7101 protected boolean isPackageForFilter(String packageName, 7102 PackageParser.ActivityIntentInfo info) { 7103 return packageName.equals(info.activity.owner.packageName); 7104 } 7105 7106 @Override 7107 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7108 int match, int userId) { 7109 if (!sUserManager.exists(userId)) return null; 7110 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7111 return null; 7112 } 7113 final PackageParser.Activity activity = info.activity; 7114 if (mSafeMode && (activity.info.applicationInfo.flags 7115 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7116 return null; 7117 } 7118 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7119 if (ps == null) { 7120 return null; 7121 } 7122 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7123 ps.readUserState(userId), userId); 7124 if (ai == null) { 7125 return null; 7126 } 7127 final ResolveInfo res = new ResolveInfo(); 7128 res.activityInfo = ai; 7129 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7130 res.filter = info; 7131 } 7132 res.priority = info.getPriority(); 7133 res.preferredOrder = activity.owner.mPreferredOrder; 7134 //System.out.println("Result: " + res.activityInfo.className + 7135 // " = " + res.priority); 7136 res.match = match; 7137 res.isDefault = info.hasDefault; 7138 res.labelRes = info.labelRes; 7139 res.nonLocalizedLabel = info.nonLocalizedLabel; 7140 if (userNeedsBadging(userId)) { 7141 res.noResourceId = true; 7142 } else { 7143 res.icon = info.icon; 7144 } 7145 res.system = isSystemApp(res.activityInfo.applicationInfo); 7146 return res; 7147 } 7148 7149 @Override 7150 protected void sortResults(List<ResolveInfo> results) { 7151 Collections.sort(results, mResolvePrioritySorter); 7152 } 7153 7154 @Override 7155 protected void dumpFilter(PrintWriter out, String prefix, 7156 PackageParser.ActivityIntentInfo filter) { 7157 out.print(prefix); out.print( 7158 Integer.toHexString(System.identityHashCode(filter.activity))); 7159 out.print(' '); 7160 filter.activity.printComponentShortName(out); 7161 out.print(" filter "); 7162 out.println(Integer.toHexString(System.identityHashCode(filter))); 7163 } 7164 7165// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7166// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7167// final List<ResolveInfo> retList = Lists.newArrayList(); 7168// while (i.hasNext()) { 7169// final ResolveInfo resolveInfo = i.next(); 7170// if (isEnabledLP(resolveInfo.activityInfo)) { 7171// retList.add(resolveInfo); 7172// } 7173// } 7174// return retList; 7175// } 7176 7177 // Keys are String (activity class name), values are Activity. 7178 private final HashMap<ComponentName, PackageParser.Activity> mActivities 7179 = new HashMap<ComponentName, PackageParser.Activity>(); 7180 private int mFlags; 7181 } 7182 7183 private final class ServiceIntentResolver 7184 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 7185 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7186 boolean defaultOnly, int userId) { 7187 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7188 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7189 } 7190 7191 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7192 int userId) { 7193 if (!sUserManager.exists(userId)) return null; 7194 mFlags = flags; 7195 return super.queryIntent(intent, resolvedType, 7196 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7197 } 7198 7199 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7200 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 7201 if (!sUserManager.exists(userId)) return null; 7202 if (packageServices == null) { 7203 return null; 7204 } 7205 mFlags = flags; 7206 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7207 final int N = packageServices.size(); 7208 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 7209 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 7210 7211 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 7212 for (int i = 0; i < N; ++i) { 7213 intentFilters = packageServices.get(i).intents; 7214 if (intentFilters != null && intentFilters.size() > 0) { 7215 PackageParser.ServiceIntentInfo[] array = 7216 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 7217 intentFilters.toArray(array); 7218 listCut.add(array); 7219 } 7220 } 7221 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7222 } 7223 7224 public final void addService(PackageParser.Service s) { 7225 mServices.put(s.getComponentName(), s); 7226 if (DEBUG_SHOW_INFO) { 7227 Log.v(TAG, " " 7228 + (s.info.nonLocalizedLabel != null 7229 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7230 Log.v(TAG, " Class=" + s.info.name); 7231 } 7232 final int NI = s.intents.size(); 7233 int j; 7234 for (j=0; j<NI; j++) { 7235 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7236 if (DEBUG_SHOW_INFO) { 7237 Log.v(TAG, " IntentFilter:"); 7238 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7239 } 7240 if (!intent.debugCheck()) { 7241 Log.w(TAG, "==> For Service " + s.info.name); 7242 } 7243 addFilter(intent); 7244 } 7245 } 7246 7247 public final void removeService(PackageParser.Service s) { 7248 mServices.remove(s.getComponentName()); 7249 if (DEBUG_SHOW_INFO) { 7250 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 7251 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7252 Log.v(TAG, " Class=" + s.info.name); 7253 } 7254 final int NI = s.intents.size(); 7255 int j; 7256 for (j=0; j<NI; j++) { 7257 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7258 if (DEBUG_SHOW_INFO) { 7259 Log.v(TAG, " IntentFilter:"); 7260 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7261 } 7262 removeFilter(intent); 7263 } 7264 } 7265 7266 @Override 7267 protected boolean allowFilterResult( 7268 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 7269 ServiceInfo filterSi = filter.service.info; 7270 for (int i=dest.size()-1; i>=0; i--) { 7271 ServiceInfo destAi = dest.get(i).serviceInfo; 7272 if (destAi.name == filterSi.name 7273 && destAi.packageName == filterSi.packageName) { 7274 return false; 7275 } 7276 } 7277 return true; 7278 } 7279 7280 @Override 7281 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 7282 return new PackageParser.ServiceIntentInfo[size]; 7283 } 7284 7285 @Override 7286 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 7287 if (!sUserManager.exists(userId)) return true; 7288 PackageParser.Package p = filter.service.owner; 7289 if (p != null) { 7290 PackageSetting ps = (PackageSetting)p.mExtras; 7291 if (ps != null) { 7292 // System apps are never considered stopped for purposes of 7293 // filtering, because there may be no way for the user to 7294 // actually re-launch them. 7295 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7296 && ps.getStopped(userId); 7297 } 7298 } 7299 return false; 7300 } 7301 7302 @Override 7303 protected boolean isPackageForFilter(String packageName, 7304 PackageParser.ServiceIntentInfo info) { 7305 return packageName.equals(info.service.owner.packageName); 7306 } 7307 7308 @Override 7309 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 7310 int match, int userId) { 7311 if (!sUserManager.exists(userId)) return null; 7312 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 7313 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 7314 return null; 7315 } 7316 final PackageParser.Service service = info.service; 7317 if (mSafeMode && (service.info.applicationInfo.flags 7318 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7319 return null; 7320 } 7321 PackageSetting ps = (PackageSetting) service.owner.mExtras; 7322 if (ps == null) { 7323 return null; 7324 } 7325 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 7326 ps.readUserState(userId), userId); 7327 if (si == null) { 7328 return null; 7329 } 7330 final ResolveInfo res = new ResolveInfo(); 7331 res.serviceInfo = si; 7332 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7333 res.filter = filter; 7334 } 7335 res.priority = info.getPriority(); 7336 res.preferredOrder = service.owner.mPreferredOrder; 7337 //System.out.println("Result: " + res.activityInfo.className + 7338 // " = " + res.priority); 7339 res.match = match; 7340 res.isDefault = info.hasDefault; 7341 res.labelRes = info.labelRes; 7342 res.nonLocalizedLabel = info.nonLocalizedLabel; 7343 res.icon = info.icon; 7344 res.system = isSystemApp(res.serviceInfo.applicationInfo); 7345 return res; 7346 } 7347 7348 @Override 7349 protected void sortResults(List<ResolveInfo> results) { 7350 Collections.sort(results, mResolvePrioritySorter); 7351 } 7352 7353 @Override 7354 protected void dumpFilter(PrintWriter out, String prefix, 7355 PackageParser.ServiceIntentInfo filter) { 7356 out.print(prefix); out.print( 7357 Integer.toHexString(System.identityHashCode(filter.service))); 7358 out.print(' '); 7359 filter.service.printComponentShortName(out); 7360 out.print(" filter "); 7361 out.println(Integer.toHexString(System.identityHashCode(filter))); 7362 } 7363 7364// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7365// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7366// final List<ResolveInfo> retList = Lists.newArrayList(); 7367// while (i.hasNext()) { 7368// final ResolveInfo resolveInfo = (ResolveInfo) i; 7369// if (isEnabledLP(resolveInfo.serviceInfo)) { 7370// retList.add(resolveInfo); 7371// } 7372// } 7373// return retList; 7374// } 7375 7376 // Keys are String (activity class name), values are Activity. 7377 private final HashMap<ComponentName, PackageParser.Service> mServices 7378 = new HashMap<ComponentName, PackageParser.Service>(); 7379 private int mFlags; 7380 }; 7381 7382 private final class ProviderIntentResolver 7383 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 7384 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7385 boolean defaultOnly, int userId) { 7386 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7387 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7388 } 7389 7390 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7391 int userId) { 7392 if (!sUserManager.exists(userId)) 7393 return null; 7394 mFlags = flags; 7395 return super.queryIntent(intent, resolvedType, 7396 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7397 } 7398 7399 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7400 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 7401 if (!sUserManager.exists(userId)) 7402 return null; 7403 if (packageProviders == null) { 7404 return null; 7405 } 7406 mFlags = flags; 7407 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 7408 final int N = packageProviders.size(); 7409 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 7410 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 7411 7412 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 7413 for (int i = 0; i < N; ++i) { 7414 intentFilters = packageProviders.get(i).intents; 7415 if (intentFilters != null && intentFilters.size() > 0) { 7416 PackageParser.ProviderIntentInfo[] array = 7417 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 7418 intentFilters.toArray(array); 7419 listCut.add(array); 7420 } 7421 } 7422 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7423 } 7424 7425 public final void addProvider(PackageParser.Provider p) { 7426 if (mProviders.containsKey(p.getComponentName())) { 7427 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 7428 return; 7429 } 7430 7431 mProviders.put(p.getComponentName(), p); 7432 if (DEBUG_SHOW_INFO) { 7433 Log.v(TAG, " " 7434 + (p.info.nonLocalizedLabel != null 7435 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7436 Log.v(TAG, " Class=" + p.info.name); 7437 } 7438 final int NI = p.intents.size(); 7439 int j; 7440 for (j = 0; j < NI; j++) { 7441 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7442 if (DEBUG_SHOW_INFO) { 7443 Log.v(TAG, " IntentFilter:"); 7444 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7445 } 7446 if (!intent.debugCheck()) { 7447 Log.w(TAG, "==> For Provider " + p.info.name); 7448 } 7449 addFilter(intent); 7450 } 7451 } 7452 7453 public final void removeProvider(PackageParser.Provider p) { 7454 mProviders.remove(p.getComponentName()); 7455 if (DEBUG_SHOW_INFO) { 7456 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 7457 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7458 Log.v(TAG, " Class=" + p.info.name); 7459 } 7460 final int NI = p.intents.size(); 7461 int j; 7462 for (j = 0; j < NI; j++) { 7463 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7464 if (DEBUG_SHOW_INFO) { 7465 Log.v(TAG, " IntentFilter:"); 7466 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7467 } 7468 removeFilter(intent); 7469 } 7470 } 7471 7472 @Override 7473 protected boolean allowFilterResult( 7474 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 7475 ProviderInfo filterPi = filter.provider.info; 7476 for (int i = dest.size() - 1; i >= 0; i--) { 7477 ProviderInfo destPi = dest.get(i).providerInfo; 7478 if (destPi.name == filterPi.name 7479 && destPi.packageName == filterPi.packageName) { 7480 return false; 7481 } 7482 } 7483 return true; 7484 } 7485 7486 @Override 7487 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 7488 return new PackageParser.ProviderIntentInfo[size]; 7489 } 7490 7491 @Override 7492 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 7493 if (!sUserManager.exists(userId)) 7494 return true; 7495 PackageParser.Package p = filter.provider.owner; 7496 if (p != null) { 7497 PackageSetting ps = (PackageSetting) p.mExtras; 7498 if (ps != null) { 7499 // System apps are never considered stopped for purposes of 7500 // filtering, because there may be no way for the user to 7501 // actually re-launch them. 7502 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7503 && ps.getStopped(userId); 7504 } 7505 } 7506 return false; 7507 } 7508 7509 @Override 7510 protected boolean isPackageForFilter(String packageName, 7511 PackageParser.ProviderIntentInfo info) { 7512 return packageName.equals(info.provider.owner.packageName); 7513 } 7514 7515 @Override 7516 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 7517 int match, int userId) { 7518 if (!sUserManager.exists(userId)) 7519 return null; 7520 final PackageParser.ProviderIntentInfo info = filter; 7521 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 7522 return null; 7523 } 7524 final PackageParser.Provider provider = info.provider; 7525 if (mSafeMode && (provider.info.applicationInfo.flags 7526 & ApplicationInfo.FLAG_SYSTEM) == 0) { 7527 return null; 7528 } 7529 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 7530 if (ps == null) { 7531 return null; 7532 } 7533 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 7534 ps.readUserState(userId), userId); 7535 if (pi == null) { 7536 return null; 7537 } 7538 final ResolveInfo res = new ResolveInfo(); 7539 res.providerInfo = pi; 7540 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 7541 res.filter = filter; 7542 } 7543 res.priority = info.getPriority(); 7544 res.preferredOrder = provider.owner.mPreferredOrder; 7545 res.match = match; 7546 res.isDefault = info.hasDefault; 7547 res.labelRes = info.labelRes; 7548 res.nonLocalizedLabel = info.nonLocalizedLabel; 7549 res.icon = info.icon; 7550 res.system = isSystemApp(res.providerInfo.applicationInfo); 7551 return res; 7552 } 7553 7554 @Override 7555 protected void sortResults(List<ResolveInfo> results) { 7556 Collections.sort(results, mResolvePrioritySorter); 7557 } 7558 7559 @Override 7560 protected void dumpFilter(PrintWriter out, String prefix, 7561 PackageParser.ProviderIntentInfo filter) { 7562 out.print(prefix); 7563 out.print( 7564 Integer.toHexString(System.identityHashCode(filter.provider))); 7565 out.print(' '); 7566 filter.provider.printComponentShortName(out); 7567 out.print(" filter "); 7568 out.println(Integer.toHexString(System.identityHashCode(filter))); 7569 } 7570 7571 private final HashMap<ComponentName, PackageParser.Provider> mProviders 7572 = new HashMap<ComponentName, PackageParser.Provider>(); 7573 private int mFlags; 7574 }; 7575 7576 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 7577 new Comparator<ResolveInfo>() { 7578 public int compare(ResolveInfo r1, ResolveInfo r2) { 7579 int v1 = r1.priority; 7580 int v2 = r2.priority; 7581 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 7582 if (v1 != v2) { 7583 return (v1 > v2) ? -1 : 1; 7584 } 7585 v1 = r1.preferredOrder; 7586 v2 = r2.preferredOrder; 7587 if (v1 != v2) { 7588 return (v1 > v2) ? -1 : 1; 7589 } 7590 if (r1.isDefault != r2.isDefault) { 7591 return r1.isDefault ? -1 : 1; 7592 } 7593 v1 = r1.match; 7594 v2 = r2.match; 7595 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 7596 if (v1 != v2) { 7597 return (v1 > v2) ? -1 : 1; 7598 } 7599 if (r1.system != r2.system) { 7600 return r1.system ? -1 : 1; 7601 } 7602 return 0; 7603 } 7604 }; 7605 7606 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 7607 new Comparator<ProviderInfo>() { 7608 public int compare(ProviderInfo p1, ProviderInfo p2) { 7609 final int v1 = p1.initOrder; 7610 final int v2 = p2.initOrder; 7611 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 7612 } 7613 }; 7614 7615 static final void sendPackageBroadcast(String action, String pkg, 7616 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 7617 int[] userIds) { 7618 IActivityManager am = ActivityManagerNative.getDefault(); 7619 if (am != null) { 7620 try { 7621 if (userIds == null) { 7622 userIds = am.getRunningUserIds(); 7623 } 7624 for (int id : userIds) { 7625 final Intent intent = new Intent(action, 7626 pkg != null ? Uri.fromParts("package", pkg, null) : null); 7627 if (extras != null) { 7628 intent.putExtras(extras); 7629 } 7630 if (targetPkg != null) { 7631 intent.setPackage(targetPkg); 7632 } 7633 // Modify the UID when posting to other users 7634 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 7635 if (uid > 0 && UserHandle.getUserId(uid) != id) { 7636 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 7637 intent.putExtra(Intent.EXTRA_UID, uid); 7638 } 7639 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 7640 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 7641 if (DEBUG_BROADCASTS) { 7642 RuntimeException here = new RuntimeException("here"); 7643 here.fillInStackTrace(); 7644 Slog.d(TAG, "Sending to user " + id + ": " 7645 + intent.toShortString(false, true, false, false) 7646 + " " + intent.getExtras(), here); 7647 } 7648 am.broadcastIntent(null, intent, null, finishedReceiver, 7649 0, null, null, null, android.app.AppOpsManager.OP_NONE, 7650 finishedReceiver != null, false, id); 7651 } 7652 } catch (RemoteException ex) { 7653 } 7654 } 7655 } 7656 7657 /** 7658 * Check if the external storage media is available. This is true if there 7659 * is a mounted external storage medium or if the external storage is 7660 * emulated. 7661 */ 7662 private boolean isExternalMediaAvailable() { 7663 return mMediaMounted || Environment.isExternalStorageEmulated(); 7664 } 7665 7666 @Override 7667 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 7668 // writer 7669 synchronized (mPackages) { 7670 if (!isExternalMediaAvailable()) { 7671 // If the external storage is no longer mounted at this point, 7672 // the caller may not have been able to delete all of this 7673 // packages files and can not delete any more. Bail. 7674 return null; 7675 } 7676 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 7677 if (lastPackage != null) { 7678 pkgs.remove(lastPackage); 7679 } 7680 if (pkgs.size() > 0) { 7681 return pkgs.get(0); 7682 } 7683 } 7684 return null; 7685 } 7686 7687 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 7688 if (false) { 7689 RuntimeException here = new RuntimeException("here"); 7690 here.fillInStackTrace(); 7691 Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId 7692 + " andCode=" + andCode, here); 7693 } 7694 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, 7695 userId, andCode ? 1 : 0, packageName)); 7696 } 7697 7698 void startCleaningPackages() { 7699 // reader 7700 synchronized (mPackages) { 7701 if (!isExternalMediaAvailable()) { 7702 return; 7703 } 7704 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 7705 return; 7706 } 7707 } 7708 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 7709 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 7710 IActivityManager am = ActivityManagerNative.getDefault(); 7711 if (am != null) { 7712 try { 7713 am.startService(null, intent, null, UserHandle.USER_OWNER); 7714 } catch (RemoteException e) { 7715 } 7716 } 7717 } 7718 7719 @Override 7720 public void installPackage(String originPath, IPackageInstallObserver2 observer, 7721 int installFlags, String installerPackageName, VerificationParams verificationParams, 7722 String packageAbiOverride) { 7723 installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams, 7724 packageAbiOverride, UserHandle.getCallingUserId()); 7725 } 7726 7727 @Override 7728 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 7729 int installFlags, String installerPackageName, VerificationParams verificationParams, 7730 String packageAbiOverride, int userId) { 7731 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7732 null); 7733 if (UserHandle.getCallingUserId() != userId) { 7734 mContext.enforceCallingOrSelfPermission( 7735 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 7736 "installPackage " + userId); 7737 } 7738 7739 final File originFile = new File(originPath); 7740 final int uid = Binder.getCallingUid(); 7741 if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) { 7742 try { 7743 if (observer != null) { 7744 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 7745 } 7746 } catch (RemoteException re) { 7747 } 7748 return; 7749 } 7750 7751 UserHandle user; 7752 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 7753 user = UserHandle.ALL; 7754 } else { 7755 user = new UserHandle(userId); 7756 } 7757 7758 final int filteredInstallFlags; 7759 if (uid == Process.SHELL_UID || uid == 0) { 7760 if (DEBUG_INSTALL) { 7761 Slog.v(TAG, "Install from ADB"); 7762 } 7763 filteredInstallFlags = installFlags | PackageManager.INSTALL_FROM_ADB; 7764 } else { 7765 filteredInstallFlags = installFlags & ~PackageManager.INSTALL_FROM_ADB; 7766 } 7767 7768 verificationParams.setInstallerUid(uid); 7769 7770 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 7771 7772 final Message msg = mHandler.obtainMessage(INIT_COPY); 7773 msg.obj = new InstallParams(origin, observer, filteredInstallFlags, 7774 installerPackageName, verificationParams, user, packageAbiOverride); 7775 mHandler.sendMessage(msg); 7776 } 7777 7778 void installStage(String packageName, File stagedDir, String stagedCid, 7779 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 7780 String installerPackageName, int installerUid, UserHandle user) { 7781 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 7782 params.referrerUri, installerUid, null); 7783 7784 final OriginInfo origin; 7785 if (stagedDir != null) { 7786 origin = OriginInfo.fromStagedFile(stagedDir); 7787 } else { 7788 origin = OriginInfo.fromStagedContainer(stagedCid); 7789 } 7790 7791 final Message msg = mHandler.obtainMessage(INIT_COPY); 7792 msg.obj = new InstallParams(origin, observer, params.installFlags, 7793 installerPackageName, verifParams, user, params.abiOverride); 7794 mHandler.sendMessage(msg); 7795 } 7796 7797 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 7798 Bundle extras = new Bundle(1); 7799 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 7800 7801 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 7802 packageName, extras, null, null, new int[] {userId}); 7803 try { 7804 IActivityManager am = ActivityManagerNative.getDefault(); 7805 final boolean isSystem = 7806 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 7807 if (isSystem && am.isUserRunning(userId, false)) { 7808 // The just-installed/enabled app is bundled on the system, so presumed 7809 // to be able to run automatically without needing an explicit launch. 7810 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 7811 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 7812 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 7813 .setPackage(packageName); 7814 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 7815 android.app.AppOpsManager.OP_NONE, false, false, userId); 7816 } 7817 } catch (RemoteException e) { 7818 // shouldn't happen 7819 Slog.w(TAG, "Unable to bootstrap installed package", e); 7820 } 7821 } 7822 7823 @Override 7824 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 7825 int userId) { 7826 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7827 PackageSetting pkgSetting; 7828 final int uid = Binder.getCallingUid(); 7829 if (UserHandle.getUserId(uid) != userId) { 7830 mContext.enforceCallingOrSelfPermission( 7831 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 7832 "setApplicationHiddenSetting for user " + userId); 7833 } 7834 7835 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 7836 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 7837 return false; 7838 } 7839 7840 long callingId = Binder.clearCallingIdentity(); 7841 try { 7842 boolean sendAdded = false; 7843 boolean sendRemoved = false; 7844 // writer 7845 synchronized (mPackages) { 7846 pkgSetting = mSettings.mPackages.get(packageName); 7847 if (pkgSetting == null) { 7848 return false; 7849 } 7850 if (pkgSetting.getHidden(userId) != hidden) { 7851 pkgSetting.setHidden(hidden, userId); 7852 mSettings.writePackageRestrictionsLPr(userId); 7853 if (hidden) { 7854 sendRemoved = true; 7855 } else { 7856 sendAdded = true; 7857 } 7858 } 7859 } 7860 if (sendAdded) { 7861 sendPackageAddedForUser(packageName, pkgSetting, userId); 7862 return true; 7863 } 7864 if (sendRemoved) { 7865 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 7866 "hiding pkg"); 7867 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 7868 } 7869 } finally { 7870 Binder.restoreCallingIdentity(callingId); 7871 } 7872 return false; 7873 } 7874 7875 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 7876 int userId) { 7877 final PackageRemovedInfo info = new PackageRemovedInfo(); 7878 info.removedPackage = packageName; 7879 info.removedUsers = new int[] {userId}; 7880 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 7881 info.sendBroadcast(false, false, false); 7882 } 7883 7884 /** 7885 * Returns true if application is not found or there was an error. Otherwise it returns 7886 * the hidden state of the package for the given user. 7887 */ 7888 @Override 7889 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 7890 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7891 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 7892 "getApplicationHidden for user " + userId); 7893 PackageSetting pkgSetting; 7894 long callingId = Binder.clearCallingIdentity(); 7895 try { 7896 // writer 7897 synchronized (mPackages) { 7898 pkgSetting = mSettings.mPackages.get(packageName); 7899 if (pkgSetting == null) { 7900 return true; 7901 } 7902 return pkgSetting.getHidden(userId); 7903 } 7904 } finally { 7905 Binder.restoreCallingIdentity(callingId); 7906 } 7907 } 7908 7909 /** 7910 * @hide 7911 */ 7912 @Override 7913 public int installExistingPackageAsUser(String packageName, int userId) { 7914 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7915 null); 7916 PackageSetting pkgSetting; 7917 final int uid = Binder.getCallingUid(); 7918 enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId); 7919 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 7920 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 7921 } 7922 7923 long callingId = Binder.clearCallingIdentity(); 7924 try { 7925 boolean sendAdded = false; 7926 Bundle extras = new Bundle(1); 7927 7928 // writer 7929 synchronized (mPackages) { 7930 pkgSetting = mSettings.mPackages.get(packageName); 7931 if (pkgSetting == null) { 7932 return PackageManager.INSTALL_FAILED_INVALID_URI; 7933 } 7934 if (!pkgSetting.getInstalled(userId)) { 7935 pkgSetting.setInstalled(true, userId); 7936 pkgSetting.setHidden(false, userId); 7937 mSettings.writePackageRestrictionsLPr(userId); 7938 sendAdded = true; 7939 } 7940 } 7941 7942 if (sendAdded) { 7943 sendPackageAddedForUser(packageName, pkgSetting, userId); 7944 } 7945 } finally { 7946 Binder.restoreCallingIdentity(callingId); 7947 } 7948 7949 return PackageManager.INSTALL_SUCCEEDED; 7950 } 7951 7952 boolean isUserRestricted(int userId, String restrictionKey) { 7953 Bundle restrictions = sUserManager.getUserRestrictions(userId); 7954 if (restrictions.getBoolean(restrictionKey, false)) { 7955 Log.w(TAG, "User is restricted: " + restrictionKey); 7956 return true; 7957 } 7958 return false; 7959 } 7960 7961 @Override 7962 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 7963 mContext.enforceCallingOrSelfPermission( 7964 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7965 "Only package verification agents can verify applications"); 7966 7967 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7968 final PackageVerificationResponse response = new PackageVerificationResponse( 7969 verificationCode, Binder.getCallingUid()); 7970 msg.arg1 = id; 7971 msg.obj = response; 7972 mHandler.sendMessage(msg); 7973 } 7974 7975 @Override 7976 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 7977 long millisecondsToDelay) { 7978 mContext.enforceCallingOrSelfPermission( 7979 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7980 "Only package verification agents can extend verification timeouts"); 7981 7982 final PackageVerificationState state = mPendingVerification.get(id); 7983 final PackageVerificationResponse response = new PackageVerificationResponse( 7984 verificationCodeAtTimeout, Binder.getCallingUid()); 7985 7986 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 7987 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 7988 } 7989 if (millisecondsToDelay < 0) { 7990 millisecondsToDelay = 0; 7991 } 7992 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 7993 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 7994 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 7995 } 7996 7997 if ((state != null) && !state.timeoutExtended()) { 7998 state.extendTimeout(); 7999 8000 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8001 msg.arg1 = id; 8002 msg.obj = response; 8003 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 8004 } 8005 } 8006 8007 private void broadcastPackageVerified(int verificationId, Uri packageUri, 8008 int verificationCode, UserHandle user) { 8009 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 8010 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 8011 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8012 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8013 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 8014 8015 mContext.sendBroadcastAsUser(intent, user, 8016 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 8017 } 8018 8019 private ComponentName matchComponentForVerifier(String packageName, 8020 List<ResolveInfo> receivers) { 8021 ActivityInfo targetReceiver = null; 8022 8023 final int NR = receivers.size(); 8024 for (int i = 0; i < NR; i++) { 8025 final ResolveInfo info = receivers.get(i); 8026 if (info.activityInfo == null) { 8027 continue; 8028 } 8029 8030 if (packageName.equals(info.activityInfo.packageName)) { 8031 targetReceiver = info.activityInfo; 8032 break; 8033 } 8034 } 8035 8036 if (targetReceiver == null) { 8037 return null; 8038 } 8039 8040 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8041 } 8042 8043 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8044 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8045 if (pkgInfo.verifiers.length == 0) { 8046 return null; 8047 } 8048 8049 final int N = pkgInfo.verifiers.length; 8050 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8051 for (int i = 0; i < N; i++) { 8052 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8053 8054 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8055 receivers); 8056 if (comp == null) { 8057 continue; 8058 } 8059 8060 final int verifierUid = getUidForVerifier(verifierInfo); 8061 if (verifierUid == -1) { 8062 continue; 8063 } 8064 8065 if (DEBUG_VERIFY) { 8066 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8067 + " with the correct signature"); 8068 } 8069 sufficientVerifiers.add(comp); 8070 verificationState.addSufficientVerifier(verifierUid); 8071 } 8072 8073 return sufficientVerifiers; 8074 } 8075 8076 private int getUidForVerifier(VerifierInfo verifierInfo) { 8077 synchronized (mPackages) { 8078 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8079 if (pkg == null) { 8080 return -1; 8081 } else if (pkg.mSignatures.length != 1) { 8082 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8083 + " has more than one signature; ignoring"); 8084 return -1; 8085 } 8086 8087 /* 8088 * If the public key of the package's signature does not match 8089 * our expected public key, then this is a different package and 8090 * we should skip. 8091 */ 8092 8093 final byte[] expectedPublicKey; 8094 try { 8095 final Signature verifierSig = pkg.mSignatures[0]; 8096 final PublicKey publicKey = verifierSig.getPublicKey(); 8097 expectedPublicKey = publicKey.getEncoded(); 8098 } catch (CertificateException e) { 8099 return -1; 8100 } 8101 8102 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8103 8104 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8105 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8106 + " does not have the expected public key; ignoring"); 8107 return -1; 8108 } 8109 8110 return pkg.applicationInfo.uid; 8111 } 8112 } 8113 8114 @Override 8115 public void finishPackageInstall(int token) { 8116 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8117 8118 if (DEBUG_INSTALL) { 8119 Slog.v(TAG, "BM finishing package install for " + token); 8120 } 8121 8122 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8123 mHandler.sendMessage(msg); 8124 } 8125 8126 /** 8127 * Get the verification agent timeout. 8128 * 8129 * @return verification timeout in milliseconds 8130 */ 8131 private long getVerificationTimeout() { 8132 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8133 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8134 DEFAULT_VERIFICATION_TIMEOUT); 8135 } 8136 8137 /** 8138 * Get the default verification agent response code. 8139 * 8140 * @return default verification response code 8141 */ 8142 private int getDefaultVerificationResponse() { 8143 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8144 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8145 DEFAULT_VERIFICATION_RESPONSE); 8146 } 8147 8148 /** 8149 * Check whether or not package verification has been enabled. 8150 * 8151 * @return true if verification should be performed 8152 */ 8153 private boolean isVerificationEnabled(int userId, int installFlags) { 8154 if (!DEFAULT_VERIFY_ENABLE) { 8155 return false; 8156 } 8157 8158 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 8159 8160 // Check if installing from ADB 8161 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 8162 // Do not run verification in a test harness environment 8163 if (ActivityManager.isRunningInTestHarness()) { 8164 return false; 8165 } 8166 if (ensureVerifyAppsEnabled) { 8167 return true; 8168 } 8169 // Check if the developer does not want package verification for ADB installs 8170 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8171 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8172 return false; 8173 } 8174 } 8175 8176 if (ensureVerifyAppsEnabled) { 8177 return true; 8178 } 8179 8180 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8181 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8182 } 8183 8184 /** 8185 * Get the "allow unknown sources" setting. 8186 * 8187 * @return the current "allow unknown sources" setting 8188 */ 8189 private int getUnknownSourcesSettings() { 8190 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8191 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 8192 -1); 8193 } 8194 8195 @Override 8196 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 8197 final int uid = Binder.getCallingUid(); 8198 // writer 8199 synchronized (mPackages) { 8200 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 8201 if (targetPackageSetting == null) { 8202 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 8203 } 8204 8205 PackageSetting installerPackageSetting; 8206 if (installerPackageName != null) { 8207 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 8208 if (installerPackageSetting == null) { 8209 throw new IllegalArgumentException("Unknown installer package: " 8210 + installerPackageName); 8211 } 8212 } else { 8213 installerPackageSetting = null; 8214 } 8215 8216 Signature[] callerSignature; 8217 Object obj = mSettings.getUserIdLPr(uid); 8218 if (obj != null) { 8219 if (obj instanceof SharedUserSetting) { 8220 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 8221 } else if (obj instanceof PackageSetting) { 8222 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 8223 } else { 8224 throw new SecurityException("Bad object " + obj + " for uid " + uid); 8225 } 8226 } else { 8227 throw new SecurityException("Unknown calling uid " + uid); 8228 } 8229 8230 // Verify: can't set installerPackageName to a package that is 8231 // not signed with the same cert as the caller. 8232 if (installerPackageSetting != null) { 8233 if (compareSignatures(callerSignature, 8234 installerPackageSetting.signatures.mSignatures) 8235 != PackageManager.SIGNATURE_MATCH) { 8236 throw new SecurityException( 8237 "Caller does not have same cert as new installer package " 8238 + installerPackageName); 8239 } 8240 } 8241 8242 // Verify: if target already has an installer package, it must 8243 // be signed with the same cert as the caller. 8244 if (targetPackageSetting.installerPackageName != null) { 8245 PackageSetting setting = mSettings.mPackages.get( 8246 targetPackageSetting.installerPackageName); 8247 // If the currently set package isn't valid, then it's always 8248 // okay to change it. 8249 if (setting != null) { 8250 if (compareSignatures(callerSignature, 8251 setting.signatures.mSignatures) 8252 != PackageManager.SIGNATURE_MATCH) { 8253 throw new SecurityException( 8254 "Caller does not have same cert as old installer package " 8255 + targetPackageSetting.installerPackageName); 8256 } 8257 } 8258 } 8259 8260 // Okay! 8261 targetPackageSetting.installerPackageName = installerPackageName; 8262 scheduleWriteSettingsLocked(); 8263 } 8264 } 8265 8266 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 8267 // Queue up an async operation since the package installation may take a little while. 8268 mHandler.post(new Runnable() { 8269 public void run() { 8270 mHandler.removeCallbacks(this); 8271 // Result object to be returned 8272 PackageInstalledInfo res = new PackageInstalledInfo(); 8273 res.returnCode = currentStatus; 8274 res.uid = -1; 8275 res.pkg = null; 8276 res.removedInfo = new PackageRemovedInfo(); 8277 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 8278 args.doPreInstall(res.returnCode); 8279 synchronized (mInstallLock) { 8280 installPackageLI(args, res); 8281 } 8282 args.doPostInstall(res.returnCode, res.uid); 8283 } 8284 8285 // A restore should be performed at this point if (a) the install 8286 // succeeded, (b) the operation is not an update, and (c) the new 8287 // package has not opted out of backup participation. 8288 final boolean update = res.removedInfo.removedPackage != null; 8289 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 8290 boolean doRestore = !update 8291 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 8292 8293 // Set up the post-install work request bookkeeping. This will be used 8294 // and cleaned up by the post-install event handling regardless of whether 8295 // there's a restore pass performed. Token values are >= 1. 8296 int token; 8297 if (mNextInstallToken < 0) mNextInstallToken = 1; 8298 token = mNextInstallToken++; 8299 8300 PostInstallData data = new PostInstallData(args, res); 8301 mRunningInstalls.put(token, data); 8302 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 8303 8304 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 8305 // Pass responsibility to the Backup Manager. It will perform a 8306 // restore if appropriate, then pass responsibility back to the 8307 // Package Manager to run the post-install observer callbacks 8308 // and broadcasts. 8309 IBackupManager bm = IBackupManager.Stub.asInterface( 8310 ServiceManager.getService(Context.BACKUP_SERVICE)); 8311 if (bm != null) { 8312 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 8313 + " to BM for possible restore"); 8314 try { 8315 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 8316 } catch (RemoteException e) { 8317 // can't happen; the backup manager is local 8318 } catch (Exception e) { 8319 Slog.e(TAG, "Exception trying to enqueue restore", e); 8320 doRestore = false; 8321 } 8322 } else { 8323 Slog.e(TAG, "Backup Manager not found!"); 8324 doRestore = false; 8325 } 8326 } 8327 8328 if (!doRestore) { 8329 // No restore possible, or the Backup Manager was mysteriously not 8330 // available -- just fire the post-install work request directly. 8331 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 8332 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8333 mHandler.sendMessage(msg); 8334 } 8335 } 8336 }); 8337 } 8338 8339 private abstract class HandlerParams { 8340 private static final int MAX_RETRIES = 4; 8341 8342 /** 8343 * Number of times startCopy() has been attempted and had a non-fatal 8344 * error. 8345 */ 8346 private int mRetries = 0; 8347 8348 /** User handle for the user requesting the information or installation. */ 8349 private final UserHandle mUser; 8350 8351 HandlerParams(UserHandle user) { 8352 mUser = user; 8353 } 8354 8355 UserHandle getUser() { 8356 return mUser; 8357 } 8358 8359 final boolean startCopy() { 8360 boolean res; 8361 try { 8362 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 8363 8364 if (++mRetries > MAX_RETRIES) { 8365 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 8366 mHandler.sendEmptyMessage(MCS_GIVE_UP); 8367 handleServiceError(); 8368 return false; 8369 } else { 8370 handleStartCopy(); 8371 res = true; 8372 } 8373 } catch (RemoteException e) { 8374 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 8375 mHandler.sendEmptyMessage(MCS_RECONNECT); 8376 res = false; 8377 } 8378 handleReturnCode(); 8379 return res; 8380 } 8381 8382 final void serviceError() { 8383 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 8384 handleServiceError(); 8385 handleReturnCode(); 8386 } 8387 8388 abstract void handleStartCopy() throws RemoteException; 8389 abstract void handleServiceError(); 8390 abstract void handleReturnCode(); 8391 } 8392 8393 class MeasureParams extends HandlerParams { 8394 private final PackageStats mStats; 8395 private boolean mSuccess; 8396 8397 private final IPackageStatsObserver mObserver; 8398 8399 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 8400 super(new UserHandle(stats.userHandle)); 8401 mObserver = observer; 8402 mStats = stats; 8403 } 8404 8405 @Override 8406 public String toString() { 8407 return "MeasureParams{" 8408 + Integer.toHexString(System.identityHashCode(this)) 8409 + " " + mStats.packageName + "}"; 8410 } 8411 8412 @Override 8413 void handleStartCopy() throws RemoteException { 8414 synchronized (mInstallLock) { 8415 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 8416 } 8417 8418 if (mSuccess) { 8419 final boolean mounted; 8420 if (Environment.isExternalStorageEmulated()) { 8421 mounted = true; 8422 } else { 8423 final String status = Environment.getExternalStorageState(); 8424 mounted = (Environment.MEDIA_MOUNTED.equals(status) 8425 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 8426 } 8427 8428 if (mounted) { 8429 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 8430 8431 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 8432 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 8433 8434 mStats.externalDataSize = calculateDirectorySize(mContainerService, 8435 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 8436 8437 // Always subtract cache size, since it's a subdirectory 8438 mStats.externalDataSize -= mStats.externalCacheSize; 8439 8440 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 8441 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 8442 8443 mStats.externalObbSize = calculateDirectorySize(mContainerService, 8444 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 8445 } 8446 } 8447 } 8448 8449 @Override 8450 void handleReturnCode() { 8451 if (mObserver != null) { 8452 try { 8453 mObserver.onGetStatsCompleted(mStats, mSuccess); 8454 } catch (RemoteException e) { 8455 Slog.i(TAG, "Observer no longer exists."); 8456 } 8457 } 8458 } 8459 8460 @Override 8461 void handleServiceError() { 8462 Slog.e(TAG, "Could not measure application " + mStats.packageName 8463 + " external storage"); 8464 } 8465 } 8466 8467 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 8468 throws RemoteException { 8469 long result = 0; 8470 for (File path : paths) { 8471 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 8472 } 8473 return result; 8474 } 8475 8476 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 8477 for (File path : paths) { 8478 try { 8479 mcs.clearDirectory(path.getAbsolutePath()); 8480 } catch (RemoteException e) { 8481 } 8482 } 8483 } 8484 8485 static class OriginInfo { 8486 /** 8487 * Location where install is coming from, before it has been 8488 * copied/renamed into place. This could be a single monolithic APK 8489 * file, or a cluster directory. This location may be untrusted. 8490 */ 8491 final File file; 8492 final String cid; 8493 8494 /** 8495 * Flag indicating that {@link #file} or {@link #cid} has already been 8496 * staged, meaning downstream users don't need to defensively copy the 8497 * contents. 8498 */ 8499 final boolean staged; 8500 8501 /** 8502 * Flag indicating that {@link #file} or {@link #cid} is an already 8503 * installed app that is being moved. 8504 */ 8505 final boolean existing; 8506 8507 final String resolvedPath; 8508 final File resolvedFile; 8509 8510 static OriginInfo fromNothing() { 8511 return new OriginInfo(null, null, false, false); 8512 } 8513 8514 static OriginInfo fromUntrustedFile(File file) { 8515 return new OriginInfo(file, null, false, false); 8516 } 8517 8518 static OriginInfo fromExistingFile(File file) { 8519 return new OriginInfo(file, null, false, true); 8520 } 8521 8522 static OriginInfo fromStagedFile(File file) { 8523 return new OriginInfo(file, null, true, false); 8524 } 8525 8526 static OriginInfo fromStagedContainer(String cid) { 8527 return new OriginInfo(null, cid, true, false); 8528 } 8529 8530 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 8531 this.file = file; 8532 this.cid = cid; 8533 this.staged = staged; 8534 this.existing = existing; 8535 8536 if (cid != null) { 8537 resolvedPath = PackageHelper.getSdDir(cid); 8538 resolvedFile = new File(resolvedPath); 8539 } else if (file != null) { 8540 resolvedPath = file.getAbsolutePath(); 8541 resolvedFile = file; 8542 } else { 8543 resolvedPath = null; 8544 resolvedFile = null; 8545 } 8546 } 8547 } 8548 8549 class InstallParams extends HandlerParams { 8550 final OriginInfo origin; 8551 final IPackageInstallObserver2 observer; 8552 int installFlags; 8553 final String installerPackageName; 8554 final VerificationParams verificationParams; 8555 private InstallArgs mArgs; 8556 private int mRet; 8557 final String packageAbiOverride; 8558 8559 InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 8560 String installerPackageName, VerificationParams verificationParams, UserHandle user, 8561 String packageAbiOverride) { 8562 super(user); 8563 this.origin = origin; 8564 this.observer = observer; 8565 this.installFlags = installFlags; 8566 this.installerPackageName = installerPackageName; 8567 this.verificationParams = verificationParams; 8568 this.packageAbiOverride = packageAbiOverride; 8569 } 8570 8571 @Override 8572 public String toString() { 8573 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 8574 + " file=" + origin.file + " cid=" + origin.cid + "}"; 8575 } 8576 8577 public ManifestDigest getManifestDigest() { 8578 if (verificationParams == null) { 8579 return null; 8580 } 8581 return verificationParams.getManifestDigest(); 8582 } 8583 8584 private int installLocationPolicy(PackageInfoLite pkgLite) { 8585 String packageName = pkgLite.packageName; 8586 int installLocation = pkgLite.installLocation; 8587 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 8588 // reader 8589 synchronized (mPackages) { 8590 PackageParser.Package pkg = mPackages.get(packageName); 8591 if (pkg != null) { 8592 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 8593 // Check for downgrading. 8594 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 8595 if (pkgLite.versionCode < pkg.mVersionCode) { 8596 Slog.w(TAG, "Can't install update of " + packageName 8597 + " update version " + pkgLite.versionCode 8598 + " is older than installed version " 8599 + pkg.mVersionCode); 8600 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 8601 } 8602 } 8603 // Check for updated system application. 8604 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8605 if (onSd) { 8606 Slog.w(TAG, "Cannot install update to system app on sdcard"); 8607 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 8608 } 8609 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8610 } else { 8611 if (onSd) { 8612 // Install flag overrides everything. 8613 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8614 } 8615 // If current upgrade specifies particular preference 8616 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 8617 // Application explicitly specified internal. 8618 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8619 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 8620 // App explictly prefers external. Let policy decide 8621 } else { 8622 // Prefer previous location 8623 if (isExternal(pkg)) { 8624 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8625 } 8626 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8627 } 8628 } 8629 } else { 8630 // Invalid install. Return error code 8631 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 8632 } 8633 } 8634 } 8635 // All the special cases have been taken care of. 8636 // Return result based on recommended install location. 8637 if (onSd) { 8638 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8639 } 8640 return pkgLite.recommendedInstallLocation; 8641 } 8642 8643 /* 8644 * Invoke remote method to get package information and install 8645 * location values. Override install location based on default 8646 * policy if needed and then create install arguments based 8647 * on the install location. 8648 */ 8649 public void handleStartCopy() throws RemoteException { 8650 int ret = PackageManager.INSTALL_SUCCEEDED; 8651 8652 // If we're already staged, we've firmly committed to an install location 8653 if (origin.staged) { 8654 if (origin.file != null) { 8655 installFlags |= PackageManager.INSTALL_INTERNAL; 8656 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 8657 } else if (origin.cid != null) { 8658 installFlags |= PackageManager.INSTALL_EXTERNAL; 8659 installFlags &= ~PackageManager.INSTALL_INTERNAL; 8660 } else { 8661 throw new IllegalStateException("Invalid stage location"); 8662 } 8663 } 8664 8665 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 8666 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 8667 8668 PackageInfoLite pkgLite = null; 8669 8670 if (onInt && onSd) { 8671 // Check if both bits are set. 8672 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 8673 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8674 } else { 8675 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 8676 packageAbiOverride); 8677 8678 /* 8679 * If we have too little free space, try to free cache 8680 * before giving up. 8681 */ 8682 if (!origin.staged && pkgLite.recommendedInstallLocation 8683 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8684 // TODO: focus freeing disk space on the target device 8685 final StorageManager storage = StorageManager.from(mContext); 8686 final long lowThreshold = storage.getStorageLowBytes( 8687 Environment.getDataDirectory()); 8688 8689 final long sizeBytes = mContainerService.calculateInstalledSize( 8690 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 8691 8692 if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) { 8693 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 8694 installFlags, packageAbiOverride); 8695 } 8696 8697 /* 8698 * The cache free must have deleted the file we 8699 * downloaded to install. 8700 * 8701 * TODO: fix the "freeCache" call to not delete 8702 * the file we care about. 8703 */ 8704 if (pkgLite.recommendedInstallLocation 8705 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8706 pkgLite.recommendedInstallLocation 8707 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 8708 } 8709 } 8710 } 8711 8712 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8713 int loc = pkgLite.recommendedInstallLocation; 8714 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 8715 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8716 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 8717 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 8718 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8719 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8720 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 8721 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 8722 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8723 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 8724 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 8725 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 8726 } else { 8727 // Override with defaults if needed. 8728 loc = installLocationPolicy(pkgLite); 8729 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 8730 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 8731 } else if (!onSd && !onInt) { 8732 // Override install location with flags 8733 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 8734 // Set the flag to install on external media. 8735 installFlags |= PackageManager.INSTALL_EXTERNAL; 8736 installFlags &= ~PackageManager.INSTALL_INTERNAL; 8737 } else { 8738 // Make sure the flag for installing on external 8739 // media is unset 8740 installFlags |= PackageManager.INSTALL_INTERNAL; 8741 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 8742 } 8743 } 8744 } 8745 } 8746 8747 final InstallArgs args = createInstallArgs(this); 8748 mArgs = args; 8749 8750 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8751 /* 8752 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 8753 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 8754 */ 8755 int userIdentifier = getUser().getIdentifier(); 8756 if (userIdentifier == UserHandle.USER_ALL 8757 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 8758 userIdentifier = UserHandle.USER_OWNER; 8759 } 8760 8761 /* 8762 * Determine if we have any installed package verifiers. If we 8763 * do, then we'll defer to them to verify the packages. 8764 */ 8765 final int requiredUid = mRequiredVerifierPackage == null ? -1 8766 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 8767 if (!origin.existing && requiredUid != -1 8768 && isVerificationEnabled(userIdentifier, installFlags)) { 8769 final Intent verification = new Intent( 8770 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 8771 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 8772 PACKAGE_MIME_TYPE); 8773 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8774 8775 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 8776 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 8777 0 /* TODO: Which userId? */); 8778 8779 if (DEBUG_VERIFY) { 8780 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 8781 + verification.toString() + " with " + pkgLite.verifiers.length 8782 + " optional verifiers"); 8783 } 8784 8785 final int verificationId = mPendingVerificationToken++; 8786 8787 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8788 8789 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 8790 installerPackageName); 8791 8792 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 8793 installFlags); 8794 8795 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 8796 pkgLite.packageName); 8797 8798 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 8799 pkgLite.versionCode); 8800 8801 if (verificationParams != null) { 8802 if (verificationParams.getVerificationURI() != null) { 8803 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 8804 verificationParams.getVerificationURI()); 8805 } 8806 if (verificationParams.getOriginatingURI() != null) { 8807 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 8808 verificationParams.getOriginatingURI()); 8809 } 8810 if (verificationParams.getReferrer() != null) { 8811 verification.putExtra(Intent.EXTRA_REFERRER, 8812 verificationParams.getReferrer()); 8813 } 8814 if (verificationParams.getOriginatingUid() >= 0) { 8815 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 8816 verificationParams.getOriginatingUid()); 8817 } 8818 if (verificationParams.getInstallerUid() >= 0) { 8819 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 8820 verificationParams.getInstallerUid()); 8821 } 8822 } 8823 8824 final PackageVerificationState verificationState = new PackageVerificationState( 8825 requiredUid, args); 8826 8827 mPendingVerification.append(verificationId, verificationState); 8828 8829 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 8830 receivers, verificationState); 8831 8832 /* 8833 * If any sufficient verifiers were listed in the package 8834 * manifest, attempt to ask them. 8835 */ 8836 if (sufficientVerifiers != null) { 8837 final int N = sufficientVerifiers.size(); 8838 if (N == 0) { 8839 Slog.i(TAG, "Additional verifiers required, but none installed."); 8840 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 8841 } else { 8842 for (int i = 0; i < N; i++) { 8843 final ComponentName verifierComponent = sufficientVerifiers.get(i); 8844 8845 final Intent sufficientIntent = new Intent(verification); 8846 sufficientIntent.setComponent(verifierComponent); 8847 8848 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 8849 } 8850 } 8851 } 8852 8853 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 8854 mRequiredVerifierPackage, receivers); 8855 if (ret == PackageManager.INSTALL_SUCCEEDED 8856 && mRequiredVerifierPackage != null) { 8857 /* 8858 * Send the intent to the required verification agent, 8859 * but only start the verification timeout after the 8860 * target BroadcastReceivers have run. 8861 */ 8862 verification.setComponent(requiredVerifierComponent); 8863 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 8864 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8865 new BroadcastReceiver() { 8866 @Override 8867 public void onReceive(Context context, Intent intent) { 8868 final Message msg = mHandler 8869 .obtainMessage(CHECK_PENDING_VERIFICATION); 8870 msg.arg1 = verificationId; 8871 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 8872 } 8873 }, null, 0, null, null); 8874 8875 /* 8876 * We don't want the copy to proceed until verification 8877 * succeeds, so null out this field. 8878 */ 8879 mArgs = null; 8880 } 8881 } else { 8882 /* 8883 * No package verification is enabled, so immediately start 8884 * the remote call to initiate copy using temporary file. 8885 */ 8886 ret = args.copyApk(mContainerService, true); 8887 } 8888 } 8889 8890 mRet = ret; 8891 } 8892 8893 @Override 8894 void handleReturnCode() { 8895 // If mArgs is null, then MCS couldn't be reached. When it 8896 // reconnects, it will try again to install. At that point, this 8897 // will succeed. 8898 if (mArgs != null) { 8899 processPendingInstall(mArgs, mRet); 8900 } 8901 } 8902 8903 @Override 8904 void handleServiceError() { 8905 mArgs = createInstallArgs(this); 8906 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8907 } 8908 8909 public boolean isForwardLocked() { 8910 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8911 } 8912 } 8913 8914 /** 8915 * Used during creation of InstallArgs 8916 * 8917 * @param installFlags package installation flags 8918 * @return true if should be installed on external storage 8919 */ 8920 private static boolean installOnSd(int installFlags) { 8921 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 8922 return false; 8923 } 8924 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 8925 return true; 8926 } 8927 return false; 8928 } 8929 8930 /** 8931 * Used during creation of InstallArgs 8932 * 8933 * @param installFlags package installation flags 8934 * @return true if should be installed as forward locked 8935 */ 8936 private static boolean installForwardLocked(int installFlags) { 8937 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8938 } 8939 8940 private InstallArgs createInstallArgs(InstallParams params) { 8941 if (installOnSd(params.installFlags) || params.isForwardLocked()) { 8942 return new AsecInstallArgs(params); 8943 } else { 8944 return new FileInstallArgs(params); 8945 } 8946 } 8947 8948 /** 8949 * Create args that describe an existing installed package. Typically used 8950 * when cleaning up old installs, or used as a move source. 8951 */ 8952 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 8953 String resourcePath, String nativeLibraryRoot, String[] instructionSets) { 8954 final boolean isInAsec; 8955 if (installOnSd(installFlags)) { 8956 /* Apps on SD card are always in ASEC containers. */ 8957 isInAsec = true; 8958 } else if (installForwardLocked(installFlags) 8959 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 8960 /* 8961 * Forward-locked apps are only in ASEC containers if they're the 8962 * new style 8963 */ 8964 isInAsec = true; 8965 } else { 8966 isInAsec = false; 8967 } 8968 8969 if (isInAsec) { 8970 return new AsecInstallArgs(codePath, instructionSets, 8971 installOnSd(installFlags), installForwardLocked(installFlags)); 8972 } else { 8973 return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot, 8974 instructionSets); 8975 } 8976 } 8977 8978 static abstract class InstallArgs { 8979 /** @see InstallParams#origin */ 8980 final OriginInfo origin; 8981 8982 final IPackageInstallObserver2 observer; 8983 // Always refers to PackageManager flags only 8984 final int installFlags; 8985 final String installerPackageName; 8986 final ManifestDigest manifestDigest; 8987 final UserHandle user; 8988 final String abiOverride; 8989 8990 // The list of instruction sets supported by this app. This is currently 8991 // only used during the rmdex() phase to clean up resources. We can get rid of this 8992 // if we move dex files under the common app path. 8993 /* nullable */ String[] instructionSets; 8994 8995 InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 8996 String installerPackageName, ManifestDigest manifestDigest, UserHandle user, 8997 String[] instructionSets, String abiOverride) { 8998 this.origin = origin; 8999 this.installFlags = installFlags; 9000 this.observer = observer; 9001 this.installerPackageName = installerPackageName; 9002 this.manifestDigest = manifestDigest; 9003 this.user = user; 9004 this.instructionSets = instructionSets; 9005 this.abiOverride = abiOverride; 9006 } 9007 9008 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 9009 abstract int doPreInstall(int status); 9010 9011 /** 9012 * Rename package into final resting place. All paths on the given 9013 * scanned package should be updated to reflect the rename. 9014 */ 9015 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 9016 abstract int doPostInstall(int status, int uid); 9017 9018 /** @see PackageSettingBase#codePathString */ 9019 abstract String getCodePath(); 9020 /** @see PackageSettingBase#resourcePathString */ 9021 abstract String getResourcePath(); 9022 abstract String getLegacyNativeLibraryPath(); 9023 9024 // Need installer lock especially for dex file removal. 9025 abstract void cleanUpResourcesLI(); 9026 abstract boolean doPostDeleteLI(boolean delete); 9027 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9028 9029 /** 9030 * Called before the source arguments are copied. This is used mostly 9031 * for MoveParams when it needs to read the source file to put it in the 9032 * destination. 9033 */ 9034 int doPreCopy() { 9035 return PackageManager.INSTALL_SUCCEEDED; 9036 } 9037 9038 /** 9039 * Called after the source arguments are copied. This is used mostly for 9040 * MoveParams when it needs to read the source file to put it in the 9041 * destination. 9042 * 9043 * @return 9044 */ 9045 int doPostCopy(int uid) { 9046 return PackageManager.INSTALL_SUCCEEDED; 9047 } 9048 9049 protected boolean isFwdLocked() { 9050 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9051 } 9052 9053 protected boolean isExternal() { 9054 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9055 } 9056 9057 UserHandle getUser() { 9058 return user; 9059 } 9060 } 9061 9062 /** 9063 * Logic to handle installation of non-ASEC applications, including copying 9064 * and renaming logic. 9065 */ 9066 class FileInstallArgs extends InstallArgs { 9067 private File codeFile; 9068 private File resourceFile; 9069 private File legacyNativeLibraryPath; 9070 9071 // Example topology: 9072 // /data/app/com.example/base.apk 9073 // /data/app/com.example/split_foo.apk 9074 // /data/app/com.example/lib/arm/libfoo.so 9075 // /data/app/com.example/lib/arm64/libfoo.so 9076 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 9077 9078 /** New install */ 9079 FileInstallArgs(InstallParams params) { 9080 super(params.origin, params.observer, params.installFlags, 9081 params.installerPackageName, params.getManifestDigest(), params.getUser(), 9082 null /* instruction sets */, params.packageAbiOverride); 9083 if (isFwdLocked()) { 9084 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 9085 } 9086 } 9087 9088 /** Existing install */ 9089 FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath, 9090 String[] instructionSets) { 9091 super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null); 9092 this.codeFile = (codePath != null) ? new File(codePath) : null; 9093 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 9094 this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ? 9095 new File(legacyNativeLibraryPath) : null; 9096 } 9097 9098 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9099 final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(), 9100 isFwdLocked(), abiOverride); 9101 9102 final StorageManager storage = StorageManager.from(mContext); 9103 return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory())); 9104 } 9105 9106 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9107 if (origin.staged) { 9108 Slog.d(TAG, origin.file + " already staged; skipping copy"); 9109 codeFile = origin.file; 9110 resourceFile = origin.file; 9111 return PackageManager.INSTALL_SUCCEEDED; 9112 } 9113 9114 try { 9115 final File tempDir = mInstallerService.allocateInternalStageDirLegacy(); 9116 codeFile = tempDir; 9117 resourceFile = tempDir; 9118 } catch (IOException e) { 9119 Slog.w(TAG, "Failed to create copy file: " + e); 9120 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9121 } 9122 9123 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 9124 @Override 9125 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 9126 if (!FileUtils.isValidExtFilename(name)) { 9127 throw new IllegalArgumentException("Invalid filename: " + name); 9128 } 9129 try { 9130 final File file = new File(codeFile, name); 9131 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 9132 O_RDWR | O_CREAT, 0644); 9133 Os.chmod(file.getAbsolutePath(), 0644); 9134 return new ParcelFileDescriptor(fd); 9135 } catch (ErrnoException e) { 9136 throw new RemoteException("Failed to open: " + e.getMessage()); 9137 } 9138 } 9139 }; 9140 9141 int ret = PackageManager.INSTALL_SUCCEEDED; 9142 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 9143 if (ret != PackageManager.INSTALL_SUCCEEDED) { 9144 Slog.e(TAG, "Failed to copy package"); 9145 return ret; 9146 } 9147 9148 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 9149 NativeLibraryHelper.Handle handle = null; 9150 try { 9151 handle = NativeLibraryHelper.Handle.create(codeFile); 9152 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 9153 abiOverride); 9154 } catch (IOException e) { 9155 Slog.e(TAG, "Copying native libraries failed", e); 9156 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9157 } finally { 9158 IoUtils.closeQuietly(handle); 9159 } 9160 9161 return ret; 9162 } 9163 9164 int doPreInstall(int status) { 9165 if (status != PackageManager.INSTALL_SUCCEEDED) { 9166 cleanUp(); 9167 } 9168 return status; 9169 } 9170 9171 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9172 if (status != PackageManager.INSTALL_SUCCEEDED) { 9173 cleanUp(); 9174 return false; 9175 } else { 9176 final File beforeCodeFile = codeFile; 9177 final File afterCodeFile = getNextCodePath(pkg.packageName); 9178 9179 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 9180 try { 9181 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 9182 } catch (ErrnoException e) { 9183 Slog.d(TAG, "Failed to rename", e); 9184 return false; 9185 } 9186 9187 if (!SELinux.restoreconRecursive(afterCodeFile)) { 9188 Slog.d(TAG, "Failed to restorecon"); 9189 return false; 9190 } 9191 9192 // Reflect the rename internally 9193 codeFile = afterCodeFile; 9194 resourceFile = afterCodeFile; 9195 9196 // Reflect the rename in scanned details 9197 pkg.codePath = afterCodeFile.getAbsolutePath(); 9198 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9199 pkg.baseCodePath); 9200 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9201 pkg.splitCodePaths); 9202 9203 // Reflect the rename in app info 9204 pkg.applicationInfo.setCodePath(pkg.codePath); 9205 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9206 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9207 pkg.applicationInfo.setResourcePath(pkg.codePath); 9208 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9209 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9210 9211 return true; 9212 } 9213 } 9214 9215 int doPostInstall(int status, int uid) { 9216 if (status != PackageManager.INSTALL_SUCCEEDED) { 9217 cleanUp(); 9218 } 9219 return status; 9220 } 9221 9222 @Override 9223 String getCodePath() { 9224 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 9225 } 9226 9227 @Override 9228 String getResourcePath() { 9229 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 9230 } 9231 9232 @Override 9233 String getLegacyNativeLibraryPath() { 9234 return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null; 9235 } 9236 9237 private boolean cleanUp() { 9238 if (codeFile == null || !codeFile.exists()) { 9239 return false; 9240 } 9241 9242 if (codeFile.isDirectory()) { 9243 FileUtils.deleteContents(codeFile); 9244 } 9245 codeFile.delete(); 9246 9247 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 9248 resourceFile.delete(); 9249 } 9250 9251 if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) { 9252 if (!FileUtils.deleteContents(legacyNativeLibraryPath)) { 9253 Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath); 9254 } 9255 legacyNativeLibraryPath.delete(); 9256 } 9257 9258 return true; 9259 } 9260 9261 void cleanUpResourcesLI() { 9262 // Try enumerating all code paths before deleting 9263 List<String> allCodePaths = Collections.EMPTY_LIST; 9264 if (codeFile != null && codeFile.exists()) { 9265 try { 9266 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9267 allCodePaths = pkg.getAllCodePaths(); 9268 } catch (PackageParserException e) { 9269 // Ignored; we tried our best 9270 } 9271 } 9272 9273 cleanUp(); 9274 9275 if (!allCodePaths.isEmpty()) { 9276 if (instructionSets == null) { 9277 throw new IllegalStateException("instructionSet == null"); 9278 } 9279 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9280 for (String codePath : allCodePaths) { 9281 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9282 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9283 if (retCode < 0) { 9284 Slog.w(TAG, "Couldn't remove dex file for package: " 9285 + " at location " + codePath + ", retcode=" + retCode); 9286 // we don't consider this to be a failure of the core package deletion 9287 } 9288 } 9289 } 9290 } 9291 } 9292 9293 boolean doPostDeleteLI(boolean delete) { 9294 // XXX err, shouldn't we respect the delete flag? 9295 cleanUpResourcesLI(); 9296 return true; 9297 } 9298 } 9299 9300 private boolean isAsecExternal(String cid) { 9301 final String asecPath = PackageHelper.getSdFilesystem(cid); 9302 return !asecPath.startsWith(mAsecInternalPath); 9303 } 9304 9305 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 9306 PackageManagerException { 9307 if (copyRet < 0) { 9308 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 9309 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 9310 throw new PackageManagerException(copyRet, message); 9311 } 9312 } 9313 } 9314 9315 /** 9316 * Extract the MountService "container ID" from the full code path of an 9317 * .apk. 9318 */ 9319 static String cidFromCodePath(String fullCodePath) { 9320 int eidx = fullCodePath.lastIndexOf("/"); 9321 String subStr1 = fullCodePath.substring(0, eidx); 9322 int sidx = subStr1.lastIndexOf("/"); 9323 return subStr1.substring(sidx+1, eidx); 9324 } 9325 9326 /** 9327 * Logic to handle installation of ASEC applications, including copying and 9328 * renaming logic. 9329 */ 9330 class AsecInstallArgs extends InstallArgs { 9331 static final String RES_FILE_NAME = "pkg.apk"; 9332 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 9333 9334 String cid; 9335 String packagePath; 9336 String resourcePath; 9337 String legacyNativeLibraryDir; 9338 9339 /** New install */ 9340 AsecInstallArgs(InstallParams params) { 9341 super(params.origin, params.observer, params.installFlags, 9342 params.installerPackageName, params.getManifestDigest(), 9343 params.getUser(), null /* instruction sets */, 9344 params.packageAbiOverride); 9345 } 9346 9347 /** Existing install */ 9348 AsecInstallArgs(String fullCodePath, String[] instructionSets, 9349 boolean isExternal, boolean isForwardLocked) { 9350 super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0) 9351 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9352 instructionSets, null); 9353 // Hackily pretend we're still looking at a full code path 9354 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 9355 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 9356 } 9357 9358 // Extract cid from fullCodePath 9359 int eidx = fullCodePath.lastIndexOf("/"); 9360 String subStr1 = fullCodePath.substring(0, eidx); 9361 int sidx = subStr1.lastIndexOf("/"); 9362 cid = subStr1.substring(sidx+1, eidx); 9363 setMountPath(subStr1); 9364 } 9365 9366 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 9367 super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 9368 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9369 instructionSets, null); 9370 this.cid = cid; 9371 setMountPath(PackageHelper.getSdDir(cid)); 9372 } 9373 9374 void createCopyFile() { 9375 cid = mInstallerService.allocateExternalStageCidLegacy(); 9376 } 9377 9378 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9379 final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(), 9380 abiOverride); 9381 9382 final File target; 9383 if (isExternal()) { 9384 target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory(); 9385 } else { 9386 target = Environment.getDataDirectory(); 9387 } 9388 9389 final StorageManager storage = StorageManager.from(mContext); 9390 return (sizeBytes <= storage.getStorageBytesUntilLow(target)); 9391 } 9392 9393 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9394 if (origin.staged) { 9395 Slog.d(TAG, origin.cid + " already staged; skipping copy"); 9396 cid = origin.cid; 9397 setMountPath(PackageHelper.getSdDir(cid)); 9398 return PackageManager.INSTALL_SUCCEEDED; 9399 } 9400 9401 if (temp) { 9402 createCopyFile(); 9403 } else { 9404 /* 9405 * Pre-emptively destroy the container since it's destroyed if 9406 * copying fails due to it existing anyway. 9407 */ 9408 PackageHelper.destroySdDir(cid); 9409 } 9410 9411 final String newMountPath = imcs.copyPackageToContainer( 9412 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(), 9413 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 9414 9415 if (newMountPath != null) { 9416 setMountPath(newMountPath); 9417 return PackageManager.INSTALL_SUCCEEDED; 9418 } else { 9419 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9420 } 9421 } 9422 9423 @Override 9424 String getCodePath() { 9425 return packagePath; 9426 } 9427 9428 @Override 9429 String getResourcePath() { 9430 return resourcePath; 9431 } 9432 9433 @Override 9434 String getLegacyNativeLibraryPath() { 9435 return legacyNativeLibraryDir; 9436 } 9437 9438 int doPreInstall(int status) { 9439 if (status != PackageManager.INSTALL_SUCCEEDED) { 9440 // Destroy container 9441 PackageHelper.destroySdDir(cid); 9442 } else { 9443 boolean mounted = PackageHelper.isContainerMounted(cid); 9444 if (!mounted) { 9445 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 9446 Process.SYSTEM_UID); 9447 if (newMountPath != null) { 9448 setMountPath(newMountPath); 9449 } else { 9450 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9451 } 9452 } 9453 } 9454 return status; 9455 } 9456 9457 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9458 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 9459 String newMountPath = null; 9460 if (PackageHelper.isContainerMounted(cid)) { 9461 // Unmount the container 9462 if (!PackageHelper.unMountSdDir(cid)) { 9463 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9464 return false; 9465 } 9466 } 9467 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9468 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9469 " which might be stale. Will try to clean up."); 9470 // Clean up the stale container and proceed to recreate. 9471 if (!PackageHelper.destroySdDir(newCacheId)) { 9472 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9473 return false; 9474 } 9475 // Successfully cleaned up stale container. Try to rename again. 9476 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9477 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9478 + " inspite of cleaning it up."); 9479 return false; 9480 } 9481 } 9482 if (!PackageHelper.isContainerMounted(newCacheId)) { 9483 Slog.w(TAG, "Mounting container " + newCacheId); 9484 newMountPath = PackageHelper.mountSdDir(newCacheId, 9485 getEncryptKey(), Process.SYSTEM_UID); 9486 } else { 9487 newMountPath = PackageHelper.getSdDir(newCacheId); 9488 } 9489 if (newMountPath == null) { 9490 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9491 return false; 9492 } 9493 Log.i(TAG, "Succesfully renamed " + cid + 9494 " to " + newCacheId + 9495 " at new path: " + newMountPath); 9496 cid = newCacheId; 9497 9498 final File beforeCodeFile = new File(packagePath); 9499 setMountPath(newMountPath); 9500 final File afterCodeFile = new File(packagePath); 9501 9502 // Reflect the rename in scanned details 9503 pkg.codePath = afterCodeFile.getAbsolutePath(); 9504 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9505 pkg.baseCodePath); 9506 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9507 pkg.splitCodePaths); 9508 9509 // Reflect the rename in app info 9510 pkg.applicationInfo.setCodePath(pkg.codePath); 9511 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9512 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9513 pkg.applicationInfo.setResourcePath(pkg.codePath); 9514 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9515 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9516 9517 return true; 9518 } 9519 9520 private void setMountPath(String mountPath) { 9521 final File mountFile = new File(mountPath); 9522 9523 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 9524 if (monolithicFile.exists()) { 9525 packagePath = monolithicFile.getAbsolutePath(); 9526 if (isFwdLocked()) { 9527 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 9528 } else { 9529 resourcePath = packagePath; 9530 } 9531 } else { 9532 packagePath = mountFile.getAbsolutePath(); 9533 resourcePath = packagePath; 9534 } 9535 9536 legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath(); 9537 } 9538 9539 int doPostInstall(int status, int uid) { 9540 if (status != PackageManager.INSTALL_SUCCEEDED) { 9541 cleanUp(); 9542 } else { 9543 final int groupOwner; 9544 final String protectedFile; 9545 if (isFwdLocked()) { 9546 groupOwner = UserHandle.getSharedAppGid(uid); 9547 protectedFile = RES_FILE_NAME; 9548 } else { 9549 groupOwner = -1; 9550 protectedFile = null; 9551 } 9552 9553 if (uid < Process.FIRST_APPLICATION_UID 9554 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9555 Slog.e(TAG, "Failed to finalize " + cid); 9556 PackageHelper.destroySdDir(cid); 9557 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9558 } 9559 9560 boolean mounted = PackageHelper.isContainerMounted(cid); 9561 if (!mounted) { 9562 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9563 } 9564 } 9565 return status; 9566 } 9567 9568 private void cleanUp() { 9569 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9570 9571 // Destroy secure container 9572 PackageHelper.destroySdDir(cid); 9573 } 9574 9575 private List<String> getAllCodePaths() { 9576 final File codeFile = new File(getCodePath()); 9577 if (codeFile != null && codeFile.exists()) { 9578 try { 9579 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9580 return pkg.getAllCodePaths(); 9581 } catch (PackageParserException e) { 9582 // Ignored; we tried our best 9583 } 9584 } 9585 return Collections.EMPTY_LIST; 9586 } 9587 9588 void cleanUpResourcesLI() { 9589 // Enumerate all code paths before deleting 9590 cleanUpResourcesLI(getAllCodePaths()); 9591 } 9592 9593 private void cleanUpResourcesLI(List<String> allCodePaths) { 9594 cleanUp(); 9595 9596 if (!allCodePaths.isEmpty()) { 9597 if (instructionSets == null) { 9598 throw new IllegalStateException("instructionSet == null"); 9599 } 9600 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9601 for (String codePath : allCodePaths) { 9602 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9603 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9604 if (retCode < 0) { 9605 Slog.w(TAG, "Couldn't remove dex file for package: " 9606 + " at location " + codePath + ", retcode=" + retCode); 9607 // we don't consider this to be a failure of the core package deletion 9608 } 9609 } 9610 } 9611 } 9612 } 9613 9614 boolean matchContainer(String app) { 9615 if (cid.startsWith(app)) { 9616 return true; 9617 } 9618 return false; 9619 } 9620 9621 String getPackageName() { 9622 return getAsecPackageName(cid); 9623 } 9624 9625 boolean doPostDeleteLI(boolean delete) { 9626 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 9627 final List<String> allCodePaths = getAllCodePaths(); 9628 boolean mounted = PackageHelper.isContainerMounted(cid); 9629 if (mounted) { 9630 // Unmount first 9631 if (PackageHelper.unMountSdDir(cid)) { 9632 mounted = false; 9633 } 9634 } 9635 if (!mounted && delete) { 9636 cleanUpResourcesLI(allCodePaths); 9637 } 9638 return !mounted; 9639 } 9640 9641 @Override 9642 int doPreCopy() { 9643 if (isFwdLocked()) { 9644 if (!PackageHelper.fixSdPermissions(cid, 9645 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 9646 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9647 } 9648 } 9649 9650 return PackageManager.INSTALL_SUCCEEDED; 9651 } 9652 9653 @Override 9654 int doPostCopy(int uid) { 9655 if (isFwdLocked()) { 9656 if (uid < Process.FIRST_APPLICATION_UID 9657 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 9658 RES_FILE_NAME)) { 9659 Slog.e(TAG, "Failed to finalize " + cid); 9660 PackageHelper.destroySdDir(cid); 9661 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9662 } 9663 } 9664 9665 return PackageManager.INSTALL_SUCCEEDED; 9666 } 9667 } 9668 9669 static String getAsecPackageName(String packageCid) { 9670 int idx = packageCid.lastIndexOf("-"); 9671 if (idx == -1) { 9672 return packageCid; 9673 } 9674 return packageCid.substring(0, idx); 9675 } 9676 9677 // Utility method used to create code paths based on package name and available index. 9678 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 9679 String idxStr = ""; 9680 int idx = 1; 9681 // Fall back to default value of idx=1 if prefix is not 9682 // part of oldCodePath 9683 if (oldCodePath != null) { 9684 String subStr = oldCodePath; 9685 // Drop the suffix right away 9686 if (suffix != null && subStr.endsWith(suffix)) { 9687 subStr = subStr.substring(0, subStr.length() - suffix.length()); 9688 } 9689 // If oldCodePath already contains prefix find out the 9690 // ending index to either increment or decrement. 9691 int sidx = subStr.lastIndexOf(prefix); 9692 if (sidx != -1) { 9693 subStr = subStr.substring(sidx + prefix.length()); 9694 if (subStr != null) { 9695 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 9696 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 9697 } 9698 try { 9699 idx = Integer.parseInt(subStr); 9700 if (idx <= 1) { 9701 idx++; 9702 } else { 9703 idx--; 9704 } 9705 } catch(NumberFormatException e) { 9706 } 9707 } 9708 } 9709 } 9710 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 9711 return prefix + idxStr; 9712 } 9713 9714 private File getNextCodePath(String packageName) { 9715 int suffix = 1; 9716 File result; 9717 do { 9718 result = new File(mAppInstallDir, packageName + "-" + suffix); 9719 suffix++; 9720 } while (result.exists()); 9721 return result; 9722 } 9723 9724 // Utility method used to ignore ADD/REMOVE events 9725 // by directory observer. 9726 private static boolean ignoreCodePath(String fullPathStr) { 9727 String apkName = deriveCodePathName(fullPathStr); 9728 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 9729 if (idx != -1 && ((idx+1) < apkName.length())) { 9730 // Make sure the package ends with a numeral 9731 String version = apkName.substring(idx+1); 9732 try { 9733 Integer.parseInt(version); 9734 return true; 9735 } catch (NumberFormatException e) {} 9736 } 9737 return false; 9738 } 9739 9740 // Utility method that returns the relative package path with respect 9741 // to the installation directory. Like say for /data/data/com.test-1.apk 9742 // string com.test-1 is returned. 9743 static String deriveCodePathName(String codePath) { 9744 if (codePath == null) { 9745 return null; 9746 } 9747 final File codeFile = new File(codePath); 9748 final String name = codeFile.getName(); 9749 if (codeFile.isDirectory()) { 9750 return name; 9751 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 9752 final int lastDot = name.lastIndexOf('.'); 9753 return name.substring(0, lastDot); 9754 } else { 9755 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 9756 return null; 9757 } 9758 } 9759 9760 class PackageInstalledInfo { 9761 String name; 9762 int uid; 9763 // The set of users that originally had this package installed. 9764 int[] origUsers; 9765 // The set of users that now have this package installed. 9766 int[] newUsers; 9767 PackageParser.Package pkg; 9768 int returnCode; 9769 String returnMsg; 9770 PackageRemovedInfo removedInfo; 9771 9772 public void setError(int code, String msg) { 9773 returnCode = code; 9774 returnMsg = msg; 9775 Slog.w(TAG, msg); 9776 } 9777 9778 public void setError(String msg, PackageParserException e) { 9779 returnCode = e.error; 9780 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9781 Slog.w(TAG, msg, e); 9782 } 9783 9784 public void setError(String msg, PackageManagerException e) { 9785 returnCode = e.error; 9786 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9787 Slog.w(TAG, msg, e); 9788 } 9789 9790 // In some error cases we want to convey more info back to the observer 9791 String origPackage; 9792 String origPermission; 9793 } 9794 9795 /* 9796 * Install a non-existing package. 9797 */ 9798 private void installNewPackageLI(PackageParser.Package pkg, 9799 int parseFlags, int scanFlags, UserHandle user, 9800 String installerPackageName, PackageInstalledInfo res) { 9801 // Remember this for later, in case we need to rollback this install 9802 String pkgName = pkg.packageName; 9803 9804 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 9805 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 9806 synchronized(mPackages) { 9807 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 9808 // A package with the same name is already installed, though 9809 // it has been renamed to an older name. The package we 9810 // are trying to install should be installed as an update to 9811 // the existing one, but that has not been requested, so bail. 9812 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9813 + " without first uninstalling package running as " 9814 + mSettings.mRenamedPackages.get(pkgName)); 9815 return; 9816 } 9817 if (mPackages.containsKey(pkgName)) { 9818 // Don't allow installation over an existing package with the same name. 9819 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9820 + " without first uninstalling."); 9821 return; 9822 } 9823 } 9824 9825 try { 9826 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 9827 System.currentTimeMillis(), user); 9828 9829 updateSettingsLI(newPackage, installerPackageName, null, null, res); 9830 // delete the partially installed application. the data directory will have to be 9831 // restored if it was already existing 9832 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9833 // remove package from internal structures. Note that we want deletePackageX to 9834 // delete the package data and cache directories that it created in 9835 // scanPackageLocked, unless those directories existed before we even tried to 9836 // install. 9837 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 9838 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 9839 res.removedInfo, true); 9840 } 9841 9842 } catch (PackageManagerException e) { 9843 res.setError("Package couldn't be installed in " + pkg.codePath, e); 9844 } 9845 } 9846 9847 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 9848 // Upgrade keysets are being used. Determine if new package has a superset of the 9849 // required keys. 9850 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 9851 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9852 for (int i = 0; i < upgradeKeySets.length; i++) { 9853 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 9854 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 9855 return true; 9856 } 9857 } 9858 return false; 9859 } 9860 9861 private void replacePackageLI(PackageParser.Package pkg, 9862 int parseFlags, int scanFlags, UserHandle user, 9863 String installerPackageName, PackageInstalledInfo res) { 9864 PackageParser.Package oldPackage; 9865 String pkgName = pkg.packageName; 9866 int[] allUsers; 9867 boolean[] perUserInstalled; 9868 9869 // First find the old package info and check signatures 9870 synchronized(mPackages) { 9871 oldPackage = mPackages.get(pkgName); 9872 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 9873 PackageSetting ps = mSettings.mPackages.get(pkgName); 9874 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 9875 // default to original signature matching 9876 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 9877 != PackageManager.SIGNATURE_MATCH) { 9878 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9879 "New package has a different signature: " + pkgName); 9880 return; 9881 } 9882 } else { 9883 if(!checkUpgradeKeySetLP(ps, pkg)) { 9884 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9885 "New package not signed by keys specified by upgrade-keysets: " 9886 + pkgName); 9887 return; 9888 } 9889 } 9890 9891 // In case of rollback, remember per-user/profile install state 9892 allUsers = sUserManager.getUserIds(); 9893 perUserInstalled = new boolean[allUsers.length]; 9894 for (int i = 0; i < allUsers.length; i++) { 9895 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 9896 } 9897 } 9898 9899 boolean sysPkg = (isSystemApp(oldPackage)); 9900 if (sysPkg) { 9901 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 9902 user, allUsers, perUserInstalled, installerPackageName, res); 9903 } else { 9904 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 9905 user, allUsers, perUserInstalled, installerPackageName, res); 9906 } 9907 } 9908 9909 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 9910 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 9911 int[] allUsers, boolean[] perUserInstalled, 9912 String installerPackageName, PackageInstalledInfo res) { 9913 String pkgName = deletedPackage.packageName; 9914 boolean deletedPkg = true; 9915 boolean updatedSettings = false; 9916 9917 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 9918 + deletedPackage); 9919 long origUpdateTime; 9920 if (pkg.mExtras != null) { 9921 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 9922 } else { 9923 origUpdateTime = 0; 9924 } 9925 9926 // First delete the existing package while retaining the data directory 9927 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 9928 res.removedInfo, true)) { 9929 // If the existing package wasn't successfully deleted 9930 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 9931 deletedPkg = false; 9932 } else { 9933 // Successfully deleted the old package; proceed with replace. 9934 9935 // If deleted package lived in a container, give users a chance to 9936 // relinquish resources before killing. 9937 if (isForwardLocked(deletedPackage) || isExternal(deletedPackage)) { 9938 if (DEBUG_INSTALL) { 9939 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 9940 } 9941 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 9942 final ArrayList<String> pkgList = new ArrayList<String>(1); 9943 pkgList.add(deletedPackage.applicationInfo.packageName); 9944 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 9945 } 9946 9947 deleteCodeCacheDirsLI(pkgName); 9948 try { 9949 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 9950 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 9951 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 9952 updatedSettings = true; 9953 } catch (PackageManagerException e) { 9954 res.setError("Package couldn't be installed in " + pkg.codePath, e); 9955 } 9956 } 9957 9958 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9959 // remove package from internal structures. Note that we want deletePackageX to 9960 // delete the package data and cache directories that it created in 9961 // scanPackageLocked, unless those directories existed before we even tried to 9962 // install. 9963 if(updatedSettings) { 9964 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 9965 deletePackageLI( 9966 pkgName, null, true, allUsers, perUserInstalled, 9967 PackageManager.DELETE_KEEP_DATA, 9968 res.removedInfo, true); 9969 } 9970 // Since we failed to install the new package we need to restore the old 9971 // package that we deleted. 9972 if (deletedPkg) { 9973 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 9974 File restoreFile = new File(deletedPackage.codePath); 9975 // Parse old package 9976 boolean oldOnSd = isExternal(deletedPackage); 9977 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 9978 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) | 9979 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 9980 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 9981 try { 9982 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 9983 } catch (PackageManagerException e) { 9984 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 9985 + e.getMessage()); 9986 return; 9987 } 9988 // Restore of old package succeeded. Update permissions. 9989 // writer 9990 synchronized (mPackages) { 9991 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 9992 UPDATE_PERMISSIONS_ALL); 9993 // can downgrade to reader 9994 mSettings.writeLPr(); 9995 } 9996 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 9997 } 9998 } 9999 } 10000 10001 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 10002 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10003 int[] allUsers, boolean[] perUserInstalled, 10004 String installerPackageName, PackageInstalledInfo res) { 10005 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 10006 + ", old=" + deletedPackage); 10007 boolean updatedSettings = false; 10008 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 10009 if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) { 10010 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10011 } 10012 String packageName = deletedPackage.packageName; 10013 if (packageName == null) { 10014 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10015 "Attempt to delete null packageName."); 10016 return; 10017 } 10018 PackageParser.Package oldPkg; 10019 PackageSetting oldPkgSetting; 10020 // reader 10021 synchronized (mPackages) { 10022 oldPkg = mPackages.get(packageName); 10023 oldPkgSetting = mSettings.mPackages.get(packageName); 10024 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 10025 (oldPkgSetting == null)) { 10026 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10027 "Couldn't find package:" + packageName + " information"); 10028 return; 10029 } 10030 } 10031 10032 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 10033 10034 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10035 res.removedInfo.removedPackage = packageName; 10036 // Remove existing system package 10037 removePackageLI(oldPkgSetting, true); 10038 // writer 10039 synchronized (mPackages) { 10040 if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) { 10041 // We didn't need to disable the .apk as a current system package, 10042 // which means we are replacing another update that is already 10043 // installed. We need to make sure to delete the older one's .apk. 10044 res.removedInfo.args = createInstallArgsForExisting(0, 10045 deletedPackage.applicationInfo.getCodePath(), 10046 deletedPackage.applicationInfo.getResourcePath(), 10047 deletedPackage.applicationInfo.nativeLibraryRootDir, 10048 getAppDexInstructionSets(deletedPackage.applicationInfo)); 10049 } else { 10050 res.removedInfo.args = null; 10051 } 10052 } 10053 10054 // Successfully disabled the old package. Now proceed with re-installation 10055 deleteCodeCacheDirsLI(packageName); 10056 10057 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10058 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10059 10060 PackageParser.Package newPackage = null; 10061 try { 10062 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 10063 if (newPackage.mExtras != null) { 10064 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 10065 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10066 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10067 10068 // is the update attempting to change shared user? that isn't going to work... 10069 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10070 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 10071 "Forbidding shared user change from " + oldPkgSetting.sharedUser 10072 + " to " + newPkgSetting.sharedUser); 10073 updatedSettings = true; 10074 } 10075 } 10076 10077 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10078 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10079 updatedSettings = true; 10080 } 10081 10082 } catch (PackageManagerException e) { 10083 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10084 } 10085 10086 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10087 // Re installation failed. Restore old information 10088 // Remove new pkg information 10089 if (newPackage != null) { 10090 removeInstalledPackageLI(newPackage, true); 10091 } 10092 // Add back the old system package 10093 try { 10094 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 10095 } catch (PackageManagerException e) { 10096 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 10097 } 10098 // Restore the old system information in Settings 10099 synchronized(mPackages) { 10100 if (updatedSettings) { 10101 mSettings.enableSystemPackageLPw(packageName); 10102 mSettings.setInstallerPackageName(packageName, 10103 oldPkgSetting.installerPackageName); 10104 } 10105 mSettings.writeLPr(); 10106 } 10107 } 10108 } 10109 10110 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10111 int[] allUsers, boolean[] perUserInstalled, 10112 PackageInstalledInfo res) { 10113 String pkgName = newPackage.packageName; 10114 synchronized (mPackages) { 10115 //write settings. the installStatus will be incomplete at this stage. 10116 //note that the new package setting would have already been 10117 //added to mPackages. It hasn't been persisted yet. 10118 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10119 mSettings.writeLPr(); 10120 } 10121 10122 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10123 10124 synchronized (mPackages) { 10125 updatePermissionsLPw(newPackage.packageName, newPackage, 10126 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10127 ? UPDATE_PERMISSIONS_ALL : 0)); 10128 // For system-bundled packages, we assume that installing an upgraded version 10129 // of the package implies that the user actually wants to run that new code, 10130 // so we enable the package. 10131 if (isSystemApp(newPackage)) { 10132 // NB: implicit assumption that system package upgrades apply to all users 10133 if (DEBUG_INSTALL) { 10134 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10135 } 10136 PackageSetting ps = mSettings.mPackages.get(pkgName); 10137 if (ps != null) { 10138 if (res.origUsers != null) { 10139 for (int userHandle : res.origUsers) { 10140 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10141 userHandle, installerPackageName); 10142 } 10143 } 10144 // Also convey the prior install/uninstall state 10145 if (allUsers != null && perUserInstalled != null) { 10146 for (int i = 0; i < allUsers.length; i++) { 10147 if (DEBUG_INSTALL) { 10148 Slog.d(TAG, " user " + allUsers[i] 10149 + " => " + perUserInstalled[i]); 10150 } 10151 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10152 } 10153 // these install state changes will be persisted in the 10154 // upcoming call to mSettings.writeLPr(). 10155 } 10156 } 10157 } 10158 res.name = pkgName; 10159 res.uid = newPackage.applicationInfo.uid; 10160 res.pkg = newPackage; 10161 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10162 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10163 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10164 //to update install status 10165 mSettings.writeLPr(); 10166 } 10167 } 10168 10169 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 10170 final int installFlags = args.installFlags; 10171 String installerPackageName = args.installerPackageName; 10172 File tmpPackageFile = new File(args.getCodePath()); 10173 boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10174 boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0); 10175 boolean replace = false; 10176 final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE; 10177 // Result object to be returned 10178 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10179 10180 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10181 // Retrieve PackageSettings and parse package 10182 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10183 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10184 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 10185 PackageParser pp = new PackageParser(); 10186 pp.setSeparateProcesses(mSeparateProcesses); 10187 pp.setDisplayMetrics(mMetrics); 10188 10189 final PackageParser.Package pkg; 10190 try { 10191 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 10192 } catch (PackageParserException e) { 10193 res.setError("Failed parse during installPackageLI", e); 10194 return; 10195 } 10196 10197 // Mark that we have an install time CPU ABI override. 10198 pkg.cpuAbiOverride = args.abiOverride; 10199 10200 String pkgName = res.name = pkg.packageName; 10201 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 10202 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 10203 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 10204 return; 10205 } 10206 } 10207 10208 try { 10209 pp.collectCertificates(pkg, parseFlags); 10210 pp.collectManifestDigest(pkg); 10211 } catch (PackageParserException e) { 10212 res.setError("Failed collect during installPackageLI", e); 10213 return; 10214 } 10215 10216 /* If the installer passed in a manifest digest, compare it now. */ 10217 if (args.manifestDigest != null) { 10218 if (DEBUG_INSTALL) { 10219 final String parsedManifest = pkg.manifestDigest == null ? "null" 10220 : pkg.manifestDigest.toString(); 10221 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 10222 + parsedManifest); 10223 } 10224 10225 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 10226 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 10227 return; 10228 } 10229 } else if (DEBUG_INSTALL) { 10230 final String parsedManifest = pkg.manifestDigest == null 10231 ? "null" : pkg.manifestDigest.toString(); 10232 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 10233 } 10234 10235 // Get rid of all references to package scan path via parser. 10236 pp = null; 10237 String oldCodePath = null; 10238 boolean systemApp = false; 10239 synchronized (mPackages) { 10240 // Check whether the newly-scanned package wants to define an already-defined perm 10241 int N = pkg.permissions.size(); 10242 for (int i = N-1; i >= 0; i--) { 10243 PackageParser.Permission perm = pkg.permissions.get(i); 10244 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 10245 if (bp != null) { 10246 // If the defining package is signed with our cert, it's okay. This 10247 // also includes the "updating the same package" case, of course. 10248 // "updating same package" could also involve key-rotation. 10249 final boolean sigsOk; 10250 if (!bp.sourcePackage.equals(pkg.packageName) 10251 || !(bp.packageSetting instanceof PackageSetting) 10252 || !bp.packageSetting.keySetData.isUsingUpgradeKeySets() 10253 || ((PackageSetting) bp.packageSetting).sharedUser != null) { 10254 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 10255 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH; 10256 } else { 10257 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 10258 } 10259 if (!sigsOk) { 10260 // If the owning package is the system itself, we log but allow 10261 // install to proceed; we fail the install on all other permission 10262 // redefinitions. 10263 if (!bp.sourcePackage.equals("android")) { 10264 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 10265 + pkg.packageName + " attempting to redeclare permission " 10266 + perm.info.name + " already owned by " + bp.sourcePackage); 10267 res.origPermission = perm.info.name; 10268 res.origPackage = bp.sourcePackage; 10269 return; 10270 } else { 10271 Slog.w(TAG, "Package " + pkg.packageName 10272 + " attempting to redeclare system permission " 10273 + perm.info.name + "; ignoring new declaration"); 10274 pkg.permissions.remove(i); 10275 } 10276 } 10277 } 10278 } 10279 10280 // Check if installing already existing package 10281 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10282 String oldName = mSettings.mRenamedPackages.get(pkgName); 10283 if (pkg.mOriginalPackages != null 10284 && pkg.mOriginalPackages.contains(oldName) 10285 && mPackages.containsKey(oldName)) { 10286 // This package is derived from an original package, 10287 // and this device has been updating from that original 10288 // name. We must continue using the original name, so 10289 // rename the new package here. 10290 pkg.setPackageName(oldName); 10291 pkgName = pkg.packageName; 10292 replace = true; 10293 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 10294 + oldName + " pkgName=" + pkgName); 10295 } else if (mPackages.containsKey(pkgName)) { 10296 // This package, under its official name, already exists 10297 // on the device; we should replace it. 10298 replace = true; 10299 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 10300 } 10301 } 10302 PackageSetting ps = mSettings.mPackages.get(pkgName); 10303 if (ps != null) { 10304 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 10305 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 10306 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 10307 systemApp = (ps.pkg.applicationInfo.flags & 10308 ApplicationInfo.FLAG_SYSTEM) != 0; 10309 } 10310 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10311 } 10312 } 10313 10314 if (systemApp && onSd) { 10315 // Disable updates to system apps on sdcard 10316 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 10317 "Cannot install updates to system apps on sdcard"); 10318 return; 10319 } 10320 10321 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 10322 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 10323 return; 10324 } 10325 10326 if (replace) { 10327 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 10328 installerPackageName, res); 10329 } else { 10330 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 10331 args.user, installerPackageName, res); 10332 } 10333 synchronized (mPackages) { 10334 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10335 if (ps != null) { 10336 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10337 } 10338 } 10339 } 10340 10341 private static boolean isForwardLocked(PackageParser.Package pkg) { 10342 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10343 } 10344 10345 private static boolean isForwardLocked(ApplicationInfo info) { 10346 return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10347 } 10348 10349 private boolean isForwardLocked(PackageSetting ps) { 10350 return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10351 } 10352 10353 private static boolean isMultiArch(PackageSetting ps) { 10354 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10355 } 10356 10357 private static boolean isMultiArch(ApplicationInfo info) { 10358 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10359 } 10360 10361 private static boolean isExternal(PackageParser.Package pkg) { 10362 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10363 } 10364 10365 private static boolean isExternal(PackageSetting ps) { 10366 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10367 } 10368 10369 private static boolean isExternal(ApplicationInfo info) { 10370 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10371 } 10372 10373 private static boolean isSystemApp(PackageParser.Package pkg) { 10374 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10375 } 10376 10377 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 10378 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0; 10379 } 10380 10381 private static boolean isSystemApp(ApplicationInfo info) { 10382 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10383 } 10384 10385 private static boolean isSystemApp(PackageSetting ps) { 10386 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 10387 } 10388 10389 private static boolean isUpdatedSystemApp(PackageSetting ps) { 10390 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10391 } 10392 10393 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 10394 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10395 } 10396 10397 private static boolean isUpdatedSystemApp(ApplicationInfo info) { 10398 return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10399 } 10400 10401 private int packageFlagsToInstallFlags(PackageSetting ps) { 10402 int installFlags = 0; 10403 if (isExternal(ps)) { 10404 installFlags |= PackageManager.INSTALL_EXTERNAL; 10405 } 10406 if (isForwardLocked(ps)) { 10407 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 10408 } 10409 return installFlags; 10410 } 10411 10412 private void deleteTempPackageFiles() { 10413 final FilenameFilter filter = new FilenameFilter() { 10414 public boolean accept(File dir, String name) { 10415 return name.startsWith("vmdl") && name.endsWith(".tmp"); 10416 } 10417 }; 10418 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 10419 file.delete(); 10420 } 10421 } 10422 10423 @Override 10424 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 10425 int flags) { 10426 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 10427 flags); 10428 } 10429 10430 @Override 10431 public void deletePackage(final String packageName, 10432 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 10433 mContext.enforceCallingOrSelfPermission( 10434 android.Manifest.permission.DELETE_PACKAGES, null); 10435 final int uid = Binder.getCallingUid(); 10436 if (UserHandle.getUserId(uid) != userId) { 10437 mContext.enforceCallingPermission( 10438 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 10439 "deletePackage for user " + userId); 10440 } 10441 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 10442 try { 10443 observer.onPackageDeleted(packageName, 10444 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 10445 } catch (RemoteException re) { 10446 } 10447 return; 10448 } 10449 10450 boolean uninstallBlocked = false; 10451 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 10452 int[] users = sUserManager.getUserIds(); 10453 for (int i = 0; i < users.length; ++i) { 10454 if (getBlockUninstallForUser(packageName, users[i])) { 10455 uninstallBlocked = true; 10456 break; 10457 } 10458 } 10459 } else { 10460 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 10461 } 10462 if (uninstallBlocked) { 10463 try { 10464 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 10465 null); 10466 } catch (RemoteException re) { 10467 } 10468 return; 10469 } 10470 10471 if (DEBUG_REMOVE) { 10472 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 10473 } 10474 // Queue up an async operation since the package deletion may take a little while. 10475 mHandler.post(new Runnable() { 10476 public void run() { 10477 mHandler.removeCallbacks(this); 10478 final int returnCode = deletePackageX(packageName, userId, flags); 10479 if (observer != null) { 10480 try { 10481 observer.onPackageDeleted(packageName, returnCode, null); 10482 } catch (RemoteException e) { 10483 Log.i(TAG, "Observer no longer exists."); 10484 } //end catch 10485 } //end if 10486 } //end run 10487 }); 10488 } 10489 10490 private boolean isPackageDeviceAdmin(String packageName, int userId) { 10491 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 10492 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 10493 try { 10494 if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId) 10495 || dpm.isDeviceOwner(packageName))) { 10496 return true; 10497 } 10498 } catch (RemoteException e) { 10499 } 10500 return false; 10501 } 10502 10503 /** 10504 * This method is an internal method that could be get invoked either 10505 * to delete an installed package or to clean up a failed installation. 10506 * After deleting an installed package, a broadcast is sent to notify any 10507 * listeners that the package has been installed. For cleaning up a failed 10508 * installation, the broadcast is not necessary since the package's 10509 * installation wouldn't have sent the initial broadcast either 10510 * The key steps in deleting a package are 10511 * deleting the package information in internal structures like mPackages, 10512 * deleting the packages base directories through installd 10513 * updating mSettings to reflect current status 10514 * persisting settings for later use 10515 * sending a broadcast if necessary 10516 */ 10517 private int deletePackageX(String packageName, int userId, int flags) { 10518 final PackageRemovedInfo info = new PackageRemovedInfo(); 10519 final boolean res; 10520 10521 if (isPackageDeviceAdmin(packageName, userId)) { 10522 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 10523 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 10524 } 10525 10526 boolean removedForAllUsers = false; 10527 boolean systemUpdate = false; 10528 10529 // for the uninstall-updates case and restricted profiles, remember the per- 10530 // userhandle installed state 10531 int[] allUsers; 10532 boolean[] perUserInstalled; 10533 synchronized (mPackages) { 10534 PackageSetting ps = mSettings.mPackages.get(packageName); 10535 allUsers = sUserManager.getUserIds(); 10536 perUserInstalled = new boolean[allUsers.length]; 10537 for (int i = 0; i < allUsers.length; i++) { 10538 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10539 } 10540 } 10541 10542 synchronized (mInstallLock) { 10543 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 10544 res = deletePackageLI(packageName, 10545 (flags & PackageManager.DELETE_ALL_USERS) != 0 10546 ? UserHandle.ALL : new UserHandle(userId), 10547 true, allUsers, perUserInstalled, 10548 flags | REMOVE_CHATTY, info, true); 10549 systemUpdate = info.isRemovedPackageSystemUpdate; 10550 if (res && !systemUpdate && mPackages.get(packageName) == null) { 10551 removedForAllUsers = true; 10552 } 10553 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 10554 + " removedForAllUsers=" + removedForAllUsers); 10555 } 10556 10557 if (res) { 10558 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 10559 10560 // If the removed package was a system update, the old system package 10561 // was re-enabled; we need to broadcast this information 10562 if (systemUpdate) { 10563 Bundle extras = new Bundle(1); 10564 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 10565 ? info.removedAppId : info.uid); 10566 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10567 10568 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 10569 extras, null, null, null); 10570 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 10571 extras, null, null, null); 10572 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 10573 null, packageName, null, null); 10574 } 10575 } 10576 // Force a gc here. 10577 Runtime.getRuntime().gc(); 10578 // Delete the resources here after sending the broadcast to let 10579 // other processes clean up before deleting resources. 10580 if (info.args != null) { 10581 synchronized (mInstallLock) { 10582 info.args.doPostDeleteLI(true); 10583 } 10584 } 10585 10586 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10587 } 10588 10589 static class PackageRemovedInfo { 10590 String removedPackage; 10591 int uid = -1; 10592 int removedAppId = -1; 10593 int[] removedUsers = null; 10594 boolean isRemovedPackageSystemUpdate = false; 10595 // Clean up resources deleted packages. 10596 InstallArgs args = null; 10597 10598 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 10599 Bundle extras = new Bundle(1); 10600 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 10601 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 10602 if (replacing) { 10603 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10604 } 10605 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 10606 if (removedPackage != null) { 10607 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 10608 extras, null, null, removedUsers); 10609 if (fullRemove && !replacing) { 10610 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 10611 extras, null, null, removedUsers); 10612 } 10613 } 10614 if (removedAppId >= 0) { 10615 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 10616 removedUsers); 10617 } 10618 } 10619 } 10620 10621 /* 10622 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 10623 * flag is not set, the data directory is removed as well. 10624 * make sure this flag is set for partially installed apps. If not its meaningless to 10625 * delete a partially installed application. 10626 */ 10627 private void removePackageDataLI(PackageSetting ps, 10628 int[] allUserHandles, boolean[] perUserInstalled, 10629 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 10630 String packageName = ps.name; 10631 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 10632 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 10633 // Retrieve object to delete permissions for shared user later on 10634 final PackageSetting deletedPs; 10635 // reader 10636 synchronized (mPackages) { 10637 deletedPs = mSettings.mPackages.get(packageName); 10638 if (outInfo != null) { 10639 outInfo.removedPackage = packageName; 10640 outInfo.removedUsers = deletedPs != null 10641 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 10642 : null; 10643 } 10644 } 10645 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10646 removeDataDirsLI(packageName); 10647 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 10648 } 10649 // writer 10650 synchronized (mPackages) { 10651 if (deletedPs != null) { 10652 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10653 if (outInfo != null) { 10654 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 10655 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 10656 } 10657 if (deletedPs != null) { 10658 updatePermissionsLPw(deletedPs.name, null, 0); 10659 if (deletedPs.sharedUser != null) { 10660 // remove permissions associated with package 10661 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 10662 } 10663 } 10664 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 10665 } 10666 // make sure to preserve per-user disabled state if this removal was just 10667 // a downgrade of a system app to the factory package 10668 if (allUserHandles != null && perUserInstalled != null) { 10669 if (DEBUG_REMOVE) { 10670 Slog.d(TAG, "Propagating install state across downgrade"); 10671 } 10672 for (int i = 0; i < allUserHandles.length; i++) { 10673 if (DEBUG_REMOVE) { 10674 Slog.d(TAG, " user " + allUserHandles[i] 10675 + " => " + perUserInstalled[i]); 10676 } 10677 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10678 } 10679 } 10680 } 10681 // can downgrade to reader 10682 if (writeSettings) { 10683 // Save settings now 10684 mSettings.writeLPr(); 10685 } 10686 } 10687 if (outInfo != null) { 10688 // A user ID was deleted here. Go through all users and remove it 10689 // from KeyStore. 10690 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 10691 } 10692 } 10693 10694 static boolean locationIsPrivileged(File path) { 10695 try { 10696 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 10697 .getCanonicalPath(); 10698 return path.getCanonicalPath().startsWith(privilegedAppDir); 10699 } catch (IOException e) { 10700 Slog.e(TAG, "Unable to access code path " + path); 10701 } 10702 return false; 10703 } 10704 10705 /* 10706 * Tries to delete system package. 10707 */ 10708 private boolean deleteSystemPackageLI(PackageSetting newPs, 10709 int[] allUserHandles, boolean[] perUserInstalled, 10710 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 10711 final boolean applyUserRestrictions 10712 = (allUserHandles != null) && (perUserInstalled != null); 10713 PackageSetting disabledPs = null; 10714 // Confirm if the system package has been updated 10715 // An updated system app can be deleted. This will also have to restore 10716 // the system pkg from system partition 10717 // reader 10718 synchronized (mPackages) { 10719 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 10720 } 10721 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 10722 + " disabledPs=" + disabledPs); 10723 if (disabledPs == null) { 10724 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 10725 return false; 10726 } else if (DEBUG_REMOVE) { 10727 Slog.d(TAG, "Deleting system pkg from data partition"); 10728 } 10729 if (DEBUG_REMOVE) { 10730 if (applyUserRestrictions) { 10731 Slog.d(TAG, "Remembering install states:"); 10732 for (int i = 0; i < allUserHandles.length; i++) { 10733 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 10734 } 10735 } 10736 } 10737 // Delete the updated package 10738 outInfo.isRemovedPackageSystemUpdate = true; 10739 if (disabledPs.versionCode < newPs.versionCode) { 10740 // Delete data for downgrades 10741 flags &= ~PackageManager.DELETE_KEEP_DATA; 10742 } else { 10743 // Preserve data by setting flag 10744 flags |= PackageManager.DELETE_KEEP_DATA; 10745 } 10746 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 10747 allUserHandles, perUserInstalled, outInfo, writeSettings); 10748 if (!ret) { 10749 return false; 10750 } 10751 // writer 10752 synchronized (mPackages) { 10753 // Reinstate the old system package 10754 mSettings.enableSystemPackageLPw(newPs.name); 10755 // Remove any native libraries from the upgraded package. 10756 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 10757 } 10758 // Install the system package 10759 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 10760 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 10761 if (locationIsPrivileged(disabledPs.codePath)) { 10762 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10763 } 10764 10765 final PackageParser.Package newPkg; 10766 try { 10767 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 10768 } catch (PackageManagerException e) { 10769 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 10770 return false; 10771 } 10772 10773 // writer 10774 synchronized (mPackages) { 10775 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 10776 updatePermissionsLPw(newPkg.packageName, newPkg, 10777 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 10778 if (applyUserRestrictions) { 10779 if (DEBUG_REMOVE) { 10780 Slog.d(TAG, "Propagating install state across reinstall"); 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 // Regardless of writeSettings we need to ensure that this restriction 10790 // state propagation is persisted 10791 mSettings.writeAllUsersPackageRestrictionsLPr(); 10792 } 10793 // can downgrade to reader here 10794 if (writeSettings) { 10795 mSettings.writeLPr(); 10796 } 10797 } 10798 return true; 10799 } 10800 10801 private boolean deleteInstalledPackageLI(PackageSetting ps, 10802 boolean deleteCodeAndResources, int flags, 10803 int[] allUserHandles, boolean[] perUserInstalled, 10804 PackageRemovedInfo outInfo, boolean writeSettings) { 10805 if (outInfo != null) { 10806 outInfo.uid = ps.appId; 10807 } 10808 10809 // Delete package data from internal structures and also remove data if flag is set 10810 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 10811 10812 // Delete application code and resources 10813 if (deleteCodeAndResources && (outInfo != null)) { 10814 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 10815 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 10816 getAppDexInstructionSets(ps)); 10817 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 10818 } 10819 return true; 10820 } 10821 10822 @Override 10823 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 10824 int userId) { 10825 mContext.enforceCallingOrSelfPermission( 10826 android.Manifest.permission.DELETE_PACKAGES, null); 10827 synchronized (mPackages) { 10828 PackageSetting ps = mSettings.mPackages.get(packageName); 10829 if (ps == null) { 10830 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 10831 return false; 10832 } 10833 if (!ps.getInstalled(userId)) { 10834 // Can't block uninstall for an app that is not installed or enabled. 10835 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 10836 return false; 10837 } 10838 ps.setBlockUninstall(blockUninstall, userId); 10839 mSettings.writePackageRestrictionsLPr(userId); 10840 } 10841 return true; 10842 } 10843 10844 @Override 10845 public boolean getBlockUninstallForUser(String packageName, int userId) { 10846 synchronized (mPackages) { 10847 PackageSetting ps = mSettings.mPackages.get(packageName); 10848 if (ps == null) { 10849 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 10850 return false; 10851 } 10852 return ps.getBlockUninstall(userId); 10853 } 10854 } 10855 10856 /* 10857 * This method handles package deletion in general 10858 */ 10859 private boolean deletePackageLI(String packageName, UserHandle user, 10860 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 10861 int flags, PackageRemovedInfo outInfo, 10862 boolean writeSettings) { 10863 if (packageName == null) { 10864 Slog.w(TAG, "Attempt to delete null packageName."); 10865 return false; 10866 } 10867 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 10868 PackageSetting ps; 10869 boolean dataOnly = false; 10870 int removeUser = -1; 10871 int appId = -1; 10872 synchronized (mPackages) { 10873 ps = mSettings.mPackages.get(packageName); 10874 if (ps == null) { 10875 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 10876 return false; 10877 } 10878 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 10879 && user.getIdentifier() != UserHandle.USER_ALL) { 10880 // The caller is asking that the package only be deleted for a single 10881 // user. To do this, we just mark its uninstalled state and delete 10882 // its data. If this is a system app, we only allow this to happen if 10883 // they have set the special DELETE_SYSTEM_APP which requests different 10884 // semantics than normal for uninstalling system apps. 10885 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 10886 ps.setUserState(user.getIdentifier(), 10887 COMPONENT_ENABLED_STATE_DEFAULT, 10888 false, //installed 10889 true, //stopped 10890 true, //notLaunched 10891 false, //hidden 10892 null, null, null, 10893 false // blockUninstall 10894 ); 10895 if (!isSystemApp(ps)) { 10896 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 10897 // Other user still have this package installed, so all 10898 // we need to do is clear this user's data and save that 10899 // it is uninstalled. 10900 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 10901 removeUser = user.getIdentifier(); 10902 appId = ps.appId; 10903 mSettings.writePackageRestrictionsLPr(removeUser); 10904 } else { 10905 // We need to set it back to 'installed' so the uninstall 10906 // broadcasts will be sent correctly. 10907 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 10908 ps.setInstalled(true, user.getIdentifier()); 10909 } 10910 } else { 10911 // This is a system app, so we assume that the 10912 // other users still have this package installed, so all 10913 // we need to do is clear this user's data and save that 10914 // it is uninstalled. 10915 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 10916 removeUser = user.getIdentifier(); 10917 appId = ps.appId; 10918 mSettings.writePackageRestrictionsLPr(removeUser); 10919 } 10920 } 10921 } 10922 10923 if (removeUser >= 0) { 10924 // From above, we determined that we are deleting this only 10925 // for a single user. Continue the work here. 10926 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 10927 if (outInfo != null) { 10928 outInfo.removedPackage = packageName; 10929 outInfo.removedAppId = appId; 10930 outInfo.removedUsers = new int[] {removeUser}; 10931 } 10932 mInstaller.clearUserData(packageName, removeUser); 10933 removeKeystoreDataIfNeeded(removeUser, appId); 10934 schedulePackageCleaning(packageName, removeUser, false); 10935 return true; 10936 } 10937 10938 if (dataOnly) { 10939 // Delete application data first 10940 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 10941 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 10942 return true; 10943 } 10944 10945 boolean ret = false; 10946 if (isSystemApp(ps)) { 10947 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 10948 // When an updated system application is deleted we delete the existing resources as well and 10949 // fall back to existing code in system partition 10950 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 10951 flags, outInfo, writeSettings); 10952 } else { 10953 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 10954 // Kill application pre-emptively especially for apps on sd. 10955 killApplication(packageName, ps.appId, "uninstall pkg"); 10956 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 10957 allUserHandles, perUserInstalled, 10958 outInfo, writeSettings); 10959 } 10960 10961 return ret; 10962 } 10963 10964 private final class ClearStorageConnection implements ServiceConnection { 10965 IMediaContainerService mContainerService; 10966 10967 @Override 10968 public void onServiceConnected(ComponentName name, IBinder service) { 10969 synchronized (this) { 10970 mContainerService = IMediaContainerService.Stub.asInterface(service); 10971 notifyAll(); 10972 } 10973 } 10974 10975 @Override 10976 public void onServiceDisconnected(ComponentName name) { 10977 } 10978 } 10979 10980 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 10981 final boolean mounted; 10982 if (Environment.isExternalStorageEmulated()) { 10983 mounted = true; 10984 } else { 10985 final String status = Environment.getExternalStorageState(); 10986 10987 mounted = status.equals(Environment.MEDIA_MOUNTED) 10988 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 10989 } 10990 10991 if (!mounted) { 10992 return; 10993 } 10994 10995 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 10996 int[] users; 10997 if (userId == UserHandle.USER_ALL) { 10998 users = sUserManager.getUserIds(); 10999 } else { 11000 users = new int[] { userId }; 11001 } 11002 final ClearStorageConnection conn = new ClearStorageConnection(); 11003 if (mContext.bindServiceAsUser( 11004 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 11005 try { 11006 for (int curUser : users) { 11007 long timeout = SystemClock.uptimeMillis() + 5000; 11008 synchronized (conn) { 11009 long now = SystemClock.uptimeMillis(); 11010 while (conn.mContainerService == null && now < timeout) { 11011 try { 11012 conn.wait(timeout - now); 11013 } catch (InterruptedException e) { 11014 } 11015 } 11016 } 11017 if (conn.mContainerService == null) { 11018 return; 11019 } 11020 11021 final UserEnvironment userEnv = new UserEnvironment(curUser); 11022 clearDirectory(conn.mContainerService, 11023 userEnv.buildExternalStorageAppCacheDirs(packageName)); 11024 if (allData) { 11025 clearDirectory(conn.mContainerService, 11026 userEnv.buildExternalStorageAppDataDirs(packageName)); 11027 clearDirectory(conn.mContainerService, 11028 userEnv.buildExternalStorageAppMediaDirs(packageName)); 11029 } 11030 } 11031 } finally { 11032 mContext.unbindService(conn); 11033 } 11034 } 11035 } 11036 11037 @Override 11038 public void clearApplicationUserData(final String packageName, 11039 final IPackageDataObserver observer, final int userId) { 11040 mContext.enforceCallingOrSelfPermission( 11041 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 11042 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data"); 11043 // Queue up an async operation since the package deletion may take a little while. 11044 mHandler.post(new Runnable() { 11045 public void run() { 11046 mHandler.removeCallbacks(this); 11047 final boolean succeeded; 11048 synchronized (mInstallLock) { 11049 succeeded = clearApplicationUserDataLI(packageName, userId); 11050 } 11051 clearExternalStorageDataSync(packageName, userId, true); 11052 if (succeeded) { 11053 // invoke DeviceStorageMonitor's update method to clear any notifications 11054 DeviceStorageMonitorInternal 11055 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 11056 if (dsm != null) { 11057 dsm.checkMemory(); 11058 } 11059 } 11060 if(observer != null) { 11061 try { 11062 observer.onRemoveCompleted(packageName, succeeded); 11063 } catch (RemoteException e) { 11064 Log.i(TAG, "Observer no longer exists."); 11065 } 11066 } //end if observer 11067 } //end run 11068 }); 11069 } 11070 11071 private boolean clearApplicationUserDataLI(String packageName, int userId) { 11072 if (packageName == null) { 11073 Slog.w(TAG, "Attempt to delete null packageName."); 11074 return false; 11075 } 11076 PackageParser.Package pkg; 11077 boolean dataOnly = false; 11078 final int appId; 11079 synchronized (mPackages) { 11080 pkg = mPackages.get(packageName); 11081 if (pkg == null) { 11082 dataOnly = true; 11083 PackageSetting ps = mSettings.mPackages.get(packageName); 11084 if ((ps == null) || (ps.pkg == null)) { 11085 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11086 return false; 11087 } 11088 pkg = ps.pkg; 11089 } 11090 if (!dataOnly) { 11091 // need to check this only for fully installed applications 11092 if (pkg == null) { 11093 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11094 return false; 11095 } 11096 final ApplicationInfo applicationInfo = pkg.applicationInfo; 11097 if (applicationInfo == null) { 11098 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11099 return false; 11100 } 11101 } 11102 if (pkg != null && pkg.applicationInfo != null) { 11103 appId = pkg.applicationInfo.uid; 11104 } else { 11105 appId = -1; 11106 } 11107 } 11108 int retCode = mInstaller.clearUserData(packageName, userId); 11109 if (retCode < 0) { 11110 Slog.w(TAG, "Couldn't remove cache files for package: " 11111 + packageName); 11112 return false; 11113 } 11114 removeKeystoreDataIfNeeded(userId, appId); 11115 11116 // Create a native library symlink only if we have native libraries 11117 // and if the native libraries are 32 bit libraries. We do not provide 11118 // this symlink for 64 bit libraries. 11119 if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null && 11120 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 11121 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 11122 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 11123 Slog.w(TAG, "Failed linking native library dir"); 11124 return false; 11125 } 11126 } 11127 11128 return true; 11129 } 11130 11131 /** 11132 * Remove entries from the keystore daemon. Will only remove it if the 11133 * {@code appId} is valid. 11134 */ 11135 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 11136 if (appId < 0) { 11137 return; 11138 } 11139 11140 final KeyStore keyStore = KeyStore.getInstance(); 11141 if (keyStore != null) { 11142 if (userId == UserHandle.USER_ALL) { 11143 for (final int individual : sUserManager.getUserIds()) { 11144 keyStore.clearUid(UserHandle.getUid(individual, appId)); 11145 } 11146 } else { 11147 keyStore.clearUid(UserHandle.getUid(userId, appId)); 11148 } 11149 } else { 11150 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 11151 } 11152 } 11153 11154 @Override 11155 public void deleteApplicationCacheFiles(final String packageName, 11156 final IPackageDataObserver observer) { 11157 mContext.enforceCallingOrSelfPermission( 11158 android.Manifest.permission.DELETE_CACHE_FILES, null); 11159 // Queue up an async operation since the package deletion may take a little while. 11160 final int userId = UserHandle.getCallingUserId(); 11161 mHandler.post(new Runnable() { 11162 public void run() { 11163 mHandler.removeCallbacks(this); 11164 final boolean succeded; 11165 synchronized (mInstallLock) { 11166 succeded = deleteApplicationCacheFilesLI(packageName, userId); 11167 } 11168 clearExternalStorageDataSync(packageName, userId, false); 11169 if(observer != null) { 11170 try { 11171 observer.onRemoveCompleted(packageName, succeded); 11172 } catch (RemoteException e) { 11173 Log.i(TAG, "Observer no longer exists."); 11174 } 11175 } //end if observer 11176 } //end run 11177 }); 11178 } 11179 11180 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 11181 if (packageName == null) { 11182 Slog.w(TAG, "Attempt to delete null packageName."); 11183 return false; 11184 } 11185 PackageParser.Package p; 11186 synchronized (mPackages) { 11187 p = mPackages.get(packageName); 11188 } 11189 if (p == null) { 11190 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11191 return false; 11192 } 11193 final ApplicationInfo applicationInfo = p.applicationInfo; 11194 if (applicationInfo == null) { 11195 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11196 return false; 11197 } 11198 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 11199 if (retCode < 0) { 11200 Slog.w(TAG, "Couldn't remove cache files for package: " 11201 + packageName + " u" + userId); 11202 return false; 11203 } 11204 return true; 11205 } 11206 11207 @Override 11208 public void getPackageSizeInfo(final String packageName, int userHandle, 11209 final IPackageStatsObserver observer) { 11210 mContext.enforceCallingOrSelfPermission( 11211 android.Manifest.permission.GET_PACKAGE_SIZE, null); 11212 if (packageName == null) { 11213 throw new IllegalArgumentException("Attempt to get size of null packageName"); 11214 } 11215 11216 PackageStats stats = new PackageStats(packageName, userHandle); 11217 11218 /* 11219 * Queue up an async operation since the package measurement may take a 11220 * little while. 11221 */ 11222 Message msg = mHandler.obtainMessage(INIT_COPY); 11223 msg.obj = new MeasureParams(stats, observer); 11224 mHandler.sendMessage(msg); 11225 } 11226 11227 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 11228 PackageStats pStats) { 11229 if (packageName == null) { 11230 Slog.w(TAG, "Attempt to get size of null packageName."); 11231 return false; 11232 } 11233 PackageParser.Package p; 11234 boolean dataOnly = false; 11235 String libDirRoot = null; 11236 String asecPath = null; 11237 PackageSetting ps = null; 11238 synchronized (mPackages) { 11239 p = mPackages.get(packageName); 11240 ps = mSettings.mPackages.get(packageName); 11241 if(p == null) { 11242 dataOnly = true; 11243 if((ps == null) || (ps.pkg == null)) { 11244 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11245 return false; 11246 } 11247 p = ps.pkg; 11248 } 11249 if (ps != null) { 11250 libDirRoot = ps.legacyNativeLibraryPathString; 11251 } 11252 if (p != null && (isExternal(p) || isForwardLocked(p))) { 11253 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 11254 if (secureContainerId != null) { 11255 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 11256 } 11257 } 11258 } 11259 String publicSrcDir = null; 11260 if(!dataOnly) { 11261 final ApplicationInfo applicationInfo = p.applicationInfo; 11262 if (applicationInfo == null) { 11263 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11264 return false; 11265 } 11266 if (isForwardLocked(p)) { 11267 publicSrcDir = applicationInfo.getBaseResourcePath(); 11268 } 11269 } 11270 // TODO: extend to measure size of split APKs 11271 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 11272 // not just the first level. 11273 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 11274 // just the primary. 11275 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 11276 int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot, 11277 publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 11278 if (res < 0) { 11279 return false; 11280 } 11281 11282 // Fix-up for forward-locked applications in ASEC containers. 11283 if (!isExternal(p)) { 11284 pStats.codeSize += pStats.externalCodeSize; 11285 pStats.externalCodeSize = 0L; 11286 } 11287 11288 return true; 11289 } 11290 11291 11292 @Override 11293 public void addPackageToPreferred(String packageName) { 11294 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 11295 } 11296 11297 @Override 11298 public void removePackageFromPreferred(String packageName) { 11299 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 11300 } 11301 11302 @Override 11303 public List<PackageInfo> getPreferredPackages(int flags) { 11304 return new ArrayList<PackageInfo>(); 11305 } 11306 11307 private int getUidTargetSdkVersionLockedLPr(int uid) { 11308 Object obj = mSettings.getUserIdLPr(uid); 11309 if (obj instanceof SharedUserSetting) { 11310 final SharedUserSetting sus = (SharedUserSetting) obj; 11311 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 11312 final Iterator<PackageSetting> it = sus.packages.iterator(); 11313 while (it.hasNext()) { 11314 final PackageSetting ps = it.next(); 11315 if (ps.pkg != null) { 11316 int v = ps.pkg.applicationInfo.targetSdkVersion; 11317 if (v < vers) vers = v; 11318 } 11319 } 11320 return vers; 11321 } else if (obj instanceof PackageSetting) { 11322 final PackageSetting ps = (PackageSetting) obj; 11323 if (ps.pkg != null) { 11324 return ps.pkg.applicationInfo.targetSdkVersion; 11325 } 11326 } 11327 return Build.VERSION_CODES.CUR_DEVELOPMENT; 11328 } 11329 11330 @Override 11331 public void addPreferredActivity(IntentFilter filter, int match, 11332 ComponentName[] set, ComponentName activity, int userId) { 11333 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11334 "Adding preferred"); 11335 } 11336 11337 private void addPreferredActivityInternal(IntentFilter filter, int match, 11338 ComponentName[] set, ComponentName activity, boolean always, int userId, 11339 String opname) { 11340 // writer 11341 int callingUid = Binder.getCallingUid(); 11342 enforceCrossUserPermission(callingUid, userId, true, "add preferred activity"); 11343 if (filter.countActions() == 0) { 11344 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11345 return; 11346 } 11347 synchronized (mPackages) { 11348 if (mContext.checkCallingOrSelfPermission( 11349 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11350 != PackageManager.PERMISSION_GRANTED) { 11351 if (getUidTargetSdkVersionLockedLPr(callingUid) 11352 < Build.VERSION_CODES.FROYO) { 11353 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 11354 + callingUid); 11355 return; 11356 } 11357 mContext.enforceCallingOrSelfPermission( 11358 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11359 } 11360 11361 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 11362 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 11363 + userId + ":"); 11364 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11365 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 11366 mSettings.writePackageRestrictionsLPr(userId); 11367 } 11368 } 11369 11370 @Override 11371 public void replacePreferredActivity(IntentFilter filter, int match, 11372 ComponentName[] set, ComponentName activity, int userId) { 11373 if (filter.countActions() != 1) { 11374 throw new IllegalArgumentException( 11375 "replacePreferredActivity expects filter to have only 1 action."); 11376 } 11377 if (filter.countDataAuthorities() != 0 11378 || filter.countDataPaths() != 0 11379 || filter.countDataSchemes() > 1 11380 || filter.countDataTypes() != 0) { 11381 throw new IllegalArgumentException( 11382 "replacePreferredActivity expects filter to have no data authorities, " + 11383 "paths, or types; and at most one scheme."); 11384 } 11385 11386 final int callingUid = Binder.getCallingUid(); 11387 enforceCrossUserPermission(callingUid, userId, true, "replace preferred activity"); 11388 synchronized (mPackages) { 11389 if (mContext.checkCallingOrSelfPermission( 11390 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11391 != PackageManager.PERMISSION_GRANTED) { 11392 if (getUidTargetSdkVersionLockedLPr(callingUid) 11393 < Build.VERSION_CODES.FROYO) { 11394 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 11395 + Binder.getCallingUid()); 11396 return; 11397 } 11398 mContext.enforceCallingOrSelfPermission( 11399 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11400 } 11401 11402 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11403 if (pir != null) { 11404 // Get all of the existing entries that exactly match this filter. 11405 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 11406 if (existing != null && existing.size() == 1) { 11407 PreferredActivity cur = existing.get(0); 11408 if (DEBUG_PREFERRED) { 11409 Slog.i(TAG, "Checking replace of preferred:"); 11410 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11411 if (!cur.mPref.mAlways) { 11412 Slog.i(TAG, " -- CUR; not mAlways!"); 11413 } else { 11414 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 11415 Slog.i(TAG, " -- CUR: mSet=" 11416 + Arrays.toString(cur.mPref.mSetComponents)); 11417 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 11418 Slog.i(TAG, " -- NEW: mMatch=" 11419 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 11420 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 11421 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 11422 } 11423 } 11424 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 11425 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 11426 && cur.mPref.sameSet(set)) { 11427 if (DEBUG_PREFERRED) { 11428 Slog.i(TAG, "Replacing with same preferred activity " 11429 + cur.mPref.mShortComponent + " for user " 11430 + userId + ":"); 11431 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11432 } else { 11433 Slog.i(TAG, "Replacing with same preferred activity " 11434 + cur.mPref.mShortComponent + " for user " 11435 + userId); 11436 } 11437 return; 11438 } 11439 } 11440 11441 if (existing != null) { 11442 if (DEBUG_PREFERRED) { 11443 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 11444 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11445 } 11446 for (int i = 0; i < existing.size(); i++) { 11447 PreferredActivity pa = existing.get(i); 11448 if (DEBUG_PREFERRED) { 11449 Slog.i(TAG, "Removing existing preferred activity " 11450 + pa.mPref.mComponent + ":"); 11451 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 11452 } 11453 pir.removeFilter(pa); 11454 } 11455 } 11456 } 11457 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11458 "Replacing preferred"); 11459 } 11460 } 11461 11462 @Override 11463 public void clearPackagePreferredActivities(String packageName) { 11464 final int uid = Binder.getCallingUid(); 11465 // writer 11466 synchronized (mPackages) { 11467 PackageParser.Package pkg = mPackages.get(packageName); 11468 if (pkg == null || pkg.applicationInfo.uid != uid) { 11469 if (mContext.checkCallingOrSelfPermission( 11470 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11471 != PackageManager.PERMISSION_GRANTED) { 11472 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11473 < Build.VERSION_CODES.FROYO) { 11474 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 11475 + Binder.getCallingUid()); 11476 return; 11477 } 11478 mContext.enforceCallingOrSelfPermission( 11479 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11480 } 11481 } 11482 11483 int user = UserHandle.getCallingUserId(); 11484 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 11485 mSettings.writePackageRestrictionsLPr(user); 11486 scheduleWriteSettingsLocked(); 11487 } 11488 } 11489 } 11490 11491 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 11492 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 11493 ArrayList<PreferredActivity> removed = null; 11494 boolean changed = false; 11495 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11496 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 11497 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11498 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 11499 continue; 11500 } 11501 Iterator<PreferredActivity> it = pir.filterIterator(); 11502 while (it.hasNext()) { 11503 PreferredActivity pa = it.next(); 11504 // Mark entry for removal only if it matches the package name 11505 // and the entry is of type "always". 11506 if (packageName == null || 11507 (pa.mPref.mComponent.getPackageName().equals(packageName) 11508 && pa.mPref.mAlways)) { 11509 if (removed == null) { 11510 removed = new ArrayList<PreferredActivity>(); 11511 } 11512 removed.add(pa); 11513 } 11514 } 11515 if (removed != null) { 11516 for (int j=0; j<removed.size(); j++) { 11517 PreferredActivity pa = removed.get(j); 11518 pir.removeFilter(pa); 11519 } 11520 changed = true; 11521 } 11522 } 11523 return changed; 11524 } 11525 11526 @Override 11527 public void resetPreferredActivities(int userId) { 11528 mContext.enforceCallingOrSelfPermission( 11529 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11530 // writer 11531 synchronized (mPackages) { 11532 int user = UserHandle.getCallingUserId(); 11533 clearPackagePreferredActivitiesLPw(null, user); 11534 mSettings.readDefaultPreferredAppsLPw(this, user); 11535 mSettings.writePackageRestrictionsLPr(user); 11536 scheduleWriteSettingsLocked(); 11537 } 11538 } 11539 11540 @Override 11541 public int getPreferredActivities(List<IntentFilter> outFilters, 11542 List<ComponentName> outActivities, String packageName) { 11543 11544 int num = 0; 11545 final int userId = UserHandle.getCallingUserId(); 11546 // reader 11547 synchronized (mPackages) { 11548 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11549 if (pir != null) { 11550 final Iterator<PreferredActivity> it = pir.filterIterator(); 11551 while (it.hasNext()) { 11552 final PreferredActivity pa = it.next(); 11553 if (packageName == null 11554 || (pa.mPref.mComponent.getPackageName().equals(packageName) 11555 && pa.mPref.mAlways)) { 11556 if (outFilters != null) { 11557 outFilters.add(new IntentFilter(pa)); 11558 } 11559 if (outActivities != null) { 11560 outActivities.add(pa.mPref.mComponent); 11561 } 11562 } 11563 } 11564 } 11565 } 11566 11567 return num; 11568 } 11569 11570 @Override 11571 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 11572 int userId) { 11573 int callingUid = Binder.getCallingUid(); 11574 if (callingUid != Process.SYSTEM_UID) { 11575 throw new SecurityException( 11576 "addPersistentPreferredActivity can only be run by the system"); 11577 } 11578 if (filter.countActions() == 0) { 11579 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11580 return; 11581 } 11582 synchronized (mPackages) { 11583 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 11584 " :"); 11585 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11586 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 11587 new PersistentPreferredActivity(filter, activity)); 11588 mSettings.writePackageRestrictionsLPr(userId); 11589 } 11590 } 11591 11592 @Override 11593 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 11594 int callingUid = Binder.getCallingUid(); 11595 if (callingUid != Process.SYSTEM_UID) { 11596 throw new SecurityException( 11597 "clearPackagePersistentPreferredActivities can only be run by the system"); 11598 } 11599 ArrayList<PersistentPreferredActivity> removed = null; 11600 boolean changed = false; 11601 synchronized (mPackages) { 11602 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 11603 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 11604 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 11605 .valueAt(i); 11606 if (userId != thisUserId) { 11607 continue; 11608 } 11609 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 11610 while (it.hasNext()) { 11611 PersistentPreferredActivity ppa = it.next(); 11612 // Mark entry for removal only if it matches the package name. 11613 if (ppa.mComponent.getPackageName().equals(packageName)) { 11614 if (removed == null) { 11615 removed = new ArrayList<PersistentPreferredActivity>(); 11616 } 11617 removed.add(ppa); 11618 } 11619 } 11620 if (removed != null) { 11621 for (int j=0; j<removed.size(); j++) { 11622 PersistentPreferredActivity ppa = removed.get(j); 11623 ppir.removeFilter(ppa); 11624 } 11625 changed = true; 11626 } 11627 } 11628 11629 if (changed) { 11630 mSettings.writePackageRestrictionsLPr(userId); 11631 } 11632 } 11633 } 11634 11635 @Override 11636 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 11637 int ownerUserId, int sourceUserId, int targetUserId, int flags) { 11638 mContext.enforceCallingOrSelfPermission( 11639 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11640 int callingUid = Binder.getCallingUid(); 11641 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11642 if (intentFilter.countActions() == 0) { 11643 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 11644 return; 11645 } 11646 synchronized (mPackages) { 11647 CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter, 11648 ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags); 11649 mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter); 11650 mSettings.writePackageRestrictionsLPr(sourceUserId); 11651 } 11652 } 11653 11654 @Override 11655 public void addCrossProfileIntentsForPackage(String packageName, 11656 int sourceUserId, int targetUserId) { 11657 mContext.enforceCallingOrSelfPermission( 11658 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11659 mSettings.addCrossProfilePackage(packageName, sourceUserId, targetUserId); 11660 mSettings.writePackageRestrictionsLPr(sourceUserId); 11661 } 11662 11663 @Override 11664 public void removeCrossProfileIntentsForPackage(String packageName, 11665 int sourceUserId, int targetUserId) { 11666 mContext.enforceCallingOrSelfPermission( 11667 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11668 mSettings.removeCrossProfilePackage(packageName, sourceUserId, targetUserId); 11669 mSettings.writePackageRestrictionsLPr(sourceUserId); 11670 } 11671 11672 @Override 11673 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage, 11674 int ownerUserId) { 11675 mContext.enforceCallingOrSelfPermission( 11676 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11677 int callingUid = Binder.getCallingUid(); 11678 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11679 int callingUserId = UserHandle.getUserId(callingUid); 11680 synchronized (mPackages) { 11681 CrossProfileIntentResolver resolver = 11682 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11683 HashSet<CrossProfileIntentFilter> set = 11684 new HashSet<CrossProfileIntentFilter>(resolver.filterSet()); 11685 for (CrossProfileIntentFilter filter : set) { 11686 if (filter.getOwnerPackage().equals(ownerPackage) 11687 && filter.getOwnerUserId() == callingUserId) { 11688 resolver.removeFilter(filter); 11689 } 11690 } 11691 mSettings.writePackageRestrictionsLPr(sourceUserId); 11692 } 11693 } 11694 11695 // Enforcing that callingUid is owning pkg on userId 11696 private void enforceOwnerRights(String pkg, int userId, int callingUid) { 11697 // The system owns everything. 11698 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 11699 return; 11700 } 11701 int callingUserId = UserHandle.getUserId(callingUid); 11702 if (callingUserId != userId) { 11703 throw new SecurityException("calling uid " + callingUid 11704 + " pretends to own " + pkg + " on user " + userId + " but belongs to user " 11705 + callingUserId); 11706 } 11707 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 11708 if (pi == null) { 11709 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 11710 + callingUserId); 11711 } 11712 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 11713 throw new SecurityException("Calling uid " + callingUid 11714 + " does not own package " + pkg); 11715 } 11716 } 11717 11718 @Override 11719 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 11720 Intent intent = new Intent(Intent.ACTION_MAIN); 11721 intent.addCategory(Intent.CATEGORY_HOME); 11722 11723 final int callingUserId = UserHandle.getCallingUserId(); 11724 List<ResolveInfo> list = queryIntentActivities(intent, null, 11725 PackageManager.GET_META_DATA, callingUserId); 11726 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 11727 true, false, false, callingUserId); 11728 11729 allHomeCandidates.clear(); 11730 if (list != null) { 11731 for (ResolveInfo ri : list) { 11732 allHomeCandidates.add(ri); 11733 } 11734 } 11735 return (preferred == null || preferred.activityInfo == null) 11736 ? null 11737 : new ComponentName(preferred.activityInfo.packageName, 11738 preferred.activityInfo.name); 11739 } 11740 11741 /** 11742 * Check if calling UID is the current home app. This handles both the case 11743 * where the user has selected a specific home app, and where there is only 11744 * one home app. 11745 */ 11746 public boolean checkCallerIsHomeApp() { 11747 final Intent intent = new Intent(Intent.ACTION_MAIN); 11748 intent.addCategory(Intent.CATEGORY_HOME); 11749 11750 final int callingUid = Binder.getCallingUid(); 11751 final int callingUserId = UserHandle.getCallingUserId(); 11752 final List<ResolveInfo> allHomes = queryIntentActivities(intent, null, 0, callingUserId); 11753 final ResolveInfo preferredHome = findPreferredActivity(intent, null, 0, allHomes, 0, true, 11754 false, false, callingUserId); 11755 11756 if (preferredHome != null) { 11757 if (callingUid == preferredHome.activityInfo.applicationInfo.uid) { 11758 return true; 11759 } 11760 } else { 11761 for (ResolveInfo info : allHomes) { 11762 if (callingUid == info.activityInfo.applicationInfo.uid) { 11763 return true; 11764 } 11765 } 11766 } 11767 11768 return false; 11769 } 11770 11771 /** 11772 * Enforce that calling UID is the current home app. This handles both the 11773 * case where the user has selected a specific home app, and where there is 11774 * only one home app. 11775 */ 11776 public void enforceCallerIsHomeApp() { 11777 if (!checkCallerIsHomeApp()) { 11778 throw new SecurityException("Caller is not currently selected home app"); 11779 } 11780 } 11781 11782 @Override 11783 public void setApplicationEnabledSetting(String appPackageName, 11784 int newState, int flags, int userId, String callingPackage) { 11785 if (!sUserManager.exists(userId)) return; 11786 if (callingPackage == null) { 11787 callingPackage = Integer.toString(Binder.getCallingUid()); 11788 } 11789 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 11790 } 11791 11792 @Override 11793 public void setComponentEnabledSetting(ComponentName componentName, 11794 int newState, int flags, int userId) { 11795 if (!sUserManager.exists(userId)) return; 11796 setEnabledSetting(componentName.getPackageName(), 11797 componentName.getClassName(), newState, flags, userId, null); 11798 } 11799 11800 private void setEnabledSetting(final String packageName, String className, int newState, 11801 final int flags, int userId, String callingPackage) { 11802 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 11803 || newState == COMPONENT_ENABLED_STATE_ENABLED 11804 || newState == COMPONENT_ENABLED_STATE_DISABLED 11805 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 11806 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 11807 throw new IllegalArgumentException("Invalid new component state: " 11808 + newState); 11809 } 11810 PackageSetting pkgSetting; 11811 final int uid = Binder.getCallingUid(); 11812 final int permission = mContext.checkCallingOrSelfPermission( 11813 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11814 enforceCrossUserPermission(uid, userId, false, "set enabled"); 11815 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11816 boolean sendNow = false; 11817 boolean isApp = (className == null); 11818 String componentName = isApp ? packageName : className; 11819 int packageUid = -1; 11820 ArrayList<String> components; 11821 11822 // writer 11823 synchronized (mPackages) { 11824 pkgSetting = mSettings.mPackages.get(packageName); 11825 if (pkgSetting == null) { 11826 if (className == null) { 11827 throw new IllegalArgumentException( 11828 "Unknown package: " + packageName); 11829 } 11830 throw new IllegalArgumentException( 11831 "Unknown component: " + packageName 11832 + "/" + className); 11833 } 11834 // Allow root and verify that userId is not being specified by a different user 11835 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 11836 throw new SecurityException( 11837 "Permission Denial: attempt to change component state from pid=" 11838 + Binder.getCallingPid() 11839 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 11840 } 11841 if (className == null) { 11842 // We're dealing with an application/package level state change 11843 if (pkgSetting.getEnabled(userId) == newState) { 11844 // Nothing to do 11845 return; 11846 } 11847 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 11848 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 11849 // Don't care about who enables an app. 11850 callingPackage = null; 11851 } 11852 pkgSetting.setEnabled(newState, userId, callingPackage); 11853 // pkgSetting.pkg.mSetEnabled = newState; 11854 } else { 11855 // We're dealing with a component level state change 11856 // First, verify that this is a valid class name. 11857 PackageParser.Package pkg = pkgSetting.pkg; 11858 if (pkg == null || !pkg.hasComponentClassName(className)) { 11859 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 11860 throw new IllegalArgumentException("Component class " + className 11861 + " does not exist in " + packageName); 11862 } else { 11863 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 11864 + className + " does not exist in " + packageName); 11865 } 11866 } 11867 switch (newState) { 11868 case COMPONENT_ENABLED_STATE_ENABLED: 11869 if (!pkgSetting.enableComponentLPw(className, userId)) { 11870 return; 11871 } 11872 break; 11873 case COMPONENT_ENABLED_STATE_DISABLED: 11874 if (!pkgSetting.disableComponentLPw(className, userId)) { 11875 return; 11876 } 11877 break; 11878 case COMPONENT_ENABLED_STATE_DEFAULT: 11879 if (!pkgSetting.restoreComponentLPw(className, userId)) { 11880 return; 11881 } 11882 break; 11883 default: 11884 Slog.e(TAG, "Invalid new component state: " + newState); 11885 return; 11886 } 11887 } 11888 mSettings.writePackageRestrictionsLPr(userId); 11889 components = mPendingBroadcasts.get(userId, packageName); 11890 final boolean newPackage = components == null; 11891 if (newPackage) { 11892 components = new ArrayList<String>(); 11893 } 11894 if (!components.contains(componentName)) { 11895 components.add(componentName); 11896 } 11897 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 11898 sendNow = true; 11899 // Purge entry from pending broadcast list if another one exists already 11900 // since we are sending one right away. 11901 mPendingBroadcasts.remove(userId, packageName); 11902 } else { 11903 if (newPackage) { 11904 mPendingBroadcasts.put(userId, packageName, components); 11905 } 11906 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 11907 // Schedule a message 11908 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 11909 } 11910 } 11911 } 11912 11913 long callingId = Binder.clearCallingIdentity(); 11914 try { 11915 if (sendNow) { 11916 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 11917 sendPackageChangedBroadcast(packageName, 11918 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 11919 } 11920 } finally { 11921 Binder.restoreCallingIdentity(callingId); 11922 } 11923 } 11924 11925 private void sendPackageChangedBroadcast(String packageName, 11926 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 11927 if (DEBUG_INSTALL) 11928 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 11929 + componentNames); 11930 Bundle extras = new Bundle(4); 11931 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 11932 String nameList[] = new String[componentNames.size()]; 11933 componentNames.toArray(nameList); 11934 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 11935 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 11936 extras.putInt(Intent.EXTRA_UID, packageUid); 11937 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 11938 new int[] {UserHandle.getUserId(packageUid)}); 11939 } 11940 11941 @Override 11942 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 11943 if (!sUserManager.exists(userId)) return; 11944 final int uid = Binder.getCallingUid(); 11945 final int permission = mContext.checkCallingOrSelfPermission( 11946 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11947 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11948 enforceCrossUserPermission(uid, userId, true, "stop package"); 11949 // writer 11950 synchronized (mPackages) { 11951 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 11952 uid, userId)) { 11953 scheduleWritePackageRestrictionsLocked(userId); 11954 } 11955 } 11956 } 11957 11958 @Override 11959 public String getInstallerPackageName(String packageName) { 11960 // reader 11961 synchronized (mPackages) { 11962 return mSettings.getInstallerPackageNameLPr(packageName); 11963 } 11964 } 11965 11966 @Override 11967 public int getApplicationEnabledSetting(String packageName, int userId) { 11968 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11969 int uid = Binder.getCallingUid(); 11970 enforceCrossUserPermission(uid, userId, false, "get enabled"); 11971 // reader 11972 synchronized (mPackages) { 11973 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 11974 } 11975 } 11976 11977 @Override 11978 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 11979 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11980 int uid = Binder.getCallingUid(); 11981 enforceCrossUserPermission(uid, userId, false, "get component enabled"); 11982 // reader 11983 synchronized (mPackages) { 11984 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 11985 } 11986 } 11987 11988 @Override 11989 public void enterSafeMode() { 11990 enforceSystemOrRoot("Only the system can request entering safe mode"); 11991 11992 if (!mSystemReady) { 11993 mSafeMode = true; 11994 } 11995 } 11996 11997 @Override 11998 public void systemReady() { 11999 mSystemReady = true; 12000 12001 // Read the compatibilty setting when the system is ready. 12002 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 12003 mContext.getContentResolver(), 12004 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 12005 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 12006 if (DEBUG_SETTINGS) { 12007 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 12008 } 12009 12010 synchronized (mPackages) { 12011 // Verify that all of the preferred activity components actually 12012 // exist. It is possible for applications to be updated and at 12013 // that point remove a previously declared activity component that 12014 // had been set as a preferred activity. We try to clean this up 12015 // the next time we encounter that preferred activity, but it is 12016 // possible for the user flow to never be able to return to that 12017 // situation so here we do a sanity check to make sure we haven't 12018 // left any junk around. 12019 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 12020 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12021 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12022 removed.clear(); 12023 for (PreferredActivity pa : pir.filterSet()) { 12024 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 12025 removed.add(pa); 12026 } 12027 } 12028 if (removed.size() > 0) { 12029 for (int r=0; r<removed.size(); r++) { 12030 PreferredActivity pa = removed.get(r); 12031 Slog.w(TAG, "Removing dangling preferred activity: " 12032 + pa.mPref.mComponent); 12033 pir.removeFilter(pa); 12034 } 12035 mSettings.writePackageRestrictionsLPr( 12036 mSettings.mPreferredActivities.keyAt(i)); 12037 } 12038 } 12039 } 12040 sUserManager.systemReady(); 12041 } 12042 12043 @Override 12044 public boolean isSafeMode() { 12045 return mSafeMode; 12046 } 12047 12048 @Override 12049 public boolean hasSystemUidErrors() { 12050 return mHasSystemUidErrors; 12051 } 12052 12053 static String arrayToString(int[] array) { 12054 StringBuffer buf = new StringBuffer(128); 12055 buf.append('['); 12056 if (array != null) { 12057 for (int i=0; i<array.length; i++) { 12058 if (i > 0) buf.append(", "); 12059 buf.append(array[i]); 12060 } 12061 } 12062 buf.append(']'); 12063 return buf.toString(); 12064 } 12065 12066 static class DumpState { 12067 public static final int DUMP_LIBS = 1 << 0; 12068 public static final int DUMP_FEATURES = 1 << 1; 12069 public static final int DUMP_RESOLVERS = 1 << 2; 12070 public static final int DUMP_PERMISSIONS = 1 << 3; 12071 public static final int DUMP_PACKAGES = 1 << 4; 12072 public static final int DUMP_SHARED_USERS = 1 << 5; 12073 public static final int DUMP_MESSAGES = 1 << 6; 12074 public static final int DUMP_PROVIDERS = 1 << 7; 12075 public static final int DUMP_VERIFIERS = 1 << 8; 12076 public static final int DUMP_PREFERRED = 1 << 9; 12077 public static final int DUMP_PREFERRED_XML = 1 << 10; 12078 public static final int DUMP_KEYSETS = 1 << 11; 12079 public static final int DUMP_VERSION = 1 << 12; 12080 public static final int DUMP_INSTALLS = 1 << 13; 12081 12082 public static final int OPTION_SHOW_FILTERS = 1 << 0; 12083 12084 private int mTypes; 12085 12086 private int mOptions; 12087 12088 private boolean mTitlePrinted; 12089 12090 private SharedUserSetting mSharedUser; 12091 12092 public boolean isDumping(int type) { 12093 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 12094 return true; 12095 } 12096 12097 return (mTypes & type) != 0; 12098 } 12099 12100 public void setDump(int type) { 12101 mTypes |= type; 12102 } 12103 12104 public boolean isOptionEnabled(int option) { 12105 return (mOptions & option) != 0; 12106 } 12107 12108 public void setOptionEnabled(int option) { 12109 mOptions |= option; 12110 } 12111 12112 public boolean onTitlePrinted() { 12113 final boolean printed = mTitlePrinted; 12114 mTitlePrinted = true; 12115 return printed; 12116 } 12117 12118 public boolean getTitlePrinted() { 12119 return mTitlePrinted; 12120 } 12121 12122 public void setTitlePrinted(boolean enabled) { 12123 mTitlePrinted = enabled; 12124 } 12125 12126 public SharedUserSetting getSharedUser() { 12127 return mSharedUser; 12128 } 12129 12130 public void setSharedUser(SharedUserSetting user) { 12131 mSharedUser = user; 12132 } 12133 } 12134 12135 @Override 12136 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 12137 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 12138 != PackageManager.PERMISSION_GRANTED) { 12139 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 12140 + Binder.getCallingPid() 12141 + ", uid=" + Binder.getCallingUid() 12142 + " without permission " 12143 + android.Manifest.permission.DUMP); 12144 return; 12145 } 12146 12147 DumpState dumpState = new DumpState(); 12148 boolean fullPreferred = false; 12149 boolean checkin = false; 12150 12151 String packageName = null; 12152 12153 int opti = 0; 12154 while (opti < args.length) { 12155 String opt = args[opti]; 12156 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 12157 break; 12158 } 12159 opti++; 12160 if ("-a".equals(opt)) { 12161 // Right now we only know how to print all. 12162 } else if ("-h".equals(opt)) { 12163 pw.println("Package manager dump options:"); 12164 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 12165 pw.println(" --checkin: dump for a checkin"); 12166 pw.println(" -f: print details of intent filters"); 12167 pw.println(" -h: print this help"); 12168 pw.println(" cmd may be one of:"); 12169 pw.println(" l[ibraries]: list known shared libraries"); 12170 pw.println(" f[ibraries]: list device features"); 12171 pw.println(" k[eysets]: print known keysets"); 12172 pw.println(" r[esolvers]: dump intent resolvers"); 12173 pw.println(" perm[issions]: dump permissions"); 12174 pw.println(" pref[erred]: print preferred package settings"); 12175 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 12176 pw.println(" prov[iders]: dump content providers"); 12177 pw.println(" p[ackages]: dump installed packages"); 12178 pw.println(" s[hared-users]: dump shared user IDs"); 12179 pw.println(" m[essages]: print collected runtime messages"); 12180 pw.println(" v[erifiers]: print package verifier info"); 12181 pw.println(" version: print database version info"); 12182 pw.println(" write: write current settings now"); 12183 pw.println(" <package.name>: info about given package"); 12184 pw.println(" installs: details about install sessions"); 12185 return; 12186 } else if ("--checkin".equals(opt)) { 12187 checkin = true; 12188 } else if ("-f".equals(opt)) { 12189 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12190 } else { 12191 pw.println("Unknown argument: " + opt + "; use -h for help"); 12192 } 12193 } 12194 12195 // Is the caller requesting to dump a particular piece of data? 12196 if (opti < args.length) { 12197 String cmd = args[opti]; 12198 opti++; 12199 // Is this a package name? 12200 if ("android".equals(cmd) || cmd.contains(".")) { 12201 packageName = cmd; 12202 // When dumping a single package, we always dump all of its 12203 // filter information since the amount of data will be reasonable. 12204 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12205 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 12206 dumpState.setDump(DumpState.DUMP_LIBS); 12207 } else if ("f".equals(cmd) || "features".equals(cmd)) { 12208 dumpState.setDump(DumpState.DUMP_FEATURES); 12209 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 12210 dumpState.setDump(DumpState.DUMP_RESOLVERS); 12211 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 12212 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 12213 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 12214 dumpState.setDump(DumpState.DUMP_PREFERRED); 12215 } else if ("preferred-xml".equals(cmd)) { 12216 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 12217 if (opti < args.length && "--full".equals(args[opti])) { 12218 fullPreferred = true; 12219 opti++; 12220 } 12221 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 12222 dumpState.setDump(DumpState.DUMP_PACKAGES); 12223 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 12224 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 12225 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 12226 dumpState.setDump(DumpState.DUMP_PROVIDERS); 12227 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 12228 dumpState.setDump(DumpState.DUMP_MESSAGES); 12229 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 12230 dumpState.setDump(DumpState.DUMP_VERIFIERS); 12231 } else if ("version".equals(cmd)) { 12232 dumpState.setDump(DumpState.DUMP_VERSION); 12233 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 12234 dumpState.setDump(DumpState.DUMP_KEYSETS); 12235 } else if ("write".equals(cmd)) { 12236 synchronized (mPackages) { 12237 mSettings.writeLPr(); 12238 pw.println("Settings written."); 12239 return; 12240 } 12241 } else if ("installs".equals(cmd)) { 12242 dumpState.setDump(DumpState.DUMP_INSTALLS); 12243 } 12244 } 12245 12246 if (checkin) { 12247 pw.println("vers,1"); 12248 } 12249 12250 // reader 12251 synchronized (mPackages) { 12252 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 12253 if (!checkin) { 12254 if (dumpState.onTitlePrinted()) 12255 pw.println(); 12256 pw.println("Database versions:"); 12257 pw.print(" SDK Version:"); 12258 pw.print(" internal="); 12259 pw.print(mSettings.mInternalSdkPlatform); 12260 pw.print(" external="); 12261 pw.println(mSettings.mExternalSdkPlatform); 12262 pw.print(" DB Version:"); 12263 pw.print(" internal="); 12264 pw.print(mSettings.mInternalDatabaseVersion); 12265 pw.print(" external="); 12266 pw.println(mSettings.mExternalDatabaseVersion); 12267 } 12268 } 12269 12270 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 12271 if (!checkin) { 12272 if (dumpState.onTitlePrinted()) 12273 pw.println(); 12274 pw.println("Verifiers:"); 12275 pw.print(" Required: "); 12276 pw.print(mRequiredVerifierPackage); 12277 pw.print(" (uid="); 12278 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 12279 pw.println(")"); 12280 } else if (mRequiredVerifierPackage != null) { 12281 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 12282 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 12283 } 12284 } 12285 12286 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 12287 boolean printedHeader = false; 12288 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 12289 while (it.hasNext()) { 12290 String name = it.next(); 12291 SharedLibraryEntry ent = mSharedLibraries.get(name); 12292 if (!checkin) { 12293 if (!printedHeader) { 12294 if (dumpState.onTitlePrinted()) 12295 pw.println(); 12296 pw.println("Libraries:"); 12297 printedHeader = true; 12298 } 12299 pw.print(" "); 12300 } else { 12301 pw.print("lib,"); 12302 } 12303 pw.print(name); 12304 if (!checkin) { 12305 pw.print(" -> "); 12306 } 12307 if (ent.path != null) { 12308 if (!checkin) { 12309 pw.print("(jar) "); 12310 pw.print(ent.path); 12311 } else { 12312 pw.print(",jar,"); 12313 pw.print(ent.path); 12314 } 12315 } else { 12316 if (!checkin) { 12317 pw.print("(apk) "); 12318 pw.print(ent.apk); 12319 } else { 12320 pw.print(",apk,"); 12321 pw.print(ent.apk); 12322 } 12323 } 12324 pw.println(); 12325 } 12326 } 12327 12328 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 12329 if (dumpState.onTitlePrinted()) 12330 pw.println(); 12331 if (!checkin) { 12332 pw.println("Features:"); 12333 } 12334 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 12335 while (it.hasNext()) { 12336 String name = it.next(); 12337 if (!checkin) { 12338 pw.print(" "); 12339 } else { 12340 pw.print("feat,"); 12341 } 12342 pw.println(name); 12343 } 12344 } 12345 12346 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 12347 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 12348 : "Activity Resolver Table:", " ", packageName, 12349 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12350 dumpState.setTitlePrinted(true); 12351 } 12352 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 12353 : "Receiver Resolver Table:", " ", packageName, 12354 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12355 dumpState.setTitlePrinted(true); 12356 } 12357 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 12358 : "Service Resolver Table:", " ", packageName, 12359 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12360 dumpState.setTitlePrinted(true); 12361 } 12362 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 12363 : "Provider Resolver Table:", " ", packageName, 12364 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12365 dumpState.setTitlePrinted(true); 12366 } 12367 } 12368 12369 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 12370 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12371 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12372 int user = mSettings.mPreferredActivities.keyAt(i); 12373 if (pir.dump(pw, 12374 dumpState.getTitlePrinted() 12375 ? "\nPreferred Activities User " + user + ":" 12376 : "Preferred Activities User " + user + ":", " ", 12377 packageName, true)) { 12378 dumpState.setTitlePrinted(true); 12379 } 12380 } 12381 } 12382 12383 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 12384 pw.flush(); 12385 FileOutputStream fout = new FileOutputStream(fd); 12386 BufferedOutputStream str = new BufferedOutputStream(fout); 12387 XmlSerializer serializer = new FastXmlSerializer(); 12388 try { 12389 serializer.setOutput(str, "utf-8"); 12390 serializer.startDocument(null, true); 12391 serializer.setFeature( 12392 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 12393 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 12394 serializer.endDocument(); 12395 serializer.flush(); 12396 } catch (IllegalArgumentException e) { 12397 pw.println("Failed writing: " + e); 12398 } catch (IllegalStateException e) { 12399 pw.println("Failed writing: " + e); 12400 } catch (IOException e) { 12401 pw.println("Failed writing: " + e); 12402 } 12403 } 12404 12405 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 12406 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 12407 if (packageName == null) { 12408 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 12409 if (iperm == 0) { 12410 if (dumpState.onTitlePrinted()) 12411 pw.println(); 12412 pw.println("AppOp Permissions:"); 12413 } 12414 pw.print(" AppOp Permission "); 12415 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 12416 pw.println(":"); 12417 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 12418 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 12419 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 12420 } 12421 } 12422 } 12423 } 12424 12425 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 12426 boolean printedSomething = false; 12427 for (PackageParser.Provider p : mProviders.mProviders.values()) { 12428 if (packageName != null && !packageName.equals(p.info.packageName)) { 12429 continue; 12430 } 12431 if (!printedSomething) { 12432 if (dumpState.onTitlePrinted()) 12433 pw.println(); 12434 pw.println("Registered ContentProviders:"); 12435 printedSomething = true; 12436 } 12437 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 12438 pw.print(" "); pw.println(p.toString()); 12439 } 12440 printedSomething = false; 12441 for (Map.Entry<String, PackageParser.Provider> entry : 12442 mProvidersByAuthority.entrySet()) { 12443 PackageParser.Provider p = entry.getValue(); 12444 if (packageName != null && !packageName.equals(p.info.packageName)) { 12445 continue; 12446 } 12447 if (!printedSomething) { 12448 if (dumpState.onTitlePrinted()) 12449 pw.println(); 12450 pw.println("ContentProvider Authorities:"); 12451 printedSomething = true; 12452 } 12453 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 12454 pw.print(" "); pw.println(p.toString()); 12455 if (p.info != null && p.info.applicationInfo != null) { 12456 final String appInfo = p.info.applicationInfo.toString(); 12457 pw.print(" applicationInfo="); pw.println(appInfo); 12458 } 12459 } 12460 } 12461 12462 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 12463 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 12464 } 12465 12466 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 12467 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 12468 } 12469 12470 if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 12471 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState); 12472 } 12473 12474 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS)) { 12475 if (dumpState.onTitlePrinted()) pw.println(); 12476 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 12477 } 12478 12479 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 12480 if (dumpState.onTitlePrinted()) pw.println(); 12481 mSettings.dumpReadMessagesLPr(pw, dumpState); 12482 12483 pw.println(); 12484 pw.println("Package warning messages:"); 12485 final File fname = getSettingsProblemFile(); 12486 FileInputStream in = null; 12487 try { 12488 in = new FileInputStream(fname); 12489 final int avail = in.available(); 12490 final byte[] data = new byte[avail]; 12491 in.read(data); 12492 pw.print(new String(data)); 12493 } catch (FileNotFoundException e) { 12494 } catch (IOException e) { 12495 } finally { 12496 if (in != null) { 12497 try { 12498 in.close(); 12499 } catch (IOException e) { 12500 } 12501 } 12502 } 12503 } 12504 } 12505 } 12506 12507 // ------- apps on sdcard specific code ------- 12508 static final boolean DEBUG_SD_INSTALL = false; 12509 12510 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 12511 12512 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 12513 12514 private boolean mMediaMounted = false; 12515 12516 static String getEncryptKey() { 12517 try { 12518 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 12519 SD_ENCRYPTION_KEYSTORE_NAME); 12520 if (sdEncKey == null) { 12521 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 12522 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 12523 if (sdEncKey == null) { 12524 Slog.e(TAG, "Failed to create encryption keys"); 12525 return null; 12526 } 12527 } 12528 return sdEncKey; 12529 } catch (NoSuchAlgorithmException nsae) { 12530 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 12531 return null; 12532 } catch (IOException ioe) { 12533 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 12534 return null; 12535 } 12536 } 12537 12538 /* 12539 * Update media status on PackageManager. 12540 */ 12541 @Override 12542 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 12543 int callingUid = Binder.getCallingUid(); 12544 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 12545 throw new SecurityException("Media status can only be updated by the system"); 12546 } 12547 // reader; this apparently protects mMediaMounted, but should probably 12548 // be a different lock in that case. 12549 synchronized (mPackages) { 12550 Log.i(TAG, "Updating external media status from " 12551 + (mMediaMounted ? "mounted" : "unmounted") + " to " 12552 + (mediaStatus ? "mounted" : "unmounted")); 12553 if (DEBUG_SD_INSTALL) 12554 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 12555 + ", mMediaMounted=" + mMediaMounted); 12556 if (mediaStatus == mMediaMounted) { 12557 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 12558 : 0, -1); 12559 mHandler.sendMessage(msg); 12560 return; 12561 } 12562 mMediaMounted = mediaStatus; 12563 } 12564 // Queue up an async operation since the package installation may take a 12565 // little while. 12566 mHandler.post(new Runnable() { 12567 public void run() { 12568 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 12569 } 12570 }); 12571 } 12572 12573 /** 12574 * Called by MountService when the initial ASECs to scan are available. 12575 * Should block until all the ASEC containers are finished being scanned. 12576 */ 12577 public void scanAvailableAsecs() { 12578 updateExternalMediaStatusInner(true, false, false); 12579 if (mShouldRestoreconData) { 12580 SELinuxMMAC.setRestoreconDone(); 12581 mShouldRestoreconData = false; 12582 } 12583 } 12584 12585 /* 12586 * Collect information of applications on external media, map them against 12587 * existing containers and update information based on current mount status. 12588 * Please note that we always have to report status if reportStatus has been 12589 * set to true especially when unloading packages. 12590 */ 12591 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 12592 boolean externalStorage) { 12593 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 12594 int[] uidArr = EmptyArray.INT; 12595 12596 final String[] list = PackageHelper.getSecureContainerList(); 12597 if (ArrayUtils.isEmpty(list)) { 12598 Log.i(TAG, "No secure containers found"); 12599 } else { 12600 // Process list of secure containers and categorize them 12601 // as active or stale based on their package internal state. 12602 12603 // reader 12604 synchronized (mPackages) { 12605 for (String cid : list) { 12606 // Leave stages untouched for now; installer service owns them 12607 if (PackageInstallerService.isStageName(cid)) continue; 12608 12609 if (DEBUG_SD_INSTALL) 12610 Log.i(TAG, "Processing container " + cid); 12611 String pkgName = getAsecPackageName(cid); 12612 if (pkgName == null) { 12613 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 12614 continue; 12615 } 12616 if (DEBUG_SD_INSTALL) 12617 Log.i(TAG, "Looking for pkg : " + pkgName); 12618 12619 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12620 if (ps == null) { 12621 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 12622 continue; 12623 } 12624 12625 /* 12626 * Skip packages that are not external if we're unmounting 12627 * external storage. 12628 */ 12629 if (externalStorage && !isMounted && !isExternal(ps)) { 12630 continue; 12631 } 12632 12633 final AsecInstallArgs args = new AsecInstallArgs(cid, 12634 getAppDexInstructionSets(ps), isForwardLocked(ps)); 12635 // The package status is changed only if the code path 12636 // matches between settings and the container id. 12637 if (ps.codePathString != null 12638 && ps.codePathString.startsWith(args.getCodePath())) { 12639 if (DEBUG_SD_INSTALL) { 12640 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 12641 + " at code path: " + ps.codePathString); 12642 } 12643 12644 // We do have a valid package installed on sdcard 12645 processCids.put(args, ps.codePathString); 12646 final int uid = ps.appId; 12647 if (uid != -1) { 12648 uidArr = ArrayUtils.appendInt(uidArr, uid); 12649 } 12650 } else { 12651 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 12652 + ps.codePathString); 12653 } 12654 } 12655 } 12656 12657 Arrays.sort(uidArr); 12658 } 12659 12660 // Process packages with valid entries. 12661 if (isMounted) { 12662 if (DEBUG_SD_INSTALL) 12663 Log.i(TAG, "Loading packages"); 12664 loadMediaPackages(processCids, uidArr); 12665 startCleaningPackages(); 12666 mInstallerService.onSecureContainersAvailable(); 12667 } else { 12668 if (DEBUG_SD_INSTALL) 12669 Log.i(TAG, "Unloading packages"); 12670 unloadMediaPackages(processCids, uidArr, reportStatus); 12671 } 12672 } 12673 12674 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 12675 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 12676 int size = pkgList.size(); 12677 if (size > 0) { 12678 // Send broadcasts here 12679 Bundle extras = new Bundle(); 12680 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 12681 .toArray(new String[size])); 12682 if (uidArr != null) { 12683 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 12684 } 12685 if (replacing) { 12686 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 12687 } 12688 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 12689 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 12690 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 12691 } 12692 } 12693 12694 /* 12695 * Look at potentially valid container ids from processCids If package 12696 * information doesn't match the one on record or package scanning fails, 12697 * the cid is added to list of removeCids. We currently don't delete stale 12698 * containers. 12699 */ 12700 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 12701 ArrayList<String> pkgList = new ArrayList<String>(); 12702 Set<AsecInstallArgs> keys = processCids.keySet(); 12703 12704 for (AsecInstallArgs args : keys) { 12705 String codePath = processCids.get(args); 12706 if (DEBUG_SD_INSTALL) 12707 Log.i(TAG, "Loading container : " + args.cid); 12708 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12709 try { 12710 // Make sure there are no container errors first. 12711 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 12712 Slog.e(TAG, "Failed to mount cid : " + args.cid 12713 + " when installing from sdcard"); 12714 continue; 12715 } 12716 // Check code path here. 12717 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 12718 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 12719 + " does not match one in settings " + codePath); 12720 continue; 12721 } 12722 // Parse package 12723 int parseFlags = mDefParseFlags; 12724 if (args.isExternal()) { 12725 parseFlags |= PackageParser.PARSE_ON_SDCARD; 12726 } 12727 if (args.isFwdLocked()) { 12728 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 12729 } 12730 12731 synchronized (mInstallLock) { 12732 PackageParser.Package pkg = null; 12733 try { 12734 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 12735 } catch (PackageManagerException e) { 12736 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 12737 } 12738 // Scan the package 12739 if (pkg != null) { 12740 /* 12741 * TODO why is the lock being held? doPostInstall is 12742 * called in other places without the lock. This needs 12743 * to be straightened out. 12744 */ 12745 // writer 12746 synchronized (mPackages) { 12747 retCode = PackageManager.INSTALL_SUCCEEDED; 12748 pkgList.add(pkg.packageName); 12749 // Post process args 12750 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 12751 pkg.applicationInfo.uid); 12752 } 12753 } else { 12754 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 12755 } 12756 } 12757 12758 } finally { 12759 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 12760 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 12761 } 12762 } 12763 } 12764 // writer 12765 synchronized (mPackages) { 12766 // If the platform SDK has changed since the last time we booted, 12767 // we need to re-grant app permission to catch any new ones that 12768 // appear. This is really a hack, and means that apps can in some 12769 // cases get permissions that the user didn't initially explicitly 12770 // allow... it would be nice to have some better way to handle 12771 // this situation. 12772 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 12773 if (regrantPermissions) 12774 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 12775 + mSdkVersion + "; regranting permissions for external storage"); 12776 mSettings.mExternalSdkPlatform = mSdkVersion; 12777 12778 // Make sure group IDs have been assigned, and any permission 12779 // changes in other apps are accounted for 12780 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 12781 | (regrantPermissions 12782 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 12783 : 0)); 12784 12785 mSettings.updateExternalDatabaseVersion(); 12786 12787 // can downgrade to reader 12788 // Persist settings 12789 mSettings.writeLPr(); 12790 } 12791 // Send a broadcast to let everyone know we are done processing 12792 if (pkgList.size() > 0) { 12793 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12794 } 12795 } 12796 12797 /* 12798 * Utility method to unload a list of specified containers 12799 */ 12800 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 12801 // Just unmount all valid containers. 12802 for (AsecInstallArgs arg : cidArgs) { 12803 synchronized (mInstallLock) { 12804 arg.doPostDeleteLI(false); 12805 } 12806 } 12807 } 12808 12809 /* 12810 * Unload packages mounted on external media. This involves deleting package 12811 * data from internal structures, sending broadcasts about diabled packages, 12812 * gc'ing to free up references, unmounting all secure containers 12813 * corresponding to packages on external media, and posting a 12814 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 12815 * that we always have to post this message if status has been requested no 12816 * matter what. 12817 */ 12818 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 12819 final boolean reportStatus) { 12820 if (DEBUG_SD_INSTALL) 12821 Log.i(TAG, "unloading media packages"); 12822 ArrayList<String> pkgList = new ArrayList<String>(); 12823 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 12824 final Set<AsecInstallArgs> keys = processCids.keySet(); 12825 for (AsecInstallArgs args : keys) { 12826 String pkgName = args.getPackageName(); 12827 if (DEBUG_SD_INSTALL) 12828 Log.i(TAG, "Trying to unload pkg : " + pkgName); 12829 // Delete package internally 12830 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 12831 synchronized (mInstallLock) { 12832 boolean res = deletePackageLI(pkgName, null, false, null, null, 12833 PackageManager.DELETE_KEEP_DATA, outInfo, false); 12834 if (res) { 12835 pkgList.add(pkgName); 12836 } else { 12837 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 12838 failedList.add(args); 12839 } 12840 } 12841 } 12842 12843 // reader 12844 synchronized (mPackages) { 12845 // We didn't update the settings after removing each package; 12846 // write them now for all packages. 12847 mSettings.writeLPr(); 12848 } 12849 12850 // We have to absolutely send UPDATED_MEDIA_STATUS only 12851 // after confirming that all the receivers processed the ordered 12852 // broadcast when packages get disabled, force a gc to clean things up. 12853 // and unload all the containers. 12854 if (pkgList.size() > 0) { 12855 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 12856 new IIntentReceiver.Stub() { 12857 public void performReceive(Intent intent, int resultCode, String data, 12858 Bundle extras, boolean ordered, boolean sticky, 12859 int sendingUser) throws RemoteException { 12860 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 12861 reportStatus ? 1 : 0, 1, keys); 12862 mHandler.sendMessage(msg); 12863 } 12864 }); 12865 } else { 12866 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 12867 keys); 12868 mHandler.sendMessage(msg); 12869 } 12870 } 12871 12872 /** Binder call */ 12873 @Override 12874 public void movePackage(final String packageName, final IPackageMoveObserver observer, 12875 final int flags) { 12876 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 12877 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 12878 int returnCode = PackageManager.MOVE_SUCCEEDED; 12879 int currInstallFlags = 0; 12880 int newInstallFlags = 0; 12881 12882 File codeFile = null; 12883 String installerPackageName = null; 12884 String packageAbiOverride = null; 12885 12886 // reader 12887 synchronized (mPackages) { 12888 final PackageParser.Package pkg = mPackages.get(packageName); 12889 final PackageSetting ps = mSettings.mPackages.get(packageName); 12890 if (pkg == null || ps == null) { 12891 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12892 } else { 12893 // Disable moving fwd locked apps and system packages 12894 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 12895 Slog.w(TAG, "Cannot move system application"); 12896 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 12897 } else if (pkg.mOperationPending) { 12898 Slog.w(TAG, "Attempt to move package which has pending operations"); 12899 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 12900 } else { 12901 // Find install location first 12902 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 12903 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 12904 Slog.w(TAG, "Ambigous flags specified for move location."); 12905 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12906 } else { 12907 newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 12908 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 12909 currInstallFlags = isExternal(pkg) 12910 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 12911 12912 if (newInstallFlags == currInstallFlags) { 12913 Slog.w(TAG, "No move required. Trying to move to same location"); 12914 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12915 } else { 12916 if (isForwardLocked(pkg)) { 12917 currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12918 newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12919 } 12920 } 12921 } 12922 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12923 pkg.mOperationPending = true; 12924 } 12925 } 12926 12927 codeFile = new File(pkg.codePath); 12928 installerPackageName = ps.installerPackageName; 12929 packageAbiOverride = ps.cpuAbiOverrideString; 12930 } 12931 } 12932 12933 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 12934 try { 12935 observer.packageMoved(packageName, returnCode); 12936 } catch (RemoteException ignored) { 12937 } 12938 return; 12939 } 12940 12941 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 12942 @Override 12943 public void onUserActionRequired(Intent intent) throws RemoteException { 12944 throw new IllegalStateException(); 12945 } 12946 12947 @Override 12948 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 12949 Bundle extras) throws RemoteException { 12950 Slog.d(TAG, "Install result for move: " 12951 + PackageManager.installStatusToString(returnCode, msg)); 12952 12953 // We usually have a new package now after the install, but if 12954 // we failed we need to clear the pending flag on the original 12955 // package object. 12956 synchronized (mPackages) { 12957 final PackageParser.Package pkg = mPackages.get(packageName); 12958 if (pkg != null) { 12959 pkg.mOperationPending = false; 12960 } 12961 } 12962 12963 final int status = PackageManager.installStatusToPublicStatus(returnCode); 12964 switch (status) { 12965 case PackageInstaller.STATUS_SUCCESS: 12966 observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED); 12967 break; 12968 case PackageInstaller.STATUS_FAILURE_STORAGE: 12969 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 12970 break; 12971 default: 12972 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR); 12973 break; 12974 } 12975 } 12976 }; 12977 12978 // Treat a move like reinstalling an existing app, which ensures that we 12979 // process everythign uniformly, like unpacking native libraries. 12980 newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 12981 12982 final Message msg = mHandler.obtainMessage(INIT_COPY); 12983 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 12984 msg.obj = new InstallParams(origin, installObserver, newInstallFlags, 12985 installerPackageName, null, user, packageAbiOverride); 12986 mHandler.sendMessage(msg); 12987 } 12988 12989 @Override 12990 public boolean setInstallLocation(int loc) { 12991 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 12992 null); 12993 if (getInstallLocation() == loc) { 12994 return true; 12995 } 12996 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 12997 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 12998 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 12999 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 13000 return true; 13001 } 13002 return false; 13003 } 13004 13005 @Override 13006 public int getInstallLocation() { 13007 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13008 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 13009 PackageHelper.APP_INSTALL_AUTO); 13010 } 13011 13012 /** Called by UserManagerService */ 13013 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 13014 mDirtyUsers.remove(userHandle); 13015 mSettings.removeUserLPw(userHandle); 13016 mPendingBroadcasts.remove(userHandle); 13017 if (mInstaller != null) { 13018 // Technically, we shouldn't be doing this with the package lock 13019 // held. However, this is very rare, and there is already so much 13020 // other disk I/O going on, that we'll let it slide for now. 13021 mInstaller.removeUserDataDirs(userHandle); 13022 } 13023 mUserNeedsBadging.delete(userHandle); 13024 removeUnusedPackagesLILPw(userManager, userHandle); 13025 } 13026 13027 /** 13028 * We're removing userHandle and would like to remove any downloaded packages 13029 * that are no longer in use by any other user. 13030 * @param userHandle the user being removed 13031 */ 13032 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 13033 final boolean DEBUG_CLEAN_APKS = false; 13034 int [] users = userManager.getUserIdsLPr(); 13035 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 13036 while (psit.hasNext()) { 13037 PackageSetting ps = psit.next(); 13038 final String packageName = ps.pkg.packageName; 13039 // Skip over if system app 13040 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 13041 continue; 13042 } 13043 if (DEBUG_CLEAN_APKS) { 13044 Slog.i(TAG, "Checking package " + packageName); 13045 } 13046 boolean keep = false; 13047 for (int i = 0; i < users.length; i++) { 13048 if (users[i] != userHandle && ps.getInstalled(users[i])) { 13049 keep = true; 13050 if (DEBUG_CLEAN_APKS) { 13051 Slog.i(TAG, " Keeping package " + packageName + " for user " 13052 + users[i]); 13053 } 13054 break; 13055 } 13056 } 13057 if (!keep) { 13058 if (DEBUG_CLEAN_APKS) { 13059 Slog.i(TAG, " Removing package " + packageName); 13060 } 13061 mHandler.post(new Runnable() { 13062 public void run() { 13063 deletePackageX(packageName, userHandle, 0); 13064 } //end run 13065 }); 13066 } 13067 } 13068 } 13069 13070 /** Called by UserManagerService */ 13071 void createNewUserLILPw(int userHandle, File path) { 13072 if (mInstaller != null) { 13073 mInstaller.createUserConfig(userHandle); 13074 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 13075 } 13076 } 13077 13078 @Override 13079 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 13080 mContext.enforceCallingOrSelfPermission( 13081 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13082 "Only package verification agents can read the verifier device identity"); 13083 13084 synchronized (mPackages) { 13085 return mSettings.getVerifierDeviceIdentityLPw(); 13086 } 13087 } 13088 13089 @Override 13090 public void setPermissionEnforced(String permission, boolean enforced) { 13091 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 13092 if (READ_EXTERNAL_STORAGE.equals(permission)) { 13093 synchronized (mPackages) { 13094 if (mSettings.mReadExternalStorageEnforced == null 13095 || mSettings.mReadExternalStorageEnforced != enforced) { 13096 mSettings.mReadExternalStorageEnforced = enforced; 13097 mSettings.writeLPr(); 13098 } 13099 } 13100 // kill any non-foreground processes so we restart them and 13101 // grant/revoke the GID. 13102 final IActivityManager am = ActivityManagerNative.getDefault(); 13103 if (am != null) { 13104 final long token = Binder.clearCallingIdentity(); 13105 try { 13106 am.killProcessesBelowForeground("setPermissionEnforcement"); 13107 } catch (RemoteException e) { 13108 } finally { 13109 Binder.restoreCallingIdentity(token); 13110 } 13111 } 13112 } else { 13113 throw new IllegalArgumentException("No selective enforcement for " + permission); 13114 } 13115 } 13116 13117 @Override 13118 @Deprecated 13119 public boolean isPermissionEnforced(String permission) { 13120 return true; 13121 } 13122 13123 @Override 13124 public boolean isStorageLow() { 13125 final long token = Binder.clearCallingIdentity(); 13126 try { 13127 final DeviceStorageMonitorInternal 13128 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13129 if (dsm != null) { 13130 return dsm.isMemoryLow(); 13131 } else { 13132 return false; 13133 } 13134 } finally { 13135 Binder.restoreCallingIdentity(token); 13136 } 13137 } 13138 13139 @Override 13140 public IPackageInstaller getPackageInstaller() { 13141 return mInstallerService; 13142 } 13143 13144 private boolean userNeedsBadging(int userId) { 13145 int index = mUserNeedsBadging.indexOfKey(userId); 13146 if (index < 0) { 13147 final UserInfo userInfo; 13148 final long token = Binder.clearCallingIdentity(); 13149 try { 13150 userInfo = sUserManager.getUserInfo(userId); 13151 } finally { 13152 Binder.restoreCallingIdentity(token); 13153 } 13154 final boolean b; 13155 if (userInfo != null && userInfo.isManagedProfile()) { 13156 b = true; 13157 } else { 13158 b = false; 13159 } 13160 mUserNeedsBadging.put(userId, b); 13161 return b; 13162 } 13163 return mUserNeedsBadging.valueAt(index); 13164 } 13165 13166 @Override 13167 public KeySet getKeySetByAlias(String packageName, String alias) { 13168 if (packageName == null || alias == null) { 13169 return null; 13170 } 13171 synchronized(mPackages) { 13172 final PackageParser.Package pkg = mPackages.get(packageName); 13173 if (pkg == null) { 13174 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13175 throw new IllegalArgumentException("Unknown package: " + packageName); 13176 } 13177 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13178 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 13179 } 13180 } 13181 13182 @Override 13183 public KeySet getSigningKeySet(String packageName) { 13184 if (packageName == null) { 13185 return null; 13186 } 13187 synchronized(mPackages) { 13188 final PackageParser.Package pkg = mPackages.get(packageName); 13189 if (pkg == null) { 13190 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13191 throw new IllegalArgumentException("Unknown package: " + packageName); 13192 } 13193 if (pkg.applicationInfo.uid != Binder.getCallingUid() 13194 && Process.SYSTEM_UID != Binder.getCallingUid()) { 13195 throw new SecurityException("May not access signing KeySet of other apps."); 13196 } 13197 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13198 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 13199 } 13200 } 13201 13202 @Override 13203 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 13204 if (packageName == null || ks == null) { 13205 return false; 13206 } 13207 synchronized(mPackages) { 13208 final PackageParser.Package pkg = mPackages.get(packageName); 13209 if (pkg == null) { 13210 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13211 throw new IllegalArgumentException("Unknown package: " + packageName); 13212 } 13213 IBinder ksh = ks.getToken(); 13214 if (ksh instanceof KeySetHandle) { 13215 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13216 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 13217 } 13218 return false; 13219 } 13220 } 13221 13222 @Override 13223 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 13224 if (packageName == null || ks == null) { 13225 return false; 13226 } 13227 synchronized(mPackages) { 13228 final PackageParser.Package pkg = mPackages.get(packageName); 13229 if (pkg == null) { 13230 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13231 throw new IllegalArgumentException("Unknown package: " + packageName); 13232 } 13233 IBinder ksh = ks.getToken(); 13234 if (ksh instanceof KeySetHandle) { 13235 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13236 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 13237 } 13238 return false; 13239 } 13240 } 13241} 13242