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