PackageManagerService.java revision aef5fcdcb5ff13cbdc64f18b315750b8a9a7fe3e
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_USER_RESTRICTED; 28import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 29import static android.content.pm.PackageParser.isApkFile; 30import static android.os.Process.PACKAGE_INFO_GID; 31import static android.os.Process.SYSTEM_UID; 32import static android.system.OsConstants.O_CREAT; 33import static android.system.OsConstants.EEXIST; 34import static android.system.OsConstants.O_EXCL; 35import static android.system.OsConstants.O_RDWR; 36import static android.system.OsConstants.S_IRGRP; 37import static android.system.OsConstants.S_IROTH; 38import static android.system.OsConstants.S_IRWXU; 39import static android.system.OsConstants.S_IXGRP; 40import static android.system.OsConstants.S_IXOTH; 41import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 42import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 43import static com.android.internal.util.ArrayUtils.appendInt; 44import static com.android.internal.util.ArrayUtils.removeInt; 45 46import android.util.ArrayMap; 47 48import com.android.internal.R; 49import com.android.internal.app.IMediaContainerService; 50import com.android.internal.app.ResolverActivity; 51import com.android.internal.content.NativeLibraryHelper; 52import com.android.internal.content.PackageHelper; 53import com.android.internal.os.IParcelFileDescriptorFactory; 54import com.android.internal.util.ArrayUtils; 55import com.android.internal.util.FastPrintWriter; 56import com.android.internal.util.FastXmlSerializer; 57import com.android.internal.util.Preconditions; 58import com.android.server.EventLogTags; 59import com.android.server.IntentResolver; 60import com.android.server.LocalServices; 61import com.android.server.ServiceThread; 62import com.android.server.SystemConfig; 63import com.android.server.Watchdog; 64import com.android.server.pm.Settings.DatabaseVersion; 65import com.android.server.storage.DeviceStorageMonitorInternal; 66 67import org.xmlpull.v1.XmlSerializer; 68 69import android.app.ActivityManager; 70import android.app.ActivityManagerNative; 71import android.app.IActivityManager; 72import android.app.admin.IDevicePolicyManager; 73import android.app.backup.IBackupManager; 74import android.content.BroadcastReceiver; 75import android.content.ComponentName; 76import android.content.Context; 77import android.content.IIntentReceiver; 78import android.content.Intent; 79import android.content.IntentFilter; 80import android.content.IntentSender; 81import android.content.IntentSender.SendIntentException; 82import android.content.ServiceConnection; 83import android.content.pm.ActivityInfo; 84import android.content.pm.ApplicationInfo; 85import android.content.pm.FeatureInfo; 86import android.content.pm.IPackageDataObserver; 87import android.content.pm.IPackageDeleteObserver; 88import android.content.pm.IPackageInstallObserver; 89import android.content.pm.IPackageInstallObserver2; 90import android.content.pm.IPackageInstaller; 91import android.content.pm.IPackageManager; 92import android.content.pm.IPackageMoveObserver; 93import android.content.pm.IPackageStatsObserver; 94import android.content.pm.InstrumentationInfo; 95import android.content.pm.ManifestDigest; 96import android.content.pm.PackageCleanItem; 97import android.content.pm.PackageInfo; 98import android.content.pm.PackageInfoLite; 99import android.content.pm.PackageInstallerParams; 100import android.content.pm.PackageManager; 101import android.content.pm.PackageParser.ActivityIntentInfo; 102import android.content.pm.PackageParser.PackageLite; 103import android.content.pm.PackageParser.PackageParserException; 104import android.content.pm.PackageParser; 105import android.content.pm.PackageStats; 106import android.content.pm.PackageUserState; 107import android.content.pm.ParceledListSlice; 108import android.content.pm.PermissionGroupInfo; 109import android.content.pm.PermissionInfo; 110import android.content.pm.ProviderInfo; 111import android.content.pm.ResolveInfo; 112import android.content.pm.ServiceInfo; 113import android.content.pm.Signature; 114import android.content.pm.UserInfo; 115import android.content.pm.VerificationParams; 116import android.content.pm.VerifierDeviceIdentity; 117import android.content.pm.VerifierInfo; 118import android.content.res.Resources; 119import android.hardware.display.DisplayManager; 120import android.net.Uri; 121import android.os.Binder; 122import android.os.Build; 123import android.os.Bundle; 124import android.os.Environment; 125import android.os.Environment.UserEnvironment; 126import android.os.FileObserver; 127import android.os.FileUtils; 128import android.os.Handler; 129import android.os.IBinder; 130import android.os.Looper; 131import android.os.Message; 132import android.os.Parcel; 133import android.os.ParcelFileDescriptor; 134import android.os.Process; 135import android.os.RemoteException; 136import android.os.SELinux; 137import android.os.ServiceManager; 138import android.os.SystemClock; 139import android.os.SystemProperties; 140import android.os.UserHandle; 141import android.os.UserManager; 142import android.security.KeyStore; 143import android.security.SystemKeyStore; 144import android.system.ErrnoException; 145import android.system.Os; 146import android.system.StructStat; 147import android.text.TextUtils; 148import android.util.ArraySet; 149import android.util.AtomicFile; 150import android.util.DisplayMetrics; 151import android.util.EventLog; 152import android.util.Log; 153import android.util.LogPrinter; 154import android.util.PrintStreamPrinter; 155import android.util.Slog; 156import android.util.SparseArray; 157import android.util.SparseBooleanArray; 158import android.view.Display; 159 160import java.io.BufferedInputStream; 161import java.io.BufferedOutputStream; 162import java.io.File; 163import java.io.FileDescriptor; 164import java.io.FileInputStream; 165import java.io.FileNotFoundException; 166import java.io.FileOutputStream; 167import java.io.FilenameFilter; 168import java.io.IOException; 169import java.io.InputStream; 170import java.io.PrintWriter; 171import java.nio.charset.StandardCharsets; 172import java.security.NoSuchAlgorithmException; 173import java.security.PublicKey; 174import java.security.cert.CertificateEncodingException; 175import java.security.cert.CertificateException; 176import java.text.SimpleDateFormat; 177import java.util.ArrayList; 178import java.util.Arrays; 179import java.util.Collection; 180import java.util.Collections; 181import java.util.Comparator; 182import java.util.Date; 183import java.util.HashMap; 184import java.util.HashSet; 185import java.util.Iterator; 186import java.util.List; 187import java.util.Map; 188import java.util.Random; 189import java.util.Set; 190import java.util.concurrent.atomic.AtomicBoolean; 191import java.util.concurrent.atomic.AtomicLong; 192 193import dalvik.system.DexFile; 194import dalvik.system.StaleDexCacheError; 195import dalvik.system.VMRuntime; 196 197import libcore.io.IoUtils; 198 199/** 200 * Keep track of all those .apks everywhere. 201 * 202 * This is very central to the platform's security; please run the unit 203 * tests whenever making modifications here: 204 * 205mmm frameworks/base/tests/AndroidTests 206adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 207adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 208 * 209 * {@hide} 210 */ 211public class PackageManagerService extends IPackageManager.Stub { 212 static final String TAG = "PackageManager"; 213 static final boolean DEBUG_SETTINGS = false; 214 static final boolean DEBUG_PREFERRED = false; 215 static final boolean DEBUG_UPGRADE = false; 216 private static final boolean DEBUG_INSTALL = false; 217 private static final boolean DEBUG_REMOVE = false; 218 private static final boolean DEBUG_BROADCASTS = false; 219 private static final boolean DEBUG_SHOW_INFO = false; 220 private static final boolean DEBUG_PACKAGE_INFO = false; 221 private static final boolean DEBUG_INTENT_MATCHING = false; 222 private static final boolean DEBUG_PACKAGE_SCANNING = false; 223 private static final boolean DEBUG_APP_DIR_OBSERVER = false; 224 private static final boolean DEBUG_VERIFY = false; 225 private static final boolean DEBUG_DEXOPT = false; 226 private static final boolean DEBUG_ABI_SELECTION = false; 227 228 private static final int RADIO_UID = Process.PHONE_UID; 229 private static final int LOG_UID = Process.LOG_UID; 230 private static final int NFC_UID = Process.NFC_UID; 231 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 232 private static final int SHELL_UID = Process.SHELL_UID; 233 234 // Cap the size of permission trees that 3rd party apps can define 235 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 236 237 private static final int REMOVE_EVENTS = 238 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM; 239 private static final int ADD_EVENTS = 240 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO; 241 242 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS; 243 // Suffix used during package installation when copying/moving 244 // package apks to install directory. 245 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 246 247 static final int SCAN_MONITOR = 1<<0; 248 static final int SCAN_NO_DEX = 1<<1; 249 static final int SCAN_FORCE_DEX = 1<<2; 250 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 251 static final int SCAN_NEW_INSTALL = 1<<4; 252 static final int SCAN_NO_PATHS = 1<<5; 253 static final int SCAN_UPDATE_TIME = 1<<6; 254 static final int SCAN_DEFER_DEX = 1<<7; 255 static final int SCAN_BOOTING = 1<<8; 256 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 257 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 258 259 static final int REMOVE_CHATTY = 1<<16; 260 261 /** 262 * Timeout (in milliseconds) after which the watchdog should declare that 263 * our handler thread is wedged. The usual default for such things is one 264 * minute but we sometimes do very lengthy I/O operations on this thread, 265 * such as installing multi-gigabyte applications, so ours needs to be longer. 266 */ 267 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 268 269 /** 270 * Whether verification is enabled by default. 271 */ 272 private static final boolean DEFAULT_VERIFY_ENABLE = true; 273 274 /** 275 * The default maximum time to wait for the verification agent to return in 276 * milliseconds. 277 */ 278 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 279 280 /** 281 * The default response for package verification timeout. 282 * 283 * This can be either PackageManager.VERIFICATION_ALLOW or 284 * PackageManager.VERIFICATION_REJECT. 285 */ 286 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 287 288 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 289 290 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 291 DEFAULT_CONTAINER_PACKAGE, 292 "com.android.defcontainer.DefaultContainerService"); 293 294 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 295 296 private static final String LIB_DIR_NAME = "lib"; 297 private static final String LIB64_DIR_NAME = "lib64"; 298 299 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 300 301 static final String mTempContainerPrefix = "smdl2tmp"; 302 303 private static String sPreferredInstructionSet; 304 305 final ServiceThread mHandlerThread; 306 307 private static final String IDMAP_PREFIX = "/data/resource-cache/"; 308 private static final String IDMAP_SUFFIX = "@idmap"; 309 310 final PackageHandler mHandler; 311 312 final int mSdkVersion = Build.VERSION.SDK_INT; 313 314 final Context mContext; 315 final boolean mFactoryTest; 316 final boolean mOnlyCore; 317 final DisplayMetrics mMetrics; 318 final int mDefParseFlags; 319 final String[] mSeparateProcesses; 320 321 // This is where all application persistent data goes. 322 final File mAppDataDir; 323 324 // This is where all application persistent data goes for secondary users. 325 final File mUserAppDataDir; 326 327 /** The location for ASEC container files on internal storage. */ 328 final String mAsecInternalPath; 329 330 // This is the object monitoring the framework dir. 331 final FileObserver mFrameworkInstallObserver; 332 333 // This is the object monitoring the system app dir. 334 final FileObserver mSystemInstallObserver; 335 336 // This is the object monitoring the privileged system app dir. 337 final FileObserver mPrivilegedInstallObserver; 338 339 // This is the object monitoring the vendor app dir. 340 final FileObserver mVendorInstallObserver; 341 342 // This is the object monitoring the vendor overlay package dir. 343 final FileObserver mVendorOverlayInstallObserver; 344 345 // This is the object monitoring the OEM app dir. 346 final FileObserver mOemInstallObserver; 347 348 // This is the object monitoring mAppInstallDir. 349 final FileObserver mAppInstallObserver; 350 351 // This is the object monitoring mDrmAppPrivateInstallDir. 352 final FileObserver mDrmAppInstallObserver; 353 354 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 355 // LOCK HELD. Can be called with mInstallLock held. 356 final Installer mInstaller; 357 358 /** Directory where installed third-party apps stored */ 359 final File mAppInstallDir; 360 361 /** 362 * Directory to which applications installed internally have their 363 * 32 bit native libraries copied. 364 */ 365 private File mAppLib32InstallDir; 366 367 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 368 // apps. 369 final File mDrmAppPrivateInstallDir; 370 371 // ---------------------------------------------------------------- 372 373 // Lock for state used when installing and doing other long running 374 // operations. Methods that must be called with this lock held have 375 // the suffix "LI". 376 final Object mInstallLock = new Object(); 377 378 // These are the directories in the 3rd party applications installed dir 379 // that we have currently loaded packages from. Keys are the application's 380 // installed zip file (absolute codePath), and values are Package. 381 final HashMap<String, PackageParser.Package> mAppDirs = 382 new HashMap<String, PackageParser.Package>(); 383 384 // Information for the parser to write more useful error messages. 385 int mLastScanError; 386 387 // ---------------------------------------------------------------- 388 389 // Keys are String (package name), values are Package. This also serves 390 // as the lock for the global state. Methods that must be called with 391 // this lock held have the prefix "LP". 392 final HashMap<String, PackageParser.Package> mPackages = 393 new HashMap<String, PackageParser.Package>(); 394 395 // Tracks available target package names -> overlay package paths. 396 final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays = 397 new HashMap<String, HashMap<String, PackageParser.Package>>(); 398 399 final Settings mSettings; 400 boolean mRestoredSettings; 401 402 // System configuration read by SystemConfig. 403 final int[] mGlobalGids; 404 final SparseArray<HashSet<String>> mSystemPermissions; 405 final HashMap<String, FeatureInfo> mAvailableFeatures; 406 407 // If mac_permissions.xml was found for seinfo labeling. 408 boolean mFoundPolicyFile; 409 410 // If a recursive restorecon of /data/data/<pkg> is needed. 411 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 412 413 public static final class SharedLibraryEntry { 414 public final String path; 415 public final String apk; 416 417 SharedLibraryEntry(String _path, String _apk) { 418 path = _path; 419 apk = _apk; 420 } 421 } 422 423 // Currently known shared libraries. 424 final HashMap<String, SharedLibraryEntry> mSharedLibraries = 425 new HashMap<String, SharedLibraryEntry>(); 426 427 // All available activities, for your resolving pleasure. 428 final ActivityIntentResolver mActivities = 429 new ActivityIntentResolver(); 430 431 // All available receivers, for your resolving pleasure. 432 final ActivityIntentResolver mReceivers = 433 new ActivityIntentResolver(); 434 435 // All available services, for your resolving pleasure. 436 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 437 438 // All available providers, for your resolving pleasure. 439 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 440 441 // Mapping from provider base names (first directory in content URI codePath) 442 // to the provider information. 443 final HashMap<String, PackageParser.Provider> mProvidersByAuthority = 444 new HashMap<String, PackageParser.Provider>(); 445 446 // Mapping from instrumentation class names to info about them. 447 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 448 new HashMap<ComponentName, PackageParser.Instrumentation>(); 449 450 // Mapping from permission names to info about them. 451 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups = 452 new HashMap<String, PackageParser.PermissionGroup>(); 453 454 // Packages whose data we have transfered into another package, thus 455 // should no longer exist. 456 final HashSet<String> mTransferedPackages = new HashSet<String>(); 457 458 // Broadcast actions that are only available to the system. 459 final HashSet<String> mProtectedBroadcasts = new HashSet<String>(); 460 461 /** List of packages waiting for verification. */ 462 final SparseArray<PackageVerificationState> mPendingVerification 463 = new SparseArray<PackageVerificationState>(); 464 465 final PackageInstallerService mInstallerService; 466 467 HashSet<PackageParser.Package> mDeferredDexOpt = null; 468 469 // Cache of users who need badging. 470 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 471 472 /** Token for keys in mPendingVerification. */ 473 private int mPendingVerificationToken = 0; 474 475 boolean mSystemReady; 476 boolean mSafeMode; 477 boolean mHasSystemUidErrors; 478 479 ApplicationInfo mAndroidApplication; 480 final ActivityInfo mResolveActivity = new ActivityInfo(); 481 final ResolveInfo mResolveInfo = new ResolveInfo(); 482 ComponentName mResolveComponentName; 483 PackageParser.Package mPlatformPackage; 484 ComponentName mCustomResolverComponentName; 485 486 boolean mResolverReplaced = false; 487 488 // Set of pending broadcasts for aggregating enable/disable of components. 489 static class PendingPackageBroadcasts { 490 // for each user id, a map of <package name -> components within that package> 491 final SparseArray<HashMap<String, ArrayList<String>>> mUidMap; 492 493 public PendingPackageBroadcasts() { 494 mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2); 495 } 496 497 public ArrayList<String> get(int userId, String packageName) { 498 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 499 return packages.get(packageName); 500 } 501 502 public void put(int userId, String packageName, ArrayList<String> components) { 503 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 504 packages.put(packageName, components); 505 } 506 507 public void remove(int userId, String packageName) { 508 HashMap<String, ArrayList<String>> packages = mUidMap.get(userId); 509 if (packages != null) { 510 packages.remove(packageName); 511 } 512 } 513 514 public void remove(int userId) { 515 mUidMap.remove(userId); 516 } 517 518 public int userIdCount() { 519 return mUidMap.size(); 520 } 521 522 public int userIdAt(int n) { 523 return mUidMap.keyAt(n); 524 } 525 526 public HashMap<String, ArrayList<String>> packagesForUserId(int userId) { 527 return mUidMap.get(userId); 528 } 529 530 public int size() { 531 // total number of pending broadcast entries across all userIds 532 int num = 0; 533 for (int i = 0; i< mUidMap.size(); i++) { 534 num += mUidMap.valueAt(i).size(); 535 } 536 return num; 537 } 538 539 public void clear() { 540 mUidMap.clear(); 541 } 542 543 private HashMap<String, ArrayList<String>> getOrAllocate(int userId) { 544 HashMap<String, ArrayList<String>> map = mUidMap.get(userId); 545 if (map == null) { 546 map = new HashMap<String, ArrayList<String>>(); 547 mUidMap.put(userId, map); 548 } 549 return map; 550 } 551 } 552 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 553 554 // Service Connection to remote media container service to copy 555 // package uri's from external media onto secure containers 556 // or internal storage. 557 private IMediaContainerService mContainerService = null; 558 559 static final int SEND_PENDING_BROADCAST = 1; 560 static final int MCS_BOUND = 3; 561 static final int END_COPY = 4; 562 static final int INIT_COPY = 5; 563 static final int MCS_UNBIND = 6; 564 static final int START_CLEANING_PACKAGE = 7; 565 static final int FIND_INSTALL_LOC = 8; 566 static final int POST_INSTALL = 9; 567 static final int MCS_RECONNECT = 10; 568 static final int MCS_GIVE_UP = 11; 569 static final int UPDATED_MEDIA_STATUS = 12; 570 static final int WRITE_SETTINGS = 13; 571 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 572 static final int PACKAGE_VERIFIED = 15; 573 static final int CHECK_PENDING_VERIFICATION = 16; 574 575 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 576 577 // Delay time in millisecs 578 static final int BROADCAST_DELAY = 10 * 1000; 579 580 static UserManagerService sUserManager; 581 582 // Stores a list of users whose package restrictions file needs to be updated 583 private HashSet<Integer> mDirtyUsers = new HashSet<Integer>(); 584 585 final private DefaultContainerConnection mDefContainerConn = 586 new DefaultContainerConnection(); 587 class DefaultContainerConnection implements ServiceConnection { 588 public void onServiceConnected(ComponentName name, IBinder service) { 589 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 590 IMediaContainerService imcs = 591 IMediaContainerService.Stub.asInterface(service); 592 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 593 } 594 595 public void onServiceDisconnected(ComponentName name) { 596 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 597 } 598 }; 599 600 // Recordkeeping of restore-after-install operations that are currently in flight 601 // between the Package Manager and the Backup Manager 602 class PostInstallData { 603 public InstallArgs args; 604 public PackageInstalledInfo res; 605 606 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 607 args = _a; 608 res = _r; 609 } 610 }; 611 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 612 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 613 614 private final String mRequiredVerifierPackage; 615 616 private final PackageUsage mPackageUsage = new PackageUsage(); 617 618 private class PackageUsage { 619 private static final int WRITE_INTERVAL 620 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 621 622 private final Object mFileLock = new Object(); 623 private final AtomicLong mLastWritten = new AtomicLong(0); 624 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 625 626 private boolean mIsHistoricalPackageUsageAvailable = true; 627 628 boolean isHistoricalPackageUsageAvailable() { 629 return mIsHistoricalPackageUsageAvailable; 630 } 631 632 void write(boolean force) { 633 if (force) { 634 writeInternal(); 635 return; 636 } 637 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 638 && !DEBUG_DEXOPT) { 639 return; 640 } 641 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 642 new Thread("PackageUsage_DiskWriter") { 643 @Override 644 public void run() { 645 try { 646 writeInternal(); 647 } finally { 648 mBackgroundWriteRunning.set(false); 649 } 650 } 651 }.start(); 652 } 653 } 654 655 private void writeInternal() { 656 synchronized (mPackages) { 657 synchronized (mFileLock) { 658 AtomicFile file = getFile(); 659 FileOutputStream f = null; 660 try { 661 f = file.startWrite(); 662 BufferedOutputStream out = new BufferedOutputStream(f); 663 FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID); 664 StringBuilder sb = new StringBuilder(); 665 for (PackageParser.Package pkg : mPackages.values()) { 666 if (pkg.mLastPackageUsageTimeInMills == 0) { 667 continue; 668 } 669 sb.setLength(0); 670 sb.append(pkg.packageName); 671 sb.append(' '); 672 sb.append((long)pkg.mLastPackageUsageTimeInMills); 673 sb.append('\n'); 674 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 675 } 676 out.flush(); 677 file.finishWrite(f); 678 } catch (IOException e) { 679 if (f != null) { 680 file.failWrite(f); 681 } 682 Log.e(TAG, "Failed to write package usage times", e); 683 } 684 } 685 } 686 mLastWritten.set(SystemClock.elapsedRealtime()); 687 } 688 689 void readLP() { 690 synchronized (mFileLock) { 691 AtomicFile file = getFile(); 692 BufferedInputStream in = null; 693 try { 694 in = new BufferedInputStream(file.openRead()); 695 StringBuffer sb = new StringBuffer(); 696 while (true) { 697 String packageName = readToken(in, sb, ' '); 698 if (packageName == null) { 699 break; 700 } 701 String timeInMillisString = readToken(in, sb, '\n'); 702 if (timeInMillisString == null) { 703 throw new IOException("Failed to find last usage time for package " 704 + packageName); 705 } 706 PackageParser.Package pkg = mPackages.get(packageName); 707 if (pkg == null) { 708 continue; 709 } 710 long timeInMillis; 711 try { 712 timeInMillis = Long.parseLong(timeInMillisString.toString()); 713 } catch (NumberFormatException e) { 714 throw new IOException("Failed to parse " + timeInMillisString 715 + " as a long.", e); 716 } 717 pkg.mLastPackageUsageTimeInMills = timeInMillis; 718 } 719 } catch (FileNotFoundException expected) { 720 mIsHistoricalPackageUsageAvailable = false; 721 } catch (IOException e) { 722 Log.w(TAG, "Failed to read package usage times", e); 723 } finally { 724 IoUtils.closeQuietly(in); 725 } 726 } 727 mLastWritten.set(SystemClock.elapsedRealtime()); 728 } 729 730 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 731 throws IOException { 732 sb.setLength(0); 733 while (true) { 734 int ch = in.read(); 735 if (ch == -1) { 736 if (sb.length() == 0) { 737 return null; 738 } 739 throw new IOException("Unexpected EOF"); 740 } 741 if (ch == endOfToken) { 742 return sb.toString(); 743 } 744 sb.append((char)ch); 745 } 746 } 747 748 private AtomicFile getFile() { 749 File dataDir = Environment.getDataDirectory(); 750 File systemDir = new File(dataDir, "system"); 751 File fname = new File(systemDir, "package-usage.list"); 752 return new AtomicFile(fname); 753 } 754 } 755 756 class PackageHandler extends Handler { 757 private boolean mBound = false; 758 final ArrayList<HandlerParams> mPendingInstalls = 759 new ArrayList<HandlerParams>(); 760 761 private boolean connectToService() { 762 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 763 " DefaultContainerService"); 764 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 765 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 766 if (mContext.bindServiceAsUser(service, mDefContainerConn, 767 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 768 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 769 mBound = true; 770 return true; 771 } 772 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 773 return false; 774 } 775 776 private void disconnectService() { 777 mContainerService = null; 778 mBound = false; 779 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 780 mContext.unbindService(mDefContainerConn); 781 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 782 } 783 784 PackageHandler(Looper looper) { 785 super(looper); 786 } 787 788 public void handleMessage(Message msg) { 789 try { 790 doHandleMessage(msg); 791 } finally { 792 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 793 } 794 } 795 796 void doHandleMessage(Message msg) { 797 switch (msg.what) { 798 case INIT_COPY: { 799 HandlerParams params = (HandlerParams) msg.obj; 800 int idx = mPendingInstalls.size(); 801 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 802 // If a bind was already initiated we dont really 803 // need to do anything. The pending install 804 // will be processed later on. 805 if (!mBound) { 806 // If this is the only one pending we might 807 // have to bind to the service again. 808 if (!connectToService()) { 809 Slog.e(TAG, "Failed to bind to media container service"); 810 params.serviceError(); 811 return; 812 } else { 813 // Once we bind to the service, the first 814 // pending request will be processed. 815 mPendingInstalls.add(idx, params); 816 } 817 } else { 818 mPendingInstalls.add(idx, params); 819 // Already bound to the service. Just make 820 // sure we trigger off processing the first request. 821 if (idx == 0) { 822 mHandler.sendEmptyMessage(MCS_BOUND); 823 } 824 } 825 break; 826 } 827 case MCS_BOUND: { 828 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 829 if (msg.obj != null) { 830 mContainerService = (IMediaContainerService) msg.obj; 831 } 832 if (mContainerService == null) { 833 // Something seriously wrong. Bail out 834 Slog.e(TAG, "Cannot bind to media container service"); 835 for (HandlerParams params : mPendingInstalls) { 836 // Indicate service bind error 837 params.serviceError(); 838 } 839 mPendingInstalls.clear(); 840 } else if (mPendingInstalls.size() > 0) { 841 HandlerParams params = mPendingInstalls.get(0); 842 if (params != null) { 843 if (params.startCopy()) { 844 // We are done... look for more work or to 845 // go idle. 846 if (DEBUG_SD_INSTALL) Log.i(TAG, 847 "Checking for more work or unbind..."); 848 // Delete pending install 849 if (mPendingInstalls.size() > 0) { 850 mPendingInstalls.remove(0); 851 } 852 if (mPendingInstalls.size() == 0) { 853 if (mBound) { 854 if (DEBUG_SD_INSTALL) Log.i(TAG, 855 "Posting delayed MCS_UNBIND"); 856 removeMessages(MCS_UNBIND); 857 Message ubmsg = obtainMessage(MCS_UNBIND); 858 // Unbind after a little delay, to avoid 859 // continual thrashing. 860 sendMessageDelayed(ubmsg, 10000); 861 } 862 } else { 863 // There are more pending requests in queue. 864 // Just post MCS_BOUND message to trigger processing 865 // of next pending install. 866 if (DEBUG_SD_INSTALL) Log.i(TAG, 867 "Posting MCS_BOUND for next work"); 868 mHandler.sendEmptyMessage(MCS_BOUND); 869 } 870 } 871 } 872 } else { 873 // Should never happen ideally. 874 Slog.w(TAG, "Empty queue"); 875 } 876 break; 877 } 878 case MCS_RECONNECT: { 879 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 880 if (mPendingInstalls.size() > 0) { 881 if (mBound) { 882 disconnectService(); 883 } 884 if (!connectToService()) { 885 Slog.e(TAG, "Failed to bind to media container service"); 886 for (HandlerParams params : mPendingInstalls) { 887 // Indicate service bind error 888 params.serviceError(); 889 } 890 mPendingInstalls.clear(); 891 } 892 } 893 break; 894 } 895 case MCS_UNBIND: { 896 // If there is no actual work left, then time to unbind. 897 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 898 899 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 900 if (mBound) { 901 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 902 903 disconnectService(); 904 } 905 } else if (mPendingInstalls.size() > 0) { 906 // There are more pending requests in queue. 907 // Just post MCS_BOUND message to trigger processing 908 // of next pending install. 909 mHandler.sendEmptyMessage(MCS_BOUND); 910 } 911 912 break; 913 } 914 case MCS_GIVE_UP: { 915 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 916 mPendingInstalls.remove(0); 917 break; 918 } 919 case SEND_PENDING_BROADCAST: { 920 String packages[]; 921 ArrayList<String> components[]; 922 int size = 0; 923 int uids[]; 924 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 925 synchronized (mPackages) { 926 if (mPendingBroadcasts == null) { 927 return; 928 } 929 size = mPendingBroadcasts.size(); 930 if (size <= 0) { 931 // Nothing to be done. Just return 932 return; 933 } 934 packages = new String[size]; 935 components = new ArrayList[size]; 936 uids = new int[size]; 937 int i = 0; // filling out the above arrays 938 939 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 940 int packageUserId = mPendingBroadcasts.userIdAt(n); 941 Iterator<Map.Entry<String, ArrayList<String>>> it 942 = mPendingBroadcasts.packagesForUserId(packageUserId) 943 .entrySet().iterator(); 944 while (it.hasNext() && i < size) { 945 Map.Entry<String, ArrayList<String>> ent = it.next(); 946 packages[i] = ent.getKey(); 947 components[i] = ent.getValue(); 948 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 949 uids[i] = (ps != null) 950 ? UserHandle.getUid(packageUserId, ps.appId) 951 : -1; 952 i++; 953 } 954 } 955 size = i; 956 mPendingBroadcasts.clear(); 957 } 958 // Send broadcasts 959 for (int i = 0; i < size; i++) { 960 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 961 } 962 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 963 break; 964 } 965 case START_CLEANING_PACKAGE: { 966 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 967 final String packageName = (String)msg.obj; 968 final int userId = msg.arg1; 969 final boolean andCode = msg.arg2 != 0; 970 synchronized (mPackages) { 971 if (userId == UserHandle.USER_ALL) { 972 int[] users = sUserManager.getUserIds(); 973 for (int user : users) { 974 mSettings.addPackageToCleanLPw( 975 new PackageCleanItem(user, packageName, andCode)); 976 } 977 } else { 978 mSettings.addPackageToCleanLPw( 979 new PackageCleanItem(userId, packageName, andCode)); 980 } 981 } 982 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 983 startCleaningPackages(); 984 } break; 985 case POST_INSTALL: { 986 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 987 PostInstallData data = mRunningInstalls.get(msg.arg1); 988 mRunningInstalls.delete(msg.arg1); 989 boolean deleteOld = false; 990 991 if (data != null) { 992 InstallArgs args = data.args; 993 PackageInstalledInfo res = data.res; 994 995 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 996 res.removedInfo.sendBroadcast(false, true, false); 997 Bundle extras = new Bundle(1); 998 extras.putInt(Intent.EXTRA_UID, res.uid); 999 // Determine the set of users who are adding this 1000 // package for the first time vs. those who are seeing 1001 // an update. 1002 int[] firstUsers; 1003 int[] updateUsers = new int[0]; 1004 if (res.origUsers == null || res.origUsers.length == 0) { 1005 firstUsers = res.newUsers; 1006 } else { 1007 firstUsers = new int[0]; 1008 for (int i=0; i<res.newUsers.length; i++) { 1009 int user = res.newUsers[i]; 1010 boolean isNew = true; 1011 for (int j=0; j<res.origUsers.length; j++) { 1012 if (res.origUsers[j] == user) { 1013 isNew = false; 1014 break; 1015 } 1016 } 1017 if (isNew) { 1018 int[] newFirst = new int[firstUsers.length+1]; 1019 System.arraycopy(firstUsers, 0, newFirst, 0, 1020 firstUsers.length); 1021 newFirst[firstUsers.length] = user; 1022 firstUsers = newFirst; 1023 } else { 1024 int[] newUpdate = new int[updateUsers.length+1]; 1025 System.arraycopy(updateUsers, 0, newUpdate, 0, 1026 updateUsers.length); 1027 newUpdate[updateUsers.length] = user; 1028 updateUsers = newUpdate; 1029 } 1030 } 1031 } 1032 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1033 res.pkg.applicationInfo.packageName, 1034 extras, null, null, firstUsers); 1035 final boolean update = res.removedInfo.removedPackage != null; 1036 if (update) { 1037 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1038 } 1039 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1040 res.pkg.applicationInfo.packageName, 1041 extras, null, null, updateUsers); 1042 if (update) { 1043 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1044 res.pkg.applicationInfo.packageName, 1045 extras, null, null, updateUsers); 1046 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1047 null, null, 1048 res.pkg.applicationInfo.packageName, null, updateUsers); 1049 1050 // treat asec-hosted packages like removable media on upgrade 1051 if (isForwardLocked(res.pkg) || isExternal(res.pkg)) { 1052 if (DEBUG_INSTALL) { 1053 Slog.i(TAG, "upgrading pkg " + res.pkg 1054 + " is ASEC-hosted -> AVAILABLE"); 1055 } 1056 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1057 ArrayList<String> pkgList = new ArrayList<String>(1); 1058 pkgList.add(res.pkg.applicationInfo.packageName); 1059 sendResourcesChangedBroadcast(true, true, 1060 pkgList,uidArray, null); 1061 } 1062 } 1063 if (res.removedInfo.args != null) { 1064 // Remove the replaced package's older resources safely now 1065 deleteOld = true; 1066 } 1067 1068 // Log current value of "unknown sources" setting 1069 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1070 getUnknownSourcesSettings()); 1071 } 1072 // Force a gc to clear up things 1073 Runtime.getRuntime().gc(); 1074 // We delete after a gc for applications on sdcard. 1075 if (deleteOld) { 1076 synchronized (mInstallLock) { 1077 res.removedInfo.args.doPostDeleteLI(true); 1078 } 1079 } 1080 if (args.observer != null) { 1081 try { 1082 Bundle extras = extrasForInstallResult(res); 1083 args.observer.packageInstalled(res.name, extras, res.returnCode); 1084 } catch (RemoteException e) { 1085 Slog.i(TAG, "Observer no longer exists."); 1086 } 1087 } 1088 } else { 1089 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1090 } 1091 } break; 1092 case UPDATED_MEDIA_STATUS: { 1093 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1094 boolean reportStatus = msg.arg1 == 1; 1095 boolean doGc = msg.arg2 == 1; 1096 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1097 if (doGc) { 1098 // Force a gc to clear up stale containers. 1099 Runtime.getRuntime().gc(); 1100 } 1101 if (msg.obj != null) { 1102 @SuppressWarnings("unchecked") 1103 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1104 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1105 // Unload containers 1106 unloadAllContainers(args); 1107 } 1108 if (reportStatus) { 1109 try { 1110 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1111 PackageHelper.getMountService().finishMediaUpdate(); 1112 } catch (RemoteException e) { 1113 Log.e(TAG, "MountService not running?"); 1114 } 1115 } 1116 } break; 1117 case WRITE_SETTINGS: { 1118 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1119 synchronized (mPackages) { 1120 removeMessages(WRITE_SETTINGS); 1121 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1122 mSettings.writeLPr(); 1123 mDirtyUsers.clear(); 1124 } 1125 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1126 } break; 1127 case WRITE_PACKAGE_RESTRICTIONS: { 1128 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1129 synchronized (mPackages) { 1130 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1131 for (int userId : mDirtyUsers) { 1132 mSettings.writePackageRestrictionsLPr(userId); 1133 } 1134 mDirtyUsers.clear(); 1135 } 1136 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1137 } break; 1138 case CHECK_PENDING_VERIFICATION: { 1139 final int verificationId = msg.arg1; 1140 final PackageVerificationState state = mPendingVerification.get(verificationId); 1141 1142 if ((state != null) && !state.timeoutExtended()) { 1143 final InstallArgs args = state.getInstallArgs(); 1144 final Uri originUri = Uri.fromFile(args.originFile); 1145 1146 Slog.i(TAG, "Verification timed out for " + originUri); 1147 mPendingVerification.remove(verificationId); 1148 1149 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1150 1151 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1152 Slog.i(TAG, "Continuing with installation of " + originUri); 1153 state.setVerifierResponse(Binder.getCallingUid(), 1154 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1155 broadcastPackageVerified(verificationId, originUri, 1156 PackageManager.VERIFICATION_ALLOW, 1157 state.getInstallArgs().getUser()); 1158 try { 1159 ret = args.copyApk(mContainerService, true); 1160 } catch (RemoteException e) { 1161 Slog.e(TAG, "Could not contact the ContainerService"); 1162 } 1163 } else { 1164 broadcastPackageVerified(verificationId, originUri, 1165 PackageManager.VERIFICATION_REJECT, 1166 state.getInstallArgs().getUser()); 1167 } 1168 1169 processPendingInstall(args, ret); 1170 mHandler.sendEmptyMessage(MCS_UNBIND); 1171 } 1172 break; 1173 } 1174 case PACKAGE_VERIFIED: { 1175 final int verificationId = msg.arg1; 1176 1177 final PackageVerificationState state = mPendingVerification.get(verificationId); 1178 if (state == null) { 1179 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1180 break; 1181 } 1182 1183 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1184 1185 state.setVerifierResponse(response.callerUid, response.code); 1186 1187 if (state.isVerificationComplete()) { 1188 mPendingVerification.remove(verificationId); 1189 1190 final InstallArgs args = state.getInstallArgs(); 1191 final Uri originUri = Uri.fromFile(args.originFile); 1192 1193 int ret; 1194 if (state.isInstallAllowed()) { 1195 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1196 broadcastPackageVerified(verificationId, originUri, 1197 response.code, state.getInstallArgs().getUser()); 1198 try { 1199 ret = args.copyApk(mContainerService, true); 1200 } catch (RemoteException e) { 1201 Slog.e(TAG, "Could not contact the ContainerService"); 1202 } 1203 } else { 1204 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1205 } 1206 1207 processPendingInstall(args, ret); 1208 1209 mHandler.sendEmptyMessage(MCS_UNBIND); 1210 } 1211 1212 break; 1213 } 1214 } 1215 } 1216 } 1217 1218 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1219 Bundle extras = null; 1220 switch (res.returnCode) { 1221 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1222 extras = new Bundle(); 1223 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1224 res.origPermission); 1225 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1226 res.origPackage); 1227 break; 1228 } 1229 } 1230 return extras; 1231 } 1232 1233 void scheduleWriteSettingsLocked() { 1234 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1235 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1236 } 1237 } 1238 1239 void scheduleWritePackageRestrictionsLocked(int userId) { 1240 if (!sUserManager.exists(userId)) return; 1241 mDirtyUsers.add(userId); 1242 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1243 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1244 } 1245 } 1246 1247 public static final PackageManagerService main(Context context, Installer installer, 1248 boolean factoryTest, boolean onlyCore) { 1249 PackageManagerService m = new PackageManagerService(context, installer, 1250 factoryTest, onlyCore); 1251 ServiceManager.addService("package", m); 1252 return m; 1253 } 1254 1255 static String[] splitString(String str, char sep) { 1256 int count = 1; 1257 int i = 0; 1258 while ((i=str.indexOf(sep, i)) >= 0) { 1259 count++; 1260 i++; 1261 } 1262 1263 String[] res = new String[count]; 1264 i=0; 1265 count = 0; 1266 int lastI=0; 1267 while ((i=str.indexOf(sep, i)) >= 0) { 1268 res[count] = str.substring(lastI, i); 1269 count++; 1270 i++; 1271 lastI = i; 1272 } 1273 res[count] = str.substring(lastI, str.length()); 1274 return res; 1275 } 1276 1277 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1278 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1279 Context.DISPLAY_SERVICE); 1280 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1281 } 1282 1283 public PackageManagerService(Context context, Installer installer, 1284 boolean factoryTest, boolean onlyCore) { 1285 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1286 SystemClock.uptimeMillis()); 1287 1288 if (mSdkVersion <= 0) { 1289 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1290 } 1291 1292 mContext = context; 1293 mFactoryTest = factoryTest; 1294 mOnlyCore = onlyCore; 1295 mMetrics = new DisplayMetrics(); 1296 mSettings = new Settings(context); 1297 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1298 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1299 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1300 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1301 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1302 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1303 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1304 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1305 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1306 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1307 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1308 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1309 1310 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1311 if (separateProcesses != null && separateProcesses.length() > 0) { 1312 if ("*".equals(separateProcesses)) { 1313 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1314 mSeparateProcesses = null; 1315 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1316 } else { 1317 mDefParseFlags = 0; 1318 mSeparateProcesses = separateProcesses.split(","); 1319 Slog.w(TAG, "Running with debug.separate_processes: " 1320 + separateProcesses); 1321 } 1322 } else { 1323 mDefParseFlags = 0; 1324 mSeparateProcesses = null; 1325 } 1326 1327 mInstaller = installer; 1328 1329 getDefaultDisplayMetrics(context, mMetrics); 1330 1331 SystemConfig systemConfig = SystemConfig.getInstance(); 1332 mGlobalGids = systemConfig.getGlobalGids(); 1333 mSystemPermissions = systemConfig.getSystemPermissions(); 1334 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1335 1336 synchronized (mInstallLock) { 1337 // writer 1338 synchronized (mPackages) { 1339 mHandlerThread = new ServiceThread(TAG, 1340 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1341 mHandlerThread.start(); 1342 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1343 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1344 1345 File dataDir = Environment.getDataDirectory(); 1346 mAppDataDir = new File(dataDir, "data"); 1347 mAppInstallDir = new File(dataDir, "app"); 1348 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1349 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1350 mUserAppDataDir = new File(dataDir, "user"); 1351 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1352 1353 sUserManager = new UserManagerService(context, this, 1354 mInstallLock, mPackages); 1355 1356 // Propagate permission configuration in to package manager. 1357 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1358 = systemConfig.getPermissions(); 1359 for (int i=0; i<permConfig.size(); i++) { 1360 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1361 BasePermission bp = mSettings.mPermissions.get(perm.name); 1362 if (bp == null) { 1363 bp = new BasePermission(perm.name, null, BasePermission.TYPE_BUILTIN); 1364 mSettings.mPermissions.put(perm.name, bp); 1365 } 1366 if (perm.gids != null) { 1367 bp.gids = appendInts(bp.gids, perm.gids); 1368 } 1369 } 1370 1371 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1372 for (int i=0; i<libConfig.size(); i++) { 1373 mSharedLibraries.put(libConfig.keyAt(i), 1374 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1375 } 1376 1377 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1378 1379 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1380 mSdkVersion, mOnlyCore); 1381 1382 String customResolverActivity = Resources.getSystem().getString( 1383 R.string.config_customResolverActivity); 1384 if (TextUtils.isEmpty(customResolverActivity)) { 1385 customResolverActivity = null; 1386 } else { 1387 mCustomResolverComponentName = ComponentName.unflattenFromString( 1388 customResolverActivity); 1389 } 1390 1391 long startTime = SystemClock.uptimeMillis(); 1392 1393 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1394 startTime); 1395 1396 // Set flag to monitor and not change apk file paths when 1397 // scanning install directories. 1398 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1399 1400 final HashSet<String> alreadyDexOpted = new HashSet<String>(); 1401 1402 /** 1403 * Add everything in the in the boot class path to the 1404 * list of process files because dexopt will have been run 1405 * if necessary during zygote startup. 1406 */ 1407 String bootClassPath = System.getProperty("java.boot.class.path"); 1408 if (bootClassPath != null) { 1409 String[] paths = splitString(bootClassPath, ':'); 1410 for (int i=0; i<paths.length; i++) { 1411 alreadyDexOpted.add(paths[i]); 1412 } 1413 } else { 1414 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1415 } 1416 1417 boolean didDexOptLibraryOrTool = false; 1418 1419 final List<String> instructionSets = getAllInstructionSets(); 1420 1421 /** 1422 * Ensure all external libraries have had dexopt run on them. 1423 */ 1424 if (mSharedLibraries.size() > 0) { 1425 // NOTE: For now, we're compiling these system "shared libraries" 1426 // (and framework jars) into all available architectures. It's possible 1427 // to compile them only when we come across an app that uses them (there's 1428 // already logic for that in scanPackageLI) but that adds some complexity. 1429 for (String instructionSet : instructionSets) { 1430 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1431 final String lib = libEntry.path; 1432 if (lib == null) { 1433 continue; 1434 } 1435 1436 try { 1437 if (DexFile.isDexOptNeededInternal(lib, null, instructionSet, false)) { 1438 alreadyDexOpted.add(lib); 1439 1440 // The list of "shared libraries" we have at this point is 1441 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, instructionSet); 1442 didDexOptLibraryOrTool = true; 1443 } 1444 } catch (FileNotFoundException e) { 1445 Slog.w(TAG, "Library not found: " + lib); 1446 } catch (IOException e) { 1447 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1448 + e.getMessage()); 1449 } 1450 } 1451 } 1452 } 1453 1454 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1455 1456 // Gross hack for now: we know this file doesn't contain any 1457 // code, so don't dexopt it to avoid the resulting log spew. 1458 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1459 1460 // Gross hack for now: we know this file is only part of 1461 // the boot class path for art, so don't dexopt it to 1462 // avoid the resulting log spew. 1463 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1464 1465 /** 1466 * And there are a number of commands implemented in Java, which 1467 * we currently need to do the dexopt on so that they can be 1468 * run from a non-root shell. 1469 */ 1470 String[] frameworkFiles = frameworkDir.list(); 1471 if (frameworkFiles != null) { 1472 // TODO: We could compile these only for the most preferred ABI. We should 1473 // first double check that the dex files for these commands are not referenced 1474 // by other system apps. 1475 for (String instructionSet : instructionSets) { 1476 for (int i=0; i<frameworkFiles.length; i++) { 1477 File libPath = new File(frameworkDir, frameworkFiles[i]); 1478 String path = libPath.getPath(); 1479 // Skip the file if we already did it. 1480 if (alreadyDexOpted.contains(path)) { 1481 continue; 1482 } 1483 // Skip the file if it is not a type we want to dexopt. 1484 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1485 continue; 1486 } 1487 try { 1488 if (DexFile.isDexOptNeededInternal(path, null, instructionSet, false)) { 1489 mInstaller.dexopt(path, Process.SYSTEM_UID, true, instructionSet); 1490 didDexOptLibraryOrTool = true; 1491 } 1492 } catch (FileNotFoundException e) { 1493 Slog.w(TAG, "Jar not found: " + path); 1494 } catch (IOException e) { 1495 Slog.w(TAG, "Exception reading jar: " + path, e); 1496 } 1497 } 1498 } 1499 } 1500 1501 if (didDexOptLibraryOrTool) { 1502 // If we dexopted a library or tool, then something on the system has 1503 // changed. Consider this significant, and wipe away all other 1504 // existing dexopt files to ensure we don't leave any dangling around. 1505 // 1506 // TODO: This should be revisited because it isn't as good an indicator 1507 // as it used to be. It used to include the boot classpath but at some point 1508 // DexFile.isDexOptNeeded started returning false for the boot 1509 // class path files in all cases. It is very possible in a 1510 // small maintenance release update that the library and tool 1511 // jars may be unchanged but APK could be removed resulting in 1512 // unused dalvik-cache files. 1513 for (String instructionSet : instructionSets) { 1514 mInstaller.pruneDexCache(instructionSet); 1515 } 1516 1517 // Additionally, delete all dex files from the root directory 1518 // since there shouldn't be any there anyway, unless we're upgrading 1519 // from an older OS version or a build that contained the "old" style 1520 // flat scheme. 1521 mInstaller.pruneDexCache("."); 1522 } 1523 1524 // Collect vendor overlay packages. 1525 // (Do this before scanning any apps.) 1526 // For security and version matching reason, only consider 1527 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1528 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1529 mVendorOverlayInstallObserver = new AppDirObserver( 1530 vendorOverlayDir.getPath(), OBSERVER_EVENTS, true, false); 1531 mVendorOverlayInstallObserver.startWatching(); 1532 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1533 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode | SCAN_TRUSTED_OVERLAY, 0); 1534 1535 // Find base frameworks (resource packages without code). 1536 mFrameworkInstallObserver = new AppDirObserver( 1537 frameworkDir.getPath(), OBSERVER_EVENTS, true, false); 1538 mFrameworkInstallObserver.startWatching(); 1539 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1540 | PackageParser.PARSE_IS_SYSTEM_DIR 1541 | PackageParser.PARSE_IS_PRIVILEGED, 1542 scanMode | SCAN_NO_DEX, 0); 1543 1544 // Collected privileged system packages. 1545 File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1546 mPrivilegedInstallObserver = new AppDirObserver( 1547 privilegedAppDir.getPath(), OBSERVER_EVENTS, true, true); 1548 mPrivilegedInstallObserver.startWatching(); 1549 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1550 | PackageParser.PARSE_IS_SYSTEM_DIR 1551 | PackageParser.PARSE_IS_PRIVILEGED, scanMode, 0); 1552 1553 // Collect ordinary system packages. 1554 File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1555 mSystemInstallObserver = new AppDirObserver( 1556 systemAppDir.getPath(), OBSERVER_EVENTS, true, false); 1557 mSystemInstallObserver.startWatching(); 1558 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1559 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1560 1561 // Collect all vendor packages. 1562 File vendorAppDir = new File("/vendor/app"); 1563 try { 1564 vendorAppDir = vendorAppDir.getCanonicalFile(); 1565 } catch (IOException e) { 1566 // failed to look up canonical path, continue with original one 1567 } 1568 mVendorInstallObserver = new AppDirObserver( 1569 vendorAppDir.getPath(), OBSERVER_EVENTS, true, false); 1570 mVendorInstallObserver.startWatching(); 1571 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1572 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1573 1574 // Collect all OEM packages. 1575 File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1576 mOemInstallObserver = new AppDirObserver( 1577 oemAppDir.getPath(), OBSERVER_EVENTS, true, false); 1578 mOemInstallObserver.startWatching(); 1579 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1580 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1581 1582 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1583 mInstaller.moveFiles(); 1584 1585 // Prune any system packages that no longer exist. 1586 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1587 if (!mOnlyCore) { 1588 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1589 while (psit.hasNext()) { 1590 PackageSetting ps = psit.next(); 1591 1592 /* 1593 * If this is not a system app, it can't be a 1594 * disable system app. 1595 */ 1596 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1597 continue; 1598 } 1599 1600 /* 1601 * If the package is scanned, it's not erased. 1602 */ 1603 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1604 if (scannedPkg != null) { 1605 /* 1606 * If the system app is both scanned and in the 1607 * disabled packages list, then it must have been 1608 * added via OTA. Remove it from the currently 1609 * scanned package so the previously user-installed 1610 * application can be scanned. 1611 */ 1612 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1613 Slog.i(TAG, "Expecting better updatd system app for " + ps.name 1614 + "; removing system app"); 1615 removePackageLI(ps, true); 1616 } 1617 1618 continue; 1619 } 1620 1621 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1622 psit.remove(); 1623 String msg = "System package " + ps.name 1624 + " no longer exists; wiping its data"; 1625 reportSettingsProblem(Log.WARN, msg); 1626 removeDataDirsLI(ps.name); 1627 } else { 1628 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1629 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1630 possiblyDeletedUpdatedSystemApps.add(ps.name); 1631 } 1632 } 1633 } 1634 } 1635 1636 //look for any incomplete package installations 1637 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1638 //clean up list 1639 for(int i = 0; i < deletePkgsList.size(); i++) { 1640 //clean up here 1641 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1642 } 1643 //delete tmp files 1644 deleteTempPackageFiles(); 1645 1646 // Remove any shared userIDs that have no associated packages 1647 mSettings.pruneSharedUsersLPw(); 1648 1649 if (!mOnlyCore) { 1650 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 1651 SystemClock.uptimeMillis()); 1652 mAppInstallObserver = new AppDirObserver( 1653 mAppInstallDir.getPath(), OBSERVER_EVENTS, false, false); 1654 mAppInstallObserver.startWatching(); 1655 scanDirLI(mAppInstallDir, 0, scanMode, 0); 1656 1657 mDrmAppInstallObserver = new AppDirObserver( 1658 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false, false); 1659 mDrmAppInstallObserver.startWatching(); 1660 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 1661 scanMode, 0); 1662 1663 /** 1664 * Remove disable package settings for any updated system 1665 * apps that were removed via an OTA. If they're not a 1666 * previously-updated app, remove them completely. 1667 * Otherwise, just revoke their system-level permissions. 1668 */ 1669 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 1670 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 1671 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 1672 1673 String msg; 1674 if (deletedPkg == null) { 1675 msg = "Updated system package " + deletedAppName 1676 + " no longer exists; wiping its data"; 1677 removeDataDirsLI(deletedAppName); 1678 } else { 1679 msg = "Updated system app + " + deletedAppName 1680 + " no longer present; removing system privileges for " 1681 + deletedAppName; 1682 1683 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 1684 1685 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 1686 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 1687 } 1688 reportSettingsProblem(Log.WARN, msg); 1689 } 1690 } else { 1691 mAppInstallObserver = null; 1692 mDrmAppInstallObserver = null; 1693 } 1694 1695 // Now that we know all of the shared libraries, update all clients to have 1696 // the correct library paths. 1697 updateAllSharedLibrariesLPw(); 1698 1699 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 1700 // NOTE: We ignore potential failures here during a system scan (like 1701 // the rest of the commands above) because there's precious little we 1702 // can do about it. A settings error is reported, though. 1703 adjustCpuAbisForSharedUserLPw(setting.packages, null, 1704 false /* force dexopt */, false /* defer dexopt */); 1705 } 1706 1707 // Now that we know all the packages we are keeping, 1708 // read and update their last usage times. 1709 mPackageUsage.readLP(); 1710 1711 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 1712 SystemClock.uptimeMillis()); 1713 Slog.i(TAG, "Time to scan packages: " 1714 + ((SystemClock.uptimeMillis()-startTime)/1000f) 1715 + " seconds"); 1716 1717 // If the platform SDK has changed since the last time we booted, 1718 // we need to re-grant app permission to catch any new ones that 1719 // appear. This is really a hack, and means that apps can in some 1720 // cases get permissions that the user didn't initially explicitly 1721 // allow... it would be nice to have some better way to handle 1722 // this situation. 1723 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 1724 != mSdkVersion; 1725 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 1726 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 1727 + "; regranting permissions for internal storage"); 1728 mSettings.mInternalSdkPlatform = mSdkVersion; 1729 1730 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 1731 | (regrantPermissions 1732 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 1733 : 0)); 1734 1735 // If this is the first boot, and it is a normal boot, then 1736 // we need to initialize the default preferred apps. 1737 if (!mRestoredSettings && !onlyCore) { 1738 mSettings.readDefaultPreferredAppsLPw(this, 0); 1739 } 1740 1741 // All the changes are done during package scanning. 1742 mSettings.updateInternalDatabaseVersion(); 1743 1744 // can downgrade to reader 1745 mSettings.writeLPr(); 1746 1747 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 1748 SystemClock.uptimeMillis()); 1749 1750 1751 mRequiredVerifierPackage = getRequiredVerifierLPr(); 1752 } // synchronized (mPackages) 1753 } // synchronized (mInstallLock) 1754 1755 mInstallerService = new PackageInstallerService(context, this, mAppInstallDir); 1756 1757 // Now after opening every single application zip, make sure they 1758 // are all flushed. Not really needed, but keeps things nice and 1759 // tidy. 1760 Runtime.getRuntime().gc(); 1761 } 1762 1763 @Override 1764 public boolean isFirstBoot() { 1765 return !mRestoredSettings; 1766 } 1767 1768 @Override 1769 public boolean isOnlyCoreApps() { 1770 return mOnlyCore; 1771 } 1772 1773 private String getRequiredVerifierLPr() { 1774 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 1775 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 1776 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 1777 1778 String requiredVerifier = null; 1779 1780 final int N = receivers.size(); 1781 for (int i = 0; i < N; i++) { 1782 final ResolveInfo info = receivers.get(i); 1783 1784 if (info.activityInfo == null) { 1785 continue; 1786 } 1787 1788 final String packageName = info.activityInfo.packageName; 1789 1790 final PackageSetting ps = mSettings.mPackages.get(packageName); 1791 if (ps == null) { 1792 continue; 1793 } 1794 1795 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1796 if (!gp.grantedPermissions 1797 .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) { 1798 continue; 1799 } 1800 1801 if (requiredVerifier != null) { 1802 throw new RuntimeException("There can be only one required verifier"); 1803 } 1804 1805 requiredVerifier = packageName; 1806 } 1807 1808 return requiredVerifier; 1809 } 1810 1811 @Override 1812 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 1813 throws RemoteException { 1814 try { 1815 return super.onTransact(code, data, reply, flags); 1816 } catch (RuntimeException e) { 1817 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 1818 Slog.wtf(TAG, "Package Manager Crash", e); 1819 } 1820 throw e; 1821 } 1822 } 1823 1824 void cleanupInstallFailedPackage(PackageSetting ps) { 1825 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name); 1826 removeDataDirsLI(ps.name); 1827 1828 // TODO: try cleaning up codePath directory contents first, since it 1829 // might be a cluster 1830 1831 if (ps.codePath != null) { 1832 if (!ps.codePath.delete()) { 1833 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath); 1834 } 1835 } 1836 if (ps.resourcePath != null) { 1837 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) { 1838 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath); 1839 } 1840 } 1841 mSettings.removePackageLPw(ps.name); 1842 } 1843 1844 static int[] appendInts(int[] cur, int[] add) { 1845 if (add == null) return cur; 1846 if (cur == null) return add; 1847 final int N = add.length; 1848 for (int i=0; i<N; i++) { 1849 cur = appendInt(cur, add[i]); 1850 } 1851 return cur; 1852 } 1853 1854 static int[] removeInts(int[] cur, int[] rem) { 1855 if (rem == null) return cur; 1856 if (cur == null) return cur; 1857 final int N = rem.length; 1858 for (int i=0; i<N; i++) { 1859 cur = removeInt(cur, rem[i]); 1860 } 1861 return cur; 1862 } 1863 1864 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 1865 if (!sUserManager.exists(userId)) return null; 1866 final PackageSetting ps = (PackageSetting) p.mExtras; 1867 if (ps == null) { 1868 return null; 1869 } 1870 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1871 final PackageUserState state = ps.readUserState(userId); 1872 return PackageParser.generatePackageInfo(p, gp.gids, flags, 1873 ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions, 1874 state, userId); 1875 } 1876 1877 @Override 1878 public boolean isPackageAvailable(String packageName, int userId) { 1879 if (!sUserManager.exists(userId)) return false; 1880 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available"); 1881 synchronized (mPackages) { 1882 PackageParser.Package p = mPackages.get(packageName); 1883 if (p != null) { 1884 final PackageSetting ps = (PackageSetting) p.mExtras; 1885 if (ps != null) { 1886 final PackageUserState state = ps.readUserState(userId); 1887 if (state != null) { 1888 return PackageParser.isAvailable(state); 1889 } 1890 } 1891 } 1892 } 1893 return false; 1894 } 1895 1896 @Override 1897 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 1898 if (!sUserManager.exists(userId)) return null; 1899 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info"); 1900 // reader 1901 synchronized (mPackages) { 1902 PackageParser.Package p = mPackages.get(packageName); 1903 if (DEBUG_PACKAGE_INFO) 1904 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 1905 if (p != null) { 1906 return generatePackageInfo(p, flags, userId); 1907 } 1908 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 1909 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 1910 } 1911 } 1912 return null; 1913 } 1914 1915 @Override 1916 public String[] currentToCanonicalPackageNames(String[] names) { 1917 String[] out = new String[names.length]; 1918 // reader 1919 synchronized (mPackages) { 1920 for (int i=names.length-1; i>=0; i--) { 1921 PackageSetting ps = mSettings.mPackages.get(names[i]); 1922 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 1923 } 1924 } 1925 return out; 1926 } 1927 1928 @Override 1929 public String[] canonicalToCurrentPackageNames(String[] names) { 1930 String[] out = new String[names.length]; 1931 // reader 1932 synchronized (mPackages) { 1933 for (int i=names.length-1; i>=0; i--) { 1934 String cur = mSettings.mRenamedPackages.get(names[i]); 1935 out[i] = cur != null ? cur : names[i]; 1936 } 1937 } 1938 return out; 1939 } 1940 1941 @Override 1942 public int getPackageUid(String packageName, int userId) { 1943 if (!sUserManager.exists(userId)) return -1; 1944 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid"); 1945 // reader 1946 synchronized (mPackages) { 1947 PackageParser.Package p = mPackages.get(packageName); 1948 if(p != null) { 1949 return UserHandle.getUid(userId, p.applicationInfo.uid); 1950 } 1951 PackageSetting ps = mSettings.mPackages.get(packageName); 1952 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 1953 return -1; 1954 } 1955 p = ps.pkg; 1956 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 1957 } 1958 } 1959 1960 @Override 1961 public int[] getPackageGids(String packageName) { 1962 // reader 1963 synchronized (mPackages) { 1964 PackageParser.Package p = mPackages.get(packageName); 1965 if (DEBUG_PACKAGE_INFO) 1966 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 1967 if (p != null) { 1968 final PackageSetting ps = (PackageSetting)p.mExtras; 1969 return ps.getGids(); 1970 } 1971 } 1972 // stupid thing to indicate an error. 1973 return new int[0]; 1974 } 1975 1976 static final PermissionInfo generatePermissionInfo( 1977 BasePermission bp, int flags) { 1978 if (bp.perm != null) { 1979 return PackageParser.generatePermissionInfo(bp.perm, flags); 1980 } 1981 PermissionInfo pi = new PermissionInfo(); 1982 pi.name = bp.name; 1983 pi.packageName = bp.sourcePackage; 1984 pi.nonLocalizedLabel = bp.name; 1985 pi.protectionLevel = bp.protectionLevel; 1986 return pi; 1987 } 1988 1989 @Override 1990 public PermissionInfo getPermissionInfo(String name, int flags) { 1991 // reader 1992 synchronized (mPackages) { 1993 final BasePermission p = mSettings.mPermissions.get(name); 1994 if (p != null) { 1995 return generatePermissionInfo(p, flags); 1996 } 1997 return null; 1998 } 1999 } 2000 2001 @Override 2002 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2003 // reader 2004 synchronized (mPackages) { 2005 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2006 for (BasePermission p : mSettings.mPermissions.values()) { 2007 if (group == null) { 2008 if (p.perm == null || p.perm.info.group == null) { 2009 out.add(generatePermissionInfo(p, flags)); 2010 } 2011 } else { 2012 if (p.perm != null && group.equals(p.perm.info.group)) { 2013 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2014 } 2015 } 2016 } 2017 2018 if (out.size() > 0) { 2019 return out; 2020 } 2021 return mPermissionGroups.containsKey(group) ? out : null; 2022 } 2023 } 2024 2025 @Override 2026 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2027 // reader 2028 synchronized (mPackages) { 2029 return PackageParser.generatePermissionGroupInfo( 2030 mPermissionGroups.get(name), flags); 2031 } 2032 } 2033 2034 @Override 2035 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2036 // reader 2037 synchronized (mPackages) { 2038 final int N = mPermissionGroups.size(); 2039 ArrayList<PermissionGroupInfo> out 2040 = new ArrayList<PermissionGroupInfo>(N); 2041 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2042 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2043 } 2044 return out; 2045 } 2046 } 2047 2048 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2049 int userId) { 2050 if (!sUserManager.exists(userId)) return null; 2051 PackageSetting ps = mSettings.mPackages.get(packageName); 2052 if (ps != null) { 2053 if (ps.pkg == null) { 2054 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2055 flags, userId); 2056 if (pInfo != null) { 2057 return pInfo.applicationInfo; 2058 } 2059 return null; 2060 } 2061 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2062 ps.readUserState(userId), userId); 2063 } 2064 return null; 2065 } 2066 2067 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2068 int userId) { 2069 if (!sUserManager.exists(userId)) return null; 2070 PackageSetting ps = mSettings.mPackages.get(packageName); 2071 if (ps != null) { 2072 PackageParser.Package pkg = ps.pkg; 2073 if (pkg == null) { 2074 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2075 return null; 2076 } 2077 // Only data remains, so we aren't worried about code paths 2078 pkg = new PackageParser.Package(packageName); 2079 pkg.applicationInfo.packageName = packageName; 2080 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2081 pkg.applicationInfo.dataDir = 2082 getDataPathForPackage(packageName, 0).getPath(); 2083 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2084 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2085 } 2086 return generatePackageInfo(pkg, flags, userId); 2087 } 2088 return null; 2089 } 2090 2091 @Override 2092 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2093 if (!sUserManager.exists(userId)) return null; 2094 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info"); 2095 // writer 2096 synchronized (mPackages) { 2097 PackageParser.Package p = mPackages.get(packageName); 2098 if (DEBUG_PACKAGE_INFO) Log.v( 2099 TAG, "getApplicationInfo " + packageName 2100 + ": " + p); 2101 if (p != null) { 2102 PackageSetting ps = mSettings.mPackages.get(packageName); 2103 if (ps == null) return null; 2104 // Note: isEnabledLP() does not apply here - always return info 2105 return PackageParser.generateApplicationInfo( 2106 p, flags, ps.readUserState(userId), userId); 2107 } 2108 if ("android".equals(packageName)||"system".equals(packageName)) { 2109 return mAndroidApplication; 2110 } 2111 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2112 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2113 } 2114 } 2115 return null; 2116 } 2117 2118 2119 @Override 2120 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2121 mContext.enforceCallingOrSelfPermission( 2122 android.Manifest.permission.CLEAR_APP_CACHE, null); 2123 // Queue up an async operation since clearing cache may take a little while. 2124 mHandler.post(new Runnable() { 2125 public void run() { 2126 mHandler.removeCallbacks(this); 2127 int retCode = -1; 2128 synchronized (mInstallLock) { 2129 retCode = mInstaller.freeCache(freeStorageSize); 2130 if (retCode < 0) { 2131 Slog.w(TAG, "Couldn't clear application caches"); 2132 } 2133 } 2134 if (observer != null) { 2135 try { 2136 observer.onRemoveCompleted(null, (retCode >= 0)); 2137 } catch (RemoteException e) { 2138 Slog.w(TAG, "RemoveException when invoking call back"); 2139 } 2140 } 2141 } 2142 }); 2143 } 2144 2145 @Override 2146 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2147 mContext.enforceCallingOrSelfPermission( 2148 android.Manifest.permission.CLEAR_APP_CACHE, null); 2149 // Queue up an async operation since clearing cache may take a little while. 2150 mHandler.post(new Runnable() { 2151 public void run() { 2152 mHandler.removeCallbacks(this); 2153 int retCode = -1; 2154 synchronized (mInstallLock) { 2155 retCode = mInstaller.freeCache(freeStorageSize); 2156 if (retCode < 0) { 2157 Slog.w(TAG, "Couldn't clear application caches"); 2158 } 2159 } 2160 if(pi != null) { 2161 try { 2162 // Callback via pending intent 2163 int code = (retCode >= 0) ? 1 : 0; 2164 pi.sendIntent(null, code, null, 2165 null, null); 2166 } catch (SendIntentException e1) { 2167 Slog.i(TAG, "Failed to send pending intent"); 2168 } 2169 } 2170 } 2171 }); 2172 } 2173 2174 void freeStorage(long freeStorageSize) throws IOException { 2175 synchronized (mInstallLock) { 2176 if (mInstaller.freeCache(freeStorageSize) < 0) { 2177 throw new IOException("Failed to free enough space"); 2178 } 2179 } 2180 } 2181 2182 @Override 2183 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2184 if (!sUserManager.exists(userId)) return null; 2185 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info"); 2186 synchronized (mPackages) { 2187 PackageParser.Activity a = mActivities.mActivities.get(component); 2188 2189 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2190 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2191 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2192 if (ps == null) return null; 2193 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2194 userId); 2195 } 2196 if (mResolveComponentName.equals(component)) { 2197 return mResolveActivity; 2198 } 2199 } 2200 return null; 2201 } 2202 2203 @Override 2204 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2205 String resolvedType) { 2206 synchronized (mPackages) { 2207 PackageParser.Activity a = mActivities.mActivities.get(component); 2208 if (a == null) { 2209 return false; 2210 } 2211 for (int i=0; i<a.intents.size(); i++) { 2212 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2213 intent.getData(), intent.getCategories(), TAG) >= 0) { 2214 return true; 2215 } 2216 } 2217 return false; 2218 } 2219 } 2220 2221 @Override 2222 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2223 if (!sUserManager.exists(userId)) return null; 2224 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info"); 2225 synchronized (mPackages) { 2226 PackageParser.Activity a = mReceivers.mActivities.get(component); 2227 if (DEBUG_PACKAGE_INFO) Log.v( 2228 TAG, "getReceiverInfo " + component + ": " + a); 2229 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2230 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2231 if (ps == null) return null; 2232 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2233 userId); 2234 } 2235 } 2236 return null; 2237 } 2238 2239 @Override 2240 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2241 if (!sUserManager.exists(userId)) return null; 2242 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info"); 2243 synchronized (mPackages) { 2244 PackageParser.Service s = mServices.mServices.get(component); 2245 if (DEBUG_PACKAGE_INFO) Log.v( 2246 TAG, "getServiceInfo " + component + ": " + s); 2247 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2248 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2249 if (ps == null) return null; 2250 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2251 userId); 2252 } 2253 } 2254 return null; 2255 } 2256 2257 @Override 2258 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2259 if (!sUserManager.exists(userId)) return null; 2260 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info"); 2261 synchronized (mPackages) { 2262 PackageParser.Provider p = mProviders.mProviders.get(component); 2263 if (DEBUG_PACKAGE_INFO) Log.v( 2264 TAG, "getProviderInfo " + component + ": " + p); 2265 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2266 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2267 if (ps == null) return null; 2268 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2269 userId); 2270 } 2271 } 2272 return null; 2273 } 2274 2275 @Override 2276 public String[] getSystemSharedLibraryNames() { 2277 Set<String> libSet; 2278 synchronized (mPackages) { 2279 libSet = mSharedLibraries.keySet(); 2280 int size = libSet.size(); 2281 if (size > 0) { 2282 String[] libs = new String[size]; 2283 libSet.toArray(libs); 2284 return libs; 2285 } 2286 } 2287 return null; 2288 } 2289 2290 @Override 2291 public FeatureInfo[] getSystemAvailableFeatures() { 2292 Collection<FeatureInfo> featSet; 2293 synchronized (mPackages) { 2294 featSet = mAvailableFeatures.values(); 2295 int size = featSet.size(); 2296 if (size > 0) { 2297 FeatureInfo[] features = new FeatureInfo[size+1]; 2298 featSet.toArray(features); 2299 FeatureInfo fi = new FeatureInfo(); 2300 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2301 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2302 features[size] = fi; 2303 return features; 2304 } 2305 } 2306 return null; 2307 } 2308 2309 @Override 2310 public boolean hasSystemFeature(String name) { 2311 synchronized (mPackages) { 2312 return mAvailableFeatures.containsKey(name); 2313 } 2314 } 2315 2316 private void checkValidCaller(int uid, int userId) { 2317 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2318 return; 2319 2320 throw new SecurityException("Caller uid=" + uid 2321 + " is not privileged to communicate with user=" + userId); 2322 } 2323 2324 @Override 2325 public int checkPermission(String permName, String pkgName) { 2326 synchronized (mPackages) { 2327 PackageParser.Package p = mPackages.get(pkgName); 2328 if (p != null && p.mExtras != null) { 2329 PackageSetting ps = (PackageSetting)p.mExtras; 2330 if (ps.sharedUser != null) { 2331 if (ps.sharedUser.grantedPermissions.contains(permName)) { 2332 return PackageManager.PERMISSION_GRANTED; 2333 } 2334 } else if (ps.grantedPermissions.contains(permName)) { 2335 return PackageManager.PERMISSION_GRANTED; 2336 } 2337 } 2338 } 2339 return PackageManager.PERMISSION_DENIED; 2340 } 2341 2342 @Override 2343 public int checkUidPermission(String permName, int uid) { 2344 synchronized (mPackages) { 2345 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2346 if (obj != null) { 2347 GrantedPermissions gp = (GrantedPermissions)obj; 2348 if (gp.grantedPermissions.contains(permName)) { 2349 return PackageManager.PERMISSION_GRANTED; 2350 } 2351 } else { 2352 HashSet<String> perms = mSystemPermissions.get(uid); 2353 if (perms != null && perms.contains(permName)) { 2354 return PackageManager.PERMISSION_GRANTED; 2355 } 2356 } 2357 } 2358 return PackageManager.PERMISSION_DENIED; 2359 } 2360 2361 /** 2362 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2363 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2364 * @param message the message to log on security exception 2365 */ 2366 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2367 String message) { 2368 if (userId < 0) { 2369 throw new IllegalArgumentException("Invalid userId " + userId); 2370 } 2371 if (userId == UserHandle.getUserId(callingUid)) return; 2372 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2373 if (requireFullPermission) { 2374 mContext.enforceCallingOrSelfPermission( 2375 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2376 } else { 2377 try { 2378 mContext.enforceCallingOrSelfPermission( 2379 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2380 } catch (SecurityException se) { 2381 mContext.enforceCallingOrSelfPermission( 2382 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2383 } 2384 } 2385 } 2386 } 2387 2388 private BasePermission findPermissionTreeLP(String permName) { 2389 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2390 if (permName.startsWith(bp.name) && 2391 permName.length() > bp.name.length() && 2392 permName.charAt(bp.name.length()) == '.') { 2393 return bp; 2394 } 2395 } 2396 return null; 2397 } 2398 2399 private BasePermission checkPermissionTreeLP(String permName) { 2400 if (permName != null) { 2401 BasePermission bp = findPermissionTreeLP(permName); 2402 if (bp != null) { 2403 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2404 return bp; 2405 } 2406 throw new SecurityException("Calling uid " 2407 + Binder.getCallingUid() 2408 + " is not allowed to add to permission tree " 2409 + bp.name + " owned by uid " + bp.uid); 2410 } 2411 } 2412 throw new SecurityException("No permission tree found for " + permName); 2413 } 2414 2415 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2416 if (s1 == null) { 2417 return s2 == null; 2418 } 2419 if (s2 == null) { 2420 return false; 2421 } 2422 if (s1.getClass() != s2.getClass()) { 2423 return false; 2424 } 2425 return s1.equals(s2); 2426 } 2427 2428 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2429 if (pi1.icon != pi2.icon) return false; 2430 if (pi1.logo != pi2.logo) return false; 2431 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2432 if (!compareStrings(pi1.name, pi2.name)) return false; 2433 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2434 // We'll take care of setting this one. 2435 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2436 // These are not currently stored in settings. 2437 //if (!compareStrings(pi1.group, pi2.group)) return false; 2438 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2439 //if (pi1.labelRes != pi2.labelRes) return false; 2440 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2441 return true; 2442 } 2443 2444 int permissionInfoFootprint(PermissionInfo info) { 2445 int size = info.name.length(); 2446 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2447 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2448 return size; 2449 } 2450 2451 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2452 int size = 0; 2453 for (BasePermission perm : mSettings.mPermissions.values()) { 2454 if (perm.uid == tree.uid) { 2455 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2456 } 2457 } 2458 return size; 2459 } 2460 2461 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2462 // We calculate the max size of permissions defined by this uid and throw 2463 // if that plus the size of 'info' would exceed our stated maximum. 2464 if (tree.uid != Process.SYSTEM_UID) { 2465 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2466 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2467 throw new SecurityException("Permission tree size cap exceeded"); 2468 } 2469 } 2470 } 2471 2472 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2473 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2474 throw new SecurityException("Label must be specified in permission"); 2475 } 2476 BasePermission tree = checkPermissionTreeLP(info.name); 2477 BasePermission bp = mSettings.mPermissions.get(info.name); 2478 boolean added = bp == null; 2479 boolean changed = true; 2480 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2481 if (added) { 2482 enforcePermissionCapLocked(info, tree); 2483 bp = new BasePermission(info.name, tree.sourcePackage, 2484 BasePermission.TYPE_DYNAMIC); 2485 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2486 throw new SecurityException( 2487 "Not allowed to modify non-dynamic permission " 2488 + info.name); 2489 } else { 2490 if (bp.protectionLevel == fixedLevel 2491 && bp.perm.owner.equals(tree.perm.owner) 2492 && bp.uid == tree.uid 2493 && comparePermissionInfos(bp.perm.info, info)) { 2494 changed = false; 2495 } 2496 } 2497 bp.protectionLevel = fixedLevel; 2498 info = new PermissionInfo(info); 2499 info.protectionLevel = fixedLevel; 2500 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 2501 bp.perm.info.packageName = tree.perm.info.packageName; 2502 bp.uid = tree.uid; 2503 if (added) { 2504 mSettings.mPermissions.put(info.name, bp); 2505 } 2506 if (changed) { 2507 if (!async) { 2508 mSettings.writeLPr(); 2509 } else { 2510 scheduleWriteSettingsLocked(); 2511 } 2512 } 2513 return added; 2514 } 2515 2516 @Override 2517 public boolean addPermission(PermissionInfo info) { 2518 synchronized (mPackages) { 2519 return addPermissionLocked(info, false); 2520 } 2521 } 2522 2523 @Override 2524 public boolean addPermissionAsync(PermissionInfo info) { 2525 synchronized (mPackages) { 2526 return addPermissionLocked(info, true); 2527 } 2528 } 2529 2530 @Override 2531 public void removePermission(String name) { 2532 synchronized (mPackages) { 2533 checkPermissionTreeLP(name); 2534 BasePermission bp = mSettings.mPermissions.get(name); 2535 if (bp != null) { 2536 if (bp.type != BasePermission.TYPE_DYNAMIC) { 2537 throw new SecurityException( 2538 "Not allowed to modify non-dynamic permission " 2539 + name); 2540 } 2541 mSettings.mPermissions.remove(name); 2542 mSettings.writeLPr(); 2543 } 2544 } 2545 } 2546 2547 private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) { 2548 int index = pkg.requestedPermissions.indexOf(bp.name); 2549 if (index == -1) { 2550 throw new SecurityException("Package " + pkg.packageName 2551 + " has not requested permission " + bp.name); 2552 } 2553 boolean isNormal = 2554 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2555 == PermissionInfo.PROTECTION_NORMAL); 2556 boolean isDangerous = 2557 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2558 == PermissionInfo.PROTECTION_DANGEROUS); 2559 boolean isDevelopment = 2560 ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0); 2561 2562 if (!isNormal && !isDangerous && !isDevelopment) { 2563 throw new SecurityException("Permission " + bp.name 2564 + " is not a changeable permission type"); 2565 } 2566 2567 if (isNormal || isDangerous) { 2568 if (pkg.requestedPermissionsRequired.get(index)) { 2569 throw new SecurityException("Can't change " + bp.name 2570 + ". It is required by the application"); 2571 } 2572 } 2573 } 2574 2575 @Override 2576 public void grantPermission(String packageName, String permissionName) { 2577 mContext.enforceCallingOrSelfPermission( 2578 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2579 synchronized (mPackages) { 2580 final PackageParser.Package pkg = mPackages.get(packageName); 2581 if (pkg == null) { 2582 throw new IllegalArgumentException("Unknown package: " + packageName); 2583 } 2584 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2585 if (bp == null) { 2586 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2587 } 2588 2589 checkGrantRevokePermissions(pkg, bp); 2590 2591 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2592 if (ps == null) { 2593 return; 2594 } 2595 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2596 if (gp.grantedPermissions.add(permissionName)) { 2597 if (ps.haveGids) { 2598 gp.gids = appendInts(gp.gids, bp.gids); 2599 } 2600 mSettings.writeLPr(); 2601 } 2602 } 2603 } 2604 2605 @Override 2606 public void revokePermission(String packageName, String permissionName) { 2607 int changedAppId = -1; 2608 2609 synchronized (mPackages) { 2610 final PackageParser.Package pkg = mPackages.get(packageName); 2611 if (pkg == null) { 2612 throw new IllegalArgumentException("Unknown package: " + packageName); 2613 } 2614 if (pkg.applicationInfo.uid != Binder.getCallingUid()) { 2615 mContext.enforceCallingOrSelfPermission( 2616 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2617 } 2618 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2619 if (bp == null) { 2620 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2621 } 2622 2623 checkGrantRevokePermissions(pkg, bp); 2624 2625 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2626 if (ps == null) { 2627 return; 2628 } 2629 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2630 if (gp.grantedPermissions.remove(permissionName)) { 2631 gp.grantedPermissions.remove(permissionName); 2632 if (ps.haveGids) { 2633 gp.gids = removeInts(gp.gids, bp.gids); 2634 } 2635 mSettings.writeLPr(); 2636 changedAppId = ps.appId; 2637 } 2638 } 2639 2640 if (changedAppId >= 0) { 2641 // We changed the perm on someone, kill its processes. 2642 IActivityManager am = ActivityManagerNative.getDefault(); 2643 if (am != null) { 2644 final int callingUserId = UserHandle.getCallingUserId(); 2645 final long ident = Binder.clearCallingIdentity(); 2646 try { 2647 //XXX we should only revoke for the calling user's app permissions, 2648 // but for now we impact all users. 2649 //am.killUid(UserHandle.getUid(callingUserId, changedAppId), 2650 // "revoke " + permissionName); 2651 int[] users = sUserManager.getUserIds(); 2652 for (int user : users) { 2653 am.killUid(UserHandle.getUid(user, changedAppId), 2654 "revoke " + permissionName); 2655 } 2656 } catch (RemoteException e) { 2657 } finally { 2658 Binder.restoreCallingIdentity(ident); 2659 } 2660 } 2661 } 2662 } 2663 2664 @Override 2665 public boolean isProtectedBroadcast(String actionName) { 2666 synchronized (mPackages) { 2667 return mProtectedBroadcasts.contains(actionName); 2668 } 2669 } 2670 2671 @Override 2672 public int checkSignatures(String pkg1, String pkg2) { 2673 synchronized (mPackages) { 2674 final PackageParser.Package p1 = mPackages.get(pkg1); 2675 final PackageParser.Package p2 = mPackages.get(pkg2); 2676 if (p1 == null || p1.mExtras == null 2677 || p2 == null || p2.mExtras == null) { 2678 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2679 } 2680 return compareSignatures(p1.mSignatures, p2.mSignatures); 2681 } 2682 } 2683 2684 @Override 2685 public int checkUidSignatures(int uid1, int uid2) { 2686 // Map to base uids. 2687 uid1 = UserHandle.getAppId(uid1); 2688 uid2 = UserHandle.getAppId(uid2); 2689 // reader 2690 synchronized (mPackages) { 2691 Signature[] s1; 2692 Signature[] s2; 2693 Object obj = mSettings.getUserIdLPr(uid1); 2694 if (obj != null) { 2695 if (obj instanceof SharedUserSetting) { 2696 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 2697 } else if (obj instanceof PackageSetting) { 2698 s1 = ((PackageSetting)obj).signatures.mSignatures; 2699 } else { 2700 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2701 } 2702 } else { 2703 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2704 } 2705 obj = mSettings.getUserIdLPr(uid2); 2706 if (obj != null) { 2707 if (obj instanceof SharedUserSetting) { 2708 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 2709 } else if (obj instanceof PackageSetting) { 2710 s2 = ((PackageSetting)obj).signatures.mSignatures; 2711 } else { 2712 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2713 } 2714 } else { 2715 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2716 } 2717 return compareSignatures(s1, s2); 2718 } 2719 } 2720 2721 /** 2722 * Compares two sets of signatures. Returns: 2723 * <br /> 2724 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 2725 * <br /> 2726 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 2727 * <br /> 2728 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 2729 * <br /> 2730 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 2731 * <br /> 2732 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 2733 */ 2734 static int compareSignatures(Signature[] s1, Signature[] s2) { 2735 if (s1 == null) { 2736 return s2 == null 2737 ? PackageManager.SIGNATURE_NEITHER_SIGNED 2738 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 2739 } 2740 2741 if (s2 == null) { 2742 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 2743 } 2744 2745 if (s1.length != s2.length) { 2746 return PackageManager.SIGNATURE_NO_MATCH; 2747 } 2748 2749 // Since both signature sets are of size 1, we can compare without HashSets. 2750 if (s1.length == 1) { 2751 return s1[0].equals(s2[0]) ? 2752 PackageManager.SIGNATURE_MATCH : 2753 PackageManager.SIGNATURE_NO_MATCH; 2754 } 2755 2756 HashSet<Signature> set1 = new HashSet<Signature>(); 2757 for (Signature sig : s1) { 2758 set1.add(sig); 2759 } 2760 HashSet<Signature> set2 = new HashSet<Signature>(); 2761 for (Signature sig : s2) { 2762 set2.add(sig); 2763 } 2764 // Make sure s2 contains all signatures in s1. 2765 if (set1.equals(set2)) { 2766 return PackageManager.SIGNATURE_MATCH; 2767 } 2768 return PackageManager.SIGNATURE_NO_MATCH; 2769 } 2770 2771 /** 2772 * If the database version for this type of package (internal storage or 2773 * external storage) is less than the version where package signatures 2774 * were updated, return true. 2775 */ 2776 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2777 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 2778 DatabaseVersion.SIGNATURE_END_ENTITY)) 2779 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 2780 DatabaseVersion.SIGNATURE_END_ENTITY)); 2781 } 2782 2783 /** 2784 * Used for backward compatibility to make sure any packages with 2785 * certificate chains get upgraded to the new style. {@code existingSigs} 2786 * will be in the old format (since they were stored on disk from before the 2787 * system upgrade) and {@code scannedSigs} will be in the newer format. 2788 */ 2789 private int compareSignaturesCompat(PackageSignatures existingSigs, 2790 PackageParser.Package scannedPkg) { 2791 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 2792 return PackageManager.SIGNATURE_NO_MATCH; 2793 } 2794 2795 HashSet<Signature> existingSet = new HashSet<Signature>(); 2796 for (Signature sig : existingSigs.mSignatures) { 2797 existingSet.add(sig); 2798 } 2799 HashSet<Signature> scannedCompatSet = new HashSet<Signature>(); 2800 for (Signature sig : scannedPkg.mSignatures) { 2801 try { 2802 Signature[] chainSignatures = sig.getChainSignatures(); 2803 for (Signature chainSig : chainSignatures) { 2804 scannedCompatSet.add(chainSig); 2805 } 2806 } catch (CertificateEncodingException e) { 2807 scannedCompatSet.add(sig); 2808 } 2809 } 2810 /* 2811 * Make sure the expanded scanned set contains all signatures in the 2812 * existing one. 2813 */ 2814 if (scannedCompatSet.equals(existingSet)) { 2815 // Migrate the old signatures to the new scheme. 2816 existingSigs.assignSignatures(scannedPkg.mSignatures); 2817 // The new KeySets will be re-added later in the scanning process. 2818 mSettings.mKeySetManagerService.removeAppKeySetData(scannedPkg.packageName); 2819 return PackageManager.SIGNATURE_MATCH; 2820 } 2821 return PackageManager.SIGNATURE_NO_MATCH; 2822 } 2823 2824 @Override 2825 public String[] getPackagesForUid(int uid) { 2826 uid = UserHandle.getAppId(uid); 2827 // reader 2828 synchronized (mPackages) { 2829 Object obj = mSettings.getUserIdLPr(uid); 2830 if (obj instanceof SharedUserSetting) { 2831 final SharedUserSetting sus = (SharedUserSetting) obj; 2832 final int N = sus.packages.size(); 2833 final String[] res = new String[N]; 2834 final Iterator<PackageSetting> it = sus.packages.iterator(); 2835 int i = 0; 2836 while (it.hasNext()) { 2837 res[i++] = it.next().name; 2838 } 2839 return res; 2840 } else if (obj instanceof PackageSetting) { 2841 final PackageSetting ps = (PackageSetting) obj; 2842 return new String[] { ps.name }; 2843 } 2844 } 2845 return null; 2846 } 2847 2848 @Override 2849 public String getNameForUid(int uid) { 2850 // reader 2851 synchronized (mPackages) { 2852 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2853 if (obj instanceof SharedUserSetting) { 2854 final SharedUserSetting sus = (SharedUserSetting) obj; 2855 return sus.name + ":" + sus.userId; 2856 } else if (obj instanceof PackageSetting) { 2857 final PackageSetting ps = (PackageSetting) obj; 2858 return ps.name; 2859 } 2860 } 2861 return null; 2862 } 2863 2864 @Override 2865 public int getUidForSharedUser(String sharedUserName) { 2866 if(sharedUserName == null) { 2867 return -1; 2868 } 2869 // reader 2870 synchronized (mPackages) { 2871 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false); 2872 if (suid == null) { 2873 return -1; 2874 } 2875 return suid.userId; 2876 } 2877 } 2878 2879 @Override 2880 public int getFlagsForUid(int uid) { 2881 synchronized (mPackages) { 2882 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2883 if (obj instanceof SharedUserSetting) { 2884 final SharedUserSetting sus = (SharedUserSetting) obj; 2885 return sus.pkgFlags; 2886 } else if (obj instanceof PackageSetting) { 2887 final PackageSetting ps = (PackageSetting) obj; 2888 return ps.pkgFlags; 2889 } 2890 } 2891 return 0; 2892 } 2893 2894 @Override 2895 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 2896 int flags, int userId) { 2897 if (!sUserManager.exists(userId)) return null; 2898 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent"); 2899 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2900 return chooseBestActivity(intent, resolvedType, flags, query, userId); 2901 } 2902 2903 @Override 2904 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 2905 IntentFilter filter, int match, ComponentName activity) { 2906 final int userId = UserHandle.getCallingUserId(); 2907 if (DEBUG_PREFERRED) { 2908 Log.v(TAG, "setLastChosenActivity intent=" + intent 2909 + " resolvedType=" + resolvedType 2910 + " flags=" + flags 2911 + " filter=" + filter 2912 + " match=" + match 2913 + " activity=" + activity); 2914 filter.dump(new PrintStreamPrinter(System.out), " "); 2915 } 2916 intent.setComponent(null); 2917 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2918 // Find any earlier preferred or last chosen entries and nuke them 2919 findPreferredActivity(intent, resolvedType, 2920 flags, query, 0, false, true, false, userId); 2921 // Add the new activity as the last chosen for this filter 2922 addPreferredActivityInternal(filter, match, null, activity, false, userId); 2923 } 2924 2925 @Override 2926 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 2927 final int userId = UserHandle.getCallingUserId(); 2928 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 2929 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2930 return findPreferredActivity(intent, resolvedType, flags, query, 0, 2931 false, false, false, userId); 2932 } 2933 2934 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 2935 int flags, List<ResolveInfo> query, int userId) { 2936 if (query != null) { 2937 final int N = query.size(); 2938 if (N == 1) { 2939 return query.get(0); 2940 } else if (N > 1) { 2941 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 2942 // If there is more than one activity with the same priority, 2943 // then let the user decide between them. 2944 ResolveInfo r0 = query.get(0); 2945 ResolveInfo r1 = query.get(1); 2946 if (DEBUG_INTENT_MATCHING || debug) { 2947 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 2948 + r1.activityInfo.name + "=" + r1.priority); 2949 } 2950 // If the first activity has a higher priority, or a different 2951 // default, then it is always desireable to pick it. 2952 if (r0.priority != r1.priority 2953 || r0.preferredOrder != r1.preferredOrder 2954 || r0.isDefault != r1.isDefault) { 2955 return query.get(0); 2956 } 2957 // If we have saved a preference for a preferred activity for 2958 // this Intent, use that. 2959 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 2960 flags, query, r0.priority, true, false, debug, userId); 2961 if (ri != null) { 2962 return ri; 2963 } 2964 if (userId != 0) { 2965 ri = new ResolveInfo(mResolveInfo); 2966 ri.activityInfo = new ActivityInfo(ri.activityInfo); 2967 ri.activityInfo.applicationInfo = new ApplicationInfo( 2968 ri.activityInfo.applicationInfo); 2969 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 2970 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 2971 return ri; 2972 } 2973 return mResolveInfo; 2974 } 2975 } 2976 return null; 2977 } 2978 2979 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 2980 int flags, List<ResolveInfo> query, boolean debug, int userId) { 2981 final int N = query.size(); 2982 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 2983 .get(userId); 2984 // Get the list of persistent preferred activities that handle the intent 2985 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 2986 List<PersistentPreferredActivity> pprefs = ppir != null 2987 ? ppir.queryIntent(intent, resolvedType, 2988 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 2989 : null; 2990 if (pprefs != null && pprefs.size() > 0) { 2991 final int M = pprefs.size(); 2992 for (int i=0; i<M; i++) { 2993 final PersistentPreferredActivity ppa = pprefs.get(i); 2994 if (DEBUG_PREFERRED || debug) { 2995 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 2996 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 2997 + "\n component=" + ppa.mComponent); 2998 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 2999 } 3000 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3001 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3002 if (DEBUG_PREFERRED || debug) { 3003 Slog.v(TAG, "Found persistent preferred activity:"); 3004 if (ai != null) { 3005 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3006 } else { 3007 Slog.v(TAG, " null"); 3008 } 3009 } 3010 if (ai == null) { 3011 // This previously registered persistent preferred activity 3012 // component is no longer known. Ignore it and do NOT remove it. 3013 continue; 3014 } 3015 for (int j=0; j<N; j++) { 3016 final ResolveInfo ri = query.get(j); 3017 if (!ri.activityInfo.applicationInfo.packageName 3018 .equals(ai.applicationInfo.packageName)) { 3019 continue; 3020 } 3021 if (!ri.activityInfo.name.equals(ai.name)) { 3022 continue; 3023 } 3024 // Found a persistent preference that can handle the intent. 3025 if (DEBUG_PREFERRED || debug) { 3026 Slog.v(TAG, "Returning persistent preferred activity: " + 3027 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3028 } 3029 return ri; 3030 } 3031 } 3032 } 3033 return null; 3034 } 3035 3036 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3037 List<ResolveInfo> query, int priority, boolean always, 3038 boolean removeMatches, boolean debug, int userId) { 3039 if (!sUserManager.exists(userId)) return null; 3040 // writer 3041 synchronized (mPackages) { 3042 if (intent.getSelector() != null) { 3043 intent = intent.getSelector(); 3044 } 3045 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3046 3047 // Try to find a matching persistent preferred activity. 3048 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3049 debug, userId); 3050 3051 // If a persistent preferred activity matched, use it. 3052 if (pri != null) { 3053 return pri; 3054 } 3055 3056 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3057 // Get the list of preferred activities that handle the intent 3058 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3059 List<PreferredActivity> prefs = pir != null 3060 ? pir.queryIntent(intent, resolvedType, 3061 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3062 : null; 3063 if (prefs != null && prefs.size() > 0) { 3064 // First figure out how good the original match set is. 3065 // We will only allow preferred activities that came 3066 // from the same match quality. 3067 int match = 0; 3068 3069 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3070 3071 final int N = query.size(); 3072 for (int j=0; j<N; j++) { 3073 final ResolveInfo ri = query.get(j); 3074 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3075 + ": 0x" + Integer.toHexString(match)); 3076 if (ri.match > match) { 3077 match = ri.match; 3078 } 3079 } 3080 3081 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3082 + Integer.toHexString(match)); 3083 3084 match &= IntentFilter.MATCH_CATEGORY_MASK; 3085 final int M = prefs.size(); 3086 for (int i=0; i<M; i++) { 3087 final PreferredActivity pa = prefs.get(i); 3088 if (DEBUG_PREFERRED || debug) { 3089 Slog.v(TAG, "Checking PreferredActivity ds=" 3090 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3091 + "\n component=" + pa.mPref.mComponent); 3092 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3093 } 3094 if (pa.mPref.mMatch != match) { 3095 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3096 + Integer.toHexString(pa.mPref.mMatch)); 3097 continue; 3098 } 3099 // If it's not an "always" type preferred activity and that's what we're 3100 // looking for, skip it. 3101 if (always && !pa.mPref.mAlways) { 3102 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3103 continue; 3104 } 3105 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3106 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3107 if (DEBUG_PREFERRED || debug) { 3108 Slog.v(TAG, "Found preferred activity:"); 3109 if (ai != null) { 3110 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3111 } else { 3112 Slog.v(TAG, " null"); 3113 } 3114 } 3115 if (ai == null) { 3116 // This previously registered preferred activity 3117 // component is no longer known. Most likely an update 3118 // to the app was installed and in the new version this 3119 // component no longer exists. Clean it up by removing 3120 // it from the preferred activities list, and skip it. 3121 Slog.w(TAG, "Removing dangling preferred activity: " 3122 + pa.mPref.mComponent); 3123 pir.removeFilter(pa); 3124 continue; 3125 } 3126 for (int j=0; j<N; j++) { 3127 final ResolveInfo ri = query.get(j); 3128 if (!ri.activityInfo.applicationInfo.packageName 3129 .equals(ai.applicationInfo.packageName)) { 3130 continue; 3131 } 3132 if (!ri.activityInfo.name.equals(ai.name)) { 3133 continue; 3134 } 3135 3136 if (removeMatches) { 3137 pir.removeFilter(pa); 3138 if (DEBUG_PREFERRED) { 3139 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3140 } 3141 break; 3142 } 3143 3144 // Okay we found a previously set preferred or last chosen app. 3145 // If the result set is different from when this 3146 // was created, we need to clear it and re-ask the 3147 // user their preference, if we're looking for an "always" type entry. 3148 if (always && !pa.mPref.sameSet(query, priority)) { 3149 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3150 + intent + " type " + resolvedType); 3151 if (DEBUG_PREFERRED) { 3152 Slog.v(TAG, "Removing preferred activity since set changed " 3153 + pa.mPref.mComponent); 3154 } 3155 pir.removeFilter(pa); 3156 // Re-add the filter as a "last chosen" entry (!always) 3157 PreferredActivity lastChosen = new PreferredActivity( 3158 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3159 pir.addFilter(lastChosen); 3160 mSettings.writePackageRestrictionsLPr(userId); 3161 return null; 3162 } 3163 3164 // Yay! Either the set matched or we're looking for the last chosen 3165 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3166 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3167 mSettings.writePackageRestrictionsLPr(userId); 3168 return ri; 3169 } 3170 } 3171 } 3172 mSettings.writePackageRestrictionsLPr(userId); 3173 } 3174 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3175 return null; 3176 } 3177 3178 /* 3179 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3180 */ 3181 @Override 3182 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3183 int targetUserId) { 3184 mContext.enforceCallingOrSelfPermission( 3185 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3186 List<CrossProfileIntentFilter> matches = 3187 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3188 if (matches != null) { 3189 int size = matches.size(); 3190 for (int i = 0; i < size; i++) { 3191 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3192 } 3193 } 3194 3195 ArrayList<String> packageNames = null; 3196 SparseArray<ArrayList<String>> fromSource = 3197 mSettings.mCrossProfilePackageInfo.get(sourceUserId); 3198 if (fromSource != null) { 3199 packageNames = fromSource.get(targetUserId); 3200 } 3201 if (packageNames.contains(intent.getPackage())) { 3202 return true; 3203 } 3204 // We need the package name, so we try to resolve with the loosest flags possible 3205 List<ResolveInfo> resolveInfos = mActivities.queryIntent( 3206 intent, resolvedType, PackageManager.GET_UNINSTALLED_PACKAGES, targetUserId); 3207 int count = resolveInfos.size(); 3208 for (int i = 0; i < count; i++) { 3209 ResolveInfo resolveInfo = resolveInfos.get(i); 3210 if (packageNames.contains(resolveInfo.activityInfo.packageName)) { 3211 return true; 3212 } 3213 } 3214 return false; 3215 } 3216 3217 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3218 String resolvedType, int userId) { 3219 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3220 if (resolver != null) { 3221 return resolver.queryIntent(intent, resolvedType, false, userId); 3222 } 3223 return null; 3224 } 3225 3226 @Override 3227 public List<ResolveInfo> queryIntentActivities(Intent intent, 3228 String resolvedType, int flags, int userId) { 3229 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3230 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities"); 3231 ComponentName comp = intent.getComponent(); 3232 if (comp == null) { 3233 if (intent.getSelector() != null) { 3234 intent = intent.getSelector(); 3235 comp = intent.getComponent(); 3236 } 3237 } 3238 3239 if (comp != null) { 3240 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3241 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3242 if (ai != null) { 3243 final ResolveInfo ri = new ResolveInfo(); 3244 ri.activityInfo = ai; 3245 list.add(ri); 3246 } 3247 return list; 3248 } 3249 3250 // reader 3251 synchronized (mPackages) { 3252 final String pkgName = intent.getPackage(); 3253 boolean queryCrossProfile = (flags & PackageManager.NO_CROSS_PROFILE) == 0; 3254 if (pkgName == null) { 3255 ResolveInfo resolveInfo = null; 3256 if (queryCrossProfile) { 3257 // Check if the intent needs to be forwarded to another user for this package 3258 ArrayList<ResolveInfo> crossProfileResult = 3259 queryIntentActivitiesCrossProfilePackage( 3260 intent, resolvedType, flags, userId); 3261 if (!crossProfileResult.isEmpty()) { 3262 // Skip the current profile 3263 return crossProfileResult; 3264 } 3265 List<CrossProfileIntentFilter> matchingFilters = 3266 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3267 // Check for results that need to skip the current profile. 3268 resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3269 resolvedType, flags, userId); 3270 if (resolveInfo != null) { 3271 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3272 result.add(resolveInfo); 3273 return result; 3274 } 3275 // Check for cross profile results. 3276 resolveInfo = queryCrossProfileIntents( 3277 matchingFilters, intent, resolvedType, flags, userId); 3278 } 3279 // Check for results in the current profile. 3280 List<ResolveInfo> result = mActivities.queryIntent( 3281 intent, resolvedType, flags, userId); 3282 if (resolveInfo != null) { 3283 result.add(resolveInfo); 3284 } 3285 return result; 3286 } 3287 final PackageParser.Package pkg = mPackages.get(pkgName); 3288 if (pkg != null) { 3289 if (queryCrossProfile) { 3290 ArrayList<ResolveInfo> crossProfileResult = 3291 queryIntentActivitiesCrossProfilePackage( 3292 intent, resolvedType, flags, userId, pkg, pkgName); 3293 if (!crossProfileResult.isEmpty()) { 3294 // Skip the current profile 3295 return crossProfileResult; 3296 } 3297 } 3298 return mActivities.queryIntentForPackage(intent, resolvedType, flags, 3299 pkg.activities, userId); 3300 } 3301 return new ArrayList<ResolveInfo>(); 3302 } 3303 } 3304 3305 private ResolveInfo querySkipCurrentProfileIntents( 3306 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3307 int flags, int sourceUserId) { 3308 if (matchingFilters != null) { 3309 int size = matchingFilters.size(); 3310 for (int i = 0; i < size; i ++) { 3311 CrossProfileIntentFilter filter = matchingFilters.get(i); 3312 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 3313 // Checking if there are activities in the target user that can handle the 3314 // intent. 3315 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3316 flags, sourceUserId); 3317 if (resolveInfo != null) { 3318 return resolveInfo; 3319 } 3320 } 3321 } 3322 } 3323 return null; 3324 } 3325 3326 private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage( 3327 Intent intent, String resolvedType, int flags, int userId) { 3328 ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>(); 3329 SparseArray<ArrayList<String>> sourceForwardingInfo = 3330 mSettings.mCrossProfilePackageInfo.get(userId); 3331 if (sourceForwardingInfo != null) { 3332 int NI = sourceForwardingInfo.size(); 3333 for (int i = 0; i < NI; i++) { 3334 int targetUserId = sourceForwardingInfo.keyAt(i); 3335 ArrayList<String> packageNames = sourceForwardingInfo.valueAt(i); 3336 List<ResolveInfo> resolveInfos = mActivities.queryIntent( 3337 intent, resolvedType, flags, targetUserId); 3338 int NJ = resolveInfos.size(); 3339 for (int j = 0; j < NJ; j++) { 3340 ResolveInfo resolveInfo = resolveInfos.get(j); 3341 if (packageNames.contains(resolveInfo.activityInfo.packageName)) { 3342 matchingResolveInfos.add(createForwardingResolveInfo( 3343 resolveInfo.filter, userId, targetUserId)); 3344 } 3345 } 3346 } 3347 } 3348 return matchingResolveInfos; 3349 } 3350 3351 private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage( 3352 Intent intent, String resolvedType, int flags, int userId, PackageParser.Package pkg, 3353 String packageName) { 3354 ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>(); 3355 SparseArray<ArrayList<String>> sourceForwardingInfo = 3356 mSettings.mCrossProfilePackageInfo.get(userId); 3357 if (sourceForwardingInfo != null) { 3358 int NI = sourceForwardingInfo.size(); 3359 for (int i = 0; i < NI; i++) { 3360 int targetUserId = sourceForwardingInfo.keyAt(i); 3361 if (sourceForwardingInfo.valueAt(i).contains(packageName)) { 3362 List<ResolveInfo> resolveInfos = mActivities.queryIntentForPackage( 3363 intent, resolvedType, flags, pkg.activities, targetUserId); 3364 int NJ = resolveInfos.size(); 3365 for (int j = 0; j < NJ; j++) { 3366 ResolveInfo resolveInfo = resolveInfos.get(j); 3367 matchingResolveInfos.add(createForwardingResolveInfo( 3368 resolveInfo.filter, userId, targetUserId)); 3369 } 3370 } 3371 } 3372 } 3373 return matchingResolveInfos; 3374 } 3375 3376 // Return matching ResolveInfo if any for skip current profile intent filters. 3377 private ResolveInfo queryCrossProfileIntents( 3378 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3379 int flags, int sourceUserId) { 3380 if (matchingFilters != null) { 3381 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 3382 // match the same intent. For performance reasons, it is better not to 3383 // run queryIntent twice for the same userId 3384 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 3385 int size = matchingFilters.size(); 3386 for (int i = 0; i < size; i++) { 3387 CrossProfileIntentFilter filter = matchingFilters.get(i); 3388 int targetUserId = filter.getTargetUserId(); 3389 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 3390 && !alreadyTriedUserIds.get(targetUserId)) { 3391 // Checking if there are activities in the target user that can handle the 3392 // intent. 3393 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3394 flags, sourceUserId); 3395 if (resolveInfo != null) return resolveInfo; 3396 alreadyTriedUserIds.put(targetUserId, true); 3397 } 3398 } 3399 } 3400 return null; 3401 } 3402 3403 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 3404 String resolvedType, int flags, int sourceUserId) { 3405 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 3406 resolvedType, flags, filter.getTargetUserId()); 3407 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 3408 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 3409 } 3410 return null; 3411 } 3412 3413 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 3414 int sourceUserId, int targetUserId) { 3415 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 3416 String className; 3417 if (targetUserId == UserHandle.USER_OWNER) { 3418 className = FORWARD_INTENT_TO_USER_OWNER; 3419 } else { 3420 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 3421 } 3422 ComponentName forwardingActivityComponentName = new ComponentName( 3423 mAndroidApplication.packageName, className); 3424 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 3425 sourceUserId); 3426 if (targetUserId == UserHandle.USER_OWNER) { 3427 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 3428 forwardingResolveInfo.noResourceId = true; 3429 } 3430 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 3431 forwardingResolveInfo.priority = 0; 3432 forwardingResolveInfo.preferredOrder = 0; 3433 forwardingResolveInfo.match = 0; 3434 forwardingResolveInfo.isDefault = true; 3435 forwardingResolveInfo.filter = filter; 3436 forwardingResolveInfo.targetUserId = targetUserId; 3437 return forwardingResolveInfo; 3438 } 3439 3440 @Override 3441 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 3442 Intent[] specifics, String[] specificTypes, Intent intent, 3443 String resolvedType, int flags, int userId) { 3444 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3445 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 3446 "query intent activity options"); 3447 final String resultsAction = intent.getAction(); 3448 3449 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 3450 | PackageManager.GET_RESOLVED_FILTER, userId); 3451 3452 if (DEBUG_INTENT_MATCHING) { 3453 Log.v(TAG, "Query " + intent + ": " + results); 3454 } 3455 3456 int specificsPos = 0; 3457 int N; 3458 3459 // todo: note that the algorithm used here is O(N^2). This 3460 // isn't a problem in our current environment, but if we start running 3461 // into situations where we have more than 5 or 10 matches then this 3462 // should probably be changed to something smarter... 3463 3464 // First we go through and resolve each of the specific items 3465 // that were supplied, taking care of removing any corresponding 3466 // duplicate items in the generic resolve list. 3467 if (specifics != null) { 3468 for (int i=0; i<specifics.length; i++) { 3469 final Intent sintent = specifics[i]; 3470 if (sintent == null) { 3471 continue; 3472 } 3473 3474 if (DEBUG_INTENT_MATCHING) { 3475 Log.v(TAG, "Specific #" + i + ": " + sintent); 3476 } 3477 3478 String action = sintent.getAction(); 3479 if (resultsAction != null && resultsAction.equals(action)) { 3480 // If this action was explicitly requested, then don't 3481 // remove things that have it. 3482 action = null; 3483 } 3484 3485 ResolveInfo ri = null; 3486 ActivityInfo ai = null; 3487 3488 ComponentName comp = sintent.getComponent(); 3489 if (comp == null) { 3490 ri = resolveIntent( 3491 sintent, 3492 specificTypes != null ? specificTypes[i] : null, 3493 flags, userId); 3494 if (ri == null) { 3495 continue; 3496 } 3497 if (ri == mResolveInfo) { 3498 // ACK! Must do something better with this. 3499 } 3500 ai = ri.activityInfo; 3501 comp = new ComponentName(ai.applicationInfo.packageName, 3502 ai.name); 3503 } else { 3504 ai = getActivityInfo(comp, flags, userId); 3505 if (ai == null) { 3506 continue; 3507 } 3508 } 3509 3510 // Look for any generic query activities that are duplicates 3511 // of this specific one, and remove them from the results. 3512 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 3513 N = results.size(); 3514 int j; 3515 for (j=specificsPos; j<N; j++) { 3516 ResolveInfo sri = results.get(j); 3517 if ((sri.activityInfo.name.equals(comp.getClassName()) 3518 && sri.activityInfo.applicationInfo.packageName.equals( 3519 comp.getPackageName())) 3520 || (action != null && sri.filter.matchAction(action))) { 3521 results.remove(j); 3522 if (DEBUG_INTENT_MATCHING) Log.v( 3523 TAG, "Removing duplicate item from " + j 3524 + " due to specific " + specificsPos); 3525 if (ri == null) { 3526 ri = sri; 3527 } 3528 j--; 3529 N--; 3530 } 3531 } 3532 3533 // Add this specific item to its proper place. 3534 if (ri == null) { 3535 ri = new ResolveInfo(); 3536 ri.activityInfo = ai; 3537 } 3538 results.add(specificsPos, ri); 3539 ri.specificIndex = i; 3540 specificsPos++; 3541 } 3542 } 3543 3544 // Now we go through the remaining generic results and remove any 3545 // duplicate actions that are found here. 3546 N = results.size(); 3547 for (int i=specificsPos; i<N-1; i++) { 3548 final ResolveInfo rii = results.get(i); 3549 if (rii.filter == null) { 3550 continue; 3551 } 3552 3553 // Iterate over all of the actions of this result's intent 3554 // filter... typically this should be just one. 3555 final Iterator<String> it = rii.filter.actionsIterator(); 3556 if (it == null) { 3557 continue; 3558 } 3559 while (it.hasNext()) { 3560 final String action = it.next(); 3561 if (resultsAction != null && resultsAction.equals(action)) { 3562 // If this action was explicitly requested, then don't 3563 // remove things that have it. 3564 continue; 3565 } 3566 for (int j=i+1; j<N; j++) { 3567 final ResolveInfo rij = results.get(j); 3568 if (rij.filter != null && rij.filter.hasAction(action)) { 3569 results.remove(j); 3570 if (DEBUG_INTENT_MATCHING) Log.v( 3571 TAG, "Removing duplicate item from " + j 3572 + " due to action " + action + " at " + i); 3573 j--; 3574 N--; 3575 } 3576 } 3577 } 3578 3579 // If the caller didn't request filter information, drop it now 3580 // so we don't have to marshall/unmarshall it. 3581 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3582 rii.filter = null; 3583 } 3584 } 3585 3586 // Filter out the caller activity if so requested. 3587 if (caller != null) { 3588 N = results.size(); 3589 for (int i=0; i<N; i++) { 3590 ActivityInfo ainfo = results.get(i).activityInfo; 3591 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 3592 && caller.getClassName().equals(ainfo.name)) { 3593 results.remove(i); 3594 break; 3595 } 3596 } 3597 } 3598 3599 // If the caller didn't request filter information, 3600 // drop them now so we don't have to 3601 // marshall/unmarshall it. 3602 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3603 N = results.size(); 3604 for (int i=0; i<N; i++) { 3605 results.get(i).filter = null; 3606 } 3607 } 3608 3609 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 3610 return results; 3611 } 3612 3613 @Override 3614 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 3615 int userId) { 3616 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3617 ComponentName comp = intent.getComponent(); 3618 if (comp == null) { 3619 if (intent.getSelector() != null) { 3620 intent = intent.getSelector(); 3621 comp = intent.getComponent(); 3622 } 3623 } 3624 if (comp != null) { 3625 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3626 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 3627 if (ai != null) { 3628 ResolveInfo ri = new ResolveInfo(); 3629 ri.activityInfo = ai; 3630 list.add(ri); 3631 } 3632 return list; 3633 } 3634 3635 // reader 3636 synchronized (mPackages) { 3637 String pkgName = intent.getPackage(); 3638 if (pkgName == null) { 3639 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 3640 } 3641 final PackageParser.Package pkg = mPackages.get(pkgName); 3642 if (pkg != null) { 3643 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 3644 userId); 3645 } 3646 return null; 3647 } 3648 } 3649 3650 @Override 3651 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 3652 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 3653 if (!sUserManager.exists(userId)) return null; 3654 if (query != null) { 3655 if (query.size() >= 1) { 3656 // If there is more than one service with the same priority, 3657 // just arbitrarily pick the first one. 3658 return query.get(0); 3659 } 3660 } 3661 return null; 3662 } 3663 3664 @Override 3665 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 3666 int userId) { 3667 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3668 ComponentName comp = intent.getComponent(); 3669 if (comp == null) { 3670 if (intent.getSelector() != null) { 3671 intent = intent.getSelector(); 3672 comp = intent.getComponent(); 3673 } 3674 } 3675 if (comp != null) { 3676 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3677 final ServiceInfo si = getServiceInfo(comp, flags, userId); 3678 if (si != null) { 3679 final ResolveInfo ri = new ResolveInfo(); 3680 ri.serviceInfo = si; 3681 list.add(ri); 3682 } 3683 return list; 3684 } 3685 3686 // reader 3687 synchronized (mPackages) { 3688 String pkgName = intent.getPackage(); 3689 if (pkgName == null) { 3690 return mServices.queryIntent(intent, resolvedType, flags, userId); 3691 } 3692 final PackageParser.Package pkg = mPackages.get(pkgName); 3693 if (pkg != null) { 3694 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 3695 userId); 3696 } 3697 return null; 3698 } 3699 } 3700 3701 @Override 3702 public List<ResolveInfo> queryIntentContentProviders( 3703 Intent intent, String resolvedType, int flags, int userId) { 3704 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3705 ComponentName comp = intent.getComponent(); 3706 if (comp == null) { 3707 if (intent.getSelector() != null) { 3708 intent = intent.getSelector(); 3709 comp = intent.getComponent(); 3710 } 3711 } 3712 if (comp != null) { 3713 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3714 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 3715 if (pi != null) { 3716 final ResolveInfo ri = new ResolveInfo(); 3717 ri.providerInfo = pi; 3718 list.add(ri); 3719 } 3720 return list; 3721 } 3722 3723 // reader 3724 synchronized (mPackages) { 3725 String pkgName = intent.getPackage(); 3726 if (pkgName == null) { 3727 return mProviders.queryIntent(intent, resolvedType, flags, userId); 3728 } 3729 final PackageParser.Package pkg = mPackages.get(pkgName); 3730 if (pkg != null) { 3731 return mProviders.queryIntentForPackage( 3732 intent, resolvedType, flags, pkg.providers, userId); 3733 } 3734 return null; 3735 } 3736 } 3737 3738 @Override 3739 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 3740 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3741 3742 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages"); 3743 3744 // writer 3745 synchronized (mPackages) { 3746 ArrayList<PackageInfo> list; 3747 if (listUninstalled) { 3748 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 3749 for (PackageSetting ps : mSettings.mPackages.values()) { 3750 PackageInfo pi; 3751 if (ps.pkg != null) { 3752 pi = generatePackageInfo(ps.pkg, flags, userId); 3753 } else { 3754 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3755 } 3756 if (pi != null) { 3757 list.add(pi); 3758 } 3759 } 3760 } else { 3761 list = new ArrayList<PackageInfo>(mPackages.size()); 3762 for (PackageParser.Package p : mPackages.values()) { 3763 PackageInfo pi = generatePackageInfo(p, flags, userId); 3764 if (pi != null) { 3765 list.add(pi); 3766 } 3767 } 3768 } 3769 3770 return new ParceledListSlice<PackageInfo>(list); 3771 } 3772 } 3773 3774 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 3775 String[] permissions, boolean[] tmp, int flags, int userId) { 3776 int numMatch = 0; 3777 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 3778 for (int i=0; i<permissions.length; i++) { 3779 if (gp.grantedPermissions.contains(permissions[i])) { 3780 tmp[i] = true; 3781 numMatch++; 3782 } else { 3783 tmp[i] = false; 3784 } 3785 } 3786 if (numMatch == 0) { 3787 return; 3788 } 3789 PackageInfo pi; 3790 if (ps.pkg != null) { 3791 pi = generatePackageInfo(ps.pkg, flags, userId); 3792 } else { 3793 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3794 } 3795 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 3796 if (numMatch == permissions.length) { 3797 pi.requestedPermissions = permissions; 3798 } else { 3799 pi.requestedPermissions = new String[numMatch]; 3800 numMatch = 0; 3801 for (int i=0; i<permissions.length; i++) { 3802 if (tmp[i]) { 3803 pi.requestedPermissions[numMatch] = permissions[i]; 3804 numMatch++; 3805 } 3806 } 3807 } 3808 } 3809 list.add(pi); 3810 } 3811 3812 @Override 3813 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 3814 String[] permissions, int flags, int userId) { 3815 if (!sUserManager.exists(userId)) return null; 3816 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3817 3818 // writer 3819 synchronized (mPackages) { 3820 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 3821 boolean[] tmpBools = new boolean[permissions.length]; 3822 if (listUninstalled) { 3823 for (PackageSetting ps : mSettings.mPackages.values()) { 3824 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 3825 } 3826 } else { 3827 for (PackageParser.Package pkg : mPackages.values()) { 3828 PackageSetting ps = (PackageSetting)pkg.mExtras; 3829 if (ps != null) { 3830 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 3831 userId); 3832 } 3833 } 3834 } 3835 3836 return new ParceledListSlice<PackageInfo>(list); 3837 } 3838 } 3839 3840 @Override 3841 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 3842 if (!sUserManager.exists(userId)) return null; 3843 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3844 3845 // writer 3846 synchronized (mPackages) { 3847 ArrayList<ApplicationInfo> list; 3848 if (listUninstalled) { 3849 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 3850 for (PackageSetting ps : mSettings.mPackages.values()) { 3851 ApplicationInfo ai; 3852 if (ps.pkg != null) { 3853 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3854 ps.readUserState(userId), userId); 3855 } else { 3856 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 3857 } 3858 if (ai != null) { 3859 list.add(ai); 3860 } 3861 } 3862 } else { 3863 list = new ArrayList<ApplicationInfo>(mPackages.size()); 3864 for (PackageParser.Package p : mPackages.values()) { 3865 if (p.mExtras != null) { 3866 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3867 ((PackageSetting)p.mExtras).readUserState(userId), userId); 3868 if (ai != null) { 3869 list.add(ai); 3870 } 3871 } 3872 } 3873 } 3874 3875 return new ParceledListSlice<ApplicationInfo>(list); 3876 } 3877 } 3878 3879 public List<ApplicationInfo> getPersistentApplications(int flags) { 3880 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 3881 3882 // reader 3883 synchronized (mPackages) { 3884 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 3885 final int userId = UserHandle.getCallingUserId(); 3886 while (i.hasNext()) { 3887 final PackageParser.Package p = i.next(); 3888 if (p.applicationInfo != null 3889 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 3890 && (!mSafeMode || isSystemApp(p))) { 3891 PackageSetting ps = mSettings.mPackages.get(p.packageName); 3892 if (ps != null) { 3893 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3894 ps.readUserState(userId), userId); 3895 if (ai != null) { 3896 finalList.add(ai); 3897 } 3898 } 3899 } 3900 } 3901 } 3902 3903 return finalList; 3904 } 3905 3906 @Override 3907 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 3908 if (!sUserManager.exists(userId)) return null; 3909 // reader 3910 synchronized (mPackages) { 3911 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 3912 PackageSetting ps = provider != null 3913 ? mSettings.mPackages.get(provider.owner.packageName) 3914 : null; 3915 return ps != null 3916 && mSettings.isEnabledLPr(provider.info, flags, userId) 3917 && (!mSafeMode || (provider.info.applicationInfo.flags 3918 &ApplicationInfo.FLAG_SYSTEM) != 0) 3919 ? PackageParser.generateProviderInfo(provider, flags, 3920 ps.readUserState(userId), userId) 3921 : null; 3922 } 3923 } 3924 3925 /** 3926 * @deprecated 3927 */ 3928 @Deprecated 3929 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 3930 // reader 3931 synchronized (mPackages) { 3932 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 3933 .entrySet().iterator(); 3934 final int userId = UserHandle.getCallingUserId(); 3935 while (i.hasNext()) { 3936 Map.Entry<String, PackageParser.Provider> entry = i.next(); 3937 PackageParser.Provider p = entry.getValue(); 3938 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3939 3940 if (ps != null && p.syncable 3941 && (!mSafeMode || (p.info.applicationInfo.flags 3942 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 3943 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 3944 ps.readUserState(userId), userId); 3945 if (info != null) { 3946 outNames.add(entry.getKey()); 3947 outInfo.add(info); 3948 } 3949 } 3950 } 3951 } 3952 } 3953 3954 @Override 3955 public List<ProviderInfo> queryContentProviders(String processName, 3956 int uid, int flags) { 3957 ArrayList<ProviderInfo> finalList = null; 3958 // reader 3959 synchronized (mPackages) { 3960 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 3961 final int userId = processName != null ? 3962 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 3963 while (i.hasNext()) { 3964 final PackageParser.Provider p = i.next(); 3965 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3966 if (ps != null && p.info.authority != null 3967 && (processName == null 3968 || (p.info.processName.equals(processName) 3969 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 3970 && mSettings.isEnabledLPr(p.info, flags, userId) 3971 && (!mSafeMode 3972 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 3973 if (finalList == null) { 3974 finalList = new ArrayList<ProviderInfo>(3); 3975 } 3976 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 3977 ps.readUserState(userId), userId); 3978 if (info != null) { 3979 finalList.add(info); 3980 } 3981 } 3982 } 3983 } 3984 3985 if (finalList != null) { 3986 Collections.sort(finalList, mProviderInitOrderSorter); 3987 } 3988 3989 return finalList; 3990 } 3991 3992 @Override 3993 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 3994 int flags) { 3995 // reader 3996 synchronized (mPackages) { 3997 final PackageParser.Instrumentation i = mInstrumentation.get(name); 3998 return PackageParser.generateInstrumentationInfo(i, flags); 3999 } 4000 } 4001 4002 @Override 4003 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4004 int flags) { 4005 ArrayList<InstrumentationInfo> finalList = 4006 new ArrayList<InstrumentationInfo>(); 4007 4008 // reader 4009 synchronized (mPackages) { 4010 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4011 while (i.hasNext()) { 4012 final PackageParser.Instrumentation p = i.next(); 4013 if (targetPackage == null 4014 || targetPackage.equals(p.info.targetPackage)) { 4015 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4016 flags); 4017 if (ii != null) { 4018 finalList.add(ii); 4019 } 4020 } 4021 } 4022 } 4023 4024 return finalList; 4025 } 4026 4027 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4028 HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4029 if (overlays == null) { 4030 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4031 return; 4032 } 4033 for (PackageParser.Package opkg : overlays.values()) { 4034 // Not much to do if idmap fails: we already logged the error 4035 // and we certainly don't want to abort installation of pkg simply 4036 // because an overlay didn't fit properly. For these reasons, 4037 // ignore the return value of createIdmapForPackagePairLI. 4038 createIdmapForPackagePairLI(pkg, opkg); 4039 } 4040 } 4041 4042 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4043 PackageParser.Package opkg) { 4044 if (!opkg.mTrustedOverlay) { 4045 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4046 opkg.baseCodePath + ": overlay not trusted"); 4047 return false; 4048 } 4049 HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4050 if (overlaySet == null) { 4051 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4052 opkg.baseCodePath + " but target package has no known overlays"); 4053 return false; 4054 } 4055 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4056 // TODO: generate idmap for split APKs 4057 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4058 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4059 + opkg.baseCodePath); 4060 return false; 4061 } 4062 PackageParser.Package[] overlayArray = 4063 overlaySet.values().toArray(new PackageParser.Package[0]); 4064 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4065 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4066 return p1.mOverlayPriority - p2.mOverlayPriority; 4067 } 4068 }; 4069 Arrays.sort(overlayArray, cmp); 4070 4071 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4072 int i = 0; 4073 for (PackageParser.Package p : overlayArray) { 4074 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4075 } 4076 return true; 4077 } 4078 4079 private void scanDirLI(File dir, int flags, int scanMode, long currentTime) { 4080 final File[] files = dir.listFiles(); 4081 if (ArrayUtils.isEmpty(files)) { 4082 Log.d(TAG, "No files in app dir " + dir); 4083 return; 4084 } 4085 4086 if (DEBUG_PACKAGE_SCANNING) { 4087 Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode 4088 + " flags=0x" + Integer.toHexString(flags)); 4089 } 4090 4091 for (File file : files) { 4092 final boolean isPackage = isApkFile(file) || file.isDirectory(); 4093 if (!isPackage) { 4094 // Ignore entries which are not apk's 4095 continue; 4096 } 4097 PackageParser.Package pkg = scanPackageLI(file, 4098 flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, null, null); 4099 // Don't mess around with apps in system partition. 4100 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4101 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) { 4102 // Delete the apk 4103 Slog.w(TAG, "Cleaning up failed install of " + file); 4104 file.delete(); 4105 } 4106 } 4107 } 4108 4109 private static File getSettingsProblemFile() { 4110 File dataDir = Environment.getDataDirectory(); 4111 File systemDir = new File(dataDir, "system"); 4112 File fname = new File(systemDir, "uiderrors.txt"); 4113 return fname; 4114 } 4115 4116 static void reportSettingsProblem(int priority, String msg) { 4117 try { 4118 File fname = getSettingsProblemFile(); 4119 FileOutputStream out = new FileOutputStream(fname, true); 4120 PrintWriter pw = new FastPrintWriter(out); 4121 SimpleDateFormat formatter = new SimpleDateFormat(); 4122 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4123 pw.println(dateString + ": " + msg); 4124 pw.close(); 4125 FileUtils.setPermissions( 4126 fname.toString(), 4127 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4128 -1, -1); 4129 } catch (java.io.IOException e) { 4130 } 4131 Slog.println(priority, TAG, msg); 4132 } 4133 4134 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps, 4135 PackageParser.Package pkg, File srcFile, int parseFlags) { 4136 if (ps != null 4137 && ps.codePath.equals(srcFile) 4138 && ps.timeStamp == srcFile.lastModified() 4139 && !isCompatSignatureUpdateNeeded(pkg)) { 4140 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4141 if (ps.signatures.mSignatures != null 4142 && ps.signatures.mSignatures.length != 0 4143 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4144 // Optimization: reuse the existing cached certificates 4145 // if the package appears to be unchanged. 4146 pkg.mSignatures = ps.signatures.mSignatures; 4147 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4148 pkg.mSigningKeys = ksms.getPublicKeysFromKeySet(mSigningKeySetId); 4149 return true; 4150 } 4151 4152 Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them."); 4153 } else { 4154 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4155 } 4156 4157 try { 4158 pp.collectCertificates(pkg, parseFlags); 4159 pp.collectManifestDigest(pkg); 4160 } catch (PackageParserException e) { 4161 Slog.e(TAG, "Failed during collect: " + e); 4162 mLastScanError = e.error; 4163 return false; 4164 } 4165 return true; 4166 } 4167 4168 /* 4169 * Scan a package and return the newly parsed package. 4170 * Returns null in case of errors and the error code is stored in mLastScanError 4171 */ 4172 private PackageParser.Package scanPackageLI(File scanFile, 4173 int parseFlags, int scanMode, long currentTime, UserHandle user, String abiOverride) { 4174 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 4175 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4176 parseFlags |= mDefParseFlags; 4177 PackageParser pp = new PackageParser(); 4178 pp.setSeparateProcesses(mSeparateProcesses); 4179 pp.setOnlyCoreApps(mOnlyCore); 4180 pp.setDisplayMetrics(mMetrics); 4181 4182 if ((scanMode & SCAN_TRUSTED_OVERLAY) != 0) { 4183 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4184 } 4185 4186 final PackageParser.Package pkg; 4187 try { 4188 pkg = pp.parsePackage(scanFile, parseFlags); 4189 } catch (PackageParserException e) { 4190 Slog.e(TAG, "Failed during scan: " + e); 4191 mLastScanError = e.error; 4192 return null; 4193 } 4194 4195 PackageSetting ps = null; 4196 PackageSetting updatedPkg; 4197 // reader 4198 synchronized (mPackages) { 4199 // Look to see if we already know about this package. 4200 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4201 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4202 // This package has been renamed to its original name. Let's 4203 // use that. 4204 ps = mSettings.peekPackageLPr(oldName); 4205 } 4206 // If there was no original package, see one for the real package name. 4207 if (ps == null) { 4208 ps = mSettings.peekPackageLPr(pkg.packageName); 4209 } 4210 // Check to see if this package could be hiding/updating a system 4211 // package. Must look for it either under the original or real 4212 // package name depending on our state. 4213 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4214 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4215 } 4216 boolean updatedPkgBetter = false; 4217 // First check if this is a system package that may involve an update 4218 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4219 if (ps != null && !ps.codePath.equals(scanFile)) { 4220 // The path has changed from what was last scanned... check the 4221 // version of the new path against what we have stored to determine 4222 // what to do. 4223 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4224 if (pkg.mVersionCode < ps.versionCode) { 4225 // The system package has been updated and the code path does not match 4226 // Ignore entry. Skip it. 4227 Log.i(TAG, "Package " + ps.name + " at " + scanFile 4228 + " ignored: updated version " + ps.versionCode 4229 + " better than this " + pkg.mVersionCode); 4230 if (!updatedPkg.codePath.equals(scanFile)) { 4231 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4232 + ps.name + " changing from " + updatedPkg.codePathString 4233 + " to " + scanFile); 4234 updatedPkg.codePath = scanFile; 4235 updatedPkg.codePathString = scanFile.toString(); 4236 // This is the point at which we know that the system-disk APK 4237 // for this package has moved during a reboot (e.g. due to an OTA), 4238 // so we need to reevaluate it for privilege policy. 4239 if (locationIsPrivileged(scanFile)) { 4240 updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED; 4241 } 4242 } 4243 updatedPkg.pkg = pkg; 4244 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 4245 return null; 4246 } else { 4247 // The current app on the system partition is better than 4248 // what we have updated to on the data partition; switch 4249 // back to the system partition version. 4250 // At this point, its safely assumed that package installation for 4251 // apps in system partition will go through. If not there won't be a working 4252 // version of the app 4253 // writer 4254 synchronized (mPackages) { 4255 // Just remove the loaded entries from package lists. 4256 mPackages.remove(ps.name); 4257 } 4258 Slog.w(TAG, "Package " + ps.name + " at " + scanFile 4259 + "reverting from " + ps.codePathString 4260 + ": new version " + pkg.mVersionCode 4261 + " better than installed " + ps.versionCode); 4262 4263 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4264 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4265 getAppDexInstructionSets(ps), isMultiArch(ps)); 4266 synchronized (mInstallLock) { 4267 args.cleanUpResourcesLI(); 4268 } 4269 synchronized (mPackages) { 4270 mSettings.enableSystemPackageLPw(ps.name); 4271 } 4272 updatedPkgBetter = true; 4273 } 4274 } 4275 } 4276 4277 if (updatedPkg != null) { 4278 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4279 // initially 4280 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4281 4282 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4283 // flag set initially 4284 if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) { 4285 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4286 } 4287 } 4288 // Verify certificates against what was last scanned 4289 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) { 4290 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName); 4291 return null; 4292 } 4293 4294 /* 4295 * A new system app appeared, but we already had a non-system one of the 4296 * same name installed earlier. 4297 */ 4298 boolean shouldHideSystemApp = false; 4299 if (updatedPkg == null && ps != null 4300 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4301 /* 4302 * Check to make sure the signatures match first. If they don't, 4303 * wipe the installed application and its data. 4304 */ 4305 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4306 != PackageManager.SIGNATURE_MATCH) { 4307 if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!"); 4308 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4309 ps = null; 4310 } else { 4311 /* 4312 * If the newly-added system app is an older version than the 4313 * already installed version, hide it. It will be scanned later 4314 * and re-added like an update. 4315 */ 4316 if (pkg.mVersionCode < ps.versionCode) { 4317 shouldHideSystemApp = true; 4318 } else { 4319 /* 4320 * The newly found system app is a newer version that the 4321 * one previously installed. Simply remove the 4322 * already-installed application and replace it with our own 4323 * while keeping the application data. 4324 */ 4325 Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from " 4326 + ps.codePathString + ": new version " + pkg.mVersionCode 4327 + " better than installed " + ps.versionCode); 4328 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4329 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4330 getAppDexInstructionSets(ps), isMultiArch(ps)); 4331 synchronized (mInstallLock) { 4332 args.cleanUpResourcesLI(); 4333 } 4334 } 4335 } 4336 } 4337 4338 // The apk is forward locked (not public) if its code and resources 4339 // are kept in different files. (except for app in either system or 4340 // vendor path). 4341 // TODO grab this value from PackageSettings 4342 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4343 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4344 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 4345 } 4346 } 4347 4348 // TODO: extend to support forward-locked splits 4349 String resourcePath = null; 4350 String baseResourcePath = null; 4351 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 4352 if (ps != null && ps.resourcePathString != null) { 4353 resourcePath = ps.resourcePathString; 4354 baseResourcePath = ps.resourcePathString; 4355 } else { 4356 // Should not happen at all. Just log an error. 4357 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 4358 } 4359 } else { 4360 resourcePath = pkg.codePath; 4361 baseResourcePath = pkg.baseCodePath; 4362 } 4363 4364 // Set application objects path explicitly. 4365 pkg.applicationInfo.setCodePath(pkg.codePath); 4366 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 4367 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 4368 pkg.applicationInfo.setResourcePath(resourcePath); 4369 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 4370 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 4371 4372 // Note that we invoke the following method only if we are about to unpack an application 4373 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode 4374 | SCAN_UPDATE_SIGNATURE, currentTime, user, abiOverride); 4375 4376 /* 4377 * If the system app should be overridden by a previously installed 4378 * data, hide the system app now and let the /data/app scan pick it up 4379 * again. 4380 */ 4381 if (shouldHideSystemApp) { 4382 synchronized (mPackages) { 4383 /* 4384 * We have to grant systems permissions before we hide, because 4385 * grantPermissions will assume the package update is trying to 4386 * expand its permissions. 4387 */ 4388 grantPermissionsLPw(pkg, true); 4389 mSettings.disableSystemPackageLPw(pkg.packageName); 4390 } 4391 } 4392 4393 return scannedPkg; 4394 } 4395 4396 private static String fixProcessName(String defProcessName, 4397 String processName, int uid) { 4398 if (processName == null) { 4399 return defProcessName; 4400 } 4401 return processName; 4402 } 4403 4404 private boolean verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) { 4405 if (pkgSetting.signatures.mSignatures != null) { 4406 // Already existing package. Make sure signatures match 4407 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 4408 == PackageManager.SIGNATURE_MATCH; 4409 if (!match) { 4410 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 4411 == PackageManager.SIGNATURE_MATCH; 4412 } 4413 if (!match) { 4414 Slog.e(TAG, "Package " + pkg.packageName 4415 + " signatures do not match the previously installed version; ignoring!"); 4416 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 4417 return false; 4418 } 4419 } 4420 4421 // Check for shared user signatures 4422 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 4423 // Already existing package. Make sure signatures match 4424 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4425 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 4426 if (!match) { 4427 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 4428 == PackageManager.SIGNATURE_MATCH; 4429 } 4430 if (!match) { 4431 Slog.e(TAG, "Package " + pkg.packageName 4432 + " has no signatures that match those in shared user " 4433 + pkgSetting.sharedUser.name + "; ignoring!"); 4434 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 4435 return false; 4436 } 4437 } 4438 return true; 4439 } 4440 4441 /** 4442 * Enforces that only the system UID or root's UID can call a method exposed 4443 * via Binder. 4444 * 4445 * @param message used as message if SecurityException is thrown 4446 * @throws SecurityException if the caller is not system or root 4447 */ 4448 private static final void enforceSystemOrRoot(String message) { 4449 final int uid = Binder.getCallingUid(); 4450 if (uid != Process.SYSTEM_UID && uid != 0) { 4451 throw new SecurityException(message); 4452 } 4453 } 4454 4455 @Override 4456 public void performBootDexOpt() { 4457 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4458 4459 final HashSet<PackageParser.Package> pkgs; 4460 synchronized (mPackages) { 4461 pkgs = mDeferredDexOpt; 4462 mDeferredDexOpt = null; 4463 } 4464 4465 if (pkgs != null) { 4466 // Filter out packages that aren't recently used. 4467 // 4468 // The exception is first boot of a non-eng device, which 4469 // should do a full dexopt. 4470 boolean eng = "eng".equals(SystemProperties.get("ro.build.type")); 4471 if (eng || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 4472 // TODO: add a property to control this? 4473 long dexOptLRUThresholdInMinutes; 4474 if (eng) { 4475 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 4476 } else { 4477 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 4478 } 4479 long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 4480 4481 int total = pkgs.size(); 4482 int skipped = 0; 4483 long now = System.currentTimeMillis(); 4484 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 4485 PackageParser.Package pkg = i.next(); 4486 long then = pkg.mLastPackageUsageTimeInMills; 4487 if (then + dexOptLRUThresholdInMills < now) { 4488 if (DEBUG_DEXOPT) { 4489 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 4490 ((then == 0) ? "never" : new Date(then))); 4491 } 4492 i.remove(); 4493 skipped++; 4494 } 4495 } 4496 if (DEBUG_DEXOPT) { 4497 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 4498 } 4499 } 4500 4501 int i = 0; 4502 for (PackageParser.Package pkg : pkgs) { 4503 i++; 4504 if (DEBUG_DEXOPT) { 4505 Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size() 4506 + ": " + pkg.packageName); 4507 } 4508 if (!isFirstBoot()) { 4509 try { 4510 ActivityManagerNative.getDefault().showBootMessage( 4511 mContext.getResources().getString( 4512 R.string.android_upgrading_apk, 4513 i, pkgs.size()), true); 4514 } catch (RemoteException e) { 4515 } 4516 } 4517 PackageParser.Package p = pkg; 4518 synchronized (mInstallLock) { 4519 if (p.mDexOptNeeded) { 4520 performDexOptLI(p, false /* force dex */, false /* defer */, 4521 true /* include dependencies */); 4522 } 4523 } 4524 } 4525 } 4526 } 4527 4528 @Override 4529 public boolean performDexOpt(String packageName) { 4530 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4531 return performDexOpt(packageName, true); 4532 } 4533 4534 public boolean performDexOpt(String packageName, boolean updateUsage) { 4535 4536 PackageParser.Package p; 4537 synchronized (mPackages) { 4538 p = mPackages.get(packageName); 4539 if (p == null) { 4540 return false; 4541 } 4542 if (updateUsage) { 4543 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 4544 } 4545 mPackageUsage.write(false); 4546 if (!p.mDexOptNeeded) { 4547 return false; 4548 } 4549 } 4550 4551 synchronized (mInstallLock) { 4552 return performDexOptLI(p, false /* force dex */, false /* defer */, 4553 true /* include dependencies */) == DEX_OPT_PERFORMED; 4554 } 4555 } 4556 4557 public HashSet<String> getPackagesThatNeedDexOpt() { 4558 HashSet<String> pkgs = null; 4559 synchronized (mPackages) { 4560 for (PackageParser.Package p : mPackages.values()) { 4561 if (DEBUG_DEXOPT) { 4562 Log.i(TAG, p.packageName + " mDexOptNeeded=" + p.mDexOptNeeded); 4563 } 4564 if (!p.mDexOptNeeded) { 4565 continue; 4566 } 4567 if (pkgs == null) { 4568 pkgs = new HashSet<String>(); 4569 } 4570 pkgs.add(p.packageName); 4571 } 4572 } 4573 return pkgs; 4574 } 4575 4576 public void shutdown() { 4577 mPackageUsage.write(true); 4578 } 4579 4580 private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets, 4581 boolean forceDex, boolean defer, HashSet<String> done) { 4582 for (int i=0; i<libs.size(); i++) { 4583 PackageParser.Package libPkg; 4584 String libName; 4585 synchronized (mPackages) { 4586 libName = libs.get(i); 4587 SharedLibraryEntry lib = mSharedLibraries.get(libName); 4588 if (lib != null && lib.apk != null) { 4589 libPkg = mPackages.get(lib.apk); 4590 } else { 4591 libPkg = null; 4592 } 4593 } 4594 if (libPkg != null && !done.contains(libName)) { 4595 performDexOptLI(libPkg, instructionSets, forceDex, defer, done); 4596 } 4597 } 4598 } 4599 4600 static final int DEX_OPT_SKIPPED = 0; 4601 static final int DEX_OPT_PERFORMED = 1; 4602 static final int DEX_OPT_DEFERRED = 2; 4603 static final int DEX_OPT_FAILED = -1; 4604 4605 private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets, 4606 boolean forceDex, boolean defer, HashSet<String> done) { 4607 final String[] instructionSets = targetInstructionSets != null ? 4608 targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo); 4609 4610 if (done != null) { 4611 done.add(pkg.packageName); 4612 if (pkg.usesLibraries != null) { 4613 performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done); 4614 } 4615 if (pkg.usesOptionalLibraries != null) { 4616 performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done); 4617 } 4618 } 4619 4620 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0) { 4621 final Collection<String> paths = pkg.getAllCodePaths(); 4622 for (String path : paths) { 4623 for (String instructionSet : instructionSets) { 4624 try { 4625 boolean isDexOptNeededInternal = DexFile.isDexOptNeededInternal(path, 4626 pkg.packageName, instructionSet, defer); 4627 // There are three basic cases here: 4628 // 1.) we need to dexopt, either because we are forced or it is needed 4629 // 2.) we are defering a needed dexopt 4630 // 3.) we are skipping an unneeded dexopt 4631 if (forceDex || (!defer && isDexOptNeededInternal)) { 4632 Log.i(TAG, "Running dexopt on: " + pkg.applicationInfo.packageName); 4633 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4634 int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg), 4635 pkg.packageName, instructionSet); 4636 // Note that we ran dexopt, since rerunning will 4637 // probably just result in an error again. 4638 pkg.mDexOptNeeded = false; 4639 if (ret < 0) { 4640 return DEX_OPT_FAILED; 4641 } 4642 return DEX_OPT_PERFORMED; 4643 } 4644 if (defer && isDexOptNeededInternal) { 4645 if (mDeferredDexOpt == null) { 4646 mDeferredDexOpt = new HashSet<PackageParser.Package>(); 4647 } 4648 mDeferredDexOpt.add(pkg); 4649 return DEX_OPT_DEFERRED; 4650 } 4651 pkg.mDexOptNeeded = false; 4652 return DEX_OPT_SKIPPED; 4653 } catch (FileNotFoundException e) { 4654 Slog.w(TAG, "Apk not found for dexopt: " + path); 4655 return DEX_OPT_FAILED; 4656 } catch (IOException e) { 4657 Slog.w(TAG, "IOException reading apk: " + path, e); 4658 return DEX_OPT_FAILED; 4659 } catch (StaleDexCacheError e) { 4660 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e); 4661 return DEX_OPT_FAILED; 4662 } catch (Exception e) { 4663 Slog.w(TAG, "Exception when doing dexopt : ", e); 4664 return DEX_OPT_FAILED; 4665 } 4666 } 4667 } 4668 } 4669 return DEX_OPT_SKIPPED; 4670 } 4671 4672 private static String[] getAppDexInstructionSets(ApplicationInfo info) { 4673 if (info.primaryCpuAbi != null) { 4674 if (info.secondaryCpuAbi != null) { 4675 return new String[] { 4676 VMRuntime.getInstructionSet(info.primaryCpuAbi), 4677 VMRuntime.getInstructionSet(info.secondaryCpuAbi) }; 4678 } else { 4679 return new String[] { 4680 VMRuntime.getInstructionSet(info.primaryCpuAbi) }; 4681 } 4682 } 4683 4684 return new String[] { getPreferredInstructionSet() }; 4685 } 4686 4687 private static String[] getAppDexInstructionSets(PackageSetting ps) { 4688 if (ps.primaryCpuAbiString != null) { 4689 if (ps.secondaryCpuAbiString != null) { 4690 return new String[] { ps.primaryCpuAbiString, ps.secondaryCpuAbiString }; 4691 } else { 4692 return new String[] { ps.primaryCpuAbiString }; 4693 } 4694 } 4695 4696 return new String[] { getPreferredInstructionSet() }; 4697 } 4698 4699 private static String getPreferredInstructionSet() { 4700 if (sPreferredInstructionSet == null) { 4701 sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]); 4702 } 4703 4704 return sPreferredInstructionSet; 4705 } 4706 4707 private static List<String> getAllInstructionSets() { 4708 final String[] allAbis = Build.SUPPORTED_ABIS; 4709 final List<String> allInstructionSets = new ArrayList<String>(allAbis.length); 4710 4711 for (String abi : allAbis) { 4712 final String instructionSet = VMRuntime.getInstructionSet(abi); 4713 if (!allInstructionSets.contains(instructionSet)) { 4714 allInstructionSets.add(instructionSet); 4715 } 4716 } 4717 4718 return allInstructionSets; 4719 } 4720 4721 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer, 4722 boolean inclDependencies) { 4723 HashSet<String> done; 4724 if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) { 4725 done = new HashSet<String>(); 4726 done.add(pkg.packageName); 4727 } else { 4728 done = null; 4729 } 4730 return performDexOptLI(pkg, null /* target instruction sets */, forceDex, defer, done); 4731 } 4732 4733 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 4734 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 4735 Slog.w(TAG, "Unable to update from " + oldPkg.name 4736 + " to " + newPkg.packageName 4737 + ": old package not in system partition"); 4738 return false; 4739 } else if (mPackages.get(oldPkg.name) != null) { 4740 Slog.w(TAG, "Unable to update from " + oldPkg.name 4741 + " to " + newPkg.packageName 4742 + ": old package still exists"); 4743 return false; 4744 } 4745 return true; 4746 } 4747 4748 File getDataPathForUser(int userId) { 4749 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId); 4750 } 4751 4752 private File getDataPathForPackage(String packageName, int userId) { 4753 /* 4754 * Until we fully support multiple users, return the directory we 4755 * previously would have. The PackageManagerTests will need to be 4756 * revised when this is changed back.. 4757 */ 4758 if (userId == 0) { 4759 return new File(mAppDataDir, packageName); 4760 } else { 4761 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 4762 + File.separator + packageName); 4763 } 4764 } 4765 4766 private int createDataDirsLI(String packageName, int uid, String seinfo) { 4767 int[] users = sUserManager.getUserIds(); 4768 int res = mInstaller.install(packageName, uid, uid, seinfo); 4769 if (res < 0) { 4770 return res; 4771 } 4772 for (int user : users) { 4773 if (user != 0) { 4774 res = mInstaller.createUserData(packageName, 4775 UserHandle.getUid(user, uid), user, seinfo); 4776 if (res < 0) { 4777 return res; 4778 } 4779 } 4780 } 4781 return res; 4782 } 4783 4784 private int removeDataDirsLI(String packageName) { 4785 int[] users = sUserManager.getUserIds(); 4786 int res = 0; 4787 for (int user : users) { 4788 int resInner = mInstaller.remove(packageName, user); 4789 if (resInner < 0) { 4790 res = resInner; 4791 } 4792 } 4793 4794 return res; 4795 } 4796 4797 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 4798 PackageParser.Package changingLib) { 4799 if (file.path != null) { 4800 usesLibraryFiles.add(file.path); 4801 return; 4802 } 4803 PackageParser.Package p = mPackages.get(file.apk); 4804 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 4805 // If we are doing this while in the middle of updating a library apk, 4806 // then we need to make sure to use that new apk for determining the 4807 // dependencies here. (We haven't yet finished committing the new apk 4808 // to the package manager state.) 4809 if (p == null || p.packageName.equals(changingLib.packageName)) { 4810 p = changingLib; 4811 } 4812 } 4813 if (p != null) { 4814 usesLibraryFiles.addAll(p.getAllCodePaths()); 4815 } 4816 } 4817 4818 private boolean updateSharedLibrariesLPw(PackageParser.Package pkg, 4819 PackageParser.Package changingLib) { 4820 // We might be upgrading from a version of the platform that did not 4821 // provide per-package native library directories for system apps. 4822 // Fix that up here. 4823 if (isSystemApp(pkg)) { 4824 PackageSetting ps = mSettings.mPackages.get(pkg.applicationInfo.packageName); 4825 if (!isUpdatedSystemApp(pkg)) { 4826 setBundledAppAbisAndRoots(pkg, ps); 4827 } 4828 } 4829 4830 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 4831 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 4832 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 4833 for (int i=0; i<N; i++) { 4834 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 4835 if (file == null) { 4836 Slog.e(TAG, "Package " + pkg.packageName 4837 + " requires unavailable shared library " 4838 + pkg.usesLibraries.get(i) + "; failing!"); 4839 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 4840 return false; 4841 } 4842 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4843 } 4844 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 4845 for (int i=0; i<N; i++) { 4846 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 4847 if (file == null) { 4848 Slog.w(TAG, "Package " + pkg.packageName 4849 + " desires unavailable shared library " 4850 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 4851 } else { 4852 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4853 } 4854 } 4855 N = usesLibraryFiles.size(); 4856 if (N > 0) { 4857 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 4858 } else { 4859 pkg.usesLibraryFiles = null; 4860 } 4861 } 4862 return true; 4863 } 4864 4865 private static boolean hasString(List<String> list, List<String> which) { 4866 if (list == null) { 4867 return false; 4868 } 4869 for (int i=list.size()-1; i>=0; i--) { 4870 for (int j=which.size()-1; j>=0; j--) { 4871 if (which.get(j).equals(list.get(i))) { 4872 return true; 4873 } 4874 } 4875 } 4876 return false; 4877 } 4878 4879 private void updateAllSharedLibrariesLPw() { 4880 for (PackageParser.Package pkg : mPackages.values()) { 4881 updateSharedLibrariesLPw(pkg, null); 4882 } 4883 } 4884 4885 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 4886 PackageParser.Package changingPkg) { 4887 ArrayList<PackageParser.Package> res = null; 4888 for (PackageParser.Package pkg : mPackages.values()) { 4889 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 4890 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 4891 if (res == null) { 4892 res = new ArrayList<PackageParser.Package>(); 4893 } 4894 res.add(pkg); 4895 updateSharedLibrariesLPw(pkg, changingPkg); 4896 } 4897 } 4898 return res; 4899 } 4900 4901 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, 4902 int parseFlags, int scanMode, long currentTime, UserHandle user, String abiOverride) { 4903 final File scanFile = new File(pkg.codePath); 4904 if (pkg.applicationInfo.getCodePath() == null || 4905 pkg.applicationInfo.getResourcePath() == null) { 4906 // Bail out. The resource and code paths haven't been set. 4907 Slog.w(TAG, " Code and resource paths haven't been set correctly"); 4908 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK; 4909 return null; 4910 } 4911 4912 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4913 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 4914 } 4915 4916 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 4917 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED; 4918 } 4919 4920 if (mCustomResolverComponentName != null && 4921 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 4922 setUpCustomResolverActivity(pkg); 4923 } 4924 4925 if (pkg.packageName.equals("android")) { 4926 synchronized (mPackages) { 4927 if (mAndroidApplication != null) { 4928 Slog.w(TAG, "*************************************************"); 4929 Slog.w(TAG, "Core android package being redefined. Skipping."); 4930 Slog.w(TAG, " file=" + scanFile); 4931 Slog.w(TAG, "*************************************************"); 4932 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 4933 return null; 4934 } 4935 4936 // Set up information for our fall-back user intent resolution activity. 4937 mPlatformPackage = pkg; 4938 pkg.mVersionCode = mSdkVersion; 4939 mAndroidApplication = pkg.applicationInfo; 4940 4941 if (!mResolverReplaced) { 4942 mResolveActivity.applicationInfo = mAndroidApplication; 4943 mResolveActivity.name = ResolverActivity.class.getName(); 4944 mResolveActivity.packageName = mAndroidApplication.packageName; 4945 mResolveActivity.processName = "system:ui"; 4946 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 4947 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 4948 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 4949 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 4950 mResolveActivity.exported = true; 4951 mResolveActivity.enabled = true; 4952 mResolveInfo.activityInfo = mResolveActivity; 4953 mResolveInfo.priority = 0; 4954 mResolveInfo.preferredOrder = 0; 4955 mResolveInfo.match = 0; 4956 mResolveComponentName = new ComponentName( 4957 mAndroidApplication.packageName, mResolveActivity.name); 4958 } 4959 } 4960 } 4961 4962 if (DEBUG_PACKAGE_SCANNING) { 4963 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 4964 Log.d(TAG, "Scanning package " + pkg.packageName); 4965 } 4966 4967 if (mPackages.containsKey(pkg.packageName) 4968 || mSharedLibraries.containsKey(pkg.packageName)) { 4969 Slog.w(TAG, "Application package " + pkg.packageName 4970 + " already installed. Skipping duplicate."); 4971 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 4972 return null; 4973 } 4974 4975 // Initialize package source and resource directories 4976 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 4977 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 4978 4979 SharedUserSetting suid = null; 4980 PackageSetting pkgSetting = null; 4981 4982 if (!isSystemApp(pkg)) { 4983 // Only system apps can use these features. 4984 pkg.mOriginalPackages = null; 4985 pkg.mRealPackage = null; 4986 pkg.mAdoptPermissions = null; 4987 } 4988 4989 // writer 4990 synchronized (mPackages) { 4991 if (pkg.mSharedUserId != null) { 4992 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true); 4993 if (suid == null) { 4994 Slog.w(TAG, "Creating application package " + pkg.packageName 4995 + " for shared user failed"); 4996 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 4997 return null; 4998 } 4999 if (DEBUG_PACKAGE_SCANNING) { 5000 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5001 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5002 + "): packages=" + suid.packages); 5003 } 5004 } 5005 5006 // Check if we are renaming from an original package name. 5007 PackageSetting origPackage = null; 5008 String realName = null; 5009 if (pkg.mOriginalPackages != null) { 5010 // This package may need to be renamed to a previously 5011 // installed name. Let's check on that... 5012 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5013 if (pkg.mOriginalPackages.contains(renamed)) { 5014 // This package had originally been installed as the 5015 // original name, and we have already taken care of 5016 // transitioning to the new one. Just update the new 5017 // one to continue using the old name. 5018 realName = pkg.mRealPackage; 5019 if (!pkg.packageName.equals(renamed)) { 5020 // Callers into this function may have already taken 5021 // care of renaming the package; only do it here if 5022 // it is not already done. 5023 pkg.setPackageName(renamed); 5024 } 5025 5026 } else { 5027 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5028 if ((origPackage = mSettings.peekPackageLPr( 5029 pkg.mOriginalPackages.get(i))) != null) { 5030 // We do have the package already installed under its 5031 // original name... should we use it? 5032 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5033 // New package is not compatible with original. 5034 origPackage = null; 5035 continue; 5036 } else if (origPackage.sharedUser != null) { 5037 // Make sure uid is compatible between packages. 5038 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5039 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5040 + " to " + pkg.packageName + ": old uid " 5041 + origPackage.sharedUser.name 5042 + " differs from " + pkg.mSharedUserId); 5043 origPackage = null; 5044 continue; 5045 } 5046 } else { 5047 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5048 + pkg.packageName + " to old name " + origPackage.name); 5049 } 5050 break; 5051 } 5052 } 5053 } 5054 } 5055 5056 if (mTransferedPackages.contains(pkg.packageName)) { 5057 Slog.w(TAG, "Package " + pkg.packageName 5058 + " was transferred to another, but its .apk remains"); 5059 } 5060 5061 // Just create the setting, don't add it yet. For already existing packages 5062 // the PkgSetting exists already and doesn't have to be created. 5063 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5064 destResourceFile, pkg.applicationInfo.legacyNativeLibraryDir, 5065 pkg.applicationInfo.primaryCpuAbi, 5066 pkg.applicationInfo.secondaryCpuAbi, 5067 pkg.applicationInfo.flags, user, false); 5068 if (pkgSetting == null) { 5069 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed"); 5070 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 5071 return null; 5072 } 5073 5074 if (pkgSetting.origPackage != null) { 5075 // If we are first transitioning from an original package, 5076 // fix up the new package's name now. We need to do this after 5077 // looking up the package under its new name, so getPackageLP 5078 // can take care of fiddling things correctly. 5079 pkg.setPackageName(origPackage.name); 5080 5081 // File a report about this. 5082 String msg = "New package " + pkgSetting.realName 5083 + " renamed to replace old package " + pkgSetting.name; 5084 reportSettingsProblem(Log.WARN, msg); 5085 5086 // Make a note of it. 5087 mTransferedPackages.add(origPackage.name); 5088 5089 // No longer need to retain this. 5090 pkgSetting.origPackage = null; 5091 } 5092 5093 if (realName != null) { 5094 // Make a note of it. 5095 mTransferedPackages.add(pkg.packageName); 5096 } 5097 5098 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5099 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5100 } 5101 5102 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5103 // Check all shared libraries and map to their actual file path. 5104 // We only do this here for apps not on a system dir, because those 5105 // are the only ones that can fail an install due to this. We 5106 // will take care of the system apps by updating all of their 5107 // library paths after the scan is done. 5108 if (!updateSharedLibrariesLPw(pkg, null)) { 5109 return null; 5110 } 5111 } 5112 5113 if (mFoundPolicyFile) { 5114 SELinuxMMAC.assignSeinfoValue(pkg); 5115 } 5116 5117 pkg.applicationInfo.uid = pkgSetting.appId; 5118 pkg.mExtras = pkgSetting; 5119 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5120 if (!verifySignaturesLP(pkgSetting, pkg)) { 5121 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5122 return null; 5123 } 5124 // The signature has changed, but this package is in the system 5125 // image... let's recover! 5126 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5127 // However... if this package is part of a shared user, but it 5128 // doesn't match the signature of the shared user, let's fail. 5129 // What this means is that you can't change the signatures 5130 // associated with an overall shared user, which doesn't seem all 5131 // that unreasonable. 5132 if (pkgSetting.sharedUser != null) { 5133 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5134 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5135 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser); 5136 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 5137 return null; 5138 } 5139 } 5140 // File a report about this. 5141 String msg = "System package " + pkg.packageName 5142 + " signature changed; retaining data."; 5143 reportSettingsProblem(Log.WARN, msg); 5144 } 5145 } else { 5146 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 5147 Slog.e(TAG, "Package " + pkg.packageName 5148 + " upgrade keys do not match the previously installed version; "); 5149 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 5150 return null; 5151 } else { 5152 // signatures may have changed as result of upgrade 5153 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5154 } 5155 } 5156 // Verify that this new package doesn't have any content providers 5157 // that conflict with existing packages. Only do this if the 5158 // package isn't already installed, since we don't want to break 5159 // things that are installed. 5160 if ((scanMode&SCAN_NEW_INSTALL) != 0) { 5161 final int N = pkg.providers.size(); 5162 int i; 5163 for (i=0; i<N; i++) { 5164 PackageParser.Provider p = pkg.providers.get(i); 5165 if (p.info.authority != null) { 5166 String names[] = p.info.authority.split(";"); 5167 for (int j = 0; j < names.length; j++) { 5168 if (mProvidersByAuthority.containsKey(names[j])) { 5169 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5170 Slog.w(TAG, "Can't install because provider name " + names[j] + 5171 " (in package " + pkg.applicationInfo.packageName + 5172 ") is already used by " 5173 + ((other != null && other.getComponentName() != null) 5174 ? other.getComponentName().getPackageName() : "?")); 5175 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 5176 return null; 5177 } 5178 } 5179 } 5180 } 5181 } 5182 5183 if (pkg.mAdoptPermissions != null) { 5184 // This package wants to adopt ownership of permissions from 5185 // another package. 5186 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 5187 final String origName = pkg.mAdoptPermissions.get(i); 5188 final PackageSetting orig = mSettings.peekPackageLPr(origName); 5189 if (orig != null) { 5190 if (verifyPackageUpdateLPr(orig, pkg)) { 5191 Slog.i(TAG, "Adopting permissions from " + origName + " to " 5192 + pkg.packageName); 5193 mSettings.transferPermissionsLPw(origName, pkg.packageName); 5194 } 5195 } 5196 } 5197 } 5198 } 5199 5200 final String pkgName = pkg.packageName; 5201 5202 final long scanFileTime = scanFile.lastModified(); 5203 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0; 5204 pkg.applicationInfo.processName = fixProcessName( 5205 pkg.applicationInfo.packageName, 5206 pkg.applicationInfo.processName, 5207 pkg.applicationInfo.uid); 5208 5209 File dataPath; 5210 if (mPlatformPackage == pkg) { 5211 // The system package is special. 5212 dataPath = new File (Environment.getDataDirectory(), "system"); 5213 pkg.applicationInfo.dataDir = dataPath.getPath(); 5214 } else { 5215 // This is a normal package, need to make its data directory. 5216 dataPath = getDataPathForPackage(pkg.packageName, 0); 5217 5218 boolean uidError = false; 5219 5220 if (dataPath.exists()) { 5221 int currentUid = 0; 5222 try { 5223 StructStat stat = Os.stat(dataPath.getPath()); 5224 currentUid = stat.st_uid; 5225 } catch (ErrnoException e) { 5226 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 5227 } 5228 5229 // If we have mismatched owners for the data path, we have a problem. 5230 if (currentUid != pkg.applicationInfo.uid) { 5231 boolean recovered = false; 5232 if (currentUid == 0) { 5233 // The directory somehow became owned by root. Wow. 5234 // This is probably because the system was stopped while 5235 // installd was in the middle of messing with its libs 5236 // directory. Ask installd to fix that. 5237 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 5238 pkg.applicationInfo.uid); 5239 if (ret >= 0) { 5240 recovered = true; 5241 String msg = "Package " + pkg.packageName 5242 + " unexpectedly changed to uid 0; recovered to " + 5243 + pkg.applicationInfo.uid; 5244 reportSettingsProblem(Log.WARN, msg); 5245 } 5246 } 5247 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5248 || (scanMode&SCAN_BOOTING) != 0)) { 5249 // If this is a system app, we can at least delete its 5250 // current data so the application will still work. 5251 int ret = removeDataDirsLI(pkgName); 5252 if (ret >= 0) { 5253 // TODO: Kill the processes first 5254 // Old data gone! 5255 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5256 ? "System package " : "Third party package "; 5257 String msg = prefix + pkg.packageName 5258 + " has changed from uid: " 5259 + currentUid + " to " 5260 + pkg.applicationInfo.uid + "; old data erased"; 5261 reportSettingsProblem(Log.WARN, msg); 5262 recovered = true; 5263 5264 // And now re-install the app. 5265 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5266 pkg.applicationInfo.seinfo); 5267 if (ret == -1) { 5268 // Ack should not happen! 5269 msg = prefix + pkg.packageName 5270 + " could not have data directory re-created after delete."; 5271 reportSettingsProblem(Log.WARN, msg); 5272 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 5273 return null; 5274 } 5275 } 5276 if (!recovered) { 5277 mHasSystemUidErrors = true; 5278 } 5279 } else if (!recovered) { 5280 // If we allow this install to proceed, we will be broken. 5281 // Abort, abort! 5282 mLastScanError = PackageManager.INSTALL_FAILED_UID_CHANGED; 5283 return null; 5284 } 5285 if (!recovered) { 5286 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 5287 + pkg.applicationInfo.uid + "/fs_" 5288 + currentUid; 5289 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 5290 pkg.applicationInfo.legacyNativeLibraryDir = pkg.applicationInfo.dataDir; 5291 String msg = "Package " + pkg.packageName 5292 + " has mismatched uid: " 5293 + currentUid + " on disk, " 5294 + pkg.applicationInfo.uid + " in settings"; 5295 // writer 5296 synchronized (mPackages) { 5297 mSettings.mReadMessages.append(msg); 5298 mSettings.mReadMessages.append('\n'); 5299 uidError = true; 5300 if (!pkgSetting.uidError) { 5301 reportSettingsProblem(Log.ERROR, msg); 5302 } 5303 } 5304 } 5305 } 5306 pkg.applicationInfo.dataDir = dataPath.getPath(); 5307 if (mShouldRestoreconData) { 5308 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 5309 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 5310 pkg.applicationInfo.uid); 5311 } 5312 } else { 5313 if (DEBUG_PACKAGE_SCANNING) { 5314 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5315 Log.v(TAG, "Want this data dir: " + dataPath); 5316 } 5317 //invoke installer to do the actual installation 5318 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5319 pkg.applicationInfo.seinfo); 5320 if (ret < 0) { 5321 // Error from installer 5322 Slog.w(TAG, "Unable to create data dirs [errorCode=" + ret + "]"); 5323 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 5324 return null; 5325 } 5326 5327 if (dataPath.exists()) { 5328 pkg.applicationInfo.dataDir = dataPath.getPath(); 5329 } else { 5330 Slog.w(TAG, "Unable to create data directory: " + dataPath); 5331 pkg.applicationInfo.dataDir = null; 5332 } 5333 } 5334 5335 pkgSetting.uidError = uidError; 5336 } 5337 5338 final String path = scanFile.getPath(); 5339 final String codePath = pkg.applicationInfo.getCodePath(); 5340 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 5341 // For the case where we had previously uninstalled an update, get rid 5342 // of any native binaries we might have unpackaged. Note that this assumes 5343 // that system app updates were not installed via ASEC. 5344 // 5345 // TODO(multiArch): Is this cleanup really necessary ? 5346 NativeLibraryHelper.removeNativeBinariesFromDirLI( 5347 new File(codePath, LIB_DIR_NAME), false /* delete dirs */); 5348 setBundledAppAbisAndRoots(pkg, pkgSetting); 5349 } else { 5350 // TODO: We can probably be smarter about this stuff. For installed apps, 5351 // we can calculate this information at install time once and for all. For 5352 // system apps, we can probably assume that this information doesn't change 5353 // after the first boot scan. As things stand, we do lots of unnecessary work. 5354 5355 final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg); 5356 final String nativeLibraryRootStr; 5357 final boolean useIsaSpecificSubdirs; 5358 if (pkg.applicationInfo.legacyNativeLibraryDir != null) { 5359 nativeLibraryRootStr = pkg.applicationInfo.legacyNativeLibraryDir; 5360 useIsaSpecificSubdirs = false; 5361 } else { 5362 nativeLibraryRootStr = new File(pkg.codePath, LIB_DIR_NAME).getAbsolutePath(); 5363 useIsaSpecificSubdirs = true; 5364 } 5365 5366 NativeLibraryHelper.Handle handle = null; 5367 try { 5368 handle = NativeLibraryHelper.Handle.create(scanFile); 5369 // TODO(multiArch): This can be null for apps that didn't go through the 5370 // usual installation process. We can calculate it again, like we 5371 // do during install time. 5372 // 5373 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 5374 // unnecessary. 5375 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 5376 5377 // Null out the abis so that they can be recalculated. 5378 pkg.applicationInfo.primaryCpuAbi = null; 5379 pkg.applicationInfo.secondaryCpuAbi = null; 5380 if (isMultiArch(pkg.applicationInfo)) { 5381 // Warn if we've set an abiOverride for multi-lib packages.. 5382 // By definition, we need to copy both 32 and 64 bit libraries for 5383 // such packages. 5384 if (abiOverride != null) { 5385 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 5386 } 5387 5388 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 5389 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 5390 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 5391 if (isAsec) { 5392 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 5393 } else { 5394 abi32 = copyNativeLibrariesForInternalApp(handle, 5395 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, useIsaSpecificSubdirs); 5396 } 5397 } 5398 5399 if (abi32 < 0 && abi32 != PackageManager.NO_NATIVE_LIBRARIES) { 5400 Slog.w(TAG, "Error unpackaging 32 bit native libs for multiarch app, errorCode=" + abi32); 5401 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5402 return null; 5403 } 5404 5405 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5406 if (isAsec) { 5407 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 5408 } else { 5409 abi64 = copyNativeLibrariesForInternalApp(handle, 5410 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, useIsaSpecificSubdirs); 5411 } 5412 } 5413 5414 if (abi64 < 0 && abi64 != PackageManager.NO_NATIVE_LIBRARIES) { 5415 Slog.w(TAG, "Error unpackaging 64 bit native libs for multiarch app, errorCode=" + abi32); 5416 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5417 return null; 5418 } 5419 5420 5421 if (abi64 >= 0) { 5422 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 5423 } 5424 5425 if (abi32 >= 0) { 5426 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 5427 if (abi64 >= 0) { 5428 pkg.applicationInfo.secondaryCpuAbi = abi; 5429 } else { 5430 pkg.applicationInfo.primaryCpuAbi = abi; 5431 } 5432 } 5433 } else { 5434 String[] abiList = (abiOverride != null) ? 5435 new String[] { abiOverride } : Build.SUPPORTED_ABIS; 5436 5437 // Enable gross and lame hacks for apps that are built with old 5438 // SDK tools. We must scan their APKs for renderscript bitcode and 5439 // not launch them if it's present. Don't bother checking on devices 5440 // that don't have 64 bit support. 5441 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && abiOverride == null && 5442 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5443 abiList = Build.SUPPORTED_32_BIT_ABIS; 5444 } 5445 5446 final int copyRet; 5447 if (isAsec) { 5448 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 5449 } else { 5450 copyRet = copyNativeLibrariesForInternalApp(handle, nativeLibraryRoot, abiList, 5451 useIsaSpecificSubdirs); 5452 } 5453 5454 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5455 Slog.w(TAG, "Error unpackaging native libs for app, errorCode=" + copyRet); 5456 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5457 return null; 5458 } 5459 5460 if (copyRet >= 0) { 5461 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 5462 } 5463 } 5464 } catch (IOException ioe) { 5465 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 5466 } finally { 5467 IoUtils.closeQuietly(handle); 5468 } 5469 5470 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 5471 final int[] userIds = sUserManager.getUserIds(); 5472 synchronized (mInstallLock) { 5473 // Create a native library symlink only if we have native libraries 5474 // and if the native libraries are 32 bit libraries. We do not provide 5475 // this symlink for 64 bit libraries. 5476 if (pkg.applicationInfo.primaryCpuAbi != null && 5477 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 5478 final String nativeLibPath; 5479 if (pkg.applicationInfo.legacyNativeLibraryDir != null) { 5480 nativeLibPath = pkg.applicationInfo.legacyNativeLibraryDir; 5481 } else { 5482 nativeLibPath = new File(nativeLibraryRootStr, 5483 VMRuntime.getInstructionSet(pkg.applicationInfo.primaryCpuAbi)).getAbsolutePath(); 5484 } 5485 5486 for (int userId : userIds) { 5487 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 5488 Slog.w(TAG, "Failed linking native library dir (user=" + userId 5489 + ")"); 5490 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5491 return null; 5492 } 5493 } 5494 } 5495 } 5496 5497 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 5498 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 5499 } 5500 5501 if (DEBUG_ABI_SELECTION) { 5502 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 5503 " primary=" + pkg.applicationInfo.primaryCpuAbi + 5504 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 5505 } 5506 5507 // Check if we have a legacy native library path, use it if we do. 5508 pkg.applicationInfo.legacyNativeLibraryDir = pkgSetting.legacyNativeLibraryPathString; 5509 5510 // Now that we've calculated the ABIs and determined if it's an internal app, 5511 // we will go ahead and populate the nativeLibraryPath. 5512 populateDefaultNativeLibraryPath(pkg, pkg.applicationInfo); 5513 5514 if ((scanMode&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 5515 // We don't do this here during boot because we can do it all 5516 // at once after scanning all existing packages. 5517 // 5518 // We also do this *before* we perform dexopt on this package, so that 5519 // we can avoid redundant dexopts, and also to make sure we've got the 5520 // code and package path correct. 5521 if (!adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 5522 pkg, forceDex, (scanMode & SCAN_DEFER_DEX) != 0)) { 5523 mLastScanError = PackageManager.INSTALL_FAILED_CPU_ABI_INCOMPATIBLE; 5524 return null; 5525 } 5526 } 5527 5528 if ((scanMode&SCAN_NO_DEX) == 0) { 5529 if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5530 == DEX_OPT_FAILED) { 5531 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5532 removeDataDirsLI(pkg.packageName); 5533 } 5534 5535 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT; 5536 return null; 5537 } 5538 } 5539 5540 if (mFactoryTest && pkg.requestedPermissions.contains( 5541 android.Manifest.permission.FACTORY_TEST)) { 5542 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 5543 } 5544 5545 ArrayList<PackageParser.Package> clientLibPkgs = null; 5546 5547 // writer 5548 synchronized (mPackages) { 5549 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5550 // Only system apps can add new shared libraries. 5551 if (pkg.libraryNames != null) { 5552 for (int i=0; i<pkg.libraryNames.size(); i++) { 5553 String name = pkg.libraryNames.get(i); 5554 boolean allowed = false; 5555 if (isUpdatedSystemApp(pkg)) { 5556 // New library entries can only be added through the 5557 // system image. This is important to get rid of a lot 5558 // of nasty edge cases: for example if we allowed a non- 5559 // system update of the app to add a library, then uninstalling 5560 // the update would make the library go away, and assumptions 5561 // we made such as through app install filtering would now 5562 // have allowed apps on the device which aren't compatible 5563 // with it. Better to just have the restriction here, be 5564 // conservative, and create many fewer cases that can negatively 5565 // impact the user experience. 5566 final PackageSetting sysPs = mSettings 5567 .getDisabledSystemPkgLPr(pkg.packageName); 5568 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 5569 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 5570 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 5571 allowed = true; 5572 allowed = true; 5573 break; 5574 } 5575 } 5576 } 5577 } else { 5578 allowed = true; 5579 } 5580 if (allowed) { 5581 if (!mSharedLibraries.containsKey(name)) { 5582 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 5583 } else if (!name.equals(pkg.packageName)) { 5584 Slog.w(TAG, "Package " + pkg.packageName + " library " 5585 + name + " already exists; skipping"); 5586 } 5587 } else { 5588 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 5589 + name + " that is not declared on system image; skipping"); 5590 } 5591 } 5592 if ((scanMode&SCAN_BOOTING) == 0) { 5593 // If we are not booting, we need to update any applications 5594 // that are clients of our shared library. If we are booting, 5595 // this will all be done once the scan is complete. 5596 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 5597 } 5598 } 5599 } 5600 } 5601 5602 // We also need to dexopt any apps that are dependent on this library. Note that 5603 // if these fail, we should abort the install since installing the library will 5604 // result in some apps being broken. 5605 if (clientLibPkgs != null) { 5606 if ((scanMode&SCAN_NO_DEX) == 0) { 5607 for (int i=0; i<clientLibPkgs.size(); i++) { 5608 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5609 if (performDexOptLI(clientPkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5610 == DEX_OPT_FAILED) { 5611 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5612 removeDataDirsLI(pkg.packageName); 5613 } 5614 5615 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT; 5616 return null; 5617 } 5618 } 5619 } 5620 } 5621 5622 // Request the ActivityManager to kill the process(only for existing packages) 5623 // so that we do not end up in a confused state while the user is still using the older 5624 // version of the application while the new one gets installed. 5625 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 5626 // If the package lives in an asec, tell everyone that the container is going 5627 // away so they can clean up any references to its resources (which would prevent 5628 // vold from being able to unmount the asec) 5629 if (isForwardLocked(pkg) || isExternal(pkg)) { 5630 if (DEBUG_INSTALL) { 5631 Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE"); 5632 } 5633 final int[] uidArray = new int[] { pkg.applicationInfo.uid }; 5634 final ArrayList<String> pkgList = new ArrayList<String>(1); 5635 pkgList.add(pkg.applicationInfo.packageName); 5636 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 5637 } 5638 5639 // Post the request that it be killed now that the going-away broadcast is en route 5640 killApplication(pkg.applicationInfo.packageName, 5641 pkg.applicationInfo.uid, "update pkg"); 5642 } 5643 5644 // Also need to kill any apps that are dependent on the library. 5645 if (clientLibPkgs != null) { 5646 for (int i=0; i<clientLibPkgs.size(); i++) { 5647 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5648 killApplication(clientPkg.applicationInfo.packageName, 5649 clientPkg.applicationInfo.uid, "update lib"); 5650 } 5651 } 5652 5653 // writer 5654 synchronized (mPackages) { 5655 // We don't expect installation to fail beyond this point, 5656 if ((scanMode&SCAN_MONITOR) != 0) { 5657 mAppDirs.put(pkg.codePath, pkg); 5658 } 5659 // Add the new setting to mSettings 5660 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 5661 // Add the new setting to mPackages 5662 mPackages.put(pkg.applicationInfo.packageName, pkg); 5663 // Make sure we don't accidentally delete its data. 5664 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 5665 while (iter.hasNext()) { 5666 PackageCleanItem item = iter.next(); 5667 if (pkgName.equals(item.packageName)) { 5668 iter.remove(); 5669 } 5670 } 5671 5672 // Take care of first install / last update times. 5673 if (currentTime != 0) { 5674 if (pkgSetting.firstInstallTime == 0) { 5675 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 5676 } else if ((scanMode&SCAN_UPDATE_TIME) != 0) { 5677 pkgSetting.lastUpdateTime = currentTime; 5678 } 5679 } else if (pkgSetting.firstInstallTime == 0) { 5680 // We need *something*. Take time time stamp of the file. 5681 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 5682 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 5683 if (scanFileTime != pkgSetting.timeStamp) { 5684 // A package on the system image has changed; consider this 5685 // to be an update. 5686 pkgSetting.lastUpdateTime = scanFileTime; 5687 } 5688 } 5689 5690 // Add the package's KeySets to the global KeySetManagerService 5691 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5692 try { 5693 // Old KeySetData no longer valid. 5694 ksms.removeAppKeySetData(pkg.packageName); 5695 ksms.addSigningKeySetToPackage(pkg.packageName, pkg.mSigningKeys); 5696 if (pkg.mKeySetMapping != null) { 5697 for (Map.Entry<String, Set<PublicKey>> entry : 5698 pkg.mKeySetMapping.entrySet()) { 5699 if (entry.getValue() != null) { 5700 ksms.addDefinedKeySetToPackage(pkg.packageName, 5701 entry.getValue(), entry.getKey()); 5702 } 5703 } 5704 if (pkg.mUpgradeKeySets != null 5705 && pkg.mKeySetMapping.keySet().containsAll(pkg.mUpgradeKeySets)) { 5706 for (String upgradeAlias : pkg.mUpgradeKeySets) { 5707 ksms.addUpgradeKeySetToPackage(pkg.packageName, upgradeAlias); 5708 } 5709 } 5710 } 5711 } catch (NullPointerException e) { 5712 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 5713 } catch (IllegalArgumentException e) { 5714 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 5715 } 5716 5717 int N = pkg.providers.size(); 5718 StringBuilder r = null; 5719 int i; 5720 for (i=0; i<N; i++) { 5721 PackageParser.Provider p = pkg.providers.get(i); 5722 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 5723 p.info.processName, pkg.applicationInfo.uid); 5724 mProviders.addProvider(p); 5725 p.syncable = p.info.isSyncable; 5726 if (p.info.authority != null) { 5727 String names[] = p.info.authority.split(";"); 5728 p.info.authority = null; 5729 for (int j = 0; j < names.length; j++) { 5730 if (j == 1 && p.syncable) { 5731 // We only want the first authority for a provider to possibly be 5732 // syncable, so if we already added this provider using a different 5733 // authority clear the syncable flag. We copy the provider before 5734 // changing it because the mProviders object contains a reference 5735 // to a provider that we don't want to change. 5736 // Only do this for the second authority since the resulting provider 5737 // object can be the same for all future authorities for this provider. 5738 p = new PackageParser.Provider(p); 5739 p.syncable = false; 5740 } 5741 if (!mProvidersByAuthority.containsKey(names[j])) { 5742 mProvidersByAuthority.put(names[j], p); 5743 if (p.info.authority == null) { 5744 p.info.authority = names[j]; 5745 } else { 5746 p.info.authority = p.info.authority + ";" + names[j]; 5747 } 5748 if (DEBUG_PACKAGE_SCANNING) { 5749 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5750 Log.d(TAG, "Registered content provider: " + names[j] 5751 + ", className = " + p.info.name + ", isSyncable = " 5752 + p.info.isSyncable); 5753 } 5754 } else { 5755 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5756 Slog.w(TAG, "Skipping provider name " + names[j] + 5757 " (in package " + pkg.applicationInfo.packageName + 5758 "): name already used by " 5759 + ((other != null && other.getComponentName() != null) 5760 ? other.getComponentName().getPackageName() : "?")); 5761 } 5762 } 5763 } 5764 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5765 if (r == null) { 5766 r = new StringBuilder(256); 5767 } else { 5768 r.append(' '); 5769 } 5770 r.append(p.info.name); 5771 } 5772 } 5773 if (r != null) { 5774 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 5775 } 5776 5777 N = pkg.services.size(); 5778 r = null; 5779 for (i=0; i<N; i++) { 5780 PackageParser.Service s = pkg.services.get(i); 5781 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 5782 s.info.processName, pkg.applicationInfo.uid); 5783 mServices.addService(s); 5784 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5785 if (r == null) { 5786 r = new StringBuilder(256); 5787 } else { 5788 r.append(' '); 5789 } 5790 r.append(s.info.name); 5791 } 5792 } 5793 if (r != null) { 5794 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 5795 } 5796 5797 N = pkg.receivers.size(); 5798 r = null; 5799 for (i=0; i<N; i++) { 5800 PackageParser.Activity a = pkg.receivers.get(i); 5801 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5802 a.info.processName, pkg.applicationInfo.uid); 5803 mReceivers.addActivity(a, "receiver"); 5804 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5805 if (r == null) { 5806 r = new StringBuilder(256); 5807 } else { 5808 r.append(' '); 5809 } 5810 r.append(a.info.name); 5811 } 5812 } 5813 if (r != null) { 5814 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 5815 } 5816 5817 N = pkg.activities.size(); 5818 r = null; 5819 for (i=0; i<N; i++) { 5820 PackageParser.Activity a = pkg.activities.get(i); 5821 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5822 a.info.processName, pkg.applicationInfo.uid); 5823 mActivities.addActivity(a, "activity"); 5824 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5825 if (r == null) { 5826 r = new StringBuilder(256); 5827 } else { 5828 r.append(' '); 5829 } 5830 r.append(a.info.name); 5831 } 5832 } 5833 if (r != null) { 5834 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 5835 } 5836 5837 N = pkg.permissionGroups.size(); 5838 r = null; 5839 for (i=0; i<N; i++) { 5840 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 5841 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 5842 if (cur == null) { 5843 mPermissionGroups.put(pg.info.name, pg); 5844 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5845 if (r == null) { 5846 r = new StringBuilder(256); 5847 } else { 5848 r.append(' '); 5849 } 5850 r.append(pg.info.name); 5851 } 5852 } else { 5853 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 5854 + pg.info.packageName + " ignored: original from " 5855 + cur.info.packageName); 5856 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5857 if (r == null) { 5858 r = new StringBuilder(256); 5859 } else { 5860 r.append(' '); 5861 } 5862 r.append("DUP:"); 5863 r.append(pg.info.name); 5864 } 5865 } 5866 } 5867 if (r != null) { 5868 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 5869 } 5870 5871 N = pkg.permissions.size(); 5872 r = null; 5873 for (i=0; i<N; i++) { 5874 PackageParser.Permission p = pkg.permissions.get(i); 5875 HashMap<String, BasePermission> permissionMap = 5876 p.tree ? mSettings.mPermissionTrees 5877 : mSettings.mPermissions; 5878 p.group = mPermissionGroups.get(p.info.group); 5879 if (p.info.group == null || p.group != null) { 5880 BasePermission bp = permissionMap.get(p.info.name); 5881 if (bp == null) { 5882 bp = new BasePermission(p.info.name, p.info.packageName, 5883 BasePermission.TYPE_NORMAL); 5884 permissionMap.put(p.info.name, bp); 5885 } 5886 if (bp.perm == null) { 5887 if (bp.sourcePackage != null 5888 && !bp.sourcePackage.equals(p.info.packageName)) { 5889 // If this is a permission that was formerly defined by a non-system 5890 // app, but is now defined by a system app (following an upgrade), 5891 // discard the previous declaration and consider the system's to be 5892 // canonical. 5893 if (isSystemApp(p.owner)) { 5894 String msg = "New decl " + p.owner + " of permission " 5895 + p.info.name + " is system"; 5896 reportSettingsProblem(Log.WARN, msg); 5897 bp.sourcePackage = null; 5898 } 5899 } 5900 if (bp.sourcePackage == null 5901 || bp.sourcePackage.equals(p.info.packageName)) { 5902 BasePermission tree = findPermissionTreeLP(p.info.name); 5903 if (tree == null 5904 || tree.sourcePackage.equals(p.info.packageName)) { 5905 bp.packageSetting = pkgSetting; 5906 bp.perm = p; 5907 bp.uid = pkg.applicationInfo.uid; 5908 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5909 if (r == null) { 5910 r = new StringBuilder(256); 5911 } else { 5912 r.append(' '); 5913 } 5914 r.append(p.info.name); 5915 } 5916 } else { 5917 Slog.w(TAG, "Permission " + p.info.name + " from package " 5918 + p.info.packageName + " ignored: base tree " 5919 + tree.name + " is from package " 5920 + tree.sourcePackage); 5921 } 5922 } else { 5923 Slog.w(TAG, "Permission " + p.info.name + " from package " 5924 + p.info.packageName + " ignored: original from " 5925 + bp.sourcePackage); 5926 } 5927 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5928 if (r == null) { 5929 r = new StringBuilder(256); 5930 } else { 5931 r.append(' '); 5932 } 5933 r.append("DUP:"); 5934 r.append(p.info.name); 5935 } 5936 if (bp.perm == p) { 5937 bp.protectionLevel = p.info.protectionLevel; 5938 } 5939 } else { 5940 Slog.w(TAG, "Permission " + p.info.name + " from package " 5941 + p.info.packageName + " ignored: no group " 5942 + p.group); 5943 } 5944 } 5945 if (r != null) { 5946 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 5947 } 5948 5949 N = pkg.instrumentation.size(); 5950 r = null; 5951 for (i=0; i<N; i++) { 5952 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 5953 a.info.packageName = pkg.applicationInfo.packageName; 5954 a.info.sourceDir = pkg.applicationInfo.sourceDir; 5955 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 5956 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 5957 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 5958 a.info.dataDir = pkg.applicationInfo.dataDir; 5959 5960 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 5961 // need other information about the application, like the ABI and what not ? 5962 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 5963 mInstrumentation.put(a.getComponentName(), a); 5964 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5965 if (r == null) { 5966 r = new StringBuilder(256); 5967 } else { 5968 r.append(' '); 5969 } 5970 r.append(a.info.name); 5971 } 5972 } 5973 if (r != null) { 5974 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 5975 } 5976 5977 if (pkg.protectedBroadcasts != null) { 5978 N = pkg.protectedBroadcasts.size(); 5979 for (i=0; i<N; i++) { 5980 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 5981 } 5982 } 5983 5984 pkgSetting.setTimeStamp(scanFileTime); 5985 5986 // Create idmap files for pairs of (packages, overlay packages). 5987 // Note: "android", ie framework-res.apk, is handled by native layers. 5988 if (pkg.mOverlayTarget != null) { 5989 // This is an overlay package. 5990 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 5991 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 5992 mOverlays.put(pkg.mOverlayTarget, 5993 new HashMap<String, PackageParser.Package>()); 5994 } 5995 HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 5996 map.put(pkg.packageName, pkg); 5997 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 5998 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 5999 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 6000 return null; 6001 } 6002 } 6003 } else if (mOverlays.containsKey(pkg.packageName) && 6004 !pkg.packageName.equals("android")) { 6005 // This is a regular package, with one or more known overlay packages. 6006 createIdmapsForPackageLI(pkg); 6007 } 6008 } 6009 6010 return pkg; 6011 } 6012 6013 /** 6014 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6015 * i.e, so that all packages can be run inside a single process if required. 6016 * 6017 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6018 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6019 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6020 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6021 * updating a package that belongs to a shared user. 6022 * 6023 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6024 * adds unnecessary complexity. 6025 */ 6026 private boolean adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6027 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6028 String requiredInstructionSet = null; 6029 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6030 requiredInstructionSet = VMRuntime.getInstructionSet( 6031 scannedPackage.applicationInfo.primaryCpuAbi); 6032 } 6033 6034 PackageSetting requirer = null; 6035 for (PackageSetting ps : packagesForUser) { 6036 // If packagesForUser contains scannedPackage, we skip it. This will happen 6037 // when scannedPackage is an update of an existing package. Without this check, 6038 // we will never be able to change the ABI of any package belonging to a shared 6039 // user, even if it's compatible with other packages. 6040 if (scannedPackage == null || ! scannedPackage.packageName.equals(ps.name)) { 6041 if (ps.primaryCpuAbiString == null) { 6042 continue; 6043 } 6044 6045 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6046 if (requiredInstructionSet != null) { 6047 if (!instructionSet.equals(requiredInstructionSet)) { 6048 // We have a mismatch between instruction sets (say arm vs arm64). 6049 // bail out. 6050 String errorMessage = "Instruction set mismatch, " 6051 + ((requirer == null) ? "[caller]" : requirer) 6052 + " requires " + requiredInstructionSet + " whereas " + ps 6053 + " requires " + instructionSet; 6054 Slog.e(TAG, errorMessage); 6055 6056 reportSettingsProblem(Log.WARN, errorMessage); 6057 // Give up, don't bother making any other changes to the package settings. 6058 return false; 6059 } 6060 } else { 6061 requiredInstructionSet = instructionSet; 6062 requirer = ps; 6063 } 6064 } 6065 } 6066 6067 if (requiredInstructionSet != null) { 6068 String adjustedAbi; 6069 if (requirer != null) { 6070 // requirer != null implies that either scannedPackage was null or that scannedPackage 6071 // did not require an ABI, in which case we have to adjust scannedPackage to match 6072 // the ABI of the set (which is the same as requirer's ABI) 6073 adjustedAbi = requirer.primaryCpuAbiString; 6074 if (scannedPackage != null) { 6075 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6076 } 6077 } else { 6078 // requirer == null implies that we're updating all ABIs in the set to 6079 // match scannedPackage. 6080 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6081 } 6082 6083 for (PackageSetting ps : packagesForUser) { 6084 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6085 if (ps.primaryCpuAbiString != null) { 6086 continue; 6087 } 6088 6089 ps.primaryCpuAbiString = adjustedAbi; 6090 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6091 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6092 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6093 6094 if (performDexOptLI(ps.pkg, forceDexOpt, deferDexOpt, true) == DEX_OPT_FAILED) { 6095 ps.primaryCpuAbiString = null; 6096 ps.pkg.applicationInfo.primaryCpuAbi = null; 6097 return false; 6098 } else { 6099 mInstaller.rmdex(ps.codePathString, getPreferredInstructionSet()); 6100 } 6101 } 6102 } 6103 } 6104 } 6105 6106 return true; 6107 } 6108 6109 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6110 synchronized (mPackages) { 6111 mResolverReplaced = true; 6112 // Set up information for custom user intent resolution activity. 6113 mResolveActivity.applicationInfo = pkg.applicationInfo; 6114 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6115 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6116 mResolveActivity.processName = null; 6117 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6118 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6119 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6120 mResolveActivity.theme = 0; 6121 mResolveActivity.exported = true; 6122 mResolveActivity.enabled = true; 6123 mResolveInfo.activityInfo = mResolveActivity; 6124 mResolveInfo.priority = 0; 6125 mResolveInfo.preferredOrder = 0; 6126 mResolveInfo.match = 0; 6127 mResolveComponentName = mCustomResolverComponentName; 6128 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6129 mResolveComponentName); 6130 } 6131 } 6132 6133 private static String calculateApkRoot(final String codePathString) { 6134 final File codePath = new File(codePathString); 6135 final File codeRoot; 6136 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6137 codeRoot = Environment.getRootDirectory(); 6138 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6139 codeRoot = Environment.getOemDirectory(); 6140 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6141 codeRoot = Environment.getVendorDirectory(); 6142 } else { 6143 // Unrecognized code path; take its top real segment as the apk root: 6144 // e.g. /something/app/blah.apk => /something 6145 try { 6146 File f = codePath.getCanonicalFile(); 6147 File parent = f.getParentFile(); // non-null because codePath is a file 6148 File tmp; 6149 while ((tmp = parent.getParentFile()) != null) { 6150 f = parent; 6151 parent = tmp; 6152 } 6153 codeRoot = f; 6154 Slog.w(TAG, "Unrecognized code path " 6155 + codePath + " - using " + codeRoot); 6156 } catch (IOException e) { 6157 // Can't canonicalize the code path -- shenanigans? 6158 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6159 return Environment.getRootDirectory().getPath(); 6160 } 6161 } 6162 return codeRoot.getPath(); 6163 } 6164 6165 private void populateDefaultNativeLibraryPath(PackageParser.Package pkg, 6166 ApplicationInfo info) { 6167 if (info.legacyNativeLibraryDir != null) { 6168 // Not a cluster install. 6169 if (DEBUG_ABI_SELECTION) { 6170 Log.i(TAG, "Set nativeLibraryDir [non_cluster] for: " + pkg.packageName + 6171 " to " + info.legacyNativeLibraryDir); 6172 } 6173 info.nativeLibraryDir = info.legacyNativeLibraryDir; 6174 } else if (info.primaryCpuAbi != null) { 6175 final boolean is64Bit = VMRuntime.is64BitAbi(info.primaryCpuAbi); 6176 if (info.apkRoot != null) { 6177 // This is a bundled system app so choose the path based on the ABI. 6178 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 6179 // is just the default path. 6180 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 6181 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 6182 info.nativeLibraryDir = (new File(info.apkRoot, new File(libDir, apkName).getAbsolutePath())) 6183 .getAbsolutePath(); 6184 6185 if (DEBUG_ABI_SELECTION) { 6186 Log.i(TAG, "Set nativeLibraryDir [system] for: " + pkg.packageName + 6187 " to " + info.nativeLibraryDir); 6188 } 6189 } else { 6190 // Cluster install. legacyNativeLibraryDir == null && primaryCpuAbi = null 6191 // implies this must be a cluster package. 6192 final String codePath = pkg.codePath; 6193 final File libPath = new File(new File(codePath, LIB_DIR_NAME), 6194 VMRuntime.getInstructionSet(info.primaryCpuAbi)); 6195 info.nativeLibraryDir = libPath.getAbsolutePath(); 6196 6197 if (DEBUG_ABI_SELECTION) { 6198 Log.i(TAG, "Set nativeLibraryDir [cluster] for: " + pkg.packageName + 6199 " to " + info.nativeLibraryDir); 6200 } 6201 } 6202 } else { 6203 if (DEBUG_ABI_SELECTION) { 6204 Log.i(TAG, "Setting nativeLibraryDir to null for: " + pkg.packageName); 6205 } 6206 6207 info.nativeLibraryDir = null; 6208 } 6209 } 6210 6211 /** 6212 * Calculate the abis and roots for a bundled app. These can uniquely 6213 * be determined from the contents of the system partition, i.e whether 6214 * it contains 64 or 32 bit shared libraries etc. We do not validate any 6215 * of this information, and instead assume that the system was built 6216 * sensibly. 6217 */ 6218 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 6219 PackageSetting pkgSetting) { 6220 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 6221 6222 // If "/system/lib64/apkname" exists, assume that is the per-package 6223 // native library directory to use; otherwise use "/system/lib/apkname". 6224 final String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir); 6225 pkg.applicationInfo.apkRoot = apkRoot; 6226 setBundledAppAbi(pkg, apkRoot, apkName); 6227 // pkgSetting might be null during rescan following uninstall of updates 6228 // to a bundled app, so accommodate that possibility. The settings in 6229 // that case will be established later from the parsed package. 6230 // 6231 // If the settings aren't null, sync them up with what we've just derived. 6232 // note that apkRoot isn't stored in the package settings. 6233 if (pkgSetting != null) { 6234 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6235 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6236 } 6237 } 6238 6239 /** 6240 * Deduces the ABI of a bundled app and sets the relevant fields on the 6241 * parsed pkg object. 6242 * 6243 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 6244 * under which system libraries are installed. 6245 * @param apkName the name of the installed package. 6246 */ 6247 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 6248 // This is of the form "/system/lib64/<packagename>", "/vendor/lib64/<packagename>" 6249 // or similar. 6250 final boolean has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 6251 final boolean has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 6252 6253 if (has64BitLibs && !has32BitLibs) { 6254 // The package has 64 bit libs, but not 32 bit libs. Its primary 6255 // ABI should be 64 bit. We can safely assume here that the bundled 6256 // native libraries correspond to the most preferred ABI in the list. 6257 6258 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6259 pkg.applicationInfo.secondaryCpuAbi = null; 6260 } else if (has32BitLibs && !has64BitLibs) { 6261 // The package has 32 bit libs but not 64 bit libs. Its primary 6262 // ABI should be 32 bit. 6263 6264 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6265 pkg.applicationInfo.secondaryCpuAbi = null; 6266 } else if (has32BitLibs && has64BitLibs) { 6267 // The application has both 64 and 32 bit bundled libraries. We check 6268 // here that the app declares multiArch support, and warn if it doesn't. 6269 // 6270 // We will be lenient here and record both ABIs. The primary will be the 6271 // ABI that's higher on the list, i.e, a device that's configured to prefer 6272 // 64 bit apps will see a 64 bit primary ABI, 6273 6274 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 6275 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 6276 } 6277 6278 if (VMRuntime.is64BitAbi(getPreferredInstructionSet())) { 6279 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6280 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6281 } else { 6282 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6283 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6284 } 6285 } else { 6286 pkg.applicationInfo.primaryCpuAbi = null; 6287 pkg.applicationInfo.secondaryCpuAbi = null; 6288 } 6289 } 6290 6291 private static void createNativeLibrarySubdir(File path) throws IOException { 6292 if (!path.isDirectory()) { 6293 path.delete(); 6294 6295 if (!path.mkdir()) { 6296 throw new IOException("Cannot create " + path.getPath()); 6297 } 6298 6299 try { 6300 Os.chmod(path.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); 6301 } catch (ErrnoException e) { 6302 throw new IOException("Cannot chmod native library directory " 6303 + path.getPath(), e); 6304 } 6305 } else if (!SELinux.restorecon(path)) { 6306 throw new IOException("Cannot set SELinux context for " + path.getPath()); 6307 } 6308 } 6309 6310 private static int copyNativeLibrariesForInternalApp(NativeLibraryHelper.Handle handle, 6311 final File nativeLibraryRoot, String[] abiList, boolean useIsaSubdir) throws IOException { 6312 createNativeLibrarySubdir(nativeLibraryRoot); 6313 6314 /* 6315 * If this is an internal application or our nativeLibraryPath points to 6316 * the app-lib directory, unpack the libraries if necessary. 6317 */ 6318 int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList); 6319 if (abi >= 0) { 6320 /* 6321 * If we have a matching instruction set, construct a subdir under the native 6322 * library root that corresponds to this instruction set. 6323 */ 6324 final String instructionSet = VMRuntime.getInstructionSet(abiList[abi]); 6325 final File subDir; 6326 if (useIsaSubdir) { 6327 final File isaSubdir = new File(nativeLibraryRoot, instructionSet); 6328 createNativeLibrarySubdir(isaSubdir); 6329 subDir = isaSubdir; 6330 } else { 6331 subDir = nativeLibraryRoot; 6332 } 6333 6334 int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle, 6335 subDir, Build.SUPPORTED_ABIS[abi]); 6336 if (copyRet != PackageManager.INSTALL_SUCCEEDED) { 6337 return copyRet; 6338 } 6339 } 6340 6341 return abi; 6342 } 6343 6344 private void killApplication(String pkgName, int appId, String reason) { 6345 // Request the ActivityManager to kill the process(only for existing packages) 6346 // so that we do not end up in a confused state while the user is still using the older 6347 // version of the application while the new one gets installed. 6348 IActivityManager am = ActivityManagerNative.getDefault(); 6349 if (am != null) { 6350 try { 6351 am.killApplicationWithAppId(pkgName, appId, reason); 6352 } catch (RemoteException e) { 6353 } 6354 } 6355 } 6356 6357 void removePackageLI(PackageSetting ps, boolean chatty) { 6358 if (DEBUG_INSTALL) { 6359 if (chatty) 6360 Log.d(TAG, "Removing package " + ps.name); 6361 } 6362 6363 // writer 6364 synchronized (mPackages) { 6365 mPackages.remove(ps.name); 6366 if (ps.codePathString != null) { 6367 mAppDirs.remove(ps.codePathString); 6368 } 6369 6370 final PackageParser.Package pkg = ps.pkg; 6371 if (pkg != null) { 6372 cleanPackageDataStructuresLILPw(pkg, chatty); 6373 } 6374 } 6375 } 6376 6377 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 6378 if (DEBUG_INSTALL) { 6379 if (chatty) 6380 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 6381 } 6382 6383 // writer 6384 synchronized (mPackages) { 6385 mPackages.remove(pkg.applicationInfo.packageName); 6386 if (pkg.codePath != null) { 6387 mAppDirs.remove(pkg.codePath); 6388 } 6389 cleanPackageDataStructuresLILPw(pkg, chatty); 6390 } 6391 } 6392 6393 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 6394 int N = pkg.providers.size(); 6395 StringBuilder r = null; 6396 int i; 6397 for (i=0; i<N; i++) { 6398 PackageParser.Provider p = pkg.providers.get(i); 6399 mProviders.removeProvider(p); 6400 if (p.info.authority == null) { 6401 6402 /* There was another ContentProvider with this authority when 6403 * this app was installed so this authority is null, 6404 * Ignore it as we don't have to unregister the provider. 6405 */ 6406 continue; 6407 } 6408 String names[] = p.info.authority.split(";"); 6409 for (int j = 0; j < names.length; j++) { 6410 if (mProvidersByAuthority.get(names[j]) == p) { 6411 mProvidersByAuthority.remove(names[j]); 6412 if (DEBUG_REMOVE) { 6413 if (chatty) 6414 Log.d(TAG, "Unregistered content provider: " + names[j] 6415 + ", className = " + p.info.name + ", isSyncable = " 6416 + p.info.isSyncable); 6417 } 6418 } 6419 } 6420 if (DEBUG_REMOVE && chatty) { 6421 if (r == null) { 6422 r = new StringBuilder(256); 6423 } else { 6424 r.append(' '); 6425 } 6426 r.append(p.info.name); 6427 } 6428 } 6429 if (r != null) { 6430 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 6431 } 6432 6433 N = pkg.services.size(); 6434 r = null; 6435 for (i=0; i<N; i++) { 6436 PackageParser.Service s = pkg.services.get(i); 6437 mServices.removeService(s); 6438 if (chatty) { 6439 if (r == null) { 6440 r = new StringBuilder(256); 6441 } else { 6442 r.append(' '); 6443 } 6444 r.append(s.info.name); 6445 } 6446 } 6447 if (r != null) { 6448 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 6449 } 6450 6451 N = pkg.receivers.size(); 6452 r = null; 6453 for (i=0; i<N; i++) { 6454 PackageParser.Activity a = pkg.receivers.get(i); 6455 mReceivers.removeActivity(a, "receiver"); 6456 if (DEBUG_REMOVE && chatty) { 6457 if (r == null) { 6458 r = new StringBuilder(256); 6459 } else { 6460 r.append(' '); 6461 } 6462 r.append(a.info.name); 6463 } 6464 } 6465 if (r != null) { 6466 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 6467 } 6468 6469 N = pkg.activities.size(); 6470 r = null; 6471 for (i=0; i<N; i++) { 6472 PackageParser.Activity a = pkg.activities.get(i); 6473 mActivities.removeActivity(a, "activity"); 6474 if (DEBUG_REMOVE && chatty) { 6475 if (r == null) { 6476 r = new StringBuilder(256); 6477 } else { 6478 r.append(' '); 6479 } 6480 r.append(a.info.name); 6481 } 6482 } 6483 if (r != null) { 6484 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 6485 } 6486 6487 N = pkg.permissions.size(); 6488 r = null; 6489 for (i=0; i<N; i++) { 6490 PackageParser.Permission p = pkg.permissions.get(i); 6491 BasePermission bp = mSettings.mPermissions.get(p.info.name); 6492 if (bp == null) { 6493 bp = mSettings.mPermissionTrees.get(p.info.name); 6494 } 6495 if (bp != null && bp.perm == p) { 6496 bp.perm = null; 6497 if (DEBUG_REMOVE && chatty) { 6498 if (r == null) { 6499 r = new StringBuilder(256); 6500 } else { 6501 r.append(' '); 6502 } 6503 r.append(p.info.name); 6504 } 6505 } 6506 } 6507 if (r != null) { 6508 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6509 } 6510 6511 N = pkg.instrumentation.size(); 6512 r = null; 6513 for (i=0; i<N; i++) { 6514 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6515 mInstrumentation.remove(a.getComponentName()); 6516 if (DEBUG_REMOVE && chatty) { 6517 if (r == null) { 6518 r = new StringBuilder(256); 6519 } else { 6520 r.append(' '); 6521 } 6522 r.append(a.info.name); 6523 } 6524 } 6525 if (r != null) { 6526 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 6527 } 6528 6529 r = null; 6530 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6531 // Only system apps can hold shared libraries. 6532 if (pkg.libraryNames != null) { 6533 for (i=0; i<pkg.libraryNames.size(); i++) { 6534 String name = pkg.libraryNames.get(i); 6535 SharedLibraryEntry cur = mSharedLibraries.get(name); 6536 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 6537 mSharedLibraries.remove(name); 6538 if (DEBUG_REMOVE && chatty) { 6539 if (r == null) { 6540 r = new StringBuilder(256); 6541 } else { 6542 r.append(' '); 6543 } 6544 r.append(name); 6545 } 6546 } 6547 } 6548 } 6549 } 6550 if (r != null) { 6551 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 6552 } 6553 } 6554 6555 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 6556 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 6557 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 6558 return true; 6559 } 6560 } 6561 return false; 6562 } 6563 6564 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 6565 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 6566 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 6567 6568 private void updatePermissionsLPw(String changingPkg, 6569 PackageParser.Package pkgInfo, int flags) { 6570 // Make sure there are no dangling permission trees. 6571 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 6572 while (it.hasNext()) { 6573 final BasePermission bp = it.next(); 6574 if (bp.packageSetting == null) { 6575 // We may not yet have parsed the package, so just see if 6576 // we still know about its settings. 6577 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6578 } 6579 if (bp.packageSetting == null) { 6580 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 6581 + " from package " + bp.sourcePackage); 6582 it.remove(); 6583 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6584 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6585 Slog.i(TAG, "Removing old permission tree: " + bp.name 6586 + " from package " + bp.sourcePackage); 6587 flags |= UPDATE_PERMISSIONS_ALL; 6588 it.remove(); 6589 } 6590 } 6591 } 6592 6593 // Make sure all dynamic permissions have been assigned to a package, 6594 // and make sure there are no dangling permissions. 6595 it = mSettings.mPermissions.values().iterator(); 6596 while (it.hasNext()) { 6597 final BasePermission bp = it.next(); 6598 if (bp.type == BasePermission.TYPE_DYNAMIC) { 6599 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 6600 + bp.name + " pkg=" + bp.sourcePackage 6601 + " info=" + bp.pendingInfo); 6602 if (bp.packageSetting == null && bp.pendingInfo != null) { 6603 final BasePermission tree = findPermissionTreeLP(bp.name); 6604 if (tree != null && tree.perm != null) { 6605 bp.packageSetting = tree.packageSetting; 6606 bp.perm = new PackageParser.Permission(tree.perm.owner, 6607 new PermissionInfo(bp.pendingInfo)); 6608 bp.perm.info.packageName = tree.perm.info.packageName; 6609 bp.perm.info.name = bp.name; 6610 bp.uid = tree.uid; 6611 } 6612 } 6613 } 6614 if (bp.packageSetting == null) { 6615 // We may not yet have parsed the package, so just see if 6616 // we still know about its settings. 6617 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6618 } 6619 if (bp.packageSetting == null) { 6620 Slog.w(TAG, "Removing dangling permission: " + bp.name 6621 + " from package " + bp.sourcePackage); 6622 it.remove(); 6623 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6624 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6625 Slog.i(TAG, "Removing old permission: " + bp.name 6626 + " from package " + bp.sourcePackage); 6627 flags |= UPDATE_PERMISSIONS_ALL; 6628 it.remove(); 6629 } 6630 } 6631 } 6632 6633 // Now update the permissions for all packages, in particular 6634 // replace the granted permissions of the system packages. 6635 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 6636 for (PackageParser.Package pkg : mPackages.values()) { 6637 if (pkg != pkgInfo) { 6638 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0); 6639 } 6640 } 6641 } 6642 6643 if (pkgInfo != null) { 6644 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0); 6645 } 6646 } 6647 6648 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) { 6649 final PackageSetting ps = (PackageSetting) pkg.mExtras; 6650 if (ps == null) { 6651 return; 6652 } 6653 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 6654 HashSet<String> origPermissions = gp.grantedPermissions; 6655 boolean changedPermission = false; 6656 6657 if (replace) { 6658 ps.permissionsFixed = false; 6659 if (gp == ps) { 6660 origPermissions = new HashSet<String>(gp.grantedPermissions); 6661 gp.grantedPermissions.clear(); 6662 gp.gids = mGlobalGids; 6663 } 6664 } 6665 6666 if (gp.gids == null) { 6667 gp.gids = mGlobalGids; 6668 } 6669 6670 final int N = pkg.requestedPermissions.size(); 6671 for (int i=0; i<N; i++) { 6672 final String name = pkg.requestedPermissions.get(i); 6673 final boolean required = pkg.requestedPermissionsRequired.get(i); 6674 final BasePermission bp = mSettings.mPermissions.get(name); 6675 if (DEBUG_INSTALL) { 6676 if (gp != ps) { 6677 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 6678 } 6679 } 6680 6681 if (bp == null || bp.packageSetting == null) { 6682 Slog.w(TAG, "Unknown permission " + name 6683 + " in package " + pkg.packageName); 6684 continue; 6685 } 6686 6687 final String perm = bp.name; 6688 boolean allowed; 6689 boolean allowedSig = false; 6690 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 6691 if (level == PermissionInfo.PROTECTION_NORMAL 6692 || level == PermissionInfo.PROTECTION_DANGEROUS) { 6693 // We grant a normal or dangerous permission if any of the following 6694 // are true: 6695 // 1) The permission is required 6696 // 2) The permission is optional, but was granted in the past 6697 // 3) The permission is optional, but was requested by an 6698 // app in /system (not /data) 6699 // 6700 // Otherwise, reject the permission. 6701 allowed = (required || origPermissions.contains(perm) 6702 || (isSystemApp(ps) && !isUpdatedSystemApp(ps))); 6703 } else if (bp.packageSetting == null) { 6704 // This permission is invalid; skip it. 6705 allowed = false; 6706 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 6707 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions); 6708 if (allowed) { 6709 allowedSig = true; 6710 } 6711 } else { 6712 allowed = false; 6713 } 6714 if (DEBUG_INSTALL) { 6715 if (gp != ps) { 6716 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 6717 } 6718 } 6719 if (allowed) { 6720 if (!isSystemApp(ps) && ps.permissionsFixed) { 6721 // If this is an existing, non-system package, then 6722 // we can't add any new permissions to it. 6723 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 6724 // Except... if this is a permission that was added 6725 // to the platform (note: need to only do this when 6726 // updating the platform). 6727 allowed = isNewPlatformPermissionForPackage(perm, pkg); 6728 } 6729 } 6730 if (allowed) { 6731 if (!gp.grantedPermissions.contains(perm)) { 6732 changedPermission = true; 6733 gp.grantedPermissions.add(perm); 6734 gp.gids = appendInts(gp.gids, bp.gids); 6735 } else if (!ps.haveGids) { 6736 gp.gids = appendInts(gp.gids, bp.gids); 6737 } 6738 } else { 6739 Slog.w(TAG, "Not granting permission " + perm 6740 + " to package " + pkg.packageName 6741 + " because it was previously installed without"); 6742 } 6743 } else { 6744 if (gp.grantedPermissions.remove(perm)) { 6745 changedPermission = true; 6746 gp.gids = removeInts(gp.gids, bp.gids); 6747 Slog.i(TAG, "Un-granting permission " + perm 6748 + " from package " + pkg.packageName 6749 + " (protectionLevel=" + bp.protectionLevel 6750 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6751 + ")"); 6752 } else { 6753 Slog.w(TAG, "Not granting permission " + perm 6754 + " to package " + pkg.packageName 6755 + " (protectionLevel=" + bp.protectionLevel 6756 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6757 + ")"); 6758 } 6759 } 6760 } 6761 6762 if ((changedPermission || replace) && !ps.permissionsFixed && 6763 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 6764 // This is the first that we have heard about this package, so the 6765 // permissions we have now selected are fixed until explicitly 6766 // changed. 6767 ps.permissionsFixed = true; 6768 } 6769 ps.haveGids = true; 6770 } 6771 6772 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 6773 boolean allowed = false; 6774 final int NP = PackageParser.NEW_PERMISSIONS.length; 6775 for (int ip=0; ip<NP; ip++) { 6776 final PackageParser.NewPermissionInfo npi 6777 = PackageParser.NEW_PERMISSIONS[ip]; 6778 if (npi.name.equals(perm) 6779 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 6780 allowed = true; 6781 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 6782 + pkg.packageName); 6783 break; 6784 } 6785 } 6786 return allowed; 6787 } 6788 6789 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 6790 BasePermission bp, HashSet<String> origPermissions) { 6791 boolean allowed; 6792 allowed = (compareSignatures( 6793 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 6794 == PackageManager.SIGNATURE_MATCH) 6795 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 6796 == PackageManager.SIGNATURE_MATCH); 6797 if (!allowed && (bp.protectionLevel 6798 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 6799 if (isSystemApp(pkg)) { 6800 // For updated system applications, a system permission 6801 // is granted only if it had been defined by the original application. 6802 if (isUpdatedSystemApp(pkg)) { 6803 final PackageSetting sysPs = mSettings 6804 .getDisabledSystemPkgLPr(pkg.packageName); 6805 final GrantedPermissions origGp = sysPs.sharedUser != null 6806 ? sysPs.sharedUser : sysPs; 6807 6808 if (origGp.grantedPermissions.contains(perm)) { 6809 // If the original was granted this permission, we take 6810 // that grant decision as read and propagate it to the 6811 // update. 6812 allowed = true; 6813 } else { 6814 // The system apk may have been updated with an older 6815 // version of the one on the data partition, but which 6816 // granted a new system permission that it didn't have 6817 // before. In this case we do want to allow the app to 6818 // now get the new permission if the ancestral apk is 6819 // privileged to get it. 6820 if (sysPs.pkg != null && sysPs.isPrivileged()) { 6821 for (int j=0; 6822 j<sysPs.pkg.requestedPermissions.size(); j++) { 6823 if (perm.equals( 6824 sysPs.pkg.requestedPermissions.get(j))) { 6825 allowed = true; 6826 break; 6827 } 6828 } 6829 } 6830 } 6831 } else { 6832 allowed = isPrivilegedApp(pkg); 6833 } 6834 } 6835 } 6836 if (!allowed && (bp.protectionLevel 6837 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 6838 // For development permissions, a development permission 6839 // is granted only if it was already granted. 6840 allowed = origPermissions.contains(perm); 6841 } 6842 return allowed; 6843 } 6844 6845 final class ActivityIntentResolver 6846 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 6847 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 6848 boolean defaultOnly, int userId) { 6849 if (!sUserManager.exists(userId)) return null; 6850 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 6851 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 6852 } 6853 6854 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 6855 int userId) { 6856 if (!sUserManager.exists(userId)) return null; 6857 mFlags = flags; 6858 return super.queryIntent(intent, resolvedType, 6859 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 6860 } 6861 6862 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 6863 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 6864 if (!sUserManager.exists(userId)) return null; 6865 if (packageActivities == null) { 6866 return null; 6867 } 6868 mFlags = flags; 6869 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 6870 final int N = packageActivities.size(); 6871 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 6872 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 6873 6874 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 6875 for (int i = 0; i < N; ++i) { 6876 intentFilters = packageActivities.get(i).intents; 6877 if (intentFilters != null && intentFilters.size() > 0) { 6878 PackageParser.ActivityIntentInfo[] array = 6879 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 6880 intentFilters.toArray(array); 6881 listCut.add(array); 6882 } 6883 } 6884 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 6885 } 6886 6887 public final void addActivity(PackageParser.Activity a, String type) { 6888 final boolean systemApp = isSystemApp(a.info.applicationInfo); 6889 mActivities.put(a.getComponentName(), a); 6890 if (DEBUG_SHOW_INFO) 6891 Log.v( 6892 TAG, " " + type + " " + 6893 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 6894 if (DEBUG_SHOW_INFO) 6895 Log.v(TAG, " Class=" + a.info.name); 6896 final int NI = a.intents.size(); 6897 for (int j=0; j<NI; j++) { 6898 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 6899 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 6900 intent.setPriority(0); 6901 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 6902 + a.className + " with priority > 0, forcing to 0"); 6903 } 6904 if (DEBUG_SHOW_INFO) { 6905 Log.v(TAG, " IntentFilter:"); 6906 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6907 } 6908 if (!intent.debugCheck()) { 6909 Log.w(TAG, "==> For Activity " + a.info.name); 6910 } 6911 addFilter(intent); 6912 } 6913 } 6914 6915 public final void removeActivity(PackageParser.Activity a, String type) { 6916 mActivities.remove(a.getComponentName()); 6917 if (DEBUG_SHOW_INFO) { 6918 Log.v(TAG, " " + type + " " 6919 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 6920 : a.info.name) + ":"); 6921 Log.v(TAG, " Class=" + a.info.name); 6922 } 6923 final int NI = a.intents.size(); 6924 for (int j=0; j<NI; j++) { 6925 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 6926 if (DEBUG_SHOW_INFO) { 6927 Log.v(TAG, " IntentFilter:"); 6928 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6929 } 6930 removeFilter(intent); 6931 } 6932 } 6933 6934 @Override 6935 protected boolean allowFilterResult( 6936 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 6937 ActivityInfo filterAi = filter.activity.info; 6938 for (int i=dest.size()-1; i>=0; i--) { 6939 ActivityInfo destAi = dest.get(i).activityInfo; 6940 if (destAi.name == filterAi.name 6941 && destAi.packageName == filterAi.packageName) { 6942 return false; 6943 } 6944 } 6945 return true; 6946 } 6947 6948 @Override 6949 protected ActivityIntentInfo[] newArray(int size) { 6950 return new ActivityIntentInfo[size]; 6951 } 6952 6953 @Override 6954 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 6955 if (!sUserManager.exists(userId)) return true; 6956 PackageParser.Package p = filter.activity.owner; 6957 if (p != null) { 6958 PackageSetting ps = (PackageSetting)p.mExtras; 6959 if (ps != null) { 6960 // System apps are never considered stopped for purposes of 6961 // filtering, because there may be no way for the user to 6962 // actually re-launch them. 6963 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 6964 && ps.getStopped(userId); 6965 } 6966 } 6967 return false; 6968 } 6969 6970 @Override 6971 protected boolean isPackageForFilter(String packageName, 6972 PackageParser.ActivityIntentInfo info) { 6973 return packageName.equals(info.activity.owner.packageName); 6974 } 6975 6976 @Override 6977 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 6978 int match, int userId) { 6979 if (!sUserManager.exists(userId)) return null; 6980 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 6981 return null; 6982 } 6983 final PackageParser.Activity activity = info.activity; 6984 if (mSafeMode && (activity.info.applicationInfo.flags 6985 &ApplicationInfo.FLAG_SYSTEM) == 0) { 6986 return null; 6987 } 6988 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 6989 if (ps == null) { 6990 return null; 6991 } 6992 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 6993 ps.readUserState(userId), userId); 6994 if (ai == null) { 6995 return null; 6996 } 6997 final ResolveInfo res = new ResolveInfo(); 6998 res.activityInfo = ai; 6999 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7000 res.filter = info; 7001 } 7002 res.priority = info.getPriority(); 7003 res.preferredOrder = activity.owner.mPreferredOrder; 7004 //System.out.println("Result: " + res.activityInfo.className + 7005 // " = " + res.priority); 7006 res.match = match; 7007 res.isDefault = info.hasDefault; 7008 res.labelRes = info.labelRes; 7009 res.nonLocalizedLabel = info.nonLocalizedLabel; 7010 if (userNeedsBadging(userId)) { 7011 res.noResourceId = true; 7012 } else { 7013 res.icon = info.icon; 7014 } 7015 res.system = isSystemApp(res.activityInfo.applicationInfo); 7016 return res; 7017 } 7018 7019 @Override 7020 protected void sortResults(List<ResolveInfo> results) { 7021 Collections.sort(results, mResolvePrioritySorter); 7022 } 7023 7024 @Override 7025 protected void dumpFilter(PrintWriter out, String prefix, 7026 PackageParser.ActivityIntentInfo filter) { 7027 out.print(prefix); out.print( 7028 Integer.toHexString(System.identityHashCode(filter.activity))); 7029 out.print(' '); 7030 filter.activity.printComponentShortName(out); 7031 out.print(" filter "); 7032 out.println(Integer.toHexString(System.identityHashCode(filter))); 7033 } 7034 7035// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7036// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7037// final List<ResolveInfo> retList = Lists.newArrayList(); 7038// while (i.hasNext()) { 7039// final ResolveInfo resolveInfo = i.next(); 7040// if (isEnabledLP(resolveInfo.activityInfo)) { 7041// retList.add(resolveInfo); 7042// } 7043// } 7044// return retList; 7045// } 7046 7047 // Keys are String (activity class name), values are Activity. 7048 private final HashMap<ComponentName, PackageParser.Activity> mActivities 7049 = new HashMap<ComponentName, PackageParser.Activity>(); 7050 private int mFlags; 7051 } 7052 7053 private final class ServiceIntentResolver 7054 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 7055 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7056 boolean defaultOnly, int userId) { 7057 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7058 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7059 } 7060 7061 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7062 int userId) { 7063 if (!sUserManager.exists(userId)) return null; 7064 mFlags = flags; 7065 return super.queryIntent(intent, resolvedType, 7066 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7067 } 7068 7069 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7070 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 7071 if (!sUserManager.exists(userId)) return null; 7072 if (packageServices == null) { 7073 return null; 7074 } 7075 mFlags = flags; 7076 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7077 final int N = packageServices.size(); 7078 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 7079 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 7080 7081 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 7082 for (int i = 0; i < N; ++i) { 7083 intentFilters = packageServices.get(i).intents; 7084 if (intentFilters != null && intentFilters.size() > 0) { 7085 PackageParser.ServiceIntentInfo[] array = 7086 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 7087 intentFilters.toArray(array); 7088 listCut.add(array); 7089 } 7090 } 7091 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7092 } 7093 7094 public final void addService(PackageParser.Service s) { 7095 mServices.put(s.getComponentName(), s); 7096 if (DEBUG_SHOW_INFO) { 7097 Log.v(TAG, " " 7098 + (s.info.nonLocalizedLabel != null 7099 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7100 Log.v(TAG, " Class=" + s.info.name); 7101 } 7102 final int NI = s.intents.size(); 7103 int j; 7104 for (j=0; j<NI; j++) { 7105 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7106 if (DEBUG_SHOW_INFO) { 7107 Log.v(TAG, " IntentFilter:"); 7108 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7109 } 7110 if (!intent.debugCheck()) { 7111 Log.w(TAG, "==> For Service " + s.info.name); 7112 } 7113 addFilter(intent); 7114 } 7115 } 7116 7117 public final void removeService(PackageParser.Service s) { 7118 mServices.remove(s.getComponentName()); 7119 if (DEBUG_SHOW_INFO) { 7120 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 7121 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7122 Log.v(TAG, " Class=" + s.info.name); 7123 } 7124 final int NI = s.intents.size(); 7125 int j; 7126 for (j=0; j<NI; j++) { 7127 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7128 if (DEBUG_SHOW_INFO) { 7129 Log.v(TAG, " IntentFilter:"); 7130 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7131 } 7132 removeFilter(intent); 7133 } 7134 } 7135 7136 @Override 7137 protected boolean allowFilterResult( 7138 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 7139 ServiceInfo filterSi = filter.service.info; 7140 for (int i=dest.size()-1; i>=0; i--) { 7141 ServiceInfo destAi = dest.get(i).serviceInfo; 7142 if (destAi.name == filterSi.name 7143 && destAi.packageName == filterSi.packageName) { 7144 return false; 7145 } 7146 } 7147 return true; 7148 } 7149 7150 @Override 7151 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 7152 return new PackageParser.ServiceIntentInfo[size]; 7153 } 7154 7155 @Override 7156 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 7157 if (!sUserManager.exists(userId)) return true; 7158 PackageParser.Package p = filter.service.owner; 7159 if (p != null) { 7160 PackageSetting ps = (PackageSetting)p.mExtras; 7161 if (ps != null) { 7162 // System apps are never considered stopped for purposes of 7163 // filtering, because there may be no way for the user to 7164 // actually re-launch them. 7165 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7166 && ps.getStopped(userId); 7167 } 7168 } 7169 return false; 7170 } 7171 7172 @Override 7173 protected boolean isPackageForFilter(String packageName, 7174 PackageParser.ServiceIntentInfo info) { 7175 return packageName.equals(info.service.owner.packageName); 7176 } 7177 7178 @Override 7179 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 7180 int match, int userId) { 7181 if (!sUserManager.exists(userId)) return null; 7182 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 7183 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 7184 return null; 7185 } 7186 final PackageParser.Service service = info.service; 7187 if (mSafeMode && (service.info.applicationInfo.flags 7188 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7189 return null; 7190 } 7191 PackageSetting ps = (PackageSetting) service.owner.mExtras; 7192 if (ps == null) { 7193 return null; 7194 } 7195 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 7196 ps.readUserState(userId), userId); 7197 if (si == null) { 7198 return null; 7199 } 7200 final ResolveInfo res = new ResolveInfo(); 7201 res.serviceInfo = si; 7202 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7203 res.filter = filter; 7204 } 7205 res.priority = info.getPriority(); 7206 res.preferredOrder = service.owner.mPreferredOrder; 7207 //System.out.println("Result: " + res.activityInfo.className + 7208 // " = " + res.priority); 7209 res.match = match; 7210 res.isDefault = info.hasDefault; 7211 res.labelRes = info.labelRes; 7212 res.nonLocalizedLabel = info.nonLocalizedLabel; 7213 res.icon = info.icon; 7214 res.system = isSystemApp(res.serviceInfo.applicationInfo); 7215 return res; 7216 } 7217 7218 @Override 7219 protected void sortResults(List<ResolveInfo> results) { 7220 Collections.sort(results, mResolvePrioritySorter); 7221 } 7222 7223 @Override 7224 protected void dumpFilter(PrintWriter out, String prefix, 7225 PackageParser.ServiceIntentInfo filter) { 7226 out.print(prefix); out.print( 7227 Integer.toHexString(System.identityHashCode(filter.service))); 7228 out.print(' '); 7229 filter.service.printComponentShortName(out); 7230 out.print(" filter "); 7231 out.println(Integer.toHexString(System.identityHashCode(filter))); 7232 } 7233 7234// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7235// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7236// final List<ResolveInfo> retList = Lists.newArrayList(); 7237// while (i.hasNext()) { 7238// final ResolveInfo resolveInfo = (ResolveInfo) i; 7239// if (isEnabledLP(resolveInfo.serviceInfo)) { 7240// retList.add(resolveInfo); 7241// } 7242// } 7243// return retList; 7244// } 7245 7246 // Keys are String (activity class name), values are Activity. 7247 private final HashMap<ComponentName, PackageParser.Service> mServices 7248 = new HashMap<ComponentName, PackageParser.Service>(); 7249 private int mFlags; 7250 }; 7251 7252 private final class ProviderIntentResolver 7253 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 7254 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7255 boolean defaultOnly, int userId) { 7256 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7257 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7258 } 7259 7260 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7261 int userId) { 7262 if (!sUserManager.exists(userId)) 7263 return null; 7264 mFlags = flags; 7265 return super.queryIntent(intent, resolvedType, 7266 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7267 } 7268 7269 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7270 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 7271 if (!sUserManager.exists(userId)) 7272 return null; 7273 if (packageProviders == null) { 7274 return null; 7275 } 7276 mFlags = flags; 7277 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 7278 final int N = packageProviders.size(); 7279 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 7280 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 7281 7282 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 7283 for (int i = 0; i < N; ++i) { 7284 intentFilters = packageProviders.get(i).intents; 7285 if (intentFilters != null && intentFilters.size() > 0) { 7286 PackageParser.ProviderIntentInfo[] array = 7287 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 7288 intentFilters.toArray(array); 7289 listCut.add(array); 7290 } 7291 } 7292 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7293 } 7294 7295 public final void addProvider(PackageParser.Provider p) { 7296 if (mProviders.containsKey(p.getComponentName())) { 7297 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 7298 return; 7299 } 7300 7301 mProviders.put(p.getComponentName(), p); 7302 if (DEBUG_SHOW_INFO) { 7303 Log.v(TAG, " " 7304 + (p.info.nonLocalizedLabel != null 7305 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7306 Log.v(TAG, " Class=" + p.info.name); 7307 } 7308 final int NI = p.intents.size(); 7309 int j; 7310 for (j = 0; j < NI; j++) { 7311 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7312 if (DEBUG_SHOW_INFO) { 7313 Log.v(TAG, " IntentFilter:"); 7314 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7315 } 7316 if (!intent.debugCheck()) { 7317 Log.w(TAG, "==> For Provider " + p.info.name); 7318 } 7319 addFilter(intent); 7320 } 7321 } 7322 7323 public final void removeProvider(PackageParser.Provider p) { 7324 mProviders.remove(p.getComponentName()); 7325 if (DEBUG_SHOW_INFO) { 7326 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 7327 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7328 Log.v(TAG, " Class=" + p.info.name); 7329 } 7330 final int NI = p.intents.size(); 7331 int j; 7332 for (j = 0; j < NI; j++) { 7333 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7334 if (DEBUG_SHOW_INFO) { 7335 Log.v(TAG, " IntentFilter:"); 7336 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7337 } 7338 removeFilter(intent); 7339 } 7340 } 7341 7342 @Override 7343 protected boolean allowFilterResult( 7344 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 7345 ProviderInfo filterPi = filter.provider.info; 7346 for (int i = dest.size() - 1; i >= 0; i--) { 7347 ProviderInfo destPi = dest.get(i).providerInfo; 7348 if (destPi.name == filterPi.name 7349 && destPi.packageName == filterPi.packageName) { 7350 return false; 7351 } 7352 } 7353 return true; 7354 } 7355 7356 @Override 7357 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 7358 return new PackageParser.ProviderIntentInfo[size]; 7359 } 7360 7361 @Override 7362 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 7363 if (!sUserManager.exists(userId)) 7364 return true; 7365 PackageParser.Package p = filter.provider.owner; 7366 if (p != null) { 7367 PackageSetting ps = (PackageSetting) p.mExtras; 7368 if (ps != null) { 7369 // System apps are never considered stopped for purposes of 7370 // filtering, because there may be no way for the user to 7371 // actually re-launch them. 7372 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7373 && ps.getStopped(userId); 7374 } 7375 } 7376 return false; 7377 } 7378 7379 @Override 7380 protected boolean isPackageForFilter(String packageName, 7381 PackageParser.ProviderIntentInfo info) { 7382 return packageName.equals(info.provider.owner.packageName); 7383 } 7384 7385 @Override 7386 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 7387 int match, int userId) { 7388 if (!sUserManager.exists(userId)) 7389 return null; 7390 final PackageParser.ProviderIntentInfo info = filter; 7391 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 7392 return null; 7393 } 7394 final PackageParser.Provider provider = info.provider; 7395 if (mSafeMode && (provider.info.applicationInfo.flags 7396 & ApplicationInfo.FLAG_SYSTEM) == 0) { 7397 return null; 7398 } 7399 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 7400 if (ps == null) { 7401 return null; 7402 } 7403 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 7404 ps.readUserState(userId), userId); 7405 if (pi == null) { 7406 return null; 7407 } 7408 final ResolveInfo res = new ResolveInfo(); 7409 res.providerInfo = pi; 7410 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 7411 res.filter = filter; 7412 } 7413 res.priority = info.getPriority(); 7414 res.preferredOrder = provider.owner.mPreferredOrder; 7415 res.match = match; 7416 res.isDefault = info.hasDefault; 7417 res.labelRes = info.labelRes; 7418 res.nonLocalizedLabel = info.nonLocalizedLabel; 7419 res.icon = info.icon; 7420 res.system = isSystemApp(res.providerInfo.applicationInfo); 7421 return res; 7422 } 7423 7424 @Override 7425 protected void sortResults(List<ResolveInfo> results) { 7426 Collections.sort(results, mResolvePrioritySorter); 7427 } 7428 7429 @Override 7430 protected void dumpFilter(PrintWriter out, String prefix, 7431 PackageParser.ProviderIntentInfo filter) { 7432 out.print(prefix); 7433 out.print( 7434 Integer.toHexString(System.identityHashCode(filter.provider))); 7435 out.print(' '); 7436 filter.provider.printComponentShortName(out); 7437 out.print(" filter "); 7438 out.println(Integer.toHexString(System.identityHashCode(filter))); 7439 } 7440 7441 private final HashMap<ComponentName, PackageParser.Provider> mProviders 7442 = new HashMap<ComponentName, PackageParser.Provider>(); 7443 private int mFlags; 7444 }; 7445 7446 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 7447 new Comparator<ResolveInfo>() { 7448 public int compare(ResolveInfo r1, ResolveInfo r2) { 7449 int v1 = r1.priority; 7450 int v2 = r2.priority; 7451 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 7452 if (v1 != v2) { 7453 return (v1 > v2) ? -1 : 1; 7454 } 7455 v1 = r1.preferredOrder; 7456 v2 = r2.preferredOrder; 7457 if (v1 != v2) { 7458 return (v1 > v2) ? -1 : 1; 7459 } 7460 if (r1.isDefault != r2.isDefault) { 7461 return r1.isDefault ? -1 : 1; 7462 } 7463 v1 = r1.match; 7464 v2 = r2.match; 7465 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 7466 if (v1 != v2) { 7467 return (v1 > v2) ? -1 : 1; 7468 } 7469 if (r1.system != r2.system) { 7470 return r1.system ? -1 : 1; 7471 } 7472 return 0; 7473 } 7474 }; 7475 7476 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 7477 new Comparator<ProviderInfo>() { 7478 public int compare(ProviderInfo p1, ProviderInfo p2) { 7479 final int v1 = p1.initOrder; 7480 final int v2 = p2.initOrder; 7481 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 7482 } 7483 }; 7484 7485 static final void sendPackageBroadcast(String action, String pkg, 7486 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 7487 int[] userIds) { 7488 IActivityManager am = ActivityManagerNative.getDefault(); 7489 if (am != null) { 7490 try { 7491 if (userIds == null) { 7492 userIds = am.getRunningUserIds(); 7493 } 7494 for (int id : userIds) { 7495 final Intent intent = new Intent(action, 7496 pkg != null ? Uri.fromParts("package", pkg, null) : null); 7497 if (extras != null) { 7498 intent.putExtras(extras); 7499 } 7500 if (targetPkg != null) { 7501 intent.setPackage(targetPkg); 7502 } 7503 // Modify the UID when posting to other users 7504 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 7505 if (uid > 0 && UserHandle.getUserId(uid) != id) { 7506 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 7507 intent.putExtra(Intent.EXTRA_UID, uid); 7508 } 7509 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 7510 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 7511 if (DEBUG_BROADCASTS) { 7512 RuntimeException here = new RuntimeException("here"); 7513 here.fillInStackTrace(); 7514 Slog.d(TAG, "Sending to user " + id + ": " 7515 + intent.toShortString(false, true, false, false) 7516 + " " + intent.getExtras(), here); 7517 } 7518 am.broadcastIntent(null, intent, null, finishedReceiver, 7519 0, null, null, null, android.app.AppOpsManager.OP_NONE, 7520 finishedReceiver != null, false, id); 7521 } 7522 } catch (RemoteException ex) { 7523 } 7524 } 7525 } 7526 7527 /** 7528 * Check if the external storage media is available. This is true if there 7529 * is a mounted external storage medium or if the external storage is 7530 * emulated. 7531 */ 7532 private boolean isExternalMediaAvailable() { 7533 return mMediaMounted || Environment.isExternalStorageEmulated(); 7534 } 7535 7536 @Override 7537 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 7538 // writer 7539 synchronized (mPackages) { 7540 if (!isExternalMediaAvailable()) { 7541 // If the external storage is no longer mounted at this point, 7542 // the caller may not have been able to delete all of this 7543 // packages files and can not delete any more. Bail. 7544 return null; 7545 } 7546 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 7547 if (lastPackage != null) { 7548 pkgs.remove(lastPackage); 7549 } 7550 if (pkgs.size() > 0) { 7551 return pkgs.get(0); 7552 } 7553 } 7554 return null; 7555 } 7556 7557 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 7558 if (false) { 7559 RuntimeException here = new RuntimeException("here"); 7560 here.fillInStackTrace(); 7561 Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId 7562 + " andCode=" + andCode, here); 7563 } 7564 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, 7565 userId, andCode ? 1 : 0, packageName)); 7566 } 7567 7568 void startCleaningPackages() { 7569 // reader 7570 synchronized (mPackages) { 7571 if (!isExternalMediaAvailable()) { 7572 return; 7573 } 7574 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 7575 return; 7576 } 7577 } 7578 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 7579 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 7580 IActivityManager am = ActivityManagerNative.getDefault(); 7581 if (am != null) { 7582 try { 7583 am.startService(null, intent, null, UserHandle.USER_OWNER); 7584 } catch (RemoteException e) { 7585 } 7586 } 7587 } 7588 7589 private final class AppDirObserver extends FileObserver { 7590 public AppDirObserver(String path, int mask, boolean isrom, boolean isPrivileged) { 7591 super(path, mask); 7592 mRootDir = path; 7593 mIsRom = isrom; 7594 mIsPrivileged = isPrivileged; 7595 } 7596 7597 public void onEvent(int event, String path) { 7598 String removedPackage = null; 7599 int removedAppId = -1; 7600 int[] removedUsers = null; 7601 String addedPackage = null; 7602 int addedAppId = -1; 7603 int[] addedUsers = null; 7604 7605 // TODO post a message to the handler to obtain serial ordering 7606 synchronized (mInstallLock) { 7607 String fullPathStr = null; 7608 File fullPath = null; 7609 if (path != null) { 7610 fullPath = new File(mRootDir, path); 7611 fullPathStr = fullPath.getPath(); 7612 } 7613 7614 if (DEBUG_APP_DIR_OBSERVER) 7615 Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event)); 7616 7617 if (!isApkFile(fullPath)) { 7618 if (DEBUG_APP_DIR_OBSERVER) 7619 Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr); 7620 return; 7621 } 7622 7623 // Ignore packages that are being installed or 7624 // have just been installed. 7625 if (ignoreCodePath(fullPathStr)) { 7626 return; 7627 } 7628 PackageParser.Package p = null; 7629 PackageSetting ps = null; 7630 // reader 7631 synchronized (mPackages) { 7632 p = mAppDirs.get(fullPathStr); 7633 if (p != null) { 7634 ps = mSettings.mPackages.get(p.applicationInfo.packageName); 7635 if (ps != null) { 7636 removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 7637 } else { 7638 removedUsers = sUserManager.getUserIds(); 7639 } 7640 } 7641 addedUsers = sUserManager.getUserIds(); 7642 } 7643 if ((event&REMOVE_EVENTS) != 0) { 7644 if (ps != null) { 7645 if (DEBUG_REMOVE) Slog.d(TAG, "Package disappeared: " + ps); 7646 removePackageLI(ps, true); 7647 removedPackage = ps.name; 7648 removedAppId = ps.appId; 7649 } 7650 } 7651 7652 if ((event&ADD_EVENTS) != 0) { 7653 if (p == null) { 7654 if (DEBUG_INSTALL) Slog.d(TAG, "New file appeared: " + fullPath); 7655 int flags = PackageParser.PARSE_CHATTY | PackageParser.PARSE_MUST_BE_APK; 7656 if (mIsRom) { 7657 flags |= PackageParser.PARSE_IS_SYSTEM 7658 | PackageParser.PARSE_IS_SYSTEM_DIR; 7659 if (mIsPrivileged) { 7660 flags |= PackageParser.PARSE_IS_PRIVILEGED; 7661 } 7662 } 7663 p = scanPackageLI(fullPath, flags, 7664 SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME, 7665 System.currentTimeMillis(), UserHandle.ALL, null); 7666 if (p != null) { 7667 /* 7668 * TODO this seems dangerous as the package may have 7669 * changed since we last acquired the mPackages 7670 * lock. 7671 */ 7672 // writer 7673 synchronized (mPackages) { 7674 updatePermissionsLPw(p.packageName, p, 7675 p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0); 7676 } 7677 addedPackage = p.applicationInfo.packageName; 7678 addedAppId = UserHandle.getAppId(p.applicationInfo.uid); 7679 } 7680 } 7681 } 7682 7683 // reader 7684 synchronized (mPackages) { 7685 mSettings.writeLPr(); 7686 } 7687 } 7688 7689 if (removedPackage != null) { 7690 Bundle extras = new Bundle(1); 7691 extras.putInt(Intent.EXTRA_UID, removedAppId); 7692 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false); 7693 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 7694 extras, null, null, removedUsers); 7695 } 7696 if (addedPackage != null) { 7697 Bundle extras = new Bundle(1); 7698 extras.putInt(Intent.EXTRA_UID, addedAppId); 7699 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, 7700 extras, null, null, addedUsers); 7701 } 7702 } 7703 7704 private final String mRootDir; 7705 private final boolean mIsRom; 7706 private final boolean mIsPrivileged; 7707 } 7708 7709 @Override 7710 public void installPackage(String originPath, IPackageInstallObserver2 observer, int flags, 7711 String installerPackageName, VerificationParams verificationParams, 7712 String packageAbiOverride) { 7713 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7714 null); 7715 7716 final File originFile = new File(originPath); 7717 final int uid = Binder.getCallingUid(); 7718 if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) { 7719 try { 7720 if (observer != null) { 7721 observer.packageInstalled("", null, INSTALL_FAILED_USER_RESTRICTED); 7722 } 7723 } catch (RemoteException re) { 7724 } 7725 return; 7726 } 7727 7728 UserHandle user; 7729 if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) { 7730 user = UserHandle.ALL; 7731 } else { 7732 user = new UserHandle(UserHandle.getUserId(uid)); 7733 } 7734 7735 final int filteredFlags; 7736 if (uid == Process.SHELL_UID || uid == 0) { 7737 if (DEBUG_INSTALL) { 7738 Slog.v(TAG, "Install from ADB"); 7739 } 7740 filteredFlags = flags | PackageManager.INSTALL_FROM_ADB; 7741 } else { 7742 filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB; 7743 } 7744 7745 verificationParams.setInstallerUid(uid); 7746 7747 final Message msg = mHandler.obtainMessage(INIT_COPY); 7748 msg.obj = new InstallParams(originFile, false, observer, filteredFlags, 7749 installerPackageName, verificationParams, user, packageAbiOverride); 7750 mHandler.sendMessage(msg); 7751 } 7752 7753 void installStage(String packageName, File stageDir, IPackageInstallObserver2 observer, 7754 PackageInstallerParams params, String installerPackageName, int installerUid, 7755 UserHandle user) { 7756 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 7757 params.referrerUri, installerUid, null); 7758 7759 final Message msg = mHandler.obtainMessage(INIT_COPY); 7760 msg.obj = new InstallParams(stageDir, true, observer, params.installFlags, 7761 installerPackageName, verifParams, user, params.abiOverride); 7762 mHandler.sendMessage(msg); 7763 } 7764 7765 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 7766 Bundle extras = new Bundle(1); 7767 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 7768 7769 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 7770 packageName, extras, null, null, new int[] {userId}); 7771 try { 7772 IActivityManager am = ActivityManagerNative.getDefault(); 7773 final boolean isSystem = 7774 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 7775 if (isSystem && am.isUserRunning(userId, false)) { 7776 // The just-installed/enabled app is bundled on the system, so presumed 7777 // to be able to run automatically without needing an explicit launch. 7778 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 7779 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 7780 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 7781 .setPackage(packageName); 7782 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 7783 android.app.AppOpsManager.OP_NONE, false, false, userId); 7784 } 7785 } catch (RemoteException e) { 7786 // shouldn't happen 7787 Slog.w(TAG, "Unable to bootstrap installed package", e); 7788 } 7789 } 7790 7791 @Override 7792 public boolean setApplicationBlockedSettingAsUser(String packageName, boolean blocked, 7793 int userId) { 7794 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7795 PackageSetting pkgSetting; 7796 final int uid = Binder.getCallingUid(); 7797 if (UserHandle.getUserId(uid) != userId) { 7798 mContext.enforceCallingOrSelfPermission( 7799 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 7800 "setApplicationBlockedSetting for user " + userId); 7801 } 7802 7803 if (blocked && isPackageDeviceAdmin(packageName, userId)) { 7804 Slog.w(TAG, "Not blocking package " + packageName + ": has active device admin"); 7805 return false; 7806 } 7807 7808 long callingId = Binder.clearCallingIdentity(); 7809 try { 7810 boolean sendAdded = false; 7811 boolean sendRemoved = false; 7812 // writer 7813 synchronized (mPackages) { 7814 pkgSetting = mSettings.mPackages.get(packageName); 7815 if (pkgSetting == null) { 7816 return false; 7817 } 7818 if (pkgSetting.getBlocked(userId) != blocked) { 7819 pkgSetting.setBlocked(blocked, userId); 7820 mSettings.writePackageRestrictionsLPr(userId); 7821 if (blocked) { 7822 sendRemoved = true; 7823 } else { 7824 sendAdded = true; 7825 } 7826 } 7827 } 7828 if (sendAdded) { 7829 sendPackageAddedForUser(packageName, pkgSetting, userId); 7830 return true; 7831 } 7832 if (sendRemoved) { 7833 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 7834 "blocking pkg"); 7835 sendPackageBlockedForUser(packageName, pkgSetting, userId); 7836 } 7837 } finally { 7838 Binder.restoreCallingIdentity(callingId); 7839 } 7840 return false; 7841 } 7842 7843 private void sendPackageBlockedForUser(String packageName, PackageSetting pkgSetting, 7844 int userId) { 7845 final PackageRemovedInfo info = new PackageRemovedInfo(); 7846 info.removedPackage = packageName; 7847 info.removedUsers = new int[] {userId}; 7848 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 7849 info.sendBroadcast(false, false, false); 7850 } 7851 7852 /** 7853 * Returns true if application is not found or there was an error. Otherwise it returns 7854 * the blocked state of the package for the given user. 7855 */ 7856 @Override 7857 public boolean getApplicationBlockedSettingAsUser(String packageName, int userId) { 7858 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7859 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 7860 "getApplicationBlocked for user " + userId); 7861 PackageSetting pkgSetting; 7862 long callingId = Binder.clearCallingIdentity(); 7863 try { 7864 // writer 7865 synchronized (mPackages) { 7866 pkgSetting = mSettings.mPackages.get(packageName); 7867 if (pkgSetting == null) { 7868 return true; 7869 } 7870 return pkgSetting.getBlocked(userId); 7871 } 7872 } finally { 7873 Binder.restoreCallingIdentity(callingId); 7874 } 7875 } 7876 7877 /** 7878 * @hide 7879 */ 7880 @Override 7881 public int installExistingPackageAsUser(String packageName, int userId) { 7882 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7883 null); 7884 PackageSetting pkgSetting; 7885 final int uid = Binder.getCallingUid(); 7886 enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId); 7887 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 7888 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 7889 } 7890 7891 long callingId = Binder.clearCallingIdentity(); 7892 try { 7893 boolean sendAdded = false; 7894 Bundle extras = new Bundle(1); 7895 7896 // writer 7897 synchronized (mPackages) { 7898 pkgSetting = mSettings.mPackages.get(packageName); 7899 if (pkgSetting == null) { 7900 return PackageManager.INSTALL_FAILED_INVALID_URI; 7901 } 7902 if (!pkgSetting.getInstalled(userId)) { 7903 pkgSetting.setInstalled(true, userId); 7904 pkgSetting.setBlocked(false, userId); 7905 mSettings.writePackageRestrictionsLPr(userId); 7906 sendAdded = true; 7907 } 7908 } 7909 7910 if (sendAdded) { 7911 sendPackageAddedForUser(packageName, pkgSetting, userId); 7912 } 7913 } finally { 7914 Binder.restoreCallingIdentity(callingId); 7915 } 7916 7917 return PackageManager.INSTALL_SUCCEEDED; 7918 } 7919 7920 boolean isUserRestricted(int userId, String restrictionKey) { 7921 Bundle restrictions = sUserManager.getUserRestrictions(userId); 7922 if (restrictions.getBoolean(restrictionKey, false)) { 7923 Log.w(TAG, "User is restricted: " + restrictionKey); 7924 return true; 7925 } 7926 return false; 7927 } 7928 7929 @Override 7930 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 7931 mContext.enforceCallingOrSelfPermission( 7932 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7933 "Only package verification agents can verify applications"); 7934 7935 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7936 final PackageVerificationResponse response = new PackageVerificationResponse( 7937 verificationCode, Binder.getCallingUid()); 7938 msg.arg1 = id; 7939 msg.obj = response; 7940 mHandler.sendMessage(msg); 7941 } 7942 7943 @Override 7944 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 7945 long millisecondsToDelay) { 7946 mContext.enforceCallingOrSelfPermission( 7947 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7948 "Only package verification agents can extend verification timeouts"); 7949 7950 final PackageVerificationState state = mPendingVerification.get(id); 7951 final PackageVerificationResponse response = new PackageVerificationResponse( 7952 verificationCodeAtTimeout, Binder.getCallingUid()); 7953 7954 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 7955 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 7956 } 7957 if (millisecondsToDelay < 0) { 7958 millisecondsToDelay = 0; 7959 } 7960 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 7961 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 7962 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 7963 } 7964 7965 if ((state != null) && !state.timeoutExtended()) { 7966 state.extendTimeout(); 7967 7968 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7969 msg.arg1 = id; 7970 msg.obj = response; 7971 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 7972 } 7973 } 7974 7975 private void broadcastPackageVerified(int verificationId, Uri packageUri, 7976 int verificationCode, UserHandle user) { 7977 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 7978 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 7979 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 7980 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 7981 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 7982 7983 mContext.sendBroadcastAsUser(intent, user, 7984 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 7985 } 7986 7987 private ComponentName matchComponentForVerifier(String packageName, 7988 List<ResolveInfo> receivers) { 7989 ActivityInfo targetReceiver = null; 7990 7991 final int NR = receivers.size(); 7992 for (int i = 0; i < NR; i++) { 7993 final ResolveInfo info = receivers.get(i); 7994 if (info.activityInfo == null) { 7995 continue; 7996 } 7997 7998 if (packageName.equals(info.activityInfo.packageName)) { 7999 targetReceiver = info.activityInfo; 8000 break; 8001 } 8002 } 8003 8004 if (targetReceiver == null) { 8005 return null; 8006 } 8007 8008 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8009 } 8010 8011 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8012 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8013 if (pkgInfo.verifiers.length == 0) { 8014 return null; 8015 } 8016 8017 final int N = pkgInfo.verifiers.length; 8018 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8019 for (int i = 0; i < N; i++) { 8020 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8021 8022 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8023 receivers); 8024 if (comp == null) { 8025 continue; 8026 } 8027 8028 final int verifierUid = getUidForVerifier(verifierInfo); 8029 if (verifierUid == -1) { 8030 continue; 8031 } 8032 8033 if (DEBUG_VERIFY) { 8034 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8035 + " with the correct signature"); 8036 } 8037 sufficientVerifiers.add(comp); 8038 verificationState.addSufficientVerifier(verifierUid); 8039 } 8040 8041 return sufficientVerifiers; 8042 } 8043 8044 private int getUidForVerifier(VerifierInfo verifierInfo) { 8045 synchronized (mPackages) { 8046 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8047 if (pkg == null) { 8048 return -1; 8049 } else if (pkg.mSignatures.length != 1) { 8050 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8051 + " has more than one signature; ignoring"); 8052 return -1; 8053 } 8054 8055 /* 8056 * If the public key of the package's signature does not match 8057 * our expected public key, then this is a different package and 8058 * we should skip. 8059 */ 8060 8061 final byte[] expectedPublicKey; 8062 try { 8063 final Signature verifierSig = pkg.mSignatures[0]; 8064 final PublicKey publicKey = verifierSig.getPublicKey(); 8065 expectedPublicKey = publicKey.getEncoded(); 8066 } catch (CertificateException e) { 8067 return -1; 8068 } 8069 8070 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8071 8072 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8073 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8074 + " does not have the expected public key; ignoring"); 8075 return -1; 8076 } 8077 8078 return pkg.applicationInfo.uid; 8079 } 8080 } 8081 8082 @Override 8083 public void finishPackageInstall(int token) { 8084 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8085 8086 if (DEBUG_INSTALL) { 8087 Slog.v(TAG, "BM finishing package install for " + token); 8088 } 8089 8090 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8091 mHandler.sendMessage(msg); 8092 } 8093 8094 /** 8095 * Get the verification agent timeout. 8096 * 8097 * @return verification timeout in milliseconds 8098 */ 8099 private long getVerificationTimeout() { 8100 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8101 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8102 DEFAULT_VERIFICATION_TIMEOUT); 8103 } 8104 8105 /** 8106 * Get the default verification agent response code. 8107 * 8108 * @return default verification response code 8109 */ 8110 private int getDefaultVerificationResponse() { 8111 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8112 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8113 DEFAULT_VERIFICATION_RESPONSE); 8114 } 8115 8116 /** 8117 * Check whether or not package verification has been enabled. 8118 * 8119 * @return true if verification should be performed 8120 */ 8121 private boolean isVerificationEnabled(int userId, int flags) { 8122 if (!DEFAULT_VERIFY_ENABLE) { 8123 return false; 8124 } 8125 8126 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 8127 8128 // Check if installing from ADB 8129 if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) { 8130 // Do not run verification in a test harness environment 8131 if (ActivityManager.isRunningInTestHarness()) { 8132 return false; 8133 } 8134 if (ensureVerifyAppsEnabled) { 8135 return true; 8136 } 8137 // Check if the developer does not want package verification for ADB installs 8138 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8139 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8140 return false; 8141 } 8142 } 8143 8144 if (ensureVerifyAppsEnabled) { 8145 return true; 8146 } 8147 8148 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8149 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8150 } 8151 8152 /** 8153 * Get the "allow unknown sources" setting. 8154 * 8155 * @return the current "allow unknown sources" setting 8156 */ 8157 private int getUnknownSourcesSettings() { 8158 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8159 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 8160 -1); 8161 } 8162 8163 @Override 8164 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 8165 final int uid = Binder.getCallingUid(); 8166 // writer 8167 synchronized (mPackages) { 8168 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 8169 if (targetPackageSetting == null) { 8170 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 8171 } 8172 8173 PackageSetting installerPackageSetting; 8174 if (installerPackageName != null) { 8175 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 8176 if (installerPackageSetting == null) { 8177 throw new IllegalArgumentException("Unknown installer package: " 8178 + installerPackageName); 8179 } 8180 } else { 8181 installerPackageSetting = null; 8182 } 8183 8184 Signature[] callerSignature; 8185 Object obj = mSettings.getUserIdLPr(uid); 8186 if (obj != null) { 8187 if (obj instanceof SharedUserSetting) { 8188 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 8189 } else if (obj instanceof PackageSetting) { 8190 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 8191 } else { 8192 throw new SecurityException("Bad object " + obj + " for uid " + uid); 8193 } 8194 } else { 8195 throw new SecurityException("Unknown calling uid " + uid); 8196 } 8197 8198 // Verify: can't set installerPackageName to a package that is 8199 // not signed with the same cert as the caller. 8200 if (installerPackageSetting != null) { 8201 if (compareSignatures(callerSignature, 8202 installerPackageSetting.signatures.mSignatures) 8203 != PackageManager.SIGNATURE_MATCH) { 8204 throw new SecurityException( 8205 "Caller does not have same cert as new installer package " 8206 + installerPackageName); 8207 } 8208 } 8209 8210 // Verify: if target already has an installer package, it must 8211 // be signed with the same cert as the caller. 8212 if (targetPackageSetting.installerPackageName != null) { 8213 PackageSetting setting = mSettings.mPackages.get( 8214 targetPackageSetting.installerPackageName); 8215 // If the currently set package isn't valid, then it's always 8216 // okay to change it. 8217 if (setting != null) { 8218 if (compareSignatures(callerSignature, 8219 setting.signatures.mSignatures) 8220 != PackageManager.SIGNATURE_MATCH) { 8221 throw new SecurityException( 8222 "Caller does not have same cert as old installer package " 8223 + targetPackageSetting.installerPackageName); 8224 } 8225 } 8226 } 8227 8228 // Okay! 8229 targetPackageSetting.installerPackageName = installerPackageName; 8230 scheduleWriteSettingsLocked(); 8231 } 8232 } 8233 8234 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 8235 // Queue up an async operation since the package installation may take a little while. 8236 mHandler.post(new Runnable() { 8237 public void run() { 8238 mHandler.removeCallbacks(this); 8239 // Result object to be returned 8240 PackageInstalledInfo res = new PackageInstalledInfo(); 8241 res.returnCode = currentStatus; 8242 res.uid = -1; 8243 res.pkg = null; 8244 res.removedInfo = new PackageRemovedInfo(); 8245 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 8246 args.doPreInstall(res.returnCode); 8247 synchronized (mInstallLock) { 8248 installPackageLI(args, true, res); 8249 } 8250 args.doPostInstall(res.returnCode, res.uid); 8251 } 8252 8253 // A restore should be performed at this point if (a) the install 8254 // succeeded, (b) the operation is not an update, and (c) the new 8255 // package has a backupAgent defined. 8256 final boolean update = res.removedInfo.removedPackage != null; 8257 boolean doRestore = (!update 8258 && res.pkg != null 8259 && res.pkg.applicationInfo.backupAgentName != null); 8260 8261 // Set up the post-install work request bookkeeping. This will be used 8262 // and cleaned up by the post-install event handling regardless of whether 8263 // there's a restore pass performed. Token values are >= 1. 8264 int token; 8265 if (mNextInstallToken < 0) mNextInstallToken = 1; 8266 token = mNextInstallToken++; 8267 8268 PostInstallData data = new PostInstallData(args, res); 8269 mRunningInstalls.put(token, data); 8270 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 8271 8272 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 8273 // Pass responsibility to the Backup Manager. It will perform a 8274 // restore if appropriate, then pass responsibility back to the 8275 // Package Manager to run the post-install observer callbacks 8276 // and broadcasts. 8277 IBackupManager bm = IBackupManager.Stub.asInterface( 8278 ServiceManager.getService(Context.BACKUP_SERVICE)); 8279 if (bm != null) { 8280 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 8281 + " to BM for possible restore"); 8282 try { 8283 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 8284 } catch (RemoteException e) { 8285 // can't happen; the backup manager is local 8286 } catch (Exception e) { 8287 Slog.e(TAG, "Exception trying to enqueue restore", e); 8288 doRestore = false; 8289 } 8290 } else { 8291 Slog.e(TAG, "Backup Manager not found!"); 8292 doRestore = false; 8293 } 8294 } 8295 8296 if (!doRestore) { 8297 // No restore possible, or the Backup Manager was mysteriously not 8298 // available -- just fire the post-install work request directly. 8299 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 8300 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8301 mHandler.sendMessage(msg); 8302 } 8303 } 8304 }); 8305 } 8306 8307 private abstract class HandlerParams { 8308 private static final int MAX_RETRIES = 4; 8309 8310 /** 8311 * Number of times startCopy() has been attempted and had a non-fatal 8312 * error. 8313 */ 8314 private int mRetries = 0; 8315 8316 /** User handle for the user requesting the information or installation. */ 8317 private final UserHandle mUser; 8318 8319 HandlerParams(UserHandle user) { 8320 mUser = user; 8321 } 8322 8323 UserHandle getUser() { 8324 return mUser; 8325 } 8326 8327 final boolean startCopy() { 8328 boolean res; 8329 try { 8330 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 8331 8332 if (++mRetries > MAX_RETRIES) { 8333 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 8334 mHandler.sendEmptyMessage(MCS_GIVE_UP); 8335 handleServiceError(); 8336 return false; 8337 } else { 8338 handleStartCopy(); 8339 res = true; 8340 } 8341 } catch (RemoteException e) { 8342 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 8343 mHandler.sendEmptyMessage(MCS_RECONNECT); 8344 res = false; 8345 } 8346 handleReturnCode(); 8347 return res; 8348 } 8349 8350 final void serviceError() { 8351 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 8352 handleServiceError(); 8353 handleReturnCode(); 8354 } 8355 8356 abstract void handleStartCopy() throws RemoteException; 8357 abstract void handleServiceError(); 8358 abstract void handleReturnCode(); 8359 } 8360 8361 class MeasureParams extends HandlerParams { 8362 private final PackageStats mStats; 8363 private boolean mSuccess; 8364 8365 private final IPackageStatsObserver mObserver; 8366 8367 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 8368 super(new UserHandle(stats.userHandle)); 8369 mObserver = observer; 8370 mStats = stats; 8371 } 8372 8373 @Override 8374 public String toString() { 8375 return "MeasureParams{" 8376 + Integer.toHexString(System.identityHashCode(this)) 8377 + " " + mStats.packageName + "}"; 8378 } 8379 8380 @Override 8381 void handleStartCopy() throws RemoteException { 8382 synchronized (mInstallLock) { 8383 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 8384 } 8385 8386 if (mSuccess) { 8387 final boolean mounted; 8388 if (Environment.isExternalStorageEmulated()) { 8389 mounted = true; 8390 } else { 8391 final String status = Environment.getExternalStorageState(); 8392 mounted = (Environment.MEDIA_MOUNTED.equals(status) 8393 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 8394 } 8395 8396 if (mounted) { 8397 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 8398 8399 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 8400 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 8401 8402 mStats.externalDataSize = calculateDirectorySize(mContainerService, 8403 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 8404 8405 // Always subtract cache size, since it's a subdirectory 8406 mStats.externalDataSize -= mStats.externalCacheSize; 8407 8408 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 8409 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 8410 8411 mStats.externalObbSize = calculateDirectorySize(mContainerService, 8412 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 8413 } 8414 } 8415 } 8416 8417 @Override 8418 void handleReturnCode() { 8419 if (mObserver != null) { 8420 try { 8421 mObserver.onGetStatsCompleted(mStats, mSuccess); 8422 } catch (RemoteException e) { 8423 Slog.i(TAG, "Observer no longer exists."); 8424 } 8425 } 8426 } 8427 8428 @Override 8429 void handleServiceError() { 8430 Slog.e(TAG, "Could not measure application " + mStats.packageName 8431 + " external storage"); 8432 } 8433 } 8434 8435 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 8436 throws RemoteException { 8437 long result = 0; 8438 for (File path : paths) { 8439 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 8440 } 8441 return result; 8442 } 8443 8444 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 8445 for (File path : paths) { 8446 try { 8447 mcs.clearDirectory(path.getAbsolutePath()); 8448 } catch (RemoteException e) { 8449 } 8450 } 8451 } 8452 8453 class InstallParams extends HandlerParams { 8454 /** 8455 * Location where install is coming from, before it has been 8456 * copied/renamed into place. This could be a single monolithic APK 8457 * file, or a cluster directory. This location may be untrusted. 8458 */ 8459 final File originFile; 8460 8461 /** 8462 * Flag indicating that {@link #originFile} has already been staged, 8463 * meaning downstream users don't need to defensively copy the contents. 8464 */ 8465 boolean originStaged; 8466 8467 final IPackageInstallObserver2 observer; 8468 int flags; 8469 final String installerPackageName; 8470 final VerificationParams verificationParams; 8471 private InstallArgs mArgs; 8472 private int mRet; 8473 final String packageAbiOverride; 8474 boolean multiArch; 8475 8476 InstallParams(File originFile, boolean originStaged, IPackageInstallObserver2 observer, 8477 int flags, String installerPackageName, VerificationParams verificationParams, 8478 UserHandle user, String packageAbiOverride) { 8479 super(user); 8480 this.originFile = Preconditions.checkNotNull(originFile); 8481 this.originStaged = originStaged; 8482 this.observer = observer; 8483 this.flags = flags; 8484 this.installerPackageName = installerPackageName; 8485 this.verificationParams = verificationParams; 8486 this.packageAbiOverride = packageAbiOverride; 8487 } 8488 8489 @Override 8490 public String toString() { 8491 return "InstallParams{" 8492 + Integer.toHexString(System.identityHashCode(this)) 8493 + " " + originFile + "}"; 8494 } 8495 8496 public ManifestDigest getManifestDigest() { 8497 if (verificationParams == null) { 8498 return null; 8499 } 8500 return verificationParams.getManifestDigest(); 8501 } 8502 8503 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) { 8504 String packageName = pkgLite.packageName; 8505 int installLocation = pkgLite.installLocation; 8506 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8507 // reader 8508 synchronized (mPackages) { 8509 PackageParser.Package pkg = mPackages.get(packageName); 8510 if (pkg != null) { 8511 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 8512 // Check for downgrading. 8513 if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 8514 if (pkgLite.versionCode < pkg.mVersionCode) { 8515 Slog.w(TAG, "Can't install update of " + packageName 8516 + " update version " + pkgLite.versionCode 8517 + " is older than installed version " 8518 + pkg.mVersionCode); 8519 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 8520 } 8521 } 8522 // Check for updated system application. 8523 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8524 if (onSd) { 8525 Slog.w(TAG, "Cannot install update to system app on sdcard"); 8526 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 8527 } 8528 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8529 } else { 8530 if (onSd) { 8531 // Install flag overrides everything. 8532 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8533 } 8534 // If current upgrade specifies particular preference 8535 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 8536 // Application explicitly specified internal. 8537 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8538 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 8539 // App explictly prefers external. Let policy decide 8540 } else { 8541 // Prefer previous location 8542 if (isExternal(pkg)) { 8543 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8544 } 8545 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8546 } 8547 } 8548 } else { 8549 // Invalid install. Return error code 8550 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 8551 } 8552 } 8553 } 8554 // All the special cases have been taken care of. 8555 // Return result based on recommended install location. 8556 if (onSd) { 8557 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8558 } 8559 return pkgLite.recommendedInstallLocation; 8560 } 8561 8562 private long getMemoryLowThreshold() { 8563 final DeviceStorageMonitorInternal 8564 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 8565 if (dsm == null) { 8566 return 0L; 8567 } 8568 return dsm.getMemoryLowThreshold(); 8569 } 8570 8571 /* 8572 * Invoke remote method to get package information and install 8573 * location values. Override install location based on default 8574 * policy if needed and then create install arguments based 8575 * on the install location. 8576 */ 8577 public void handleStartCopy() throws RemoteException { 8578 int ret = PackageManager.INSTALL_SUCCEEDED; 8579 final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8580 final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0; 8581 PackageInfoLite pkgLite = null; 8582 8583 if (onInt && onSd) { 8584 // Check if both bits are set. 8585 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 8586 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8587 } else { 8588 final long lowThreshold = getMemoryLowThreshold(); 8589 if (lowThreshold == 0L) { 8590 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 8591 } 8592 8593 // Remote call to find out default install location 8594 final String originPath = originFile.getAbsolutePath(); 8595 pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags, lowThreshold, 8596 packageAbiOverride); 8597 // Keep track of whether this package is a multiArch package until 8598 // we perform a full scan of it. We need to do this because we might 8599 // end up extracting the package shared libraries before we perform 8600 // a full scan. 8601 multiArch = pkgLite.multiArch; 8602 8603 /* 8604 * If we have too little free space, try to free cache 8605 * before giving up. 8606 */ 8607 if (pkgLite.recommendedInstallLocation 8608 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8609 final long size = mContainerService.calculateInstalledSize( 8610 originPath, isForwardLocked(), packageAbiOverride); 8611 if (mInstaller.freeCache(size + lowThreshold) >= 0) { 8612 pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags, 8613 lowThreshold, packageAbiOverride); 8614 } 8615 /* 8616 * The cache free must have deleted the file we 8617 * downloaded to install. 8618 * 8619 * TODO: fix the "freeCache" call to not delete 8620 * the file we care about. 8621 */ 8622 if (pkgLite.recommendedInstallLocation 8623 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8624 pkgLite.recommendedInstallLocation 8625 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 8626 } 8627 } 8628 } 8629 8630 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8631 int loc = pkgLite.recommendedInstallLocation; 8632 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 8633 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8634 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 8635 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 8636 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8637 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8638 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 8639 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 8640 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8641 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 8642 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 8643 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 8644 } else { 8645 // Override with defaults if needed. 8646 loc = installLocationPolicy(pkgLite, flags); 8647 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 8648 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 8649 } else if (!onSd && !onInt) { 8650 // Override install location with flags 8651 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 8652 // Set the flag to install on external media. 8653 flags |= PackageManager.INSTALL_EXTERNAL; 8654 flags &= ~PackageManager.INSTALL_INTERNAL; 8655 } else { 8656 // Make sure the flag for installing on external 8657 // media is unset 8658 flags |= PackageManager.INSTALL_INTERNAL; 8659 flags &= ~PackageManager.INSTALL_EXTERNAL; 8660 } 8661 } 8662 } 8663 } 8664 8665 final InstallArgs args = createInstallArgs(this); 8666 mArgs = args; 8667 8668 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8669 /* 8670 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 8671 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 8672 */ 8673 int userIdentifier = getUser().getIdentifier(); 8674 if (userIdentifier == UserHandle.USER_ALL 8675 && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) { 8676 userIdentifier = UserHandle.USER_OWNER; 8677 } 8678 8679 /* 8680 * Determine if we have any installed package verifiers. If we 8681 * do, then we'll defer to them to verify the packages. 8682 */ 8683 final int requiredUid = mRequiredVerifierPackage == null ? -1 8684 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 8685 if (requiredUid != -1 && isVerificationEnabled(userIdentifier, flags)) { 8686 // TODO: send verifier the install session instead of uri 8687 final Intent verification = new Intent( 8688 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 8689 verification.setDataAndType(Uri.fromFile(originFile), PACKAGE_MIME_TYPE); 8690 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8691 8692 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 8693 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 8694 0 /* TODO: Which userId? */); 8695 8696 if (DEBUG_VERIFY) { 8697 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 8698 + verification.toString() + " with " + pkgLite.verifiers.length 8699 + " optional verifiers"); 8700 } 8701 8702 final int verificationId = mPendingVerificationToken++; 8703 8704 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8705 8706 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 8707 installerPackageName); 8708 8709 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags); 8710 8711 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 8712 pkgLite.packageName); 8713 8714 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 8715 pkgLite.versionCode); 8716 8717 if (verificationParams != null) { 8718 if (verificationParams.getVerificationURI() != null) { 8719 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 8720 verificationParams.getVerificationURI()); 8721 } 8722 if (verificationParams.getOriginatingURI() != null) { 8723 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 8724 verificationParams.getOriginatingURI()); 8725 } 8726 if (verificationParams.getReferrer() != null) { 8727 verification.putExtra(Intent.EXTRA_REFERRER, 8728 verificationParams.getReferrer()); 8729 } 8730 if (verificationParams.getOriginatingUid() >= 0) { 8731 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 8732 verificationParams.getOriginatingUid()); 8733 } 8734 if (verificationParams.getInstallerUid() >= 0) { 8735 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 8736 verificationParams.getInstallerUid()); 8737 } 8738 } 8739 8740 final PackageVerificationState verificationState = new PackageVerificationState( 8741 requiredUid, args); 8742 8743 mPendingVerification.append(verificationId, verificationState); 8744 8745 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 8746 receivers, verificationState); 8747 8748 /* 8749 * If any sufficient verifiers were listed in the package 8750 * manifest, attempt to ask them. 8751 */ 8752 if (sufficientVerifiers != null) { 8753 final int N = sufficientVerifiers.size(); 8754 if (N == 0) { 8755 Slog.i(TAG, "Additional verifiers required, but none installed."); 8756 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 8757 } else { 8758 for (int i = 0; i < N; i++) { 8759 final ComponentName verifierComponent = sufficientVerifiers.get(i); 8760 8761 final Intent sufficientIntent = new Intent(verification); 8762 sufficientIntent.setComponent(verifierComponent); 8763 8764 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 8765 } 8766 } 8767 } 8768 8769 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 8770 mRequiredVerifierPackage, receivers); 8771 if (ret == PackageManager.INSTALL_SUCCEEDED 8772 && mRequiredVerifierPackage != null) { 8773 /* 8774 * Send the intent to the required verification agent, 8775 * but only start the verification timeout after the 8776 * target BroadcastReceivers have run. 8777 */ 8778 verification.setComponent(requiredVerifierComponent); 8779 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 8780 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8781 new BroadcastReceiver() { 8782 @Override 8783 public void onReceive(Context context, Intent intent) { 8784 final Message msg = mHandler 8785 .obtainMessage(CHECK_PENDING_VERIFICATION); 8786 msg.arg1 = verificationId; 8787 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 8788 } 8789 }, null, 0, null, null); 8790 8791 /* 8792 * We don't want the copy to proceed until verification 8793 * succeeds, so null out this field. 8794 */ 8795 mArgs = null; 8796 } 8797 } else { 8798 /* 8799 * No package verification is enabled, so immediately start 8800 * the remote call to initiate copy using temporary file. 8801 */ 8802 ret = args.copyApk(mContainerService, true); 8803 } 8804 } 8805 8806 mRet = ret; 8807 } 8808 8809 @Override 8810 void handleReturnCode() { 8811 // If mArgs is null, then MCS couldn't be reached. When it 8812 // reconnects, it will try again to install. At that point, this 8813 // will succeed. 8814 if (mArgs != null) { 8815 processPendingInstall(mArgs, mRet); 8816 } 8817 } 8818 8819 @Override 8820 void handleServiceError() { 8821 mArgs = createInstallArgs(this); 8822 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8823 } 8824 8825 public boolean isForwardLocked() { 8826 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8827 } 8828 } 8829 8830 /* 8831 * Utility class used in movePackage api. 8832 * srcArgs and targetArgs are not set for invalid flags and make 8833 * sure to do null checks when invoking methods on them. 8834 * We probably want to return ErrorPrams for both failed installs 8835 * and moves. 8836 */ 8837 class MoveParams extends HandlerParams { 8838 final IPackageMoveObserver observer; 8839 final int flags; 8840 final String packageName; 8841 final InstallArgs srcArgs; 8842 final InstallArgs targetArgs; 8843 int uid; 8844 int mRet; 8845 8846 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags, 8847 String packageName, String[] instructionSets, int uid, UserHandle user, 8848 boolean isMultiArch) { 8849 super(user); 8850 this.srcArgs = srcArgs; 8851 this.observer = observer; 8852 this.flags = flags; 8853 this.packageName = packageName; 8854 this.uid = uid; 8855 if (srcArgs != null) { 8856 final String codePath = srcArgs.getCodePath(); 8857 targetArgs = createInstallArgsForMoveTarget(codePath, flags, packageName, 8858 instructionSets, isMultiArch); 8859 } else { 8860 targetArgs = null; 8861 } 8862 } 8863 8864 @Override 8865 public String toString() { 8866 return "MoveParams{" 8867 + Integer.toHexString(System.identityHashCode(this)) 8868 + " " + packageName + "}"; 8869 } 8870 8871 public void handleStartCopy() throws RemoteException { 8872 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8873 // Check for storage space on target medium 8874 if (!targetArgs.checkFreeStorage(mContainerService)) { 8875 Log.w(TAG, "Insufficient storage to install"); 8876 return; 8877 } 8878 8879 mRet = srcArgs.doPreCopy(); 8880 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8881 return; 8882 } 8883 8884 mRet = targetArgs.copyApk(mContainerService, false); 8885 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8886 srcArgs.doPostCopy(uid); 8887 return; 8888 } 8889 8890 mRet = srcArgs.doPostCopy(uid); 8891 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8892 return; 8893 } 8894 8895 mRet = targetArgs.doPreInstall(mRet); 8896 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8897 return; 8898 } 8899 8900 if (DEBUG_SD_INSTALL) { 8901 StringBuilder builder = new StringBuilder(); 8902 if (srcArgs != null) { 8903 builder.append("src: "); 8904 builder.append(srcArgs.getCodePath()); 8905 } 8906 if (targetArgs != null) { 8907 builder.append(" target : "); 8908 builder.append(targetArgs.getCodePath()); 8909 } 8910 Log.i(TAG, builder.toString()); 8911 } 8912 } 8913 8914 @Override 8915 void handleReturnCode() { 8916 targetArgs.doPostInstall(mRet, uid); 8917 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 8918 if (mRet == PackageManager.INSTALL_SUCCEEDED) { 8919 currentStatus = PackageManager.MOVE_SUCCEEDED; 8920 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){ 8921 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 8922 } 8923 processPendingMove(this, currentStatus); 8924 } 8925 8926 @Override 8927 void handleServiceError() { 8928 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8929 } 8930 } 8931 8932 /** 8933 * Used during creation of InstallArgs 8934 * 8935 * @param flags package installation flags 8936 * @return true if should be installed on external storage 8937 */ 8938 private static boolean installOnSd(int flags) { 8939 if ((flags & PackageManager.INSTALL_INTERNAL) != 0) { 8940 return false; 8941 } 8942 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) { 8943 return true; 8944 } 8945 return false; 8946 } 8947 8948 /** 8949 * Used during creation of InstallArgs 8950 * 8951 * @param flags package installation flags 8952 * @return true if should be installed as forward locked 8953 */ 8954 private static boolean installForwardLocked(int flags) { 8955 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8956 } 8957 8958 private InstallArgs createInstallArgs(InstallParams params) { 8959 // TODO: extend to support incoming zero-copy locations 8960 8961 if (installOnSd(params.flags) || params.isForwardLocked()) { 8962 return new AsecInstallArgs(params); 8963 } else { 8964 return new FileInstallArgs(params); 8965 } 8966 } 8967 8968 /** 8969 * Create args that describe an existing installed package. Typically used 8970 * when cleaning up old installs, or used as a move source. 8971 */ 8972 private InstallArgs createInstallArgsForExisting(int flags, String codePath, 8973 String resourcePath, String nativeLibraryRoot, String[] instructionSets, 8974 boolean isMultiArch) { 8975 final boolean isInAsec; 8976 if (installOnSd(flags)) { 8977 /* Apps on SD card are always in ASEC containers. */ 8978 isInAsec = true; 8979 } else if (installForwardLocked(flags) 8980 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 8981 /* 8982 * Forward-locked apps are only in ASEC containers if they're the 8983 * new style 8984 */ 8985 isInAsec = true; 8986 } else { 8987 isInAsec = false; 8988 } 8989 8990 if (isInAsec) { 8991 return new AsecInstallArgs(codePath, instructionSets, 8992 installOnSd(flags), installForwardLocked(flags), isMultiArch); 8993 } else { 8994 return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot, 8995 instructionSets, isMultiArch); 8996 } 8997 } 8998 8999 private InstallArgs createInstallArgsForMoveTarget(String codePath, int flags, String pkgName, 9000 String[] instructionSets, boolean isMultiArch) { 9001 final File codeFile = new File(codePath); 9002 if (installOnSd(flags) || installForwardLocked(flags)) { 9003 String cid = getNextCodePath(codePath, pkgName, "/" 9004 + AsecInstallArgs.RES_FILE_NAME); 9005 return new AsecInstallArgs(codeFile, cid, instructionSets, installOnSd(flags), 9006 installForwardLocked(flags), isMultiArch); 9007 } else { 9008 return new FileInstallArgs(codeFile, instructionSets, isMultiArch); 9009 } 9010 } 9011 9012 static abstract class InstallArgs { 9013 /** @see InstallParams#originFile */ 9014 final File originFile; 9015 /** @see InstallParams#originStaged */ 9016 final boolean originStaged; 9017 9018 // TODO: define inherit location 9019 9020 final IPackageInstallObserver2 observer; 9021 // Always refers to PackageManager flags only 9022 final int flags; 9023 final String installerPackageName; 9024 final ManifestDigest manifestDigest; 9025 final UserHandle user; 9026 final String abiOverride; 9027 final boolean multiArch; 9028 9029 // The list of instruction sets supported by this app. This is currently 9030 // only used during the rmdex() phase to clean up resources. We can get rid of this 9031 // if we move dex files under the common app path. 9032 /* nullable */ String[] instructionSets; 9033 9034 InstallArgs(File originFile, boolean originStaged, IPackageInstallObserver2 observer, 9035 int flags, String installerPackageName, ManifestDigest manifestDigest, 9036 UserHandle user, String[] instructionSets, 9037 String abiOverride, boolean multiArch) { 9038 this.originFile = originFile; 9039 this.originStaged = originStaged; 9040 this.flags = flags; 9041 this.observer = observer; 9042 this.installerPackageName = installerPackageName; 9043 this.manifestDigest = manifestDigest; 9044 this.user = user; 9045 this.instructionSets = instructionSets; 9046 this.abiOverride = abiOverride; 9047 this.multiArch = multiArch; 9048 } 9049 9050 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 9051 abstract int doPreInstall(int status); 9052 9053 /** 9054 * Rename package into final resting place. All paths on the given 9055 * scanned package should be updated to reflect the rename. 9056 */ 9057 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 9058 abstract int doPostInstall(int status, int uid); 9059 9060 /** @see PackageSettingBase#codePathString */ 9061 abstract String getCodePath(); 9062 /** @see PackageSettingBase#resourcePathString */ 9063 abstract String getResourcePath(); 9064 abstract String getLegacyNativeLibraryPath(); 9065 9066 // Need installer lock especially for dex file removal. 9067 abstract void cleanUpResourcesLI(); 9068 abstract boolean doPostDeleteLI(boolean delete); 9069 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9070 9071 /** 9072 * Called before the source arguments are copied. This is used mostly 9073 * for MoveParams when it needs to read the source file to put it in the 9074 * destination. 9075 */ 9076 int doPreCopy() { 9077 return PackageManager.INSTALL_SUCCEEDED; 9078 } 9079 9080 /** 9081 * Called after the source arguments are copied. This is used mostly for 9082 * MoveParams when it needs to read the source file to put it in the 9083 * destination. 9084 * 9085 * @return 9086 */ 9087 int doPostCopy(int uid) { 9088 return PackageManager.INSTALL_SUCCEEDED; 9089 } 9090 9091 protected boolean isFwdLocked() { 9092 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9093 } 9094 9095 UserHandle getUser() { 9096 return user; 9097 } 9098 } 9099 9100 /** 9101 * Logic to handle installation of non-ASEC applications, including copying 9102 * and renaming logic. 9103 */ 9104 class FileInstallArgs extends InstallArgs { 9105 private File codeFile; 9106 private File resourceFile; 9107 private File legacyNativeLibraryPath; 9108 9109 // Example topology: 9110 // /data/app/com.example/base.apk 9111 // /data/app/com.example/split_foo.apk 9112 // /data/app/com.example/lib/arm/libfoo.so 9113 // /data/app/com.example/lib/arm64/libfoo.so 9114 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 9115 9116 /** New install */ 9117 FileInstallArgs(InstallParams params) { 9118 super(params.originFile, params.originStaged, params.observer, params.flags, 9119 params.installerPackageName, params.getManifestDigest(), params.getUser(), 9120 null /* instruction sets */, params.packageAbiOverride, 9121 params.multiArch); 9122 if (isFwdLocked()) { 9123 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 9124 } 9125 } 9126 9127 /** Existing install */ 9128 FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryRoot, 9129 String[] instructionSets, boolean isMultiArch) { 9130 super(null, false, null, 0, null, null, null, instructionSets, null, isMultiArch); 9131 this.codeFile = (codePath != null) ? new File(codePath) : null; 9132 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 9133 this.legacyNativeLibraryPath = (legacyNativeLibraryRoot != null) ? 9134 new File(legacyNativeLibraryRoot) : null; 9135 } 9136 9137 /** New install from existing */ 9138 FileInstallArgs(File originFile, String[] instructionSets, boolean isMultiArch) { 9139 super(originFile, false, null, 0, null, null, null, instructionSets, null, 9140 isMultiArch); 9141 } 9142 9143 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9144 final long lowThreshold; 9145 9146 final DeviceStorageMonitorInternal 9147 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 9148 if (dsm == null) { 9149 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 9150 lowThreshold = 0L; 9151 } else { 9152 if (dsm.isMemoryLow()) { 9153 Log.w(TAG, "Memory is reported as being too low; aborting package install"); 9154 return false; 9155 } 9156 9157 lowThreshold = dsm.getMemoryLowThreshold(); 9158 } 9159 9160 return imcs.checkInternalFreeStorage(originFile.getAbsolutePath(), isFwdLocked(), 9161 lowThreshold); 9162 } 9163 9164 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9165 int ret = PackageManager.INSTALL_SUCCEEDED; 9166 9167 if (originStaged) { 9168 Slog.d(TAG, originFile + " already staged; skipping copy"); 9169 codeFile = originFile; 9170 resourceFile = originFile; 9171 } else { 9172 try { 9173 final File tempDir = mInstallerService.allocateSessionDir(); 9174 codeFile = tempDir; 9175 resourceFile = tempDir; 9176 } catch (IOException e) { 9177 Slog.w(TAG, "Failed to create copy file: " + e); 9178 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9179 } 9180 9181 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 9182 @Override 9183 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 9184 if (!FileUtils.isValidExtFilename(name)) { 9185 throw new IllegalArgumentException("Invalid filename: " + name); 9186 } 9187 try { 9188 final File file = new File(codeFile, name); 9189 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 9190 O_RDWR | O_CREAT, 0644); 9191 Os.chmod(file.getAbsolutePath(), 0644); 9192 return new ParcelFileDescriptor(fd); 9193 } catch (ErrnoException e) { 9194 throw new RemoteException("Failed to open: " + e.getMessage()); 9195 } 9196 } 9197 }; 9198 9199 ret = imcs.copyPackage(originFile.getAbsolutePath(), target); 9200 if (ret != PackageManager.INSTALL_SUCCEEDED) { 9201 Slog.e(TAG, "Failed to copy package"); 9202 return ret; 9203 } 9204 } 9205 9206 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 9207 NativeLibraryHelper.Handle handle = null; 9208 try { 9209 handle = NativeLibraryHelper.Handle.create(codeFile); 9210 if (multiArch) { 9211 // Warn if we've set an abiOverride for multi-lib packages.. 9212 // By definition, we need to copy both 32 and 64 bit libraries for 9213 // such packages. 9214 if (abiOverride != null) { 9215 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 9216 } 9217 9218 int copyRet = PackageManager.NO_NATIVE_LIBRARIES; 9219 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 9220 copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot, 9221 Build.SUPPORTED_32_BIT_ABIS, true /* use isa specific subdirs */); 9222 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9223 Slog.w(TAG, "Failure copying 32 bit native libraries [errorCode=" + copyRet + "]"); 9224 return copyRet; 9225 } 9226 } 9227 9228 if (DEBUG_ABI_SELECTION && copyRet >= 0) { 9229 Log.d(TAG, "Installed 32 bit libraries under: " + codeFile + " abi=" + 9230 Build.SUPPORTED_32_BIT_ABIS[copyRet]); 9231 } 9232 9233 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 9234 copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot, 9235 Build.SUPPORTED_64_BIT_ABIS, true /* use isa specific subdirs */); 9236 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9237 Slog.w(TAG, "Failure copying 64 bit native libraries [errorCode=" + copyRet + "]"); 9238 return copyRet; 9239 } 9240 } 9241 9242 if (DEBUG_ABI_SELECTION && copyRet >= 0) { 9243 Log.d(TAG, "Installed 64 bit libraries under: " + codeFile + " abi=" + 9244 Build.SUPPORTED_64_BIT_ABIS[copyRet]); 9245 } 9246 } else { 9247 String[] abiList = (abiOverride != null) ? 9248 new String[] { abiOverride } : Build.SUPPORTED_ABIS; 9249 9250 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && abiOverride == null && 9251 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9252 abiList = Build.SUPPORTED_32_BIT_ABIS; 9253 } 9254 9255 int copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot, abiList, 9256 true /* use isa specific subdirs */); 9257 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9258 Slog.w(TAG, "Failure copying native libraries [errorCode=" + copyRet + "]"); 9259 return copyRet; 9260 } 9261 9262 if (DEBUG_ABI_SELECTION && copyRet >= 0) { 9263 Log.d(TAG, "Installed libraries under: " + codeFile + " abi=" + abiList[copyRet]); 9264 } 9265 } 9266 } catch (IOException e) { 9267 Slog.e(TAG, "Copying native libraries failed", e); 9268 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9269 } finally { 9270 IoUtils.closeQuietly(handle); 9271 } 9272 9273 return ret; 9274 } 9275 9276 int doPreInstall(int status) { 9277 if (status != PackageManager.INSTALL_SUCCEEDED) { 9278 cleanUp(); 9279 } 9280 return status; 9281 } 9282 9283 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9284 if (status != PackageManager.INSTALL_SUCCEEDED) { 9285 cleanUp(); 9286 return false; 9287 } else { 9288 final File beforeCodeFile = codeFile; 9289 final File afterCodeFile = new File(mAppInstallDir, 9290 getNextCodePath(oldCodePath, pkg.packageName, null)); 9291 9292 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 9293 if (!beforeCodeFile.renameTo(afterCodeFile)) { 9294 return false; 9295 } 9296 if (!SELinux.restoreconRecursive(afterCodeFile)) { 9297 return false; 9298 } 9299 9300 // Reflect the rename internally 9301 codeFile = afterCodeFile; 9302 resourceFile = afterCodeFile; 9303 9304 // Reflect the rename in scanned details 9305 pkg.codePath = afterCodeFile.getAbsolutePath(); 9306 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9307 pkg.baseCodePath); 9308 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9309 pkg.splitCodePaths); 9310 9311 // Reflect the rename in app info 9312 pkg.applicationInfo.setCodePath(pkg.codePath); 9313 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9314 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9315 pkg.applicationInfo.setResourcePath(pkg.codePath); 9316 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9317 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9318 // Null out the legacy native dir so we stop using it. 9319 pkg.applicationInfo.legacyNativeLibraryDir = null; 9320 9321 return true; 9322 } 9323 } 9324 9325 int doPostInstall(int status, int uid) { 9326 if (status != PackageManager.INSTALL_SUCCEEDED) { 9327 cleanUp(); 9328 } 9329 return status; 9330 } 9331 9332 @Override 9333 String getCodePath() { 9334 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 9335 } 9336 9337 @Override 9338 String getResourcePath() { 9339 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 9340 } 9341 9342 @Override 9343 String getLegacyNativeLibraryPath() { 9344 return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null; 9345 } 9346 9347 private boolean cleanUp() { 9348 if (codeFile == null || !codeFile.exists()) { 9349 return false; 9350 } 9351 9352 if (codeFile.isDirectory()) { 9353 FileUtils.deleteContents(codeFile); 9354 } 9355 codeFile.delete(); 9356 9357 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 9358 resourceFile.delete(); 9359 } 9360 9361 if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) { 9362 if (!FileUtils.deleteContents(legacyNativeLibraryPath)) { 9363 Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath); 9364 } 9365 legacyNativeLibraryPath.delete(); 9366 } 9367 9368 return true; 9369 } 9370 9371 void cleanUpResourcesLI() { 9372 // Try enumerating all code paths before deleting 9373 List<String> allCodePaths = Collections.EMPTY_LIST; 9374 if (codeFile != null && codeFile.exists()) { 9375 try { 9376 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9377 allCodePaths = pkg.getAllCodePaths(); 9378 } catch (PackageParserException e) { 9379 // Ignored; we tried our best 9380 } 9381 } 9382 9383 cleanUp(); 9384 9385 if (!allCodePaths.isEmpty()) { 9386 if (instructionSets == null) { 9387 throw new IllegalStateException("instructionSet == null"); 9388 } 9389 9390 for (String codePath : allCodePaths) { 9391 for (String instructionSet : instructionSets) { 9392 int retCode = mInstaller.rmdex(codePath, instructionSet); 9393 if (retCode < 0) { 9394 Slog.w(TAG, "Couldn't remove dex file for package: " 9395 + " at location " + codePath + ", retcode=" + retCode); 9396 // we don't consider this to be a failure of the core package deletion 9397 } 9398 } 9399 } 9400 } 9401 } 9402 9403 boolean doPostDeleteLI(boolean delete) { 9404 // XXX err, shouldn't we respect the delete flag? 9405 cleanUpResourcesLI(); 9406 return true; 9407 } 9408 } 9409 9410 private boolean isAsecExternal(String cid) { 9411 final String asecPath = PackageHelper.getSdFilesystem(cid); 9412 return !asecPath.startsWith(mAsecInternalPath); 9413 } 9414 9415 /** 9416 * Extract the MountService "container ID" from the full code path of an 9417 * .apk. 9418 */ 9419 static String cidFromCodePath(String fullCodePath) { 9420 int eidx = fullCodePath.lastIndexOf("/"); 9421 String subStr1 = fullCodePath.substring(0, eidx); 9422 int sidx = subStr1.lastIndexOf("/"); 9423 return subStr1.substring(sidx+1, eidx); 9424 } 9425 9426 /** 9427 * Logic to handle installation of ASEC applications, including copying and 9428 * renaming logic. 9429 */ 9430 class AsecInstallArgs extends InstallArgs { 9431 // TODO: teach about handling cluster directories 9432 9433 static final String RES_FILE_NAME = "pkg.apk"; 9434 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 9435 9436 String cid; 9437 String packagePath; 9438 String resourcePath; 9439 String legacyNativeLibraryDir; 9440 9441 /** New install */ 9442 AsecInstallArgs(InstallParams params) { 9443 super(params.originFile, params.originStaged, params.observer, params.flags, 9444 params.installerPackageName, params.getManifestDigest(), 9445 params.getUser(), null /* instruction sets */, 9446 params.packageAbiOverride, params.multiArch); 9447 } 9448 9449 /** Existing install */ 9450 AsecInstallArgs(String fullCodePath, String[] instructionSets, 9451 boolean isExternal, boolean isForwardLocked, boolean isMultiArch) { 9452 super(null, false, null, (isExternal ? INSTALL_EXTERNAL : 0) 9453 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9454 instructionSets, null, isMultiArch); 9455 // Extract cid from fullCodePath 9456 int eidx = fullCodePath.lastIndexOf("/"); 9457 String subStr1 = fullCodePath.substring(0, eidx); 9458 int sidx = subStr1.lastIndexOf("/"); 9459 cid = subStr1.substring(sidx+1, eidx); 9460 setCachePath(subStr1); 9461 } 9462 9463 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked, 9464 boolean isMultiArch) { 9465 super(null, false, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 9466 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9467 instructionSets, null, isMultiArch); 9468 this.cid = cid; 9469 setCachePath(PackageHelper.getSdDir(cid)); 9470 } 9471 9472 /** New install from existing */ 9473 AsecInstallArgs(File originPackageFile, String cid, String[] instructionSets, 9474 boolean isExternal, boolean isForwardLocked, boolean isMultiArch) { 9475 super(originPackageFile, false, null, (isExternal ? INSTALL_EXTERNAL : 0) 9476 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9477 instructionSets, null, isMultiArch); 9478 this.cid = cid; 9479 } 9480 9481 void createCopyFile() { 9482 cid = getTempContainerId(); 9483 } 9484 9485 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9486 return imcs.checkExternalFreeStorage(originFile.getAbsolutePath(), isFwdLocked(), 9487 abiOverride); 9488 } 9489 9490 private final boolean isExternal() { 9491 return (flags & PackageManager.INSTALL_EXTERNAL) != 0; 9492 } 9493 9494 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9495 if (temp) { 9496 createCopyFile(); 9497 } else { 9498 /* 9499 * Pre-emptively destroy the container since it's destroyed if 9500 * copying fails due to it existing anyway. 9501 */ 9502 PackageHelper.destroySdDir(cid); 9503 } 9504 9505 final String newCachePath = imcs.copyPackageToContainer( 9506 originFile.getAbsolutePath(), cid, getEncryptKey(), isExternal(), 9507 isFwdLocked(), abiOverride); 9508 9509 if (newCachePath != null) { 9510 setCachePath(newCachePath); 9511 return PackageManager.INSTALL_SUCCEEDED; 9512 } else { 9513 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9514 } 9515 } 9516 9517 @Override 9518 String getCodePath() { 9519 return packagePath; 9520 } 9521 9522 @Override 9523 String getResourcePath() { 9524 return resourcePath; 9525 } 9526 9527 @Override 9528 String getLegacyNativeLibraryPath() { 9529 return legacyNativeLibraryDir; 9530 } 9531 9532 int doPreInstall(int status) { 9533 if (status != PackageManager.INSTALL_SUCCEEDED) { 9534 // Destroy container 9535 PackageHelper.destroySdDir(cid); 9536 } else { 9537 boolean mounted = PackageHelper.isContainerMounted(cid); 9538 if (!mounted) { 9539 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), 9540 Process.SYSTEM_UID); 9541 if (newCachePath != null) { 9542 setCachePath(newCachePath); 9543 } else { 9544 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9545 } 9546 } 9547 } 9548 return status; 9549 } 9550 9551 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9552 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 9553 String newCachePath = null; 9554 if (PackageHelper.isContainerMounted(cid)) { 9555 // Unmount the container 9556 if (!PackageHelper.unMountSdDir(cid)) { 9557 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9558 return false; 9559 } 9560 } 9561 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9562 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9563 " which might be stale. Will try to clean up."); 9564 // Clean up the stale container and proceed to recreate. 9565 if (!PackageHelper.destroySdDir(newCacheId)) { 9566 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9567 return false; 9568 } 9569 // Successfully cleaned up stale container. Try to rename again. 9570 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9571 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9572 + " inspite of cleaning it up."); 9573 return false; 9574 } 9575 } 9576 if (!PackageHelper.isContainerMounted(newCacheId)) { 9577 Slog.w(TAG, "Mounting container " + newCacheId); 9578 newCachePath = PackageHelper.mountSdDir(newCacheId, 9579 getEncryptKey(), Process.SYSTEM_UID); 9580 } else { 9581 newCachePath = PackageHelper.getSdDir(newCacheId); 9582 } 9583 if (newCachePath == null) { 9584 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9585 return false; 9586 } 9587 Log.i(TAG, "Succesfully renamed " + cid + 9588 " to " + newCacheId + 9589 " at new path: " + newCachePath); 9590 cid = newCacheId; 9591 setCachePath(newCachePath); 9592 9593 // TODO: extend to support split APKs 9594 pkg.codePath = getCodePath(); 9595 pkg.baseCodePath = getCodePath(); 9596 pkg.splitCodePaths = null; 9597 9598 pkg.applicationInfo.setCodePath(getCodePath()); 9599 pkg.applicationInfo.setBaseCodePath(getCodePath()); 9600 pkg.applicationInfo.setSplitCodePaths(null); 9601 pkg.applicationInfo.setResourcePath(getResourcePath()); 9602 pkg.applicationInfo.setBaseResourcePath(getResourcePath()); 9603 pkg.applicationInfo.setSplitResourcePaths(null); 9604 // ASEC installs are considered "legacy" because we don't support 9605 // multiarch on them yet, and use the old style paths on them. 9606 pkg.applicationInfo.legacyNativeLibraryDir = legacyNativeLibraryDir; 9607 9608 return true; 9609 } 9610 9611 private void setCachePath(String newCachePath) { 9612 File cachePath = new File(newCachePath); 9613 legacyNativeLibraryDir = new File(cachePath, LIB_DIR_NAME).getPath(); 9614 packagePath = new File(cachePath, RES_FILE_NAME).getPath(); 9615 9616 if (isFwdLocked()) { 9617 resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath(); 9618 } else { 9619 resourcePath = packagePath; 9620 } 9621 } 9622 9623 int doPostInstall(int status, int uid) { 9624 if (status != PackageManager.INSTALL_SUCCEEDED) { 9625 cleanUp(); 9626 } else { 9627 final int groupOwner; 9628 final String protectedFile; 9629 if (isFwdLocked()) { 9630 groupOwner = UserHandle.getSharedAppGid(uid); 9631 protectedFile = RES_FILE_NAME; 9632 } else { 9633 groupOwner = -1; 9634 protectedFile = null; 9635 } 9636 9637 if (uid < Process.FIRST_APPLICATION_UID 9638 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9639 Slog.e(TAG, "Failed to finalize " + cid); 9640 PackageHelper.destroySdDir(cid); 9641 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9642 } 9643 9644 boolean mounted = PackageHelper.isContainerMounted(cid); 9645 if (!mounted) { 9646 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9647 } 9648 } 9649 return status; 9650 } 9651 9652 private void cleanUp() { 9653 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9654 9655 // Destroy secure container 9656 PackageHelper.destroySdDir(cid); 9657 } 9658 9659 void cleanUpResourcesLI() { 9660 String sourceFile = getCodePath(); 9661 // Remove dex file 9662 if (instructionSets == null) { 9663 throw new IllegalStateException("instructionSet == null"); 9664 } 9665 for (String instructionSet : instructionSets) { 9666 int retCode = mInstaller.rmdex(sourceFile, instructionSet); 9667 if (retCode < 0) { 9668 Slog.w(TAG, "Couldn't remove dex file for package: " 9669 + " at location " 9670 + sourceFile.toString() + ", retcode=" + retCode); 9671 // we don't consider this to be a failure of the core package deletion 9672 } 9673 } 9674 cleanUp(); 9675 } 9676 9677 boolean matchContainer(String app) { 9678 if (cid.startsWith(app)) { 9679 return true; 9680 } 9681 return false; 9682 } 9683 9684 String getPackageName() { 9685 return getAsecPackageName(cid); 9686 } 9687 9688 boolean doPostDeleteLI(boolean delete) { 9689 boolean ret = false; 9690 boolean mounted = PackageHelper.isContainerMounted(cid); 9691 if (mounted) { 9692 // Unmount first 9693 ret = PackageHelper.unMountSdDir(cid); 9694 } 9695 if (ret && delete) { 9696 cleanUpResourcesLI(); 9697 } 9698 return ret; 9699 } 9700 9701 @Override 9702 int doPreCopy() { 9703 if (isFwdLocked()) { 9704 if (!PackageHelper.fixSdPermissions(cid, 9705 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 9706 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9707 } 9708 } 9709 9710 return PackageManager.INSTALL_SUCCEEDED; 9711 } 9712 9713 @Override 9714 int doPostCopy(int uid) { 9715 if (isFwdLocked()) { 9716 if (uid < Process.FIRST_APPLICATION_UID 9717 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 9718 RES_FILE_NAME)) { 9719 Slog.e(TAG, "Failed to finalize " + cid); 9720 PackageHelper.destroySdDir(cid); 9721 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9722 } 9723 } 9724 9725 return PackageManager.INSTALL_SUCCEEDED; 9726 } 9727 } 9728 9729 static String getAsecPackageName(String packageCid) { 9730 int idx = packageCid.lastIndexOf("-"); 9731 if (idx == -1) { 9732 return packageCid; 9733 } 9734 return packageCid.substring(0, idx); 9735 } 9736 9737 // Utility method used to create code paths based on package name and available index. 9738 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 9739 String idxStr = ""; 9740 int idx = 1; 9741 // Fall back to default value of idx=1 if prefix is not 9742 // part of oldCodePath 9743 if (oldCodePath != null) { 9744 String subStr = oldCodePath; 9745 // Drop the suffix right away 9746 if (suffix != null && subStr.endsWith(suffix)) { 9747 subStr = subStr.substring(0, subStr.length() - suffix.length()); 9748 } 9749 // If oldCodePath already contains prefix find out the 9750 // ending index to either increment or decrement. 9751 int sidx = subStr.lastIndexOf(prefix); 9752 if (sidx != -1) { 9753 subStr = subStr.substring(sidx + prefix.length()); 9754 if (subStr != null) { 9755 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 9756 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 9757 } 9758 try { 9759 idx = Integer.parseInt(subStr); 9760 if (idx <= 1) { 9761 idx++; 9762 } else { 9763 idx--; 9764 } 9765 } catch(NumberFormatException e) { 9766 } 9767 } 9768 } 9769 } 9770 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 9771 return prefix + idxStr; 9772 } 9773 9774 // Utility method used to ignore ADD/REMOVE events 9775 // by directory observer. 9776 private static boolean ignoreCodePath(String fullPathStr) { 9777 String apkName = deriveCodePathName(fullPathStr); 9778 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 9779 if (idx != -1 && ((idx+1) < apkName.length())) { 9780 // Make sure the package ends with a numeral 9781 String version = apkName.substring(idx+1); 9782 try { 9783 Integer.parseInt(version); 9784 return true; 9785 } catch (NumberFormatException e) {} 9786 } 9787 return false; 9788 } 9789 9790 // Utility method that returns the relative package path with respect 9791 // to the installation directory. Like say for /data/data/com.test-1.apk 9792 // string com.test-1 is returned. 9793 static String deriveCodePathName(String codePath) { 9794 if (codePath == null) { 9795 return null; 9796 } 9797 final File codeFile = new File(codePath); 9798 final String name = codeFile.getName(); 9799 if (codeFile.isDirectory()) { 9800 return name; 9801 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 9802 final int lastDot = name.lastIndexOf('.'); 9803 return name.substring(0, lastDot); 9804 } else { 9805 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 9806 return null; 9807 } 9808 } 9809 9810 class PackageInstalledInfo { 9811 String name; 9812 int uid; 9813 // The set of users that originally had this package installed. 9814 int[] origUsers; 9815 // The set of users that now have this package installed. 9816 int[] newUsers; 9817 PackageParser.Package pkg; 9818 int returnCode; 9819 PackageRemovedInfo removedInfo; 9820 9821 // In some error cases we want to convey more info back to the observer 9822 String origPackage; 9823 String origPermission; 9824 } 9825 9826 /* 9827 * Install a non-existing package. 9828 */ 9829 private void installNewPackageLI(PackageParser.Package pkg, 9830 int parseFlags, int scanMode, UserHandle user, 9831 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9832 // Remember this for later, in case we need to rollback this install 9833 String pkgName = pkg.packageName; 9834 9835 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 9836 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 9837 synchronized(mPackages) { 9838 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 9839 // A package with the same name is already installed, though 9840 // it has been renamed to an older name. The package we 9841 // are trying to install should be installed as an update to 9842 // the existing one, but that has not been requested, so bail. 9843 Slog.w(TAG, "Attempt to re-install " + pkgName 9844 + " without first uninstalling package running as " 9845 + mSettings.mRenamedPackages.get(pkgName)); 9846 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9847 return; 9848 } 9849 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.codePath)) { 9850 // Don't allow installation over an existing package with the same name. 9851 Slog.w(TAG, "Attempt to re-install " + pkgName 9852 + " without first uninstalling."); 9853 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9854 return; 9855 } 9856 } 9857 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 9858 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode, 9859 System.currentTimeMillis(), user, abiOverride); 9860 if (newPackage == null) { 9861 Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath); 9862 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 9863 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 9864 } 9865 } else { 9866 updateSettingsLI(newPackage, installerPackageName, null, null, res); 9867 // delete the partially installed application. the data directory will have to be 9868 // restored if it was already existing 9869 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9870 // remove package from internal structures. Note that we want deletePackageX to 9871 // delete the package data and cache directories that it created in 9872 // scanPackageLocked, unless those directories existed before we even tried to 9873 // install. 9874 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 9875 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 9876 res.removedInfo, true); 9877 } 9878 } 9879 } 9880 9881 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 9882 // Upgrade keysets are being used. Determine if new package has a superset of the 9883 // required keys. 9884 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 9885 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9886 Set<Long> newSigningKeyIds = new ArraySet<Long>(); 9887 for (PublicKey pk : newPkg.mSigningKeys) { 9888 newSigningKeyIds.add(ksms.getIdForPublicKey(pk)); 9889 } 9890 //remove PUBLIC_KEY_NOT_FOUND, although not necessary 9891 newSigningKeyIds.remove(ksms.PUBLIC_KEY_NOT_FOUND); 9892 for (int i = 0; i < upgradeKeySets.length; i++) { 9893 if (newSigningKeyIds.containsAll(ksms.mKeySetMapping.get(upgradeKeySets[i]))) { 9894 return true; 9895 } 9896 } 9897 return false; 9898 } 9899 9900 private void replacePackageLI(PackageParser.Package pkg, 9901 int parseFlags, int scanMode, UserHandle user, 9902 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9903 PackageParser.Package oldPackage; 9904 String pkgName = pkg.packageName; 9905 int[] allUsers; 9906 boolean[] perUserInstalled; 9907 9908 // First find the old package info and check signatures 9909 synchronized(mPackages) { 9910 oldPackage = mPackages.get(pkgName); 9911 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 9912 PackageSetting ps = mSettings.mPackages.get(pkgName); 9913 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 9914 // default to original signature matching 9915 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 9916 != PackageManager.SIGNATURE_MATCH) { 9917 Slog.w(TAG, "New package has a different signature: " + pkgName); 9918 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 9919 return; 9920 } 9921 } else { 9922 if(!checkUpgradeKeySetLP(ps, pkg)) { 9923 Slog.w(TAG, "New package not signed by keys specified by upgrade-keysets: " 9924 + pkgName); 9925 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 9926 return; 9927 } 9928 } 9929 9930 // In case of rollback, remember per-user/profile install state 9931 allUsers = sUserManager.getUserIds(); 9932 perUserInstalled = new boolean[allUsers.length]; 9933 for (int i = 0; i < allUsers.length; i++) { 9934 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 9935 } 9936 } 9937 boolean sysPkg = (isSystemApp(oldPackage)); 9938 if (sysPkg) { 9939 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 9940 user, allUsers, perUserInstalled, installerPackageName, res, 9941 abiOverride); 9942 } else { 9943 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 9944 user, allUsers, perUserInstalled, installerPackageName, res, 9945 abiOverride); 9946 } 9947 } 9948 9949 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 9950 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 9951 int[] allUsers, boolean[] perUserInstalled, 9952 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9953 PackageParser.Package newPackage = null; 9954 String pkgName = deletedPackage.packageName; 9955 boolean deletedPkg = true; 9956 boolean updatedSettings = false; 9957 9958 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 9959 + deletedPackage); 9960 long origUpdateTime; 9961 if (pkg.mExtras != null) { 9962 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 9963 } else { 9964 origUpdateTime = 0; 9965 } 9966 9967 // First delete the existing package while retaining the data directory 9968 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 9969 res.removedInfo, true)) { 9970 // If the existing package wasn't successfully deleted 9971 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 9972 deletedPkg = false; 9973 } else { 9974 // Successfully deleted the old package. Now proceed with re-installation 9975 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 9976 newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME, 9977 System.currentTimeMillis(), user, abiOverride); 9978 if (newPackage == null) { 9979 Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath); 9980 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 9981 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 9982 } 9983 } else { 9984 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 9985 updatedSettings = true; 9986 } 9987 } 9988 9989 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9990 // remove package from internal structures. Note that we want deletePackageX to 9991 // delete the package data and cache directories that it created in 9992 // scanPackageLocked, unless those directories existed before we even tried to 9993 // install. 9994 if(updatedSettings) { 9995 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 9996 deletePackageLI( 9997 pkgName, null, true, allUsers, perUserInstalled, 9998 PackageManager.DELETE_KEEP_DATA, 9999 res.removedInfo, true); 10000 } 10001 // Since we failed to install the new package we need to restore the old 10002 // package that we deleted. 10003 if (deletedPkg) { 10004 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 10005 File restoreFile = new File(deletedPackage.codePath); 10006 // Parse old package 10007 boolean oldOnSd = isExternal(deletedPackage); 10008 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 10009 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) | 10010 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 10011 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE 10012 | SCAN_UPDATE_TIME; 10013 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode, 10014 origUpdateTime, null, null) == null) { 10015 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade"); 10016 return; 10017 } 10018 // Restore of old package succeeded. Update permissions. 10019 // writer 10020 synchronized (mPackages) { 10021 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 10022 UPDATE_PERMISSIONS_ALL); 10023 // can downgrade to reader 10024 mSettings.writeLPr(); 10025 } 10026 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 10027 } 10028 } 10029 } 10030 10031 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 10032 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 10033 int[] allUsers, boolean[] perUserInstalled, 10034 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 10035 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 10036 + ", old=" + deletedPackage); 10037 PackageParser.Package newPackage = null; 10038 boolean updatedSettings = false; 10039 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING | 10040 PackageParser.PARSE_IS_SYSTEM; 10041 if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) { 10042 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10043 } 10044 String packageName = deletedPackage.packageName; 10045 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 10046 if (packageName == null) { 10047 Slog.w(TAG, "Attempt to delete null packageName."); 10048 return; 10049 } 10050 PackageParser.Package oldPkg; 10051 PackageSetting oldPkgSetting; 10052 // reader 10053 synchronized (mPackages) { 10054 oldPkg = mPackages.get(packageName); 10055 oldPkgSetting = mSettings.mPackages.get(packageName); 10056 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 10057 (oldPkgSetting == null)) { 10058 Slog.w(TAG, "Couldn't find package:"+packageName+" information"); 10059 return; 10060 } 10061 } 10062 10063 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 10064 10065 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10066 res.removedInfo.removedPackage = packageName; 10067 // Remove existing system package 10068 removePackageLI(oldPkgSetting, true); 10069 // writer 10070 synchronized (mPackages) { 10071 if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) { 10072 // We didn't need to disable the .apk as a current system package, 10073 // which means we are replacing another update that is already 10074 // installed. We need to make sure to delete the older one's .apk. 10075 res.removedInfo.args = createInstallArgsForExisting(0, 10076 deletedPackage.applicationInfo.getCodePath(), 10077 deletedPackage.applicationInfo.getResourcePath(), 10078 deletedPackage.applicationInfo.legacyNativeLibraryDir, 10079 getAppDexInstructionSets(deletedPackage.applicationInfo), 10080 isMultiArch(deletedPackage.applicationInfo)); 10081 } else { 10082 res.removedInfo.args = null; 10083 } 10084 } 10085 10086 // Successfully disabled the old package. Now proceed with re-installation 10087 res.returnCode = mLastScanError = PackageManager.INSTALL_SUCCEEDED; 10088 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10089 newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user, abiOverride); 10090 if (newPackage == null) { 10091 Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath); 10092 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 10093 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 10094 } 10095 } else { 10096 if (newPackage.mExtras != null) { 10097 final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras; 10098 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10099 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10100 10101 // is the update attempting to change shared user? that isn't going to work... 10102 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10103 Slog.w(TAG, "Forbidding shared user change from " + oldPkgSetting.sharedUser 10104 + " to " + newPkgSetting.sharedUser); 10105 res.returnCode = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 10106 updatedSettings = true; 10107 } 10108 } 10109 10110 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10111 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10112 updatedSettings = true; 10113 } 10114 } 10115 10116 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10117 // Re installation failed. Restore old information 10118 // Remove new pkg information 10119 if (newPackage != null) { 10120 removeInstalledPackageLI(newPackage, true); 10121 } 10122 // Add back the old system package 10123 scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user, null); 10124 // Restore the old system information in Settings 10125 synchronized(mPackages) { 10126 if (updatedSettings) { 10127 mSettings.enableSystemPackageLPw(packageName); 10128 mSettings.setInstallerPackageName(packageName, 10129 oldPkgSetting.installerPackageName); 10130 } 10131 mSettings.writeLPr(); 10132 } 10133 } 10134 } 10135 10136 // Utility method used to move dex files during install. 10137 private int moveDexFilesLI(String oldCodePath, PackageParser.Package newPackage) { 10138 // TODO: extend to move split APK dex files 10139 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) { 10140 final String[] instructionSets = getAppDexInstructionSets(newPackage.applicationInfo); 10141 for (String instructionSet : instructionSets) { 10142 int retCode = mInstaller.movedex(oldCodePath, newPackage.baseCodePath, 10143 instructionSet); 10144 if (retCode != 0) { 10145 /* 10146 * Programs may be lazily run through dexopt, so the 10147 * source may not exist. However, something seems to 10148 * have gone wrong, so note that dexopt needs to be 10149 * run again and remove the source file. In addition, 10150 * remove the target to make sure there isn't a stale 10151 * file from a previous version of the package. 10152 */ 10153 newPackage.mDexOptNeeded = true; 10154 mInstaller.rmdex(oldCodePath, instructionSet); 10155 mInstaller.rmdex(newPackage.baseCodePath, instructionSet); 10156 } 10157 } 10158 } 10159 return PackageManager.INSTALL_SUCCEEDED; 10160 } 10161 10162 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10163 int[] allUsers, boolean[] perUserInstalled, 10164 PackageInstalledInfo res) { 10165 String pkgName = newPackage.packageName; 10166 synchronized (mPackages) { 10167 //write settings. the installStatus will be incomplete at this stage. 10168 //note that the new package setting would have already been 10169 //added to mPackages. It hasn't been persisted yet. 10170 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10171 mSettings.writeLPr(); 10172 } 10173 10174 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10175 10176 synchronized (mPackages) { 10177 updatePermissionsLPw(newPackage.packageName, newPackage, 10178 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10179 ? UPDATE_PERMISSIONS_ALL : 0)); 10180 // For system-bundled packages, we assume that installing an upgraded version 10181 // of the package implies that the user actually wants to run that new code, 10182 // so we enable the package. 10183 if (isSystemApp(newPackage)) { 10184 // NB: implicit assumption that system package upgrades apply to all users 10185 if (DEBUG_INSTALL) { 10186 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10187 } 10188 PackageSetting ps = mSettings.mPackages.get(pkgName); 10189 if (ps != null) { 10190 if (res.origUsers != null) { 10191 for (int userHandle : res.origUsers) { 10192 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10193 userHandle, installerPackageName); 10194 } 10195 } 10196 // Also convey the prior install/uninstall state 10197 if (allUsers != null && perUserInstalled != null) { 10198 for (int i = 0; i < allUsers.length; i++) { 10199 if (DEBUG_INSTALL) { 10200 Slog.d(TAG, " user " + allUsers[i] 10201 + " => " + perUserInstalled[i]); 10202 } 10203 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10204 } 10205 // these install state changes will be persisted in the 10206 // upcoming call to mSettings.writeLPr(). 10207 } 10208 } 10209 } 10210 res.name = pkgName; 10211 res.uid = newPackage.applicationInfo.uid; 10212 res.pkg = newPackage; 10213 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10214 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10215 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10216 //to update install status 10217 mSettings.writeLPr(); 10218 } 10219 } 10220 10221 private void installPackageLI(InstallArgs args, boolean newInstall, PackageInstalledInfo res) { 10222 int pFlags = args.flags; 10223 String installerPackageName = args.installerPackageName; 10224 File tmpPackageFile = new File(args.getCodePath()); 10225 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10226 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0); 10227 boolean replace = false; 10228 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE 10229 | (newInstall ? SCAN_NEW_INSTALL : 0); 10230 // Result object to be returned 10231 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10232 10233 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10234 // Retrieve PackageSettings and parse package 10235 int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10236 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10237 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 10238 PackageParser pp = new PackageParser(); 10239 pp.setSeparateProcesses(mSeparateProcesses); 10240 pp.setDisplayMetrics(mMetrics); 10241 10242 final PackageParser.Package pkg; 10243 try { 10244 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 10245 } catch (PackageParserException e) { 10246 Slog.e(TAG, "Failed during install: " + e); 10247 res.returnCode = e.error; 10248 return; 10249 } 10250 10251 String pkgName = res.name = pkg.packageName; 10252 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 10253 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) { 10254 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY; 10255 return; 10256 } 10257 } 10258 10259 try { 10260 pp.collectCertificates(pkg, parseFlags); 10261 pp.collectManifestDigest(pkg); 10262 } catch (PackageParserException e) { 10263 Slog.e(TAG, "Failed during install: " + e); 10264 res.returnCode = e.error; 10265 return; 10266 } 10267 10268 /* If the installer passed in a manifest digest, compare it now. */ 10269 if (args.manifestDigest != null) { 10270 if (DEBUG_INSTALL) { 10271 final String parsedManifest = pkg.manifestDigest == null ? "null" 10272 : pkg.manifestDigest.toString(); 10273 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 10274 + parsedManifest); 10275 } 10276 10277 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 10278 res.returnCode = PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 10279 return; 10280 } 10281 } else if (DEBUG_INSTALL) { 10282 final String parsedManifest = pkg.manifestDigest == null 10283 ? "null" : pkg.manifestDigest.toString(); 10284 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 10285 } 10286 10287 // Get rid of all references to package scan path via parser. 10288 pp = null; 10289 String oldCodePath = null; 10290 boolean systemApp = false; 10291 synchronized (mPackages) { 10292 // Check whether the newly-scanned package wants to define an already-defined perm 10293 int N = pkg.permissions.size(); 10294 for (int i = N-1; i >= 0; i--) { 10295 PackageParser.Permission perm = pkg.permissions.get(i); 10296 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 10297 if (bp != null) { 10298 // If the defining package is signed with our cert, it's okay. This 10299 // also includes the "updating the same package" case, of course. 10300 if (compareSignatures(bp.packageSetting.signatures.mSignatures, 10301 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 10302 // If the owning package is the system itself, we log but allow 10303 // install to proceed; we fail the install on all other permission 10304 // redefinitions. 10305 if (!bp.sourcePackage.equals("android")) { 10306 Slog.w(TAG, "Package " + pkg.packageName 10307 + " attempting to redeclare permission " + perm.info.name 10308 + " already owned by " + bp.sourcePackage); 10309 res.returnCode = PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 10310 res.origPermission = perm.info.name; 10311 res.origPackage = bp.sourcePackage; 10312 return; 10313 } else { 10314 Slog.w(TAG, "Package " + pkg.packageName 10315 + " attempting to redeclare system permission " 10316 + perm.info.name + "; ignoring new declaration"); 10317 pkg.permissions.remove(i); 10318 } 10319 } 10320 } 10321 } 10322 10323 // Check if installing already existing package 10324 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10325 String oldName = mSettings.mRenamedPackages.get(pkgName); 10326 if (pkg.mOriginalPackages != null 10327 && pkg.mOriginalPackages.contains(oldName) 10328 && mPackages.containsKey(oldName)) { 10329 // This package is derived from an original package, 10330 // and this device has been updating from that original 10331 // name. We must continue using the original name, so 10332 // rename the new package here. 10333 pkg.setPackageName(oldName); 10334 pkgName = pkg.packageName; 10335 replace = true; 10336 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 10337 + oldName + " pkgName=" + pkgName); 10338 } else if (mPackages.containsKey(pkgName)) { 10339 // This package, under its official name, already exists 10340 // on the device; we should replace it. 10341 replace = true; 10342 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 10343 } 10344 } 10345 PackageSetting ps = mSettings.mPackages.get(pkgName); 10346 if (ps != null) { 10347 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 10348 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 10349 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 10350 systemApp = (ps.pkg.applicationInfo.flags & 10351 ApplicationInfo.FLAG_SYSTEM) != 0; 10352 } 10353 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10354 } 10355 } 10356 10357 if (systemApp && onSd) { 10358 // Disable updates to system apps on sdcard 10359 Slog.w(TAG, "Cannot install updates to system apps on sdcard"); 10360 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10361 return; 10362 } 10363 10364 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 10365 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10366 return; 10367 } 10368 10369 if (replace) { 10370 replacePackageLI(pkg, parseFlags, scanMode, args.user, 10371 installerPackageName, res, args.abiOverride); 10372 } else { 10373 installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user, 10374 installerPackageName, res, args.abiOverride); 10375 } 10376 synchronized (mPackages) { 10377 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10378 if (ps != null) { 10379 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10380 } 10381 } 10382 } 10383 10384 private static boolean isForwardLocked(PackageParser.Package pkg) { 10385 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10386 } 10387 10388 10389 private boolean isForwardLocked(PackageSetting ps) { 10390 return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10391 } 10392 10393 private static boolean isMultiArch(PackageSetting ps) { 10394 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10395 } 10396 10397 private static boolean isMultiArch(ApplicationInfo info) { 10398 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10399 } 10400 10401 private static boolean isExternal(PackageParser.Package pkg) { 10402 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10403 } 10404 10405 private static boolean isExternal(PackageSetting ps) { 10406 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10407 } 10408 10409 private static boolean isSystemApp(PackageParser.Package pkg) { 10410 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10411 } 10412 10413 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 10414 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0; 10415 } 10416 10417 private static boolean isSystemApp(ApplicationInfo info) { 10418 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10419 } 10420 10421 private static boolean isSystemApp(PackageSetting ps) { 10422 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 10423 } 10424 10425 private static boolean isUpdatedSystemApp(PackageSetting ps) { 10426 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10427 } 10428 10429 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 10430 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10431 } 10432 10433 private int packageFlagsToInstallFlags(PackageSetting ps) { 10434 int installFlags = 0; 10435 if (isExternal(ps)) { 10436 installFlags |= PackageManager.INSTALL_EXTERNAL; 10437 } 10438 if (isForwardLocked(ps)) { 10439 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 10440 } 10441 return installFlags; 10442 } 10443 10444 private void deleteTempPackageFiles() { 10445 final FilenameFilter filter = new FilenameFilter() { 10446 public boolean accept(File dir, String name) { 10447 return name.startsWith("vmdl") && name.endsWith(".tmp"); 10448 } 10449 }; 10450 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 10451 file.delete(); 10452 } 10453 } 10454 10455 @Override 10456 public void deletePackageAsUser(final String packageName, 10457 final IPackageDeleteObserver observer, 10458 final int userId, final int flags) { 10459 mContext.enforceCallingOrSelfPermission( 10460 android.Manifest.permission.DELETE_PACKAGES, null); 10461 final int uid = Binder.getCallingUid(); 10462 if (UserHandle.getUserId(uid) != userId) { 10463 mContext.enforceCallingPermission( 10464 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 10465 "deletePackage for user " + userId); 10466 } 10467 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 10468 try { 10469 observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_USER_RESTRICTED); 10470 } catch (RemoteException re) { 10471 } 10472 return; 10473 } 10474 10475 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 10476 // Queue up an async operation since the package deletion may take a little while. 10477 mHandler.post(new Runnable() { 10478 public void run() { 10479 mHandler.removeCallbacks(this); 10480 final int returnCode = deletePackageX(packageName, userId, flags); 10481 if (observer != null) { 10482 try { 10483 observer.packageDeleted(packageName, returnCode); 10484 } catch (RemoteException e) { 10485 Log.i(TAG, "Observer no longer exists."); 10486 } //end catch 10487 } //end if 10488 } //end run 10489 }); 10490 } 10491 10492 private boolean isPackageDeviceAdmin(String packageName, int userId) { 10493 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 10494 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 10495 try { 10496 if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId) 10497 || dpm.isDeviceOwner(packageName))) { 10498 return true; 10499 } 10500 } catch (RemoteException e) { 10501 } 10502 return false; 10503 } 10504 10505 /** 10506 * This method is an internal method that could be get invoked either 10507 * to delete an installed package or to clean up a failed installation. 10508 * After deleting an installed package, a broadcast is sent to notify any 10509 * listeners that the package has been installed. For cleaning up a failed 10510 * installation, the broadcast is not necessary since the package's 10511 * installation wouldn't have sent the initial broadcast either 10512 * The key steps in deleting a package are 10513 * deleting the package information in internal structures like mPackages, 10514 * deleting the packages base directories through installd 10515 * updating mSettings to reflect current status 10516 * persisting settings for later use 10517 * sending a broadcast if necessary 10518 */ 10519 private int deletePackageX(String packageName, int userId, int flags) { 10520 final PackageRemovedInfo info = new PackageRemovedInfo(); 10521 final boolean res; 10522 10523 if (isPackageDeviceAdmin(packageName, userId)) { 10524 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 10525 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 10526 } 10527 10528 boolean removedForAllUsers = false; 10529 boolean systemUpdate = false; 10530 10531 // for the uninstall-updates case and restricted profiles, remember the per- 10532 // userhandle installed state 10533 int[] allUsers; 10534 boolean[] perUserInstalled; 10535 synchronized (mPackages) { 10536 PackageSetting ps = mSettings.mPackages.get(packageName); 10537 allUsers = sUserManager.getUserIds(); 10538 perUserInstalled = new boolean[allUsers.length]; 10539 for (int i = 0; i < allUsers.length; i++) { 10540 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10541 } 10542 } 10543 10544 synchronized (mInstallLock) { 10545 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 10546 res = deletePackageLI(packageName, 10547 (flags & PackageManager.DELETE_ALL_USERS) != 0 10548 ? UserHandle.ALL : new UserHandle(userId), 10549 true, allUsers, perUserInstalled, 10550 flags | REMOVE_CHATTY, info, true); 10551 systemUpdate = info.isRemovedPackageSystemUpdate; 10552 if (res && !systemUpdate && mPackages.get(packageName) == null) { 10553 removedForAllUsers = true; 10554 } 10555 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 10556 + " removedForAllUsers=" + removedForAllUsers); 10557 } 10558 10559 if (res) { 10560 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 10561 10562 // If the removed package was a system update, the old system package 10563 // was re-enabled; we need to broadcast this information 10564 if (systemUpdate) { 10565 Bundle extras = new Bundle(1); 10566 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 10567 ? info.removedAppId : info.uid); 10568 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10569 10570 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 10571 extras, null, null, null); 10572 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 10573 extras, null, null, null); 10574 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 10575 null, packageName, null, null); 10576 } 10577 } 10578 // Force a gc here. 10579 Runtime.getRuntime().gc(); 10580 // Delete the resources here after sending the broadcast to let 10581 // other processes clean up before deleting resources. 10582 if (info.args != null) { 10583 synchronized (mInstallLock) { 10584 info.args.doPostDeleteLI(true); 10585 } 10586 } 10587 10588 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10589 } 10590 10591 static class PackageRemovedInfo { 10592 String removedPackage; 10593 int uid = -1; 10594 int removedAppId = -1; 10595 int[] removedUsers = null; 10596 boolean isRemovedPackageSystemUpdate = false; 10597 // Clean up resources deleted packages. 10598 InstallArgs args = null; 10599 10600 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 10601 Bundle extras = new Bundle(1); 10602 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 10603 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 10604 if (replacing) { 10605 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10606 } 10607 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 10608 if (removedPackage != null) { 10609 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 10610 extras, null, null, removedUsers); 10611 if (fullRemove && !replacing) { 10612 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 10613 extras, null, null, removedUsers); 10614 } 10615 } 10616 if (removedAppId >= 0) { 10617 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 10618 removedUsers); 10619 } 10620 } 10621 } 10622 10623 /* 10624 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 10625 * flag is not set, the data directory is removed as well. 10626 * make sure this flag is set for partially installed apps. If not its meaningless to 10627 * delete a partially installed application. 10628 */ 10629 private void removePackageDataLI(PackageSetting ps, 10630 int[] allUserHandles, boolean[] perUserInstalled, 10631 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 10632 String packageName = ps.name; 10633 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 10634 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 10635 // Retrieve object to delete permissions for shared user later on 10636 final PackageSetting deletedPs; 10637 // reader 10638 synchronized (mPackages) { 10639 deletedPs = mSettings.mPackages.get(packageName); 10640 if (outInfo != null) { 10641 outInfo.removedPackage = packageName; 10642 outInfo.removedUsers = deletedPs != null 10643 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 10644 : null; 10645 } 10646 } 10647 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10648 removeDataDirsLI(packageName); 10649 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 10650 } 10651 // writer 10652 synchronized (mPackages) { 10653 if (deletedPs != null) { 10654 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10655 if (outInfo != null) { 10656 mSettings.mKeySetManagerService.removeAppKeySetData(packageName); 10657 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 10658 } 10659 if (deletedPs != null) { 10660 updatePermissionsLPw(deletedPs.name, null, 0); 10661 if (deletedPs.sharedUser != null) { 10662 // remove permissions associated with package 10663 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 10664 } 10665 } 10666 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 10667 } 10668 // make sure to preserve per-user disabled state if this removal was just 10669 // a downgrade of a system app to the factory package 10670 if (allUserHandles != null && perUserInstalled != null) { 10671 if (DEBUG_REMOVE) { 10672 Slog.d(TAG, "Propagating install state across downgrade"); 10673 } 10674 for (int i = 0; i < allUserHandles.length; i++) { 10675 if (DEBUG_REMOVE) { 10676 Slog.d(TAG, " user " + allUserHandles[i] 10677 + " => " + perUserInstalled[i]); 10678 } 10679 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10680 } 10681 } 10682 } 10683 // can downgrade to reader 10684 if (writeSettings) { 10685 // Save settings now 10686 mSettings.writeLPr(); 10687 } 10688 } 10689 if (outInfo != null) { 10690 // A user ID was deleted here. Go through all users and remove it 10691 // from KeyStore. 10692 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 10693 } 10694 } 10695 10696 static boolean locationIsPrivileged(File path) { 10697 try { 10698 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 10699 .getCanonicalPath(); 10700 return path.getCanonicalPath().startsWith(privilegedAppDir); 10701 } catch (IOException e) { 10702 Slog.e(TAG, "Unable to access code path " + path); 10703 } 10704 return false; 10705 } 10706 10707 /* 10708 * Tries to delete system package. 10709 */ 10710 private boolean deleteSystemPackageLI(PackageSetting newPs, 10711 int[] allUserHandles, boolean[] perUserInstalled, 10712 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 10713 final boolean applyUserRestrictions 10714 = (allUserHandles != null) && (perUserInstalled != null); 10715 PackageSetting disabledPs = null; 10716 // Confirm if the system package has been updated 10717 // An updated system app can be deleted. This will also have to restore 10718 // the system pkg from system partition 10719 // reader 10720 synchronized (mPackages) { 10721 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 10722 } 10723 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 10724 + " disabledPs=" + disabledPs); 10725 if (disabledPs == null) { 10726 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 10727 return false; 10728 } else if (DEBUG_REMOVE) { 10729 Slog.d(TAG, "Deleting system pkg from data partition"); 10730 } 10731 if (DEBUG_REMOVE) { 10732 if (applyUserRestrictions) { 10733 Slog.d(TAG, "Remembering install states:"); 10734 for (int i = 0; i < allUserHandles.length; i++) { 10735 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 10736 } 10737 } 10738 } 10739 // Delete the updated package 10740 outInfo.isRemovedPackageSystemUpdate = true; 10741 if (disabledPs.versionCode < newPs.versionCode) { 10742 // Delete data for downgrades 10743 flags &= ~PackageManager.DELETE_KEEP_DATA; 10744 } else { 10745 // Preserve data by setting flag 10746 flags |= PackageManager.DELETE_KEEP_DATA; 10747 } 10748 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 10749 allUserHandles, perUserInstalled, outInfo, writeSettings); 10750 if (!ret) { 10751 return false; 10752 } 10753 // writer 10754 synchronized (mPackages) { 10755 // Reinstate the old system package 10756 mSettings.enableSystemPackageLPw(newPs.name); 10757 // Remove any native libraries from the upgraded package. 10758 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 10759 } 10760 // Install the system package 10761 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 10762 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 10763 if (locationIsPrivileged(disabledPs.codePath)) { 10764 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10765 } 10766 PackageParser.Package newPkg = scanPackageLI(disabledPs.codePath, 10767 parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, null, null); 10768 10769 if (newPkg == null) { 10770 Slog.w(TAG, "Failed to restore system package:" + newPs.name 10771 + " with error:" + mLastScanError); 10772 return false; 10773 } 10774 // writer 10775 synchronized (mPackages) { 10776 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 10777 setBundledAppAbisAndRoots(newPkg, ps); 10778 updatePermissionsLPw(newPkg.packageName, newPkg, 10779 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 10780 if (applyUserRestrictions) { 10781 if (DEBUG_REMOVE) { 10782 Slog.d(TAG, "Propagating install state across reinstall"); 10783 } 10784 for (int i = 0; i < allUserHandles.length; i++) { 10785 if (DEBUG_REMOVE) { 10786 Slog.d(TAG, " user " + allUserHandles[i] 10787 + " => " + perUserInstalled[i]); 10788 } 10789 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10790 } 10791 // Regardless of writeSettings we need to ensure that this restriction 10792 // state propagation is persisted 10793 mSettings.writeAllUsersPackageRestrictionsLPr(); 10794 } 10795 // can downgrade to reader here 10796 if (writeSettings) { 10797 mSettings.writeLPr(); 10798 } 10799 } 10800 return true; 10801 } 10802 10803 private boolean deleteInstalledPackageLI(PackageSetting ps, 10804 boolean deleteCodeAndResources, int flags, 10805 int[] allUserHandles, boolean[] perUserInstalled, 10806 PackageRemovedInfo outInfo, boolean writeSettings) { 10807 if (outInfo != null) { 10808 outInfo.uid = ps.appId; 10809 } 10810 10811 // Delete package data from internal structures and also remove data if flag is set 10812 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 10813 10814 // Delete application code and resources 10815 if (deleteCodeAndResources && (outInfo != null)) { 10816 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 10817 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 10818 getAppDexInstructionSets(ps), isMultiArch(ps)); 10819 } 10820 return true; 10821 } 10822 10823 @Override 10824 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 10825 int userId) { 10826 mContext.enforceCallingOrSelfPermission( 10827 android.Manifest.permission.DELETE_PACKAGES, null); 10828 synchronized (mPackages) { 10829 PackageSetting ps = mSettings.mPackages.get(packageName); 10830 if (ps == null) { 10831 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 10832 return false; 10833 } 10834 if (!ps.getInstalled(userId)) { 10835 // Can't block uninstall for an app that is not installed or enabled. 10836 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 10837 return false; 10838 } 10839 ps.setBlockUninstall(blockUninstall, userId); 10840 mSettings.writePackageRestrictionsLPr(userId); 10841 } 10842 return true; 10843 } 10844 10845 @Override 10846 public boolean getBlockUninstallForUser(String packageName, int userId) { 10847 synchronized (mPackages) { 10848 PackageSetting ps = mSettings.mPackages.get(packageName); 10849 if (ps == null) { 10850 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 10851 return false; 10852 } 10853 return ps.getBlockUninstall(userId); 10854 } 10855 } 10856 10857 /* 10858 * This method handles package deletion in general 10859 */ 10860 private boolean deletePackageLI(String packageName, UserHandle user, 10861 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 10862 int flags, PackageRemovedInfo outInfo, 10863 boolean writeSettings) { 10864 if (packageName == null) { 10865 Slog.w(TAG, "Attempt to delete null packageName."); 10866 return false; 10867 } 10868 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 10869 PackageSetting ps; 10870 boolean dataOnly = false; 10871 int removeUser = -1; 10872 int appId = -1; 10873 synchronized (mPackages) { 10874 ps = mSettings.mPackages.get(packageName); 10875 if (ps == null) { 10876 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 10877 return false; 10878 } 10879 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 10880 && user.getIdentifier() != UserHandle.USER_ALL) { 10881 // The caller is asking that the package only be deleted for a single 10882 // user. To do this, we just mark its uninstalled state and delete 10883 // its data. If this is a system app, we only allow this to happen if 10884 // they have set the special DELETE_SYSTEM_APP which requests different 10885 // semantics than normal for uninstalling system apps. 10886 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 10887 ps.setUserState(user.getIdentifier(), 10888 COMPONENT_ENABLED_STATE_DEFAULT, 10889 false, //installed 10890 true, //stopped 10891 true, //notLaunched 10892 false, //blocked 10893 null, null, null, 10894 false // blockUninstall 10895 ); 10896 if (!isSystemApp(ps)) { 10897 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 10898 // Other user still have this package installed, so all 10899 // we need to do is clear this user's data and save that 10900 // it is uninstalled. 10901 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 10902 removeUser = user.getIdentifier(); 10903 appId = ps.appId; 10904 mSettings.writePackageRestrictionsLPr(removeUser); 10905 } else { 10906 // We need to set it back to 'installed' so the uninstall 10907 // broadcasts will be sent correctly. 10908 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 10909 ps.setInstalled(true, user.getIdentifier()); 10910 } 10911 } else { 10912 // This is a system app, so we assume that the 10913 // other users still have this package installed, so all 10914 // we need to do is clear this user's data and save that 10915 // it is uninstalled. 10916 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 10917 removeUser = user.getIdentifier(); 10918 appId = ps.appId; 10919 mSettings.writePackageRestrictionsLPr(removeUser); 10920 } 10921 } 10922 } 10923 10924 if (removeUser >= 0) { 10925 // From above, we determined that we are deleting this only 10926 // for a single user. Continue the work here. 10927 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 10928 if (outInfo != null) { 10929 outInfo.removedPackage = packageName; 10930 outInfo.removedAppId = appId; 10931 outInfo.removedUsers = new int[] {removeUser}; 10932 } 10933 mInstaller.clearUserData(packageName, removeUser); 10934 removeKeystoreDataIfNeeded(removeUser, appId); 10935 schedulePackageCleaning(packageName, removeUser, false); 10936 return true; 10937 } 10938 10939 if (dataOnly) { 10940 // Delete application data first 10941 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 10942 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 10943 return true; 10944 } 10945 10946 boolean ret = false; 10947 if (isSystemApp(ps)) { 10948 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 10949 // When an updated system application is deleted we delete the existing resources as well and 10950 // fall back to existing code in system partition 10951 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 10952 flags, outInfo, writeSettings); 10953 } else { 10954 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 10955 // Kill application pre-emptively especially for apps on sd. 10956 killApplication(packageName, ps.appId, "uninstall pkg"); 10957 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 10958 allUserHandles, perUserInstalled, 10959 outInfo, writeSettings); 10960 } 10961 10962 return ret; 10963 } 10964 10965 private final class ClearStorageConnection implements ServiceConnection { 10966 IMediaContainerService mContainerService; 10967 10968 @Override 10969 public void onServiceConnected(ComponentName name, IBinder service) { 10970 synchronized (this) { 10971 mContainerService = IMediaContainerService.Stub.asInterface(service); 10972 notifyAll(); 10973 } 10974 } 10975 10976 @Override 10977 public void onServiceDisconnected(ComponentName name) { 10978 } 10979 } 10980 10981 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 10982 final boolean mounted; 10983 if (Environment.isExternalStorageEmulated()) { 10984 mounted = true; 10985 } else { 10986 final String status = Environment.getExternalStorageState(); 10987 10988 mounted = status.equals(Environment.MEDIA_MOUNTED) 10989 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 10990 } 10991 10992 if (!mounted) { 10993 return; 10994 } 10995 10996 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 10997 int[] users; 10998 if (userId == UserHandle.USER_ALL) { 10999 users = sUserManager.getUserIds(); 11000 } else { 11001 users = new int[] { userId }; 11002 } 11003 final ClearStorageConnection conn = new ClearStorageConnection(); 11004 if (mContext.bindServiceAsUser( 11005 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 11006 try { 11007 for (int curUser : users) { 11008 long timeout = SystemClock.uptimeMillis() + 5000; 11009 synchronized (conn) { 11010 long now = SystemClock.uptimeMillis(); 11011 while (conn.mContainerService == null && now < timeout) { 11012 try { 11013 conn.wait(timeout - now); 11014 } catch (InterruptedException e) { 11015 } 11016 } 11017 } 11018 if (conn.mContainerService == null) { 11019 return; 11020 } 11021 11022 final UserEnvironment userEnv = new UserEnvironment(curUser); 11023 clearDirectory(conn.mContainerService, 11024 userEnv.buildExternalStorageAppCacheDirs(packageName)); 11025 if (allData) { 11026 clearDirectory(conn.mContainerService, 11027 userEnv.buildExternalStorageAppDataDirs(packageName)); 11028 clearDirectory(conn.mContainerService, 11029 userEnv.buildExternalStorageAppMediaDirs(packageName)); 11030 } 11031 } 11032 } finally { 11033 mContext.unbindService(conn); 11034 } 11035 } 11036 } 11037 11038 @Override 11039 public void clearApplicationUserData(final String packageName, 11040 final IPackageDataObserver observer, final int userId) { 11041 mContext.enforceCallingOrSelfPermission( 11042 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 11043 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data"); 11044 // Queue up an async operation since the package deletion may take a little while. 11045 mHandler.post(new Runnable() { 11046 public void run() { 11047 mHandler.removeCallbacks(this); 11048 final boolean succeeded; 11049 synchronized (mInstallLock) { 11050 succeeded = clearApplicationUserDataLI(packageName, userId); 11051 } 11052 clearExternalStorageDataSync(packageName, userId, true); 11053 if (succeeded) { 11054 // invoke DeviceStorageMonitor's update method to clear any notifications 11055 DeviceStorageMonitorInternal 11056 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 11057 if (dsm != null) { 11058 dsm.checkMemory(); 11059 } 11060 } 11061 if(observer != null) { 11062 try { 11063 observer.onRemoveCompleted(packageName, succeeded); 11064 } catch (RemoteException e) { 11065 Log.i(TAG, "Observer no longer exists."); 11066 } 11067 } //end if observer 11068 } //end run 11069 }); 11070 } 11071 11072 private boolean clearApplicationUserDataLI(String packageName, int userId) { 11073 if (packageName == null) { 11074 Slog.w(TAG, "Attempt to delete null packageName."); 11075 return false; 11076 } 11077 PackageParser.Package p; 11078 boolean dataOnly = false; 11079 final int appId; 11080 synchronized (mPackages) { 11081 p = mPackages.get(packageName); 11082 if (p == null) { 11083 dataOnly = true; 11084 PackageSetting ps = mSettings.mPackages.get(packageName); 11085 if ((ps == null) || (ps.pkg == null)) { 11086 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11087 return false; 11088 } 11089 p = ps.pkg; 11090 } 11091 if (!dataOnly) { 11092 // need to check this only for fully installed applications 11093 if (p == null) { 11094 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11095 return false; 11096 } 11097 final ApplicationInfo applicationInfo = p.applicationInfo; 11098 if (applicationInfo == null) { 11099 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11100 return false; 11101 } 11102 } 11103 if (p != null && p.applicationInfo != null) { 11104 appId = p.applicationInfo.uid; 11105 } else { 11106 appId = -1; 11107 } 11108 } 11109 int retCode = mInstaller.clearUserData(packageName, userId); 11110 if (retCode < 0) { 11111 Slog.w(TAG, "Couldn't remove cache files for package: " 11112 + packageName); 11113 return false; 11114 } 11115 removeKeystoreDataIfNeeded(userId, appId); 11116 return true; 11117 } 11118 11119 /** 11120 * Remove entries from the keystore daemon. Will only remove it if the 11121 * {@code appId} is valid. 11122 */ 11123 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 11124 if (appId < 0) { 11125 return; 11126 } 11127 11128 final KeyStore keyStore = KeyStore.getInstance(); 11129 if (keyStore != null) { 11130 if (userId == UserHandle.USER_ALL) { 11131 for (final int individual : sUserManager.getUserIds()) { 11132 keyStore.clearUid(UserHandle.getUid(individual, appId)); 11133 } 11134 } else { 11135 keyStore.clearUid(UserHandle.getUid(userId, appId)); 11136 } 11137 } else { 11138 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 11139 } 11140 } 11141 11142 @Override 11143 public void deleteApplicationCacheFiles(final String packageName, 11144 final IPackageDataObserver observer) { 11145 mContext.enforceCallingOrSelfPermission( 11146 android.Manifest.permission.DELETE_CACHE_FILES, null); 11147 // Queue up an async operation since the package deletion may take a little while. 11148 final int userId = UserHandle.getCallingUserId(); 11149 mHandler.post(new Runnable() { 11150 public void run() { 11151 mHandler.removeCallbacks(this); 11152 final boolean succeded; 11153 synchronized (mInstallLock) { 11154 succeded = deleteApplicationCacheFilesLI(packageName, userId); 11155 } 11156 clearExternalStorageDataSync(packageName, userId, false); 11157 if(observer != null) { 11158 try { 11159 observer.onRemoveCompleted(packageName, succeded); 11160 } catch (RemoteException e) { 11161 Log.i(TAG, "Observer no longer exists."); 11162 } 11163 } //end if observer 11164 } //end run 11165 }); 11166 } 11167 11168 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 11169 if (packageName == null) { 11170 Slog.w(TAG, "Attempt to delete null packageName."); 11171 return false; 11172 } 11173 PackageParser.Package p; 11174 synchronized (mPackages) { 11175 p = mPackages.get(packageName); 11176 } 11177 if (p == null) { 11178 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11179 return false; 11180 } 11181 final ApplicationInfo applicationInfo = p.applicationInfo; 11182 if (applicationInfo == null) { 11183 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11184 return false; 11185 } 11186 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 11187 if (retCode < 0) { 11188 Slog.w(TAG, "Couldn't remove cache files for package: " 11189 + packageName + " u" + userId); 11190 return false; 11191 } 11192 return true; 11193 } 11194 11195 @Override 11196 public void getPackageSizeInfo(final String packageName, int userHandle, 11197 final IPackageStatsObserver observer) { 11198 mContext.enforceCallingOrSelfPermission( 11199 android.Manifest.permission.GET_PACKAGE_SIZE, null); 11200 if (packageName == null) { 11201 throw new IllegalArgumentException("Attempt to get size of null packageName"); 11202 } 11203 11204 PackageStats stats = new PackageStats(packageName, userHandle); 11205 11206 /* 11207 * Queue up an async operation since the package measurement may take a 11208 * little while. 11209 */ 11210 Message msg = mHandler.obtainMessage(INIT_COPY); 11211 msg.obj = new MeasureParams(stats, observer); 11212 mHandler.sendMessage(msg); 11213 } 11214 11215 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 11216 PackageStats pStats) { 11217 if (packageName == null) { 11218 Slog.w(TAG, "Attempt to get size of null packageName."); 11219 return false; 11220 } 11221 PackageParser.Package p; 11222 boolean dataOnly = false; 11223 String libDirRoot = null; 11224 String asecPath = null; 11225 PackageSetting ps = null; 11226 synchronized (mPackages) { 11227 p = mPackages.get(packageName); 11228 ps = mSettings.mPackages.get(packageName); 11229 if(p == null) { 11230 dataOnly = true; 11231 if((ps == null) || (ps.pkg == null)) { 11232 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11233 return false; 11234 } 11235 p = ps.pkg; 11236 } 11237 if (ps != null) { 11238 libDirRoot = ps.legacyNativeLibraryPathString; 11239 } 11240 if (p != null && (isExternal(p) || isForwardLocked(p))) { 11241 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 11242 if (secureContainerId != null) { 11243 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 11244 } 11245 } 11246 } 11247 String publicSrcDir = null; 11248 if(!dataOnly) { 11249 final ApplicationInfo applicationInfo = p.applicationInfo; 11250 if (applicationInfo == null) { 11251 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11252 return false; 11253 } 11254 if (isForwardLocked(p)) { 11255 publicSrcDir = applicationInfo.getBaseResourcePath(); 11256 } 11257 } 11258 // TODO: extend to measure size of split APKs 11259 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 11260 // not just the first level. 11261 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 11262 // just the primary. 11263 int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot, 11264 publicSrcDir, asecPath, getAppDexInstructionSets(ps), 11265 pStats); 11266 if (res < 0) { 11267 return false; 11268 } 11269 11270 // Fix-up for forward-locked applications in ASEC containers. 11271 if (!isExternal(p)) { 11272 pStats.codeSize += pStats.externalCodeSize; 11273 pStats.externalCodeSize = 0L; 11274 } 11275 11276 return true; 11277 } 11278 11279 11280 @Override 11281 public void addPackageToPreferred(String packageName) { 11282 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 11283 } 11284 11285 @Override 11286 public void removePackageFromPreferred(String packageName) { 11287 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 11288 } 11289 11290 @Override 11291 public List<PackageInfo> getPreferredPackages(int flags) { 11292 return new ArrayList<PackageInfo>(); 11293 } 11294 11295 private int getUidTargetSdkVersionLockedLPr(int uid) { 11296 Object obj = mSettings.getUserIdLPr(uid); 11297 if (obj instanceof SharedUserSetting) { 11298 final SharedUserSetting sus = (SharedUserSetting) obj; 11299 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 11300 final Iterator<PackageSetting> it = sus.packages.iterator(); 11301 while (it.hasNext()) { 11302 final PackageSetting ps = it.next(); 11303 if (ps.pkg != null) { 11304 int v = ps.pkg.applicationInfo.targetSdkVersion; 11305 if (v < vers) vers = v; 11306 } 11307 } 11308 return vers; 11309 } else if (obj instanceof PackageSetting) { 11310 final PackageSetting ps = (PackageSetting) obj; 11311 if (ps.pkg != null) { 11312 return ps.pkg.applicationInfo.targetSdkVersion; 11313 } 11314 } 11315 return Build.VERSION_CODES.CUR_DEVELOPMENT; 11316 } 11317 11318 @Override 11319 public void addPreferredActivity(IntentFilter filter, int match, 11320 ComponentName[] set, ComponentName activity, int userId) { 11321 addPreferredActivityInternal(filter, match, set, activity, true, userId); 11322 } 11323 11324 private void addPreferredActivityInternal(IntentFilter filter, int match, 11325 ComponentName[] set, ComponentName activity, boolean always, int userId) { 11326 // writer 11327 int callingUid = Binder.getCallingUid(); 11328 enforceCrossUserPermission(callingUid, userId, true, "add preferred activity"); 11329 if (filter.countActions() == 0) { 11330 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11331 return; 11332 } 11333 synchronized (mPackages) { 11334 if (mContext.checkCallingOrSelfPermission( 11335 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11336 != PackageManager.PERMISSION_GRANTED) { 11337 if (getUidTargetSdkVersionLockedLPr(callingUid) 11338 < Build.VERSION_CODES.FROYO) { 11339 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 11340 + callingUid); 11341 return; 11342 } 11343 mContext.enforceCallingOrSelfPermission( 11344 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11345 } 11346 11347 Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :"); 11348 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11349 mSettings.editPreferredActivitiesLPw(userId).addFilter( 11350 new PreferredActivity(filter, match, set, activity, always)); 11351 mSettings.writePackageRestrictionsLPr(userId); 11352 } 11353 } 11354 11355 @Override 11356 public void replacePreferredActivity(IntentFilter filter, int match, 11357 ComponentName[] set, ComponentName activity) { 11358 if (filter.countActions() != 1) { 11359 throw new IllegalArgumentException( 11360 "replacePreferredActivity expects filter to have only 1 action."); 11361 } 11362 if (filter.countDataAuthorities() != 0 11363 || filter.countDataPaths() != 0 11364 || filter.countDataSchemes() > 1 11365 || filter.countDataTypes() != 0) { 11366 throw new IllegalArgumentException( 11367 "replacePreferredActivity expects filter to have no data authorities, " + 11368 "paths, or types; and at most one scheme."); 11369 } 11370 synchronized (mPackages) { 11371 if (mContext.checkCallingOrSelfPermission( 11372 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11373 != PackageManager.PERMISSION_GRANTED) { 11374 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11375 < Build.VERSION_CODES.FROYO) { 11376 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 11377 + Binder.getCallingUid()); 11378 return; 11379 } 11380 mContext.enforceCallingOrSelfPermission( 11381 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11382 } 11383 11384 final int callingUserId = UserHandle.getCallingUserId(); 11385 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId); 11386 if (pir != null) { 11387 Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0)); 11388 if (filter.countDataSchemes() == 1) { 11389 Uri.Builder builder = new Uri.Builder(); 11390 builder.scheme(filter.getDataScheme(0)); 11391 intent.setData(builder.build()); 11392 } 11393 List<PreferredActivity> matches = pir.queryIntent( 11394 intent, null, true, callingUserId); 11395 if (DEBUG_PREFERRED) { 11396 Slog.i(TAG, matches.size() + " preferred matches for " + intent); 11397 } 11398 for (int i = 0; i < matches.size(); i++) { 11399 PreferredActivity pa = matches.get(i); 11400 if (DEBUG_PREFERRED) { 11401 Slog.i(TAG, "Removing preferred activity " 11402 + pa.mPref.mComponent + ":"); 11403 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11404 } 11405 pir.removeFilter(pa); 11406 } 11407 } 11408 addPreferredActivityInternal(filter, match, set, activity, true, callingUserId); 11409 } 11410 } 11411 11412 @Override 11413 public void clearPackagePreferredActivities(String packageName) { 11414 final int uid = Binder.getCallingUid(); 11415 // writer 11416 synchronized (mPackages) { 11417 PackageParser.Package pkg = mPackages.get(packageName); 11418 if (pkg == null || pkg.applicationInfo.uid != uid) { 11419 if (mContext.checkCallingOrSelfPermission( 11420 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11421 != PackageManager.PERMISSION_GRANTED) { 11422 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11423 < Build.VERSION_CODES.FROYO) { 11424 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 11425 + Binder.getCallingUid()); 11426 return; 11427 } 11428 mContext.enforceCallingOrSelfPermission( 11429 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11430 } 11431 } 11432 11433 int user = UserHandle.getCallingUserId(); 11434 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 11435 mSettings.writePackageRestrictionsLPr(user); 11436 scheduleWriteSettingsLocked(); 11437 } 11438 } 11439 } 11440 11441 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 11442 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 11443 ArrayList<PreferredActivity> removed = null; 11444 boolean changed = false; 11445 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11446 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 11447 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11448 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 11449 continue; 11450 } 11451 Iterator<PreferredActivity> it = pir.filterIterator(); 11452 while (it.hasNext()) { 11453 PreferredActivity pa = it.next(); 11454 // Mark entry for removal only if it matches the package name 11455 // and the entry is of type "always". 11456 if (packageName == null || 11457 (pa.mPref.mComponent.getPackageName().equals(packageName) 11458 && pa.mPref.mAlways)) { 11459 if (removed == null) { 11460 removed = new ArrayList<PreferredActivity>(); 11461 } 11462 removed.add(pa); 11463 } 11464 } 11465 if (removed != null) { 11466 for (int j=0; j<removed.size(); j++) { 11467 PreferredActivity pa = removed.get(j); 11468 pir.removeFilter(pa); 11469 } 11470 changed = true; 11471 } 11472 } 11473 return changed; 11474 } 11475 11476 @Override 11477 public void resetPreferredActivities(int userId) { 11478 mContext.enforceCallingOrSelfPermission( 11479 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11480 // writer 11481 synchronized (mPackages) { 11482 int user = UserHandle.getCallingUserId(); 11483 clearPackagePreferredActivitiesLPw(null, user); 11484 mSettings.readDefaultPreferredAppsLPw(this, user); 11485 mSettings.writePackageRestrictionsLPr(user); 11486 scheduleWriteSettingsLocked(); 11487 } 11488 } 11489 11490 @Override 11491 public int getPreferredActivities(List<IntentFilter> outFilters, 11492 List<ComponentName> outActivities, String packageName) { 11493 11494 int num = 0; 11495 final int userId = UserHandle.getCallingUserId(); 11496 // reader 11497 synchronized (mPackages) { 11498 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11499 if (pir != null) { 11500 final Iterator<PreferredActivity> it = pir.filterIterator(); 11501 while (it.hasNext()) { 11502 final PreferredActivity pa = it.next(); 11503 if (packageName == null 11504 || (pa.mPref.mComponent.getPackageName().equals(packageName) 11505 && pa.mPref.mAlways)) { 11506 if (outFilters != null) { 11507 outFilters.add(new IntentFilter(pa)); 11508 } 11509 if (outActivities != null) { 11510 outActivities.add(pa.mPref.mComponent); 11511 } 11512 } 11513 } 11514 } 11515 } 11516 11517 return num; 11518 } 11519 11520 @Override 11521 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 11522 int userId) { 11523 int callingUid = Binder.getCallingUid(); 11524 if (callingUid != Process.SYSTEM_UID) { 11525 throw new SecurityException( 11526 "addPersistentPreferredActivity can only be run by the system"); 11527 } 11528 if (filter.countActions() == 0) { 11529 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11530 return; 11531 } 11532 synchronized (mPackages) { 11533 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 11534 " :"); 11535 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11536 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 11537 new PersistentPreferredActivity(filter, activity)); 11538 mSettings.writePackageRestrictionsLPr(userId); 11539 } 11540 } 11541 11542 @Override 11543 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 11544 int callingUid = Binder.getCallingUid(); 11545 if (callingUid != Process.SYSTEM_UID) { 11546 throw new SecurityException( 11547 "clearPackagePersistentPreferredActivities can only be run by the system"); 11548 } 11549 ArrayList<PersistentPreferredActivity> removed = null; 11550 boolean changed = false; 11551 synchronized (mPackages) { 11552 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 11553 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 11554 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 11555 .valueAt(i); 11556 if (userId != thisUserId) { 11557 continue; 11558 } 11559 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 11560 while (it.hasNext()) { 11561 PersistentPreferredActivity ppa = it.next(); 11562 // Mark entry for removal only if it matches the package name. 11563 if (ppa.mComponent.getPackageName().equals(packageName)) { 11564 if (removed == null) { 11565 removed = new ArrayList<PersistentPreferredActivity>(); 11566 } 11567 removed.add(ppa); 11568 } 11569 } 11570 if (removed != null) { 11571 for (int j=0; j<removed.size(); j++) { 11572 PersistentPreferredActivity ppa = removed.get(j); 11573 ppir.removeFilter(ppa); 11574 } 11575 changed = true; 11576 } 11577 } 11578 11579 if (changed) { 11580 mSettings.writePackageRestrictionsLPr(userId); 11581 } 11582 } 11583 } 11584 11585 @Override 11586 public void addCrossProfileIntentFilter(IntentFilter intentFilter, int sourceUserId, 11587 int targetUserId, int flags) { 11588 mContext.enforceCallingOrSelfPermission( 11589 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11590 if (intentFilter.countActions() == 0) { 11591 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 11592 return; 11593 } 11594 synchronized (mPackages) { 11595 CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter, 11596 targetUserId, flags); 11597 mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter); 11598 mSettings.writePackageRestrictionsLPr(sourceUserId); 11599 } 11600 } 11601 11602 public void addCrossProfileIntentsForPackage(String packageName, 11603 int sourceUserId, int targetUserId) { 11604 mContext.enforceCallingOrSelfPermission( 11605 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11606 mSettings.addCrossProfilePackage(packageName, sourceUserId, targetUserId); 11607 mSettings.writePackageRestrictionsLPr(sourceUserId); 11608 } 11609 11610 public void removeCrossProfileIntentsForPackage(String packageName, 11611 int sourceUserId, int targetUserId) { 11612 mContext.enforceCallingOrSelfPermission( 11613 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11614 mSettings.removeCrossProfilePackage(packageName, sourceUserId, targetUserId); 11615 mSettings.writePackageRestrictionsLPr(sourceUserId); 11616 } 11617 11618 @Override 11619 public void clearCrossProfileIntentFilters(int sourceUserId) { 11620 mContext.enforceCallingOrSelfPermission( 11621 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11622 synchronized (mPackages) { 11623 CrossProfileIntentResolver resolver = 11624 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11625 HashSet<CrossProfileIntentFilter> set = 11626 new HashSet<CrossProfileIntentFilter>(resolver.filterSet()); 11627 for (CrossProfileIntentFilter filter : set) { 11628 if ((filter.getFlags() & PackageManager.SET_BY_PROFILE_OWNER) != 0) { 11629 resolver.removeFilter(filter); 11630 } 11631 } 11632 mSettings.writePackageRestrictionsLPr(sourceUserId); 11633 } 11634 } 11635 11636 @Override 11637 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 11638 Intent intent = new Intent(Intent.ACTION_MAIN); 11639 intent.addCategory(Intent.CATEGORY_HOME); 11640 11641 final int callingUserId = UserHandle.getCallingUserId(); 11642 List<ResolveInfo> list = queryIntentActivities(intent, null, 11643 PackageManager.GET_META_DATA, callingUserId); 11644 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 11645 true, false, false, callingUserId); 11646 11647 allHomeCandidates.clear(); 11648 if (list != null) { 11649 for (ResolveInfo ri : list) { 11650 allHomeCandidates.add(ri); 11651 } 11652 } 11653 return (preferred == null || preferred.activityInfo == null) 11654 ? null 11655 : new ComponentName(preferred.activityInfo.packageName, 11656 preferred.activityInfo.name); 11657 } 11658 11659 @Override 11660 public void setApplicationEnabledSetting(String appPackageName, 11661 int newState, int flags, int userId, String callingPackage) { 11662 if (!sUserManager.exists(userId)) return; 11663 if (callingPackage == null) { 11664 callingPackage = Integer.toString(Binder.getCallingUid()); 11665 } 11666 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 11667 } 11668 11669 @Override 11670 public void setComponentEnabledSetting(ComponentName componentName, 11671 int newState, int flags, int userId) { 11672 if (!sUserManager.exists(userId)) return; 11673 setEnabledSetting(componentName.getPackageName(), 11674 componentName.getClassName(), newState, flags, userId, null); 11675 } 11676 11677 private void setEnabledSetting(final String packageName, String className, int newState, 11678 final int flags, int userId, String callingPackage) { 11679 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 11680 || newState == COMPONENT_ENABLED_STATE_ENABLED 11681 || newState == COMPONENT_ENABLED_STATE_DISABLED 11682 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 11683 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 11684 throw new IllegalArgumentException("Invalid new component state: " 11685 + newState); 11686 } 11687 PackageSetting pkgSetting; 11688 final int uid = Binder.getCallingUid(); 11689 final int permission = mContext.checkCallingOrSelfPermission( 11690 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11691 enforceCrossUserPermission(uid, userId, false, "set enabled"); 11692 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11693 boolean sendNow = false; 11694 boolean isApp = (className == null); 11695 String componentName = isApp ? packageName : className; 11696 int packageUid = -1; 11697 ArrayList<String> components; 11698 11699 // writer 11700 synchronized (mPackages) { 11701 pkgSetting = mSettings.mPackages.get(packageName); 11702 if (pkgSetting == null) { 11703 if (className == null) { 11704 throw new IllegalArgumentException( 11705 "Unknown package: " + packageName); 11706 } 11707 throw new IllegalArgumentException( 11708 "Unknown component: " + packageName 11709 + "/" + className); 11710 } 11711 // Allow root and verify that userId is not being specified by a different user 11712 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 11713 throw new SecurityException( 11714 "Permission Denial: attempt to change component state from pid=" 11715 + Binder.getCallingPid() 11716 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 11717 } 11718 if (className == null) { 11719 // We're dealing with an application/package level state change 11720 if (pkgSetting.getEnabled(userId) == newState) { 11721 // Nothing to do 11722 return; 11723 } 11724 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 11725 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 11726 // Don't care about who enables an app. 11727 callingPackage = null; 11728 } 11729 pkgSetting.setEnabled(newState, userId, callingPackage); 11730 // pkgSetting.pkg.mSetEnabled = newState; 11731 } else { 11732 // We're dealing with a component level state change 11733 // First, verify that this is a valid class name. 11734 PackageParser.Package pkg = pkgSetting.pkg; 11735 if (pkg == null || !pkg.hasComponentClassName(className)) { 11736 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 11737 throw new IllegalArgumentException("Component class " + className 11738 + " does not exist in " + packageName); 11739 } else { 11740 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 11741 + className + " does not exist in " + packageName); 11742 } 11743 } 11744 switch (newState) { 11745 case COMPONENT_ENABLED_STATE_ENABLED: 11746 if (!pkgSetting.enableComponentLPw(className, userId)) { 11747 return; 11748 } 11749 break; 11750 case COMPONENT_ENABLED_STATE_DISABLED: 11751 if (!pkgSetting.disableComponentLPw(className, userId)) { 11752 return; 11753 } 11754 break; 11755 case COMPONENT_ENABLED_STATE_DEFAULT: 11756 if (!pkgSetting.restoreComponentLPw(className, userId)) { 11757 return; 11758 } 11759 break; 11760 default: 11761 Slog.e(TAG, "Invalid new component state: " + newState); 11762 return; 11763 } 11764 } 11765 mSettings.writePackageRestrictionsLPr(userId); 11766 components = mPendingBroadcasts.get(userId, packageName); 11767 final boolean newPackage = components == null; 11768 if (newPackage) { 11769 components = new ArrayList<String>(); 11770 } 11771 if (!components.contains(componentName)) { 11772 components.add(componentName); 11773 } 11774 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 11775 sendNow = true; 11776 // Purge entry from pending broadcast list if another one exists already 11777 // since we are sending one right away. 11778 mPendingBroadcasts.remove(userId, packageName); 11779 } else { 11780 if (newPackage) { 11781 mPendingBroadcasts.put(userId, packageName, components); 11782 } 11783 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 11784 // Schedule a message 11785 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 11786 } 11787 } 11788 } 11789 11790 long callingId = Binder.clearCallingIdentity(); 11791 try { 11792 if (sendNow) { 11793 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 11794 sendPackageChangedBroadcast(packageName, 11795 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 11796 } 11797 } finally { 11798 Binder.restoreCallingIdentity(callingId); 11799 } 11800 } 11801 11802 private void sendPackageChangedBroadcast(String packageName, 11803 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 11804 if (DEBUG_INSTALL) 11805 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 11806 + componentNames); 11807 Bundle extras = new Bundle(4); 11808 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 11809 String nameList[] = new String[componentNames.size()]; 11810 componentNames.toArray(nameList); 11811 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 11812 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 11813 extras.putInt(Intent.EXTRA_UID, packageUid); 11814 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 11815 new int[] {UserHandle.getUserId(packageUid)}); 11816 } 11817 11818 @Override 11819 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 11820 if (!sUserManager.exists(userId)) return; 11821 final int uid = Binder.getCallingUid(); 11822 final int permission = mContext.checkCallingOrSelfPermission( 11823 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11824 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11825 enforceCrossUserPermission(uid, userId, true, "stop package"); 11826 // writer 11827 synchronized (mPackages) { 11828 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 11829 uid, userId)) { 11830 scheduleWritePackageRestrictionsLocked(userId); 11831 } 11832 } 11833 } 11834 11835 @Override 11836 public String getInstallerPackageName(String packageName) { 11837 // reader 11838 synchronized (mPackages) { 11839 return mSettings.getInstallerPackageNameLPr(packageName); 11840 } 11841 } 11842 11843 @Override 11844 public int getApplicationEnabledSetting(String packageName, int userId) { 11845 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11846 int uid = Binder.getCallingUid(); 11847 enforceCrossUserPermission(uid, userId, false, "get enabled"); 11848 // reader 11849 synchronized (mPackages) { 11850 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 11851 } 11852 } 11853 11854 @Override 11855 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 11856 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11857 int uid = Binder.getCallingUid(); 11858 enforceCrossUserPermission(uid, userId, false, "get component enabled"); 11859 // reader 11860 synchronized (mPackages) { 11861 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 11862 } 11863 } 11864 11865 @Override 11866 public void enterSafeMode() { 11867 enforceSystemOrRoot("Only the system can request entering safe mode"); 11868 11869 if (!mSystemReady) { 11870 mSafeMode = true; 11871 } 11872 } 11873 11874 @Override 11875 public void systemReady() { 11876 mSystemReady = true; 11877 11878 // Read the compatibilty setting when the system is ready. 11879 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 11880 mContext.getContentResolver(), 11881 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 11882 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 11883 if (DEBUG_SETTINGS) { 11884 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 11885 } 11886 11887 synchronized (mPackages) { 11888 // Verify that all of the preferred activity components actually 11889 // exist. It is possible for applications to be updated and at 11890 // that point remove a previously declared activity component that 11891 // had been set as a preferred activity. We try to clean this up 11892 // the next time we encounter that preferred activity, but it is 11893 // possible for the user flow to never be able to return to that 11894 // situation so here we do a sanity check to make sure we haven't 11895 // left any junk around. 11896 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 11897 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11898 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11899 removed.clear(); 11900 for (PreferredActivity pa : pir.filterSet()) { 11901 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 11902 removed.add(pa); 11903 } 11904 } 11905 if (removed.size() > 0) { 11906 for (int r=0; r<removed.size(); r++) { 11907 PreferredActivity pa = removed.get(r); 11908 Slog.w(TAG, "Removing dangling preferred activity: " 11909 + pa.mPref.mComponent); 11910 pir.removeFilter(pa); 11911 } 11912 mSettings.writePackageRestrictionsLPr( 11913 mSettings.mPreferredActivities.keyAt(i)); 11914 } 11915 } 11916 } 11917 sUserManager.systemReady(); 11918 } 11919 11920 @Override 11921 public boolean isSafeMode() { 11922 return mSafeMode; 11923 } 11924 11925 @Override 11926 public boolean hasSystemUidErrors() { 11927 return mHasSystemUidErrors; 11928 } 11929 11930 static String arrayToString(int[] array) { 11931 StringBuffer buf = new StringBuffer(128); 11932 buf.append('['); 11933 if (array != null) { 11934 for (int i=0; i<array.length; i++) { 11935 if (i > 0) buf.append(", "); 11936 buf.append(array[i]); 11937 } 11938 } 11939 buf.append(']'); 11940 return buf.toString(); 11941 } 11942 11943 static class DumpState { 11944 public static final int DUMP_LIBS = 1 << 0; 11945 11946 public static final int DUMP_FEATURES = 1 << 1; 11947 11948 public static final int DUMP_RESOLVERS = 1 << 2; 11949 11950 public static final int DUMP_PERMISSIONS = 1 << 3; 11951 11952 public static final int DUMP_PACKAGES = 1 << 4; 11953 11954 public static final int DUMP_SHARED_USERS = 1 << 5; 11955 11956 public static final int DUMP_MESSAGES = 1 << 6; 11957 11958 public static final int DUMP_PROVIDERS = 1 << 7; 11959 11960 public static final int DUMP_VERIFIERS = 1 << 8; 11961 11962 public static final int DUMP_PREFERRED = 1 << 9; 11963 11964 public static final int DUMP_PREFERRED_XML = 1 << 10; 11965 11966 public static final int DUMP_KEYSETS = 1 << 11; 11967 11968 public static final int DUMP_VERSION = 1 << 12; 11969 11970 public static final int OPTION_SHOW_FILTERS = 1 << 0; 11971 11972 private int mTypes; 11973 11974 private int mOptions; 11975 11976 private boolean mTitlePrinted; 11977 11978 private SharedUserSetting mSharedUser; 11979 11980 public boolean isDumping(int type) { 11981 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 11982 return true; 11983 } 11984 11985 return (mTypes & type) != 0; 11986 } 11987 11988 public void setDump(int type) { 11989 mTypes |= type; 11990 } 11991 11992 public boolean isOptionEnabled(int option) { 11993 return (mOptions & option) != 0; 11994 } 11995 11996 public void setOptionEnabled(int option) { 11997 mOptions |= option; 11998 } 11999 12000 public boolean onTitlePrinted() { 12001 final boolean printed = mTitlePrinted; 12002 mTitlePrinted = true; 12003 return printed; 12004 } 12005 12006 public boolean getTitlePrinted() { 12007 return mTitlePrinted; 12008 } 12009 12010 public void setTitlePrinted(boolean enabled) { 12011 mTitlePrinted = enabled; 12012 } 12013 12014 public SharedUserSetting getSharedUser() { 12015 return mSharedUser; 12016 } 12017 12018 public void setSharedUser(SharedUserSetting user) { 12019 mSharedUser = user; 12020 } 12021 } 12022 12023 @Override 12024 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 12025 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 12026 != PackageManager.PERMISSION_GRANTED) { 12027 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 12028 + Binder.getCallingPid() 12029 + ", uid=" + Binder.getCallingUid() 12030 + " without permission " 12031 + android.Manifest.permission.DUMP); 12032 return; 12033 } 12034 12035 DumpState dumpState = new DumpState(); 12036 boolean fullPreferred = false; 12037 boolean checkin = false; 12038 12039 String packageName = null; 12040 12041 int opti = 0; 12042 while (opti < args.length) { 12043 String opt = args[opti]; 12044 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 12045 break; 12046 } 12047 opti++; 12048 if ("-a".equals(opt)) { 12049 // Right now we only know how to print all. 12050 } else if ("-h".equals(opt)) { 12051 pw.println("Package manager dump options:"); 12052 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 12053 pw.println(" --checkin: dump for a checkin"); 12054 pw.println(" -f: print details of intent filters"); 12055 pw.println(" -h: print this help"); 12056 pw.println(" cmd may be one of:"); 12057 pw.println(" l[ibraries]: list known shared libraries"); 12058 pw.println(" f[ibraries]: list device features"); 12059 pw.println(" k[eysets]: print known keysets"); 12060 pw.println(" r[esolvers]: dump intent resolvers"); 12061 pw.println(" perm[issions]: dump permissions"); 12062 pw.println(" pref[erred]: print preferred package settings"); 12063 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 12064 pw.println(" prov[iders]: dump content providers"); 12065 pw.println(" p[ackages]: dump installed packages"); 12066 pw.println(" s[hared-users]: dump shared user IDs"); 12067 pw.println(" m[essages]: print collected runtime messages"); 12068 pw.println(" v[erifiers]: print package verifier info"); 12069 pw.println(" version: print database version info"); 12070 pw.println(" write: write current settings now"); 12071 pw.println(" <package.name>: info about given package"); 12072 return; 12073 } else if ("--checkin".equals(opt)) { 12074 checkin = true; 12075 } else if ("-f".equals(opt)) { 12076 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12077 } else { 12078 pw.println("Unknown argument: " + opt + "; use -h for help"); 12079 } 12080 } 12081 12082 // Is the caller requesting to dump a particular piece of data? 12083 if (opti < args.length) { 12084 String cmd = args[opti]; 12085 opti++; 12086 // Is this a package name? 12087 if ("android".equals(cmd) || cmd.contains(".")) { 12088 packageName = cmd; 12089 // When dumping a single package, we always dump all of its 12090 // filter information since the amount of data will be reasonable. 12091 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12092 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 12093 dumpState.setDump(DumpState.DUMP_LIBS); 12094 } else if ("f".equals(cmd) || "features".equals(cmd)) { 12095 dumpState.setDump(DumpState.DUMP_FEATURES); 12096 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 12097 dumpState.setDump(DumpState.DUMP_RESOLVERS); 12098 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 12099 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 12100 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 12101 dumpState.setDump(DumpState.DUMP_PREFERRED); 12102 } else if ("preferred-xml".equals(cmd)) { 12103 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 12104 if (opti < args.length && "--full".equals(args[opti])) { 12105 fullPreferred = true; 12106 opti++; 12107 } 12108 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 12109 dumpState.setDump(DumpState.DUMP_PACKAGES); 12110 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 12111 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 12112 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 12113 dumpState.setDump(DumpState.DUMP_PROVIDERS); 12114 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 12115 dumpState.setDump(DumpState.DUMP_MESSAGES); 12116 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 12117 dumpState.setDump(DumpState.DUMP_VERIFIERS); 12118 } else if ("version".equals(cmd)) { 12119 dumpState.setDump(DumpState.DUMP_VERSION); 12120 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 12121 dumpState.setDump(DumpState.DUMP_KEYSETS); 12122 } else if ("write".equals(cmd)) { 12123 synchronized (mPackages) { 12124 mSettings.writeLPr(); 12125 pw.println("Settings written."); 12126 return; 12127 } 12128 } 12129 } 12130 12131 if (checkin) { 12132 pw.println("vers,1"); 12133 } 12134 12135 // reader 12136 synchronized (mPackages) { 12137 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 12138 if (!checkin) { 12139 if (dumpState.onTitlePrinted()) 12140 pw.println(); 12141 pw.println("Database versions:"); 12142 pw.print(" SDK Version:"); 12143 pw.print(" internal="); 12144 pw.print(mSettings.mInternalSdkPlatform); 12145 pw.print(" external="); 12146 pw.println(mSettings.mExternalSdkPlatform); 12147 pw.print(" DB Version:"); 12148 pw.print(" internal="); 12149 pw.print(mSettings.mInternalDatabaseVersion); 12150 pw.print(" external="); 12151 pw.println(mSettings.mExternalDatabaseVersion); 12152 } 12153 } 12154 12155 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 12156 if (!checkin) { 12157 if (dumpState.onTitlePrinted()) 12158 pw.println(); 12159 pw.println("Verifiers:"); 12160 pw.print(" Required: "); 12161 pw.print(mRequiredVerifierPackage); 12162 pw.print(" (uid="); 12163 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 12164 pw.println(")"); 12165 } else if (mRequiredVerifierPackage != null) { 12166 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 12167 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 12168 } 12169 } 12170 12171 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 12172 boolean printedHeader = false; 12173 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 12174 while (it.hasNext()) { 12175 String name = it.next(); 12176 SharedLibraryEntry ent = mSharedLibraries.get(name); 12177 if (!checkin) { 12178 if (!printedHeader) { 12179 if (dumpState.onTitlePrinted()) 12180 pw.println(); 12181 pw.println("Libraries:"); 12182 printedHeader = true; 12183 } 12184 pw.print(" "); 12185 } else { 12186 pw.print("lib,"); 12187 } 12188 pw.print(name); 12189 if (!checkin) { 12190 pw.print(" -> "); 12191 } 12192 if (ent.path != null) { 12193 if (!checkin) { 12194 pw.print("(jar) "); 12195 pw.print(ent.path); 12196 } else { 12197 pw.print(",jar,"); 12198 pw.print(ent.path); 12199 } 12200 } else { 12201 if (!checkin) { 12202 pw.print("(apk) "); 12203 pw.print(ent.apk); 12204 } else { 12205 pw.print(",apk,"); 12206 pw.print(ent.apk); 12207 } 12208 } 12209 pw.println(); 12210 } 12211 } 12212 12213 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 12214 if (dumpState.onTitlePrinted()) 12215 pw.println(); 12216 if (!checkin) { 12217 pw.println("Features:"); 12218 } 12219 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 12220 while (it.hasNext()) { 12221 String name = it.next(); 12222 if (!checkin) { 12223 pw.print(" "); 12224 } else { 12225 pw.print("feat,"); 12226 } 12227 pw.println(name); 12228 } 12229 } 12230 12231 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 12232 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 12233 : "Activity Resolver Table:", " ", packageName, 12234 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12235 dumpState.setTitlePrinted(true); 12236 } 12237 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 12238 : "Receiver Resolver Table:", " ", packageName, 12239 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12240 dumpState.setTitlePrinted(true); 12241 } 12242 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 12243 : "Service Resolver Table:", " ", packageName, 12244 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12245 dumpState.setTitlePrinted(true); 12246 } 12247 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 12248 : "Provider Resolver Table:", " ", packageName, 12249 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12250 dumpState.setTitlePrinted(true); 12251 } 12252 } 12253 12254 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 12255 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12256 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12257 int user = mSettings.mPreferredActivities.keyAt(i); 12258 if (pir.dump(pw, 12259 dumpState.getTitlePrinted() 12260 ? "\nPreferred Activities User " + user + ":" 12261 : "Preferred Activities User " + user + ":", " ", 12262 packageName, true)) { 12263 dumpState.setTitlePrinted(true); 12264 } 12265 } 12266 } 12267 12268 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 12269 pw.flush(); 12270 FileOutputStream fout = new FileOutputStream(fd); 12271 BufferedOutputStream str = new BufferedOutputStream(fout); 12272 XmlSerializer serializer = new FastXmlSerializer(); 12273 try { 12274 serializer.setOutput(str, "utf-8"); 12275 serializer.startDocument(null, true); 12276 serializer.setFeature( 12277 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 12278 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 12279 serializer.endDocument(); 12280 serializer.flush(); 12281 } catch (IllegalArgumentException e) { 12282 pw.println("Failed writing: " + e); 12283 } catch (IllegalStateException e) { 12284 pw.println("Failed writing: " + e); 12285 } catch (IOException e) { 12286 pw.println("Failed writing: " + e); 12287 } 12288 } 12289 12290 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 12291 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 12292 } 12293 12294 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 12295 boolean printedSomething = false; 12296 for (PackageParser.Provider p : mProviders.mProviders.values()) { 12297 if (packageName != null && !packageName.equals(p.info.packageName)) { 12298 continue; 12299 } 12300 if (!printedSomething) { 12301 if (dumpState.onTitlePrinted()) 12302 pw.println(); 12303 pw.println("Registered ContentProviders:"); 12304 printedSomething = true; 12305 } 12306 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 12307 pw.print(" "); pw.println(p.toString()); 12308 } 12309 printedSomething = false; 12310 for (Map.Entry<String, PackageParser.Provider> entry : 12311 mProvidersByAuthority.entrySet()) { 12312 PackageParser.Provider p = entry.getValue(); 12313 if (packageName != null && !packageName.equals(p.info.packageName)) { 12314 continue; 12315 } 12316 if (!printedSomething) { 12317 if (dumpState.onTitlePrinted()) 12318 pw.println(); 12319 pw.println("ContentProvider Authorities:"); 12320 printedSomething = true; 12321 } 12322 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 12323 pw.print(" "); pw.println(p.toString()); 12324 if (p.info != null && p.info.applicationInfo != null) { 12325 final String appInfo = p.info.applicationInfo.toString(); 12326 pw.print(" applicationInfo="); pw.println(appInfo); 12327 } 12328 } 12329 } 12330 12331 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 12332 mSettings.mKeySetManagerService.dump(pw, packageName, dumpState); 12333 } 12334 12335 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 12336 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 12337 } 12338 12339 if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 12340 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState); 12341 } 12342 12343 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 12344 if (dumpState.onTitlePrinted()) 12345 pw.println(); 12346 mSettings.dumpReadMessagesLPr(pw, dumpState); 12347 12348 pw.println(); 12349 pw.println("Package warning messages:"); 12350 final File fname = getSettingsProblemFile(); 12351 FileInputStream in = null; 12352 try { 12353 in = new FileInputStream(fname); 12354 final int avail = in.available(); 12355 final byte[] data = new byte[avail]; 12356 in.read(data); 12357 pw.print(new String(data)); 12358 } catch (FileNotFoundException e) { 12359 } catch (IOException e) { 12360 } finally { 12361 if (in != null) { 12362 try { 12363 in.close(); 12364 } catch (IOException e) { 12365 } 12366 } 12367 } 12368 } 12369 } 12370 } 12371 12372 // ------- apps on sdcard specific code ------- 12373 static final boolean DEBUG_SD_INSTALL = false; 12374 12375 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 12376 12377 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 12378 12379 private boolean mMediaMounted = false; 12380 12381 private String getEncryptKey() { 12382 try { 12383 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 12384 SD_ENCRYPTION_KEYSTORE_NAME); 12385 if (sdEncKey == null) { 12386 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 12387 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 12388 if (sdEncKey == null) { 12389 Slog.e(TAG, "Failed to create encryption keys"); 12390 return null; 12391 } 12392 } 12393 return sdEncKey; 12394 } catch (NoSuchAlgorithmException nsae) { 12395 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 12396 return null; 12397 } catch (IOException ioe) { 12398 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 12399 return null; 12400 } 12401 12402 } 12403 12404 /* package */static String getTempContainerId() { 12405 int tmpIdx = 1; 12406 String list[] = PackageHelper.getSecureContainerList(); 12407 if (list != null) { 12408 for (final String name : list) { 12409 // Ignore null and non-temporary container entries 12410 if (name == null || !name.startsWith(mTempContainerPrefix)) { 12411 continue; 12412 } 12413 12414 String subStr = name.substring(mTempContainerPrefix.length()); 12415 try { 12416 int cid = Integer.parseInt(subStr); 12417 if (cid >= tmpIdx) { 12418 tmpIdx = cid + 1; 12419 } 12420 } catch (NumberFormatException e) { 12421 } 12422 } 12423 } 12424 return mTempContainerPrefix + tmpIdx; 12425 } 12426 12427 /* 12428 * Update media status on PackageManager. 12429 */ 12430 @Override 12431 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 12432 int callingUid = Binder.getCallingUid(); 12433 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 12434 throw new SecurityException("Media status can only be updated by the system"); 12435 } 12436 // reader; this apparently protects mMediaMounted, but should probably 12437 // be a different lock in that case. 12438 synchronized (mPackages) { 12439 Log.i(TAG, "Updating external media status from " 12440 + (mMediaMounted ? "mounted" : "unmounted") + " to " 12441 + (mediaStatus ? "mounted" : "unmounted")); 12442 if (DEBUG_SD_INSTALL) 12443 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 12444 + ", mMediaMounted=" + mMediaMounted); 12445 if (mediaStatus == mMediaMounted) { 12446 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 12447 : 0, -1); 12448 mHandler.sendMessage(msg); 12449 return; 12450 } 12451 mMediaMounted = mediaStatus; 12452 } 12453 // Queue up an async operation since the package installation may take a 12454 // little while. 12455 mHandler.post(new Runnable() { 12456 public void run() { 12457 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 12458 } 12459 }); 12460 } 12461 12462 /** 12463 * Called by MountService when the initial ASECs to scan are available. 12464 * Should block until all the ASEC containers are finished being scanned. 12465 */ 12466 public void scanAvailableAsecs() { 12467 updateExternalMediaStatusInner(true, false, false); 12468 if (mShouldRestoreconData) { 12469 SELinuxMMAC.setRestoreconDone(); 12470 mShouldRestoreconData = false; 12471 } 12472 } 12473 12474 /* 12475 * Collect information of applications on external media, map them against 12476 * existing containers and update information based on current mount status. 12477 * Please note that we always have to report status if reportStatus has been 12478 * set to true especially when unloading packages. 12479 */ 12480 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 12481 boolean externalStorage) { 12482 // Collection of uids 12483 int uidArr[] = null; 12484 // Collection of stale containers 12485 HashSet<String> removeCids = new HashSet<String>(); 12486 // Collection of packages on external media with valid containers. 12487 HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>(); 12488 // Get list of secure containers. 12489 final String list[] = PackageHelper.getSecureContainerList(); 12490 if (list == null || list.length == 0) { 12491 Log.i(TAG, "No secure containers on sdcard"); 12492 } else { 12493 // Process list of secure containers and categorize them 12494 // as active or stale based on their package internal state. 12495 int uidList[] = new int[list.length]; 12496 int num = 0; 12497 // reader 12498 synchronized (mPackages) { 12499 for (String cid : list) { 12500 if (DEBUG_SD_INSTALL) 12501 Log.i(TAG, "Processing container " + cid); 12502 String pkgName = getAsecPackageName(cid); 12503 if (pkgName == null) { 12504 if (DEBUG_SD_INSTALL) 12505 Log.i(TAG, "Container : " + cid + " stale"); 12506 removeCids.add(cid); 12507 continue; 12508 } 12509 if (DEBUG_SD_INSTALL) 12510 Log.i(TAG, "Looking for pkg : " + pkgName); 12511 12512 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12513 if (ps == null) { 12514 Log.i(TAG, "Deleting container with no matching settings " + cid); 12515 removeCids.add(cid); 12516 continue; 12517 } 12518 12519 /* 12520 * Skip packages that are not external if we're unmounting 12521 * external storage. 12522 */ 12523 if (externalStorage && !isMounted && !isExternal(ps)) { 12524 continue; 12525 } 12526 12527 final AsecInstallArgs args = new AsecInstallArgs(cid, 12528 getAppDexInstructionSets(ps), isForwardLocked(ps), isMultiArch(ps)); 12529 // The package status is changed only if the code path 12530 // matches between settings and the container id. 12531 if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) { 12532 if (DEBUG_SD_INSTALL) { 12533 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 12534 + " at code path: " + ps.codePathString); 12535 } 12536 12537 // We do have a valid package installed on sdcard 12538 processCids.put(args, ps.codePathString); 12539 final int uid = ps.appId; 12540 if (uid != -1) { 12541 uidList[num++] = uid; 12542 } 12543 } else { 12544 Log.i(TAG, "Deleting stale container for " + cid); 12545 removeCids.add(cid); 12546 } 12547 } 12548 } 12549 12550 if (num > 0) { 12551 // Sort uid list 12552 Arrays.sort(uidList, 0, num); 12553 // Throw away duplicates 12554 uidArr = new int[num]; 12555 uidArr[0] = uidList[0]; 12556 int di = 0; 12557 for (int i = 1; i < num; i++) { 12558 if (uidList[i - 1] != uidList[i]) { 12559 uidArr[di++] = uidList[i]; 12560 } 12561 } 12562 } 12563 } 12564 // Process packages with valid entries. 12565 if (isMounted) { 12566 if (DEBUG_SD_INSTALL) 12567 Log.i(TAG, "Loading packages"); 12568 loadMediaPackages(processCids, uidArr, removeCids); 12569 startCleaningPackages(); 12570 } else { 12571 if (DEBUG_SD_INSTALL) 12572 Log.i(TAG, "Unloading packages"); 12573 unloadMediaPackages(processCids, uidArr, reportStatus); 12574 } 12575 } 12576 12577 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 12578 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 12579 int size = pkgList.size(); 12580 if (size > 0) { 12581 // Send broadcasts here 12582 Bundle extras = new Bundle(); 12583 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 12584 .toArray(new String[size])); 12585 if (uidArr != null) { 12586 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 12587 } 12588 if (replacing) { 12589 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 12590 } 12591 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 12592 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 12593 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 12594 } 12595 } 12596 12597 /* 12598 * Look at potentially valid container ids from processCids If package 12599 * information doesn't match the one on record or package scanning fails, 12600 * the cid is added to list of removeCids. We currently don't delete stale 12601 * containers. 12602 */ 12603 private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 12604 HashSet<String> removeCids) { 12605 ArrayList<String> pkgList = new ArrayList<String>(); 12606 Set<AsecInstallArgs> keys = processCids.keySet(); 12607 boolean doGc = false; 12608 for (AsecInstallArgs args : keys) { 12609 String codePath = processCids.get(args); 12610 if (DEBUG_SD_INSTALL) 12611 Log.i(TAG, "Loading container : " + args.cid); 12612 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12613 try { 12614 // Make sure there are no container errors first. 12615 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 12616 Slog.e(TAG, "Failed to mount cid : " + args.cid 12617 + " when installing from sdcard"); 12618 continue; 12619 } 12620 // Check code path here. 12621 if (codePath == null || !codePath.equals(args.getCodePath())) { 12622 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 12623 + " does not match one in settings " + codePath); 12624 continue; 12625 } 12626 // Parse package 12627 int parseFlags = mDefParseFlags; 12628 if (args.isExternal()) { 12629 parseFlags |= PackageParser.PARSE_ON_SDCARD; 12630 } 12631 if (args.isFwdLocked()) { 12632 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 12633 } 12634 12635 doGc = true; 12636 synchronized (mInstallLock) { 12637 final PackageParser.Package pkg = scanPackageLI(new File(codePath), parseFlags, 12638 0, 0, null, null); 12639 // Scan the package 12640 if (pkg != null) { 12641 /* 12642 * TODO why is the lock being held? doPostInstall is 12643 * called in other places without the lock. This needs 12644 * to be straightened out. 12645 */ 12646 // writer 12647 synchronized (mPackages) { 12648 retCode = PackageManager.INSTALL_SUCCEEDED; 12649 pkgList.add(pkg.packageName); 12650 // Post process args 12651 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 12652 pkg.applicationInfo.uid); 12653 } 12654 } else { 12655 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 12656 } 12657 } 12658 12659 } finally { 12660 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 12661 // Don't destroy container here. Wait till gc clears things 12662 // up. 12663 removeCids.add(args.cid); 12664 } 12665 } 12666 } 12667 // writer 12668 synchronized (mPackages) { 12669 // If the platform SDK has changed since the last time we booted, 12670 // we need to re-grant app permission to catch any new ones that 12671 // appear. This is really a hack, and means that apps can in some 12672 // cases get permissions that the user didn't initially explicitly 12673 // allow... it would be nice to have some better way to handle 12674 // this situation. 12675 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 12676 if (regrantPermissions) 12677 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 12678 + mSdkVersion + "; regranting permissions for external storage"); 12679 mSettings.mExternalSdkPlatform = mSdkVersion; 12680 12681 // Make sure group IDs have been assigned, and any permission 12682 // changes in other apps are accounted for 12683 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 12684 | (regrantPermissions 12685 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 12686 : 0)); 12687 12688 mSettings.updateExternalDatabaseVersion(); 12689 12690 // can downgrade to reader 12691 // Persist settings 12692 mSettings.writeLPr(); 12693 } 12694 // Send a broadcast to let everyone know we are done processing 12695 if (pkgList.size() > 0) { 12696 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12697 } 12698 // Force gc to avoid any stale parser references that we might have. 12699 if (doGc) { 12700 Runtime.getRuntime().gc(); 12701 } 12702 // List stale containers and destroy stale temporary containers. 12703 if (removeCids != null) { 12704 for (String cid : removeCids) { 12705 if (cid.startsWith(mTempContainerPrefix)) { 12706 Log.i(TAG, "Destroying stale temporary container " + cid); 12707 PackageHelper.destroySdDir(cid); 12708 } else { 12709 Log.w(TAG, "Container " + cid + " is stale"); 12710 } 12711 } 12712 } 12713 } 12714 12715 /* 12716 * Utility method to unload a list of specified containers 12717 */ 12718 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 12719 // Just unmount all valid containers. 12720 for (AsecInstallArgs arg : cidArgs) { 12721 synchronized (mInstallLock) { 12722 arg.doPostDeleteLI(false); 12723 } 12724 } 12725 } 12726 12727 /* 12728 * Unload packages mounted on external media. This involves deleting package 12729 * data from internal structures, sending broadcasts about diabled packages, 12730 * gc'ing to free up references, unmounting all secure containers 12731 * corresponding to packages on external media, and posting a 12732 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 12733 * that we always have to post this message if status has been requested no 12734 * matter what. 12735 */ 12736 private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 12737 final boolean reportStatus) { 12738 if (DEBUG_SD_INSTALL) 12739 Log.i(TAG, "unloading media packages"); 12740 ArrayList<String> pkgList = new ArrayList<String>(); 12741 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 12742 final Set<AsecInstallArgs> keys = processCids.keySet(); 12743 for (AsecInstallArgs args : keys) { 12744 String pkgName = args.getPackageName(); 12745 if (DEBUG_SD_INSTALL) 12746 Log.i(TAG, "Trying to unload pkg : " + pkgName); 12747 // Delete package internally 12748 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 12749 synchronized (mInstallLock) { 12750 boolean res = deletePackageLI(pkgName, null, false, null, null, 12751 PackageManager.DELETE_KEEP_DATA, outInfo, false); 12752 if (res) { 12753 pkgList.add(pkgName); 12754 } else { 12755 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 12756 failedList.add(args); 12757 } 12758 } 12759 } 12760 12761 // reader 12762 synchronized (mPackages) { 12763 // We didn't update the settings after removing each package; 12764 // write them now for all packages. 12765 mSettings.writeLPr(); 12766 } 12767 12768 // We have to absolutely send UPDATED_MEDIA_STATUS only 12769 // after confirming that all the receivers processed the ordered 12770 // broadcast when packages get disabled, force a gc to clean things up. 12771 // and unload all the containers. 12772 if (pkgList.size() > 0) { 12773 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 12774 new IIntentReceiver.Stub() { 12775 public void performReceive(Intent intent, int resultCode, String data, 12776 Bundle extras, boolean ordered, boolean sticky, 12777 int sendingUser) throws RemoteException { 12778 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 12779 reportStatus ? 1 : 0, 1, keys); 12780 mHandler.sendMessage(msg); 12781 } 12782 }); 12783 } else { 12784 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 12785 keys); 12786 mHandler.sendMessage(msg); 12787 } 12788 } 12789 12790 /** Binder call */ 12791 @Override 12792 public void movePackage(final String packageName, final IPackageMoveObserver observer, 12793 final int flags) { 12794 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 12795 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 12796 int returnCode = PackageManager.MOVE_SUCCEEDED; 12797 int currFlags = 0; 12798 int newFlags = 0; 12799 // reader 12800 synchronized (mPackages) { 12801 PackageParser.Package pkg = mPackages.get(packageName); 12802 if (pkg == null) { 12803 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12804 } else { 12805 // Disable moving fwd locked apps and system packages 12806 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 12807 Slog.w(TAG, "Cannot move system application"); 12808 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 12809 } else if (pkg.mOperationPending) { 12810 Slog.w(TAG, "Attempt to move package which has pending operations"); 12811 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 12812 } else { 12813 // Find install location first 12814 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 12815 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 12816 Slog.w(TAG, "Ambigous flags specified for move location."); 12817 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12818 } else { 12819 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL 12820 : PackageManager.INSTALL_INTERNAL; 12821 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL 12822 : PackageManager.INSTALL_INTERNAL; 12823 12824 if (newFlags == currFlags) { 12825 Slog.w(TAG, "No move required. Trying to move to same location"); 12826 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12827 } else { 12828 if (isForwardLocked(pkg)) { 12829 currFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12830 newFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12831 } 12832 } 12833 } 12834 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12835 pkg.mOperationPending = true; 12836 } 12837 } 12838 } 12839 12840 /* 12841 * TODO this next block probably shouldn't be inside the lock. We 12842 * can't guarantee these won't change after this is fired off 12843 * anyway. 12844 */ 12845 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 12846 processPendingMove(new MoveParams(null, observer, 0, packageName, null, -1, user, false), 12847 returnCode); 12848 } else { 12849 Message msg = mHandler.obtainMessage(INIT_COPY); 12850 final String[] instructionSets = getAppDexInstructionSets(pkg.applicationInfo); 12851 final boolean multiArch = isMultiArch(pkg.applicationInfo); 12852 InstallArgs srcArgs = createInstallArgsForExisting(currFlags, 12853 pkg.applicationInfo.getCodePath(), pkg.applicationInfo.getResourcePath(), 12854 pkg.applicationInfo.legacyNativeLibraryDir, instructionSets, multiArch); 12855 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName, 12856 instructionSets, pkg.applicationInfo.uid, user, multiArch); 12857 msg.obj = mp; 12858 mHandler.sendMessage(msg); 12859 } 12860 } 12861 } 12862 12863 private void processPendingMove(final MoveParams mp, final int currentStatus) { 12864 // Queue up an async operation since the package deletion may take a 12865 // little while. 12866 mHandler.post(new Runnable() { 12867 public void run() { 12868 // TODO fix this; this does nothing. 12869 mHandler.removeCallbacks(this); 12870 int returnCode = currentStatus; 12871 if (currentStatus == PackageManager.MOVE_SUCCEEDED) { 12872 int uidArr[] = null; 12873 ArrayList<String> pkgList = null; 12874 synchronized (mPackages) { 12875 PackageParser.Package pkg = mPackages.get(mp.packageName); 12876 if (pkg == null) { 12877 Slog.w(TAG, " Package " + mp.packageName 12878 + " doesn't exist. Aborting move"); 12879 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12880 } else if (!mp.srcArgs.getCodePath().equals( 12881 pkg.applicationInfo.getCodePath())) { 12882 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " 12883 + mp.srcArgs.getCodePath() + " to " 12884 + pkg.applicationInfo.getCodePath() 12885 + " Aborting move and returning error"); 12886 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 12887 } else { 12888 uidArr = new int[] { 12889 pkg.applicationInfo.uid 12890 }; 12891 pkgList = new ArrayList<String>(); 12892 pkgList.add(mp.packageName); 12893 } 12894 } 12895 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12896 // Send resources unavailable broadcast 12897 sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null); 12898 // Update package code and resource paths 12899 synchronized (mInstallLock) { 12900 synchronized (mPackages) { 12901 PackageParser.Package pkg = mPackages.get(mp.packageName); 12902 // Recheck for package again. 12903 if (pkg == null) { 12904 Slog.w(TAG, " Package " + mp.packageName 12905 + " doesn't exist. Aborting move"); 12906 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12907 } else if (!mp.srcArgs.getCodePath().equals( 12908 pkg.applicationInfo.getCodePath())) { 12909 Slog.w(TAG, "Package " + mp.packageName 12910 + " code path changed from " + mp.srcArgs.getCodePath() 12911 + " to " + pkg.applicationInfo.getCodePath() 12912 + " Aborting move and returning error"); 12913 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 12914 } else { 12915 final String oldCodePath = pkg.codePath; 12916 final String newCodePath = mp.targetArgs.getCodePath(); 12917 final String newResPath = mp.targetArgs.getResourcePath(); 12918 // TODO: This assumes the new style of installation. 12919 // should we look at legacyNativeLibraryPath ? 12920 final String newNativeRoot = new File(pkg.codePath, LIB_DIR_NAME).getAbsolutePath(); 12921 final File newNativeDir = new File(newNativeRoot); 12922 12923 if (!isForwardLocked(pkg) && !isExternal(pkg)) { 12924 // TODO(multiArch): Fix this so that it looks at the existing 12925 // recorded CPU abis from the package. There's no need for a separate 12926 // round of ABI scanning here. 12927 NativeLibraryHelper.Handle handle = null; 12928 try { 12929 handle = NativeLibraryHelper.Handle.create( 12930 new File(newCodePath)); 12931 final int abi = NativeLibraryHelper.findSupportedAbi( 12932 handle, Build.SUPPORTED_ABIS); 12933 if (abi >= 0) { 12934 NativeLibraryHelper.copyNativeBinariesIfNeededLI( 12935 handle, newNativeDir, Build.SUPPORTED_ABIS[abi]); 12936 } 12937 } catch (IOException ioe) { 12938 Slog.w(TAG, "Unable to extract native libs for package :" 12939 + mp.packageName, ioe); 12940 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 12941 } finally { 12942 IoUtils.closeQuietly(handle); 12943 } 12944 } 12945 12946 final int[] users = sUserManager.getUserIds(); 12947 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12948 for (int user : users) { 12949 // TODO(multiArch): Fix this so that it links to the 12950 // correct directory. We're currently pointing to root. but we 12951 // must point to the arch specific subdirectory (if applicable). 12952 // 12953 // TODO(multiArch): Bogus reference to nativeLibraryDir. 12954 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, 12955 newNativeRoot, user) < 0) { 12956 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 12957 } 12958 } 12959 } 12960 12961 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12962 pkg.codePath = newCodePath; 12963 pkg.baseCodePath = newCodePath; 12964 // Move dex files around 12965 if (moveDexFilesLI(oldCodePath, pkg) != PackageManager.INSTALL_SUCCEEDED) { 12966 // Moving of dex files failed. Set 12967 // error code and abort move. 12968 pkg.codePath = oldCodePath; 12969 pkg.baseCodePath = oldCodePath; 12970 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 12971 } 12972 } 12973 12974 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12975 pkg.applicationInfo.setCodePath(newCodePath); 12976 pkg.applicationInfo.setBaseCodePath(newCodePath); 12977 pkg.applicationInfo.setSplitCodePaths(null); 12978 pkg.applicationInfo.setResourcePath(newResPath); 12979 pkg.applicationInfo.setBaseResourcePath(newResPath); 12980 pkg.applicationInfo.setSplitResourcePaths(null); 12981 // Null out the legacy nativeLibraryDir so that we stop using it and 12982 // always derive the codepath. 12983 pkg.applicationInfo.legacyNativeLibraryDir = null; 12984 12985 PackageSetting ps = (PackageSetting) pkg.mExtras; 12986 ps.codePath = new File(pkg.applicationInfo.getCodePath()); 12987 ps.codePathString = ps.codePath.getPath(); 12988 ps.resourcePath = new File(pkg.applicationInfo.getResourcePath()); 12989 ps.resourcePathString = ps.resourcePath.getPath(); 12990 12991 // Note that we don't have to recalculate the primary and secondary 12992 // CPU ABIs because they must already have been calculated during the 12993 // initial install of the app. 12994 ps.legacyNativeLibraryPathString = null; 12995 12996 // Set the application info flag 12997 // correctly. 12998 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) { 12999 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE; 13000 } else { 13001 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE; 13002 } 13003 ps.setFlags(pkg.applicationInfo.flags); 13004 mAppDirs.remove(oldCodePath); 13005 mAppDirs.put(newCodePath, pkg); 13006 // Persist settings 13007 mSettings.writeLPr(); 13008 } 13009 } 13010 } 13011 } 13012 // Send resources available broadcast 13013 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 13014 } 13015 } 13016 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 13017 // Clean up failed installation 13018 if (mp.targetArgs != null) { 13019 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR, 13020 -1); 13021 } 13022 } else { 13023 // Force a gc to clear things up. 13024 Runtime.getRuntime().gc(); 13025 // Delete older code 13026 synchronized (mInstallLock) { 13027 mp.srcArgs.doPostDeleteLI(true); 13028 } 13029 } 13030 13031 // Allow more operations on this file if we didn't fail because 13032 // an operation was already pending for this package. 13033 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) { 13034 synchronized (mPackages) { 13035 PackageParser.Package pkg = mPackages.get(mp.packageName); 13036 if (pkg != null) { 13037 pkg.mOperationPending = false; 13038 } 13039 } 13040 } 13041 13042 IPackageMoveObserver observer = mp.observer; 13043 if (observer != null) { 13044 try { 13045 observer.packageMoved(mp.packageName, returnCode); 13046 } catch (RemoteException e) { 13047 Log.i(TAG, "Observer no longer exists."); 13048 } 13049 } 13050 } 13051 }); 13052 } 13053 13054 @Override 13055 public boolean setInstallLocation(int loc) { 13056 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 13057 null); 13058 if (getInstallLocation() == loc) { 13059 return true; 13060 } 13061 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 13062 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 13063 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 13064 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 13065 return true; 13066 } 13067 return false; 13068 } 13069 13070 @Override 13071 public int getInstallLocation() { 13072 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13073 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 13074 PackageHelper.APP_INSTALL_AUTO); 13075 } 13076 13077 /** Called by UserManagerService */ 13078 void cleanUpUserLILPw(int userHandle) { 13079 mDirtyUsers.remove(userHandle); 13080 mSettings.removeUserLPw(userHandle); 13081 mPendingBroadcasts.remove(userHandle); 13082 if (mInstaller != null) { 13083 // Technically, we shouldn't be doing this with the package lock 13084 // held. However, this is very rare, and there is already so much 13085 // other disk I/O going on, that we'll let it slide for now. 13086 mInstaller.removeUserDataDirs(userHandle); 13087 } 13088 mUserNeedsBadging.delete(userHandle); 13089 } 13090 13091 /** Called by UserManagerService */ 13092 void createNewUserLILPw(int userHandle, File path) { 13093 if (mInstaller != null) { 13094 mInstaller.createUserConfig(userHandle); 13095 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 13096 } 13097 } 13098 13099 @Override 13100 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 13101 mContext.enforceCallingOrSelfPermission( 13102 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13103 "Only package verification agents can read the verifier device identity"); 13104 13105 synchronized (mPackages) { 13106 return mSettings.getVerifierDeviceIdentityLPw(); 13107 } 13108 } 13109 13110 @Override 13111 public void setPermissionEnforced(String permission, boolean enforced) { 13112 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 13113 if (READ_EXTERNAL_STORAGE.equals(permission)) { 13114 synchronized (mPackages) { 13115 if (mSettings.mReadExternalStorageEnforced == null 13116 || mSettings.mReadExternalStorageEnforced != enforced) { 13117 mSettings.mReadExternalStorageEnforced = enforced; 13118 mSettings.writeLPr(); 13119 } 13120 } 13121 // kill any non-foreground processes so we restart them and 13122 // grant/revoke the GID. 13123 final IActivityManager am = ActivityManagerNative.getDefault(); 13124 if (am != null) { 13125 final long token = Binder.clearCallingIdentity(); 13126 try { 13127 am.killProcessesBelowForeground("setPermissionEnforcement"); 13128 } catch (RemoteException e) { 13129 } finally { 13130 Binder.restoreCallingIdentity(token); 13131 } 13132 } 13133 } else { 13134 throw new IllegalArgumentException("No selective enforcement for " + permission); 13135 } 13136 } 13137 13138 @Override 13139 @Deprecated 13140 public boolean isPermissionEnforced(String permission) { 13141 return true; 13142 } 13143 13144 @Override 13145 public boolean isStorageLow() { 13146 final long token = Binder.clearCallingIdentity(); 13147 try { 13148 final DeviceStorageMonitorInternal 13149 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13150 if (dsm != null) { 13151 return dsm.isMemoryLow(); 13152 } else { 13153 return false; 13154 } 13155 } finally { 13156 Binder.restoreCallingIdentity(token); 13157 } 13158 } 13159 13160 @Override 13161 public IPackageInstaller getPackageInstaller() { 13162 return mInstallerService; 13163 } 13164 13165 private boolean userNeedsBadging(int userId) { 13166 int index = mUserNeedsBadging.indexOfKey(userId); 13167 if (index < 0) { 13168 final UserInfo userInfo; 13169 final long token = Binder.clearCallingIdentity(); 13170 try { 13171 userInfo = sUserManager.getUserInfo(userId); 13172 } finally { 13173 Binder.restoreCallingIdentity(token); 13174 } 13175 final boolean b; 13176 if (userInfo != null && userInfo.isManagedProfile()) { 13177 b = true; 13178 } else { 13179 b = false; 13180 } 13181 mUserNeedsBadging.put(userId, b); 13182 return b; 13183 } 13184 return mUserNeedsBadging.valueAt(index); 13185 } 13186} 13187