PackageManagerService.java revision 398b6c26c3c46724e4c44b81d9a2541720f8750b
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS; 20import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 21import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 26import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 27import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 28import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 29import static android.content.pm.PackageParser.isApkFile; 30import static android.os.Process.PACKAGE_INFO_GID; 31import static android.os.Process.SYSTEM_UID; 32import static android.system.OsConstants.O_CREAT; 33import static android.system.OsConstants.EEXIST; 34import static android.system.OsConstants.O_EXCL; 35import static android.system.OsConstants.O_RDWR; 36import static android.system.OsConstants.S_IRGRP; 37import static android.system.OsConstants.S_IROTH; 38import static android.system.OsConstants.S_IRWXU; 39import static android.system.OsConstants.S_IXGRP; 40import static android.system.OsConstants.S_IXOTH; 41import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 42import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 43import static com.android.internal.util.ArrayUtils.appendInt; 44import static com.android.internal.util.ArrayUtils.removeInt; 45 46import android.util.ArrayMap; 47 48import com.android.internal.R; 49import com.android.internal.app.IMediaContainerService; 50import com.android.internal.app.ResolverActivity; 51import com.android.internal.content.NativeLibraryHelper; 52import com.android.internal.content.PackageHelper; 53import com.android.internal.os.IParcelFileDescriptorFactory; 54import com.android.internal.util.ArrayUtils; 55import com.android.internal.util.FastPrintWriter; 56import com.android.internal.util.FastXmlSerializer; 57import com.android.internal.util.Preconditions; 58import com.android.server.EventLogTags; 59import com.android.server.IntentResolver; 60import com.android.server.LocalServices; 61import com.android.server.ServiceThread; 62import com.android.server.SystemConfig; 63import com.android.server.Watchdog; 64import com.android.server.pm.Settings.DatabaseVersion; 65import com.android.server.storage.DeviceStorageMonitorInternal; 66 67import org.xmlpull.v1.XmlSerializer; 68 69import android.app.ActivityManager; 70import android.app.ActivityManagerNative; 71import android.app.IActivityManager; 72import android.app.admin.IDevicePolicyManager; 73import android.app.backup.IBackupManager; 74import android.content.BroadcastReceiver; 75import android.content.ComponentName; 76import android.content.Context; 77import android.content.IIntentReceiver; 78import android.content.Intent; 79import android.content.IntentFilter; 80import android.content.IntentSender; 81import android.content.IntentSender.SendIntentException; 82import android.content.ServiceConnection; 83import android.content.pm.ActivityInfo; 84import android.content.pm.ApplicationInfo; 85import android.content.pm.FeatureInfo; 86import android.content.pm.IPackageDataObserver; 87import android.content.pm.IPackageDeleteObserver; 88import android.content.pm.IPackageInstallObserver; 89import android.content.pm.IPackageInstallObserver2; 90import android.content.pm.IPackageInstaller; 91import android.content.pm.IPackageManager; 92import android.content.pm.IPackageMoveObserver; 93import android.content.pm.IPackageStatsObserver; 94import android.content.pm.InstrumentationInfo; 95import android.content.pm.ManifestDigest; 96import android.content.pm.PackageCleanItem; 97import android.content.pm.PackageInfo; 98import android.content.pm.PackageInfoLite; 99import android.content.pm.PackageInstallerParams; 100import android.content.pm.PackageManager; 101import android.content.pm.PackageParser.ActivityIntentInfo; 102import android.content.pm.PackageParser.PackageLite; 103import android.content.pm.PackageParser.PackageParserException; 104import android.content.pm.PackageParser; 105import android.content.pm.PackageStats; 106import android.content.pm.PackageUserState; 107import android.content.pm.ParceledListSlice; 108import android.content.pm.PermissionGroupInfo; 109import android.content.pm.PermissionInfo; 110import android.content.pm.ProviderInfo; 111import android.content.pm.ResolveInfo; 112import android.content.pm.ServiceInfo; 113import android.content.pm.Signature; 114import android.content.pm.UserInfo; 115import android.content.pm.VerificationParams; 116import android.content.pm.VerifierDeviceIdentity; 117import android.content.pm.VerifierInfo; 118import android.content.res.Resources; 119import android.hardware.display.DisplayManager; 120import android.net.Uri; 121import android.os.Binder; 122import android.os.Build; 123import android.os.Bundle; 124import android.os.Environment; 125import android.os.Environment.UserEnvironment; 126import android.os.FileObserver; 127import android.os.FileUtils; 128import android.os.Handler; 129import android.os.IBinder; 130import android.os.Looper; 131import android.os.Message; 132import android.os.Parcel; 133import android.os.ParcelFileDescriptor; 134import android.os.Process; 135import android.os.RemoteException; 136import android.os.SELinux; 137import android.os.ServiceManager; 138import android.os.SystemClock; 139import android.os.SystemProperties; 140import android.os.UserHandle; 141import android.os.UserManager; 142import android.security.KeyStore; 143import android.security.SystemKeyStore; 144import android.system.ErrnoException; 145import android.system.Os; 146import android.system.StructStat; 147import android.text.TextUtils; 148import android.util.ArraySet; 149import android.util.AtomicFile; 150import android.util.DisplayMetrics; 151import android.util.EventLog; 152import android.util.Log; 153import android.util.LogPrinter; 154import android.util.PrintStreamPrinter; 155import android.util.Slog; 156import android.util.SparseArray; 157import android.util.SparseBooleanArray; 158import android.view.Display; 159 160import java.io.BufferedInputStream; 161import java.io.BufferedOutputStream; 162import java.io.File; 163import java.io.FileDescriptor; 164import java.io.FileInputStream; 165import java.io.FileNotFoundException; 166import java.io.FileOutputStream; 167import java.io.FilenameFilter; 168import java.io.IOException; 169import java.io.InputStream; 170import java.io.PrintWriter; 171import java.nio.charset.StandardCharsets; 172import java.security.NoSuchAlgorithmException; 173import java.security.PublicKey; 174import java.security.cert.CertificateEncodingException; 175import java.security.cert.CertificateException; 176import java.text.SimpleDateFormat; 177import java.util.ArrayList; 178import java.util.Arrays; 179import java.util.Collection; 180import java.util.Collections; 181import java.util.Comparator; 182import java.util.Date; 183import java.util.HashMap; 184import java.util.HashSet; 185import java.util.Iterator; 186import java.util.List; 187import java.util.Map; 188import java.util.Random; 189import java.util.Set; 190import java.util.concurrent.atomic.AtomicBoolean; 191import java.util.concurrent.atomic.AtomicLong; 192 193import dalvik.system.DexFile; 194import dalvik.system.StaleDexCacheError; 195import dalvik.system.VMRuntime; 196 197import libcore.io.IoUtils; 198 199/** 200 * Keep track of all those .apks everywhere. 201 * 202 * This is very central to the platform's security; please run the unit 203 * tests whenever making modifications here: 204 * 205mmm frameworks/base/tests/AndroidTests 206adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 207adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 208 * 209 * {@hide} 210 */ 211public class PackageManagerService extends IPackageManager.Stub { 212 static final String TAG = "PackageManager"; 213 static final boolean DEBUG_SETTINGS = false; 214 static final boolean DEBUG_PREFERRED = false; 215 static final boolean DEBUG_UPGRADE = false; 216 private static final boolean DEBUG_INSTALL = false; 217 private static final boolean DEBUG_REMOVE = false; 218 private static final boolean DEBUG_BROADCASTS = false; 219 private static final boolean DEBUG_SHOW_INFO = false; 220 private static final boolean DEBUG_PACKAGE_INFO = false; 221 private static final boolean DEBUG_INTENT_MATCHING = false; 222 private static final boolean DEBUG_PACKAGE_SCANNING = false; 223 private static final boolean DEBUG_APP_DIR_OBSERVER = false; 224 private static final boolean DEBUG_VERIFY = false; 225 private static final boolean DEBUG_DEXOPT = false; 226 private static final boolean DEBUG_ABI_SELECTION = false; 227 228 private static final int RADIO_UID = Process.PHONE_UID; 229 private static final int LOG_UID = Process.LOG_UID; 230 private static final int NFC_UID = Process.NFC_UID; 231 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 232 private static final int SHELL_UID = Process.SHELL_UID; 233 234 // Cap the size of permission trees that 3rd party apps can define 235 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 236 237 private static final int REMOVE_EVENTS = 238 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM; 239 private static final int ADD_EVENTS = 240 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO; 241 242 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS; 243 // Suffix used during package installation when copying/moving 244 // package apks to install directory. 245 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 246 247 static final int SCAN_MONITOR = 1<<0; 248 static final int SCAN_NO_DEX = 1<<1; 249 static final int SCAN_FORCE_DEX = 1<<2; 250 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 251 static final int SCAN_NEW_INSTALL = 1<<4; 252 static final int SCAN_NO_PATHS = 1<<5; 253 static final int SCAN_UPDATE_TIME = 1<<6; 254 static final int SCAN_DEFER_DEX = 1<<7; 255 static final int SCAN_BOOTING = 1<<8; 256 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 257 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 258 259 static final int REMOVE_CHATTY = 1<<16; 260 261 /** 262 * Timeout (in milliseconds) after which the watchdog should declare that 263 * our handler thread is wedged. The usual default for such things is one 264 * minute but we sometimes do very lengthy I/O operations on this thread, 265 * such as installing multi-gigabyte applications, so ours needs to be longer. 266 */ 267 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 268 269 /** 270 * Whether verification is enabled by default. 271 */ 272 private static final boolean DEFAULT_VERIFY_ENABLE = true; 273 274 /** 275 * The default maximum time to wait for the verification agent to return in 276 * milliseconds. 277 */ 278 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 279 280 /** 281 * The default response for package verification timeout. 282 * 283 * This can be either PackageManager.VERIFICATION_ALLOW or 284 * PackageManager.VERIFICATION_REJECT. 285 */ 286 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 287 288 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 289 290 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 291 DEFAULT_CONTAINER_PACKAGE, 292 "com.android.defcontainer.DefaultContainerService"); 293 294 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 295 296 private static final String LIB_DIR_NAME = "lib"; 297 private static final String LIB64_DIR_NAME = "lib64"; 298 299 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 300 301 static final String mTempContainerPrefix = "smdl2tmp"; 302 303 private static String sPreferredInstructionSet; 304 305 final ServiceThread mHandlerThread; 306 307 private static final String IDMAP_PREFIX = "/data/resource-cache/"; 308 private static final String IDMAP_SUFFIX = "@idmap"; 309 310 final PackageHandler mHandler; 311 312 final int mSdkVersion = Build.VERSION.SDK_INT; 313 314 final Context mContext; 315 final boolean mFactoryTest; 316 final boolean mOnlyCore; 317 final DisplayMetrics mMetrics; 318 final int mDefParseFlags; 319 final String[] mSeparateProcesses; 320 321 // This is where all application persistent data goes. 322 final File mAppDataDir; 323 324 // This is where all application persistent data goes for secondary users. 325 final File mUserAppDataDir; 326 327 /** The location for ASEC container files on internal storage. */ 328 final String mAsecInternalPath; 329 330 // This is the object monitoring the framework dir. 331 final FileObserver mFrameworkInstallObserver; 332 333 // This is the object monitoring the system app dir. 334 final FileObserver mSystemInstallObserver; 335 336 // This is the object monitoring the privileged system app dir. 337 final FileObserver mPrivilegedInstallObserver; 338 339 // This is the object monitoring the vendor app dir. 340 final FileObserver mVendorInstallObserver; 341 342 // This is the object monitoring the vendor overlay package dir. 343 final FileObserver mVendorOverlayInstallObserver; 344 345 // This is the object monitoring the OEM app dir. 346 final FileObserver mOemInstallObserver; 347 348 // This is the object monitoring mAppInstallDir. 349 final FileObserver mAppInstallObserver; 350 351 // This is the object monitoring mDrmAppPrivateInstallDir. 352 final FileObserver mDrmAppInstallObserver; 353 354 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 355 // LOCK HELD. Can be called with mInstallLock held. 356 final Installer mInstaller; 357 358 /** Directory where installed third-party apps stored */ 359 final File mAppInstallDir; 360 361 /** 362 * Directory to which applications installed internally have their 363 * 32 bit native libraries copied. 364 */ 365 private File mAppLib32InstallDir; 366 367 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 368 // apps. 369 final File mDrmAppPrivateInstallDir; 370 371 // ---------------------------------------------------------------- 372 373 // Lock for state used when installing and doing other long running 374 // operations. Methods that must be called with this lock held have 375 // the suffix "LI". 376 final Object mInstallLock = new Object(); 377 378 // These are the directories in the 3rd party applications installed dir 379 // that we have currently loaded packages from. Keys are the application's 380 // installed zip file (absolute codePath), and values are Package. 381 final HashMap<String, PackageParser.Package> mAppDirs = 382 new HashMap<String, PackageParser.Package>(); 383 384 // Information for the parser to write more useful error messages. 385 int mLastScanError; 386 387 // ---------------------------------------------------------------- 388 389 // Keys are String (package name), values are Package. This also serves 390 // as the lock for the global state. Methods that must be called with 391 // this lock held have the prefix "LP". 392 final HashMap<String, PackageParser.Package> mPackages = 393 new HashMap<String, PackageParser.Package>(); 394 395 // Tracks available target package names -> overlay package paths. 396 final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays = 397 new HashMap<String, HashMap<String, PackageParser.Package>>(); 398 399 final Settings mSettings; 400 boolean mRestoredSettings; 401 402 // System configuration read by SystemConfig. 403 final int[] mGlobalGids; 404 final SparseArray<HashSet<String>> mSystemPermissions; 405 final HashMap<String, FeatureInfo> mAvailableFeatures; 406 407 // If mac_permissions.xml was found for seinfo labeling. 408 boolean mFoundPolicyFile; 409 410 // If a recursive restorecon of /data/data/<pkg> is needed. 411 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 412 413 public static final class SharedLibraryEntry { 414 public final String path; 415 public final String apk; 416 417 SharedLibraryEntry(String _path, String _apk) { 418 path = _path; 419 apk = _apk; 420 } 421 } 422 423 // Currently known shared libraries. 424 final HashMap<String, SharedLibraryEntry> mSharedLibraries = 425 new HashMap<String, SharedLibraryEntry>(); 426 427 // All available activities, for your resolving pleasure. 428 final ActivityIntentResolver mActivities = 429 new ActivityIntentResolver(); 430 431 // All available receivers, for your resolving pleasure. 432 final ActivityIntentResolver mReceivers = 433 new ActivityIntentResolver(); 434 435 // All available services, for your resolving pleasure. 436 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 437 438 // All available providers, for your resolving pleasure. 439 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 440 441 // Mapping from provider base names (first directory in content URI codePath) 442 // to the provider information. 443 final HashMap<String, PackageParser.Provider> mProvidersByAuthority = 444 new HashMap<String, PackageParser.Provider>(); 445 446 // Mapping from instrumentation class names to info about them. 447 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 448 new HashMap<ComponentName, PackageParser.Instrumentation>(); 449 450 // Mapping from permission names to info about them. 451 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups = 452 new HashMap<String, PackageParser.PermissionGroup>(); 453 454 // Packages whose data we have transfered into another package, thus 455 // should no longer exist. 456 final HashSet<String> mTransferedPackages = new HashSet<String>(); 457 458 // Broadcast actions that are only available to the system. 459 final HashSet<String> mProtectedBroadcasts = new HashSet<String>(); 460 461 /** List of packages waiting for verification. */ 462 final SparseArray<PackageVerificationState> mPendingVerification 463 = new SparseArray<PackageVerificationState>(); 464 465 final PackageInstallerService mInstallerService; 466 467 HashSet<PackageParser.Package> mDeferredDexOpt = null; 468 469 // Cache of users who need badging. 470 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 471 472 /** Token for keys in mPendingVerification. */ 473 private int mPendingVerificationToken = 0; 474 475 boolean mSystemReady; 476 boolean mSafeMode; 477 boolean mHasSystemUidErrors; 478 479 ApplicationInfo mAndroidApplication; 480 final ActivityInfo mResolveActivity = new ActivityInfo(); 481 final ResolveInfo mResolveInfo = new ResolveInfo(); 482 ComponentName mResolveComponentName; 483 PackageParser.Package mPlatformPackage; 484 ComponentName mCustomResolverComponentName; 485 486 boolean mResolverReplaced = false; 487 488 // Set of pending broadcasts for aggregating enable/disable of components. 489 static class PendingPackageBroadcasts { 490 // for each user id, a map of <package name -> components within that package> 491 final SparseArray<HashMap<String, ArrayList<String>>> mUidMap; 492 493 public PendingPackageBroadcasts() { 494 mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2); 495 } 496 497 public ArrayList<String> get(int userId, String packageName) { 498 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 499 return packages.get(packageName); 500 } 501 502 public void put(int userId, String packageName, ArrayList<String> components) { 503 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 504 packages.put(packageName, components); 505 } 506 507 public void remove(int userId, String packageName) { 508 HashMap<String, ArrayList<String>> packages = mUidMap.get(userId); 509 if (packages != null) { 510 packages.remove(packageName); 511 } 512 } 513 514 public void remove(int userId) { 515 mUidMap.remove(userId); 516 } 517 518 public int userIdCount() { 519 return mUidMap.size(); 520 } 521 522 public int userIdAt(int n) { 523 return mUidMap.keyAt(n); 524 } 525 526 public HashMap<String, ArrayList<String>> packagesForUserId(int userId) { 527 return mUidMap.get(userId); 528 } 529 530 public int size() { 531 // total number of pending broadcast entries across all userIds 532 int num = 0; 533 for (int i = 0; i< mUidMap.size(); i++) { 534 num += mUidMap.valueAt(i).size(); 535 } 536 return num; 537 } 538 539 public void clear() { 540 mUidMap.clear(); 541 } 542 543 private HashMap<String, ArrayList<String>> getOrAllocate(int userId) { 544 HashMap<String, ArrayList<String>> map = mUidMap.get(userId); 545 if (map == null) { 546 map = new HashMap<String, ArrayList<String>>(); 547 mUidMap.put(userId, map); 548 } 549 return map; 550 } 551 } 552 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 553 554 // Service Connection to remote media container service to copy 555 // package uri's from external media onto secure containers 556 // or internal storage. 557 private IMediaContainerService mContainerService = null; 558 559 static final int SEND_PENDING_BROADCAST = 1; 560 static final int MCS_BOUND = 3; 561 static final int END_COPY = 4; 562 static final int INIT_COPY = 5; 563 static final int MCS_UNBIND = 6; 564 static final int START_CLEANING_PACKAGE = 7; 565 static final int FIND_INSTALL_LOC = 8; 566 static final int POST_INSTALL = 9; 567 static final int MCS_RECONNECT = 10; 568 static final int MCS_GIVE_UP = 11; 569 static final int UPDATED_MEDIA_STATUS = 12; 570 static final int WRITE_SETTINGS = 13; 571 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 572 static final int PACKAGE_VERIFIED = 15; 573 static final int CHECK_PENDING_VERIFICATION = 16; 574 575 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 576 577 // Delay time in millisecs 578 static final int BROADCAST_DELAY = 10 * 1000; 579 580 static UserManagerService sUserManager; 581 582 // Stores a list of users whose package restrictions file needs to be updated 583 private HashSet<Integer> mDirtyUsers = new HashSet<Integer>(); 584 585 final private DefaultContainerConnection mDefContainerConn = 586 new DefaultContainerConnection(); 587 class DefaultContainerConnection implements ServiceConnection { 588 public void onServiceConnected(ComponentName name, IBinder service) { 589 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 590 IMediaContainerService imcs = 591 IMediaContainerService.Stub.asInterface(service); 592 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 593 } 594 595 public void onServiceDisconnected(ComponentName name) { 596 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 597 } 598 }; 599 600 // Recordkeeping of restore-after-install operations that are currently in flight 601 // between the Package Manager and the Backup Manager 602 class PostInstallData { 603 public InstallArgs args; 604 public PackageInstalledInfo res; 605 606 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 607 args = _a; 608 res = _r; 609 } 610 }; 611 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 612 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 613 614 private final String mRequiredVerifierPackage; 615 616 private final PackageUsage mPackageUsage = new PackageUsage(); 617 618 private class PackageUsage { 619 private static final int WRITE_INTERVAL 620 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 621 622 private final Object mFileLock = new Object(); 623 private final AtomicLong mLastWritten = new AtomicLong(0); 624 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 625 626 private boolean mIsHistoricalPackageUsageAvailable = true; 627 628 boolean isHistoricalPackageUsageAvailable() { 629 return mIsHistoricalPackageUsageAvailable; 630 } 631 632 void write(boolean force) { 633 if (force) { 634 writeInternal(); 635 return; 636 } 637 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 638 && !DEBUG_DEXOPT) { 639 return; 640 } 641 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 642 new Thread("PackageUsage_DiskWriter") { 643 @Override 644 public void run() { 645 try { 646 writeInternal(); 647 } finally { 648 mBackgroundWriteRunning.set(false); 649 } 650 } 651 }.start(); 652 } 653 } 654 655 private void writeInternal() { 656 synchronized (mPackages) { 657 synchronized (mFileLock) { 658 AtomicFile file = getFile(); 659 FileOutputStream f = null; 660 try { 661 f = file.startWrite(); 662 BufferedOutputStream out = new BufferedOutputStream(f); 663 FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID); 664 StringBuilder sb = new StringBuilder(); 665 for (PackageParser.Package pkg : mPackages.values()) { 666 if (pkg.mLastPackageUsageTimeInMills == 0) { 667 continue; 668 } 669 sb.setLength(0); 670 sb.append(pkg.packageName); 671 sb.append(' '); 672 sb.append((long)pkg.mLastPackageUsageTimeInMills); 673 sb.append('\n'); 674 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 675 } 676 out.flush(); 677 file.finishWrite(f); 678 } catch (IOException e) { 679 if (f != null) { 680 file.failWrite(f); 681 } 682 Log.e(TAG, "Failed to write package usage times", e); 683 } 684 } 685 } 686 mLastWritten.set(SystemClock.elapsedRealtime()); 687 } 688 689 void readLP() { 690 synchronized (mFileLock) { 691 AtomicFile file = getFile(); 692 BufferedInputStream in = null; 693 try { 694 in = new BufferedInputStream(file.openRead()); 695 StringBuffer sb = new StringBuffer(); 696 while (true) { 697 String packageName = readToken(in, sb, ' '); 698 if (packageName == null) { 699 break; 700 } 701 String timeInMillisString = readToken(in, sb, '\n'); 702 if (timeInMillisString == null) { 703 throw new IOException("Failed to find last usage time for package " 704 + packageName); 705 } 706 PackageParser.Package pkg = mPackages.get(packageName); 707 if (pkg == null) { 708 continue; 709 } 710 long timeInMillis; 711 try { 712 timeInMillis = Long.parseLong(timeInMillisString.toString()); 713 } catch (NumberFormatException e) { 714 throw new IOException("Failed to parse " + timeInMillisString 715 + " as a long.", e); 716 } 717 pkg.mLastPackageUsageTimeInMills = timeInMillis; 718 } 719 } catch (FileNotFoundException expected) { 720 mIsHistoricalPackageUsageAvailable = false; 721 } catch (IOException e) { 722 Log.w(TAG, "Failed to read package usage times", e); 723 } finally { 724 IoUtils.closeQuietly(in); 725 } 726 } 727 mLastWritten.set(SystemClock.elapsedRealtime()); 728 } 729 730 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 731 throws IOException { 732 sb.setLength(0); 733 while (true) { 734 int ch = in.read(); 735 if (ch == -1) { 736 if (sb.length() == 0) { 737 return null; 738 } 739 throw new IOException("Unexpected EOF"); 740 } 741 if (ch == endOfToken) { 742 return sb.toString(); 743 } 744 sb.append((char)ch); 745 } 746 } 747 748 private AtomicFile getFile() { 749 File dataDir = Environment.getDataDirectory(); 750 File systemDir = new File(dataDir, "system"); 751 File fname = new File(systemDir, "package-usage.list"); 752 return new AtomicFile(fname); 753 } 754 } 755 756 class PackageHandler extends Handler { 757 private boolean mBound = false; 758 final ArrayList<HandlerParams> mPendingInstalls = 759 new ArrayList<HandlerParams>(); 760 761 private boolean connectToService() { 762 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 763 " DefaultContainerService"); 764 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 765 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 766 if (mContext.bindServiceAsUser(service, mDefContainerConn, 767 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 768 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 769 mBound = true; 770 return true; 771 } 772 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 773 return false; 774 } 775 776 private void disconnectService() { 777 mContainerService = null; 778 mBound = false; 779 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 780 mContext.unbindService(mDefContainerConn); 781 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 782 } 783 784 PackageHandler(Looper looper) { 785 super(looper); 786 } 787 788 public void handleMessage(Message msg) { 789 try { 790 doHandleMessage(msg); 791 } finally { 792 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 793 } 794 } 795 796 void doHandleMessage(Message msg) { 797 switch (msg.what) { 798 case INIT_COPY: { 799 HandlerParams params = (HandlerParams) msg.obj; 800 int idx = mPendingInstalls.size(); 801 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 802 // If a bind was already initiated we dont really 803 // need to do anything. The pending install 804 // will be processed later on. 805 if (!mBound) { 806 // If this is the only one pending we might 807 // have to bind to the service again. 808 if (!connectToService()) { 809 Slog.e(TAG, "Failed to bind to media container service"); 810 params.serviceError(); 811 return; 812 } else { 813 // Once we bind to the service, the first 814 // pending request will be processed. 815 mPendingInstalls.add(idx, params); 816 } 817 } else { 818 mPendingInstalls.add(idx, params); 819 // Already bound to the service. Just make 820 // sure we trigger off processing the first request. 821 if (idx == 0) { 822 mHandler.sendEmptyMessage(MCS_BOUND); 823 } 824 } 825 break; 826 } 827 case MCS_BOUND: { 828 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 829 if (msg.obj != null) { 830 mContainerService = (IMediaContainerService) msg.obj; 831 } 832 if (mContainerService == null) { 833 // Something seriously wrong. Bail out 834 Slog.e(TAG, "Cannot bind to media container service"); 835 for (HandlerParams params : mPendingInstalls) { 836 // Indicate service bind error 837 params.serviceError(); 838 } 839 mPendingInstalls.clear(); 840 } else if (mPendingInstalls.size() > 0) { 841 HandlerParams params = mPendingInstalls.get(0); 842 if (params != null) { 843 if (params.startCopy()) { 844 // We are done... look for more work or to 845 // go idle. 846 if (DEBUG_SD_INSTALL) Log.i(TAG, 847 "Checking for more work or unbind..."); 848 // Delete pending install 849 if (mPendingInstalls.size() > 0) { 850 mPendingInstalls.remove(0); 851 } 852 if (mPendingInstalls.size() == 0) { 853 if (mBound) { 854 if (DEBUG_SD_INSTALL) Log.i(TAG, 855 "Posting delayed MCS_UNBIND"); 856 removeMessages(MCS_UNBIND); 857 Message ubmsg = obtainMessage(MCS_UNBIND); 858 // Unbind after a little delay, to avoid 859 // continual thrashing. 860 sendMessageDelayed(ubmsg, 10000); 861 } 862 } else { 863 // There are more pending requests in queue. 864 // Just post MCS_BOUND message to trigger processing 865 // of next pending install. 866 if (DEBUG_SD_INSTALL) Log.i(TAG, 867 "Posting MCS_BOUND for next work"); 868 mHandler.sendEmptyMessage(MCS_BOUND); 869 } 870 } 871 } 872 } else { 873 // Should never happen ideally. 874 Slog.w(TAG, "Empty queue"); 875 } 876 break; 877 } 878 case MCS_RECONNECT: { 879 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 880 if (mPendingInstalls.size() > 0) { 881 if (mBound) { 882 disconnectService(); 883 } 884 if (!connectToService()) { 885 Slog.e(TAG, "Failed to bind to media container service"); 886 for (HandlerParams params : mPendingInstalls) { 887 // Indicate service bind error 888 params.serviceError(); 889 } 890 mPendingInstalls.clear(); 891 } 892 } 893 break; 894 } 895 case MCS_UNBIND: { 896 // If there is no actual work left, then time to unbind. 897 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 898 899 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 900 if (mBound) { 901 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 902 903 disconnectService(); 904 } 905 } else if (mPendingInstalls.size() > 0) { 906 // There are more pending requests in queue. 907 // Just post MCS_BOUND message to trigger processing 908 // of next pending install. 909 mHandler.sendEmptyMessage(MCS_BOUND); 910 } 911 912 break; 913 } 914 case MCS_GIVE_UP: { 915 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 916 mPendingInstalls.remove(0); 917 break; 918 } 919 case SEND_PENDING_BROADCAST: { 920 String packages[]; 921 ArrayList<String> components[]; 922 int size = 0; 923 int uids[]; 924 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 925 synchronized (mPackages) { 926 if (mPendingBroadcasts == null) { 927 return; 928 } 929 size = mPendingBroadcasts.size(); 930 if (size <= 0) { 931 // Nothing to be done. Just return 932 return; 933 } 934 packages = new String[size]; 935 components = new ArrayList[size]; 936 uids = new int[size]; 937 int i = 0; // filling out the above arrays 938 939 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 940 int packageUserId = mPendingBroadcasts.userIdAt(n); 941 Iterator<Map.Entry<String, ArrayList<String>>> it 942 = mPendingBroadcasts.packagesForUserId(packageUserId) 943 .entrySet().iterator(); 944 while (it.hasNext() && i < size) { 945 Map.Entry<String, ArrayList<String>> ent = it.next(); 946 packages[i] = ent.getKey(); 947 components[i] = ent.getValue(); 948 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 949 uids[i] = (ps != null) 950 ? UserHandle.getUid(packageUserId, ps.appId) 951 : -1; 952 i++; 953 } 954 } 955 size = i; 956 mPendingBroadcasts.clear(); 957 } 958 // Send broadcasts 959 for (int i = 0; i < size; i++) { 960 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 961 } 962 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 963 break; 964 } 965 case START_CLEANING_PACKAGE: { 966 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 967 final String packageName = (String)msg.obj; 968 final int userId = msg.arg1; 969 final boolean andCode = msg.arg2 != 0; 970 synchronized (mPackages) { 971 if (userId == UserHandle.USER_ALL) { 972 int[] users = sUserManager.getUserIds(); 973 for (int user : users) { 974 mSettings.addPackageToCleanLPw( 975 new PackageCleanItem(user, packageName, andCode)); 976 } 977 } else { 978 mSettings.addPackageToCleanLPw( 979 new PackageCleanItem(userId, packageName, andCode)); 980 } 981 } 982 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 983 startCleaningPackages(); 984 } break; 985 case POST_INSTALL: { 986 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 987 PostInstallData data = mRunningInstalls.get(msg.arg1); 988 mRunningInstalls.delete(msg.arg1); 989 boolean deleteOld = false; 990 991 if (data != null) { 992 InstallArgs args = data.args; 993 PackageInstalledInfo res = data.res; 994 995 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 996 res.removedInfo.sendBroadcast(false, true, false); 997 Bundle extras = new Bundle(1); 998 extras.putInt(Intent.EXTRA_UID, res.uid); 999 // Determine the set of users who are adding this 1000 // package for the first time vs. those who are seeing 1001 // an update. 1002 int[] firstUsers; 1003 int[] updateUsers = new int[0]; 1004 if (res.origUsers == null || res.origUsers.length == 0) { 1005 firstUsers = res.newUsers; 1006 } else { 1007 firstUsers = new int[0]; 1008 for (int i=0; i<res.newUsers.length; i++) { 1009 int user = res.newUsers[i]; 1010 boolean isNew = true; 1011 for (int j=0; j<res.origUsers.length; j++) { 1012 if (res.origUsers[j] == user) { 1013 isNew = false; 1014 break; 1015 } 1016 } 1017 if (isNew) { 1018 int[] newFirst = new int[firstUsers.length+1]; 1019 System.arraycopy(firstUsers, 0, newFirst, 0, 1020 firstUsers.length); 1021 newFirst[firstUsers.length] = user; 1022 firstUsers = newFirst; 1023 } else { 1024 int[] newUpdate = new int[updateUsers.length+1]; 1025 System.arraycopy(updateUsers, 0, newUpdate, 0, 1026 updateUsers.length); 1027 newUpdate[updateUsers.length] = user; 1028 updateUsers = newUpdate; 1029 } 1030 } 1031 } 1032 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1033 res.pkg.applicationInfo.packageName, 1034 extras, null, null, firstUsers); 1035 final boolean update = res.removedInfo.removedPackage != null; 1036 if (update) { 1037 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1038 } 1039 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1040 res.pkg.applicationInfo.packageName, 1041 extras, null, null, updateUsers); 1042 if (update) { 1043 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1044 res.pkg.applicationInfo.packageName, 1045 extras, null, null, updateUsers); 1046 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1047 null, null, 1048 res.pkg.applicationInfo.packageName, null, updateUsers); 1049 1050 // treat asec-hosted packages like removable media on upgrade 1051 if (isForwardLocked(res.pkg) || isExternal(res.pkg)) { 1052 if (DEBUG_INSTALL) { 1053 Slog.i(TAG, "upgrading pkg " + res.pkg 1054 + " is ASEC-hosted -> AVAILABLE"); 1055 } 1056 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1057 ArrayList<String> pkgList = new ArrayList<String>(1); 1058 pkgList.add(res.pkg.applicationInfo.packageName); 1059 sendResourcesChangedBroadcast(true, true, 1060 pkgList,uidArray, null); 1061 } 1062 } 1063 if (res.removedInfo.args != null) { 1064 // Remove the replaced package's older resources safely now 1065 deleteOld = true; 1066 } 1067 1068 // Log current value of "unknown sources" setting 1069 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1070 getUnknownSourcesSettings()); 1071 } 1072 // Force a gc to clear up things 1073 Runtime.getRuntime().gc(); 1074 // We delete after a gc for applications on sdcard. 1075 if (deleteOld) { 1076 synchronized (mInstallLock) { 1077 res.removedInfo.args.doPostDeleteLI(true); 1078 } 1079 } 1080 if (args.observer != null) { 1081 try { 1082 Bundle extras = extrasForInstallResult(res); 1083 args.observer.packageInstalled(res.name, extras, res.returnCode); 1084 } catch (RemoteException e) { 1085 Slog.i(TAG, "Observer no longer exists."); 1086 } 1087 } 1088 } else { 1089 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1090 } 1091 } break; 1092 case UPDATED_MEDIA_STATUS: { 1093 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1094 boolean reportStatus = msg.arg1 == 1; 1095 boolean doGc = msg.arg2 == 1; 1096 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1097 if (doGc) { 1098 // Force a gc to clear up stale containers. 1099 Runtime.getRuntime().gc(); 1100 } 1101 if (msg.obj != null) { 1102 @SuppressWarnings("unchecked") 1103 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1104 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1105 // Unload containers 1106 unloadAllContainers(args); 1107 } 1108 if (reportStatus) { 1109 try { 1110 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1111 PackageHelper.getMountService().finishMediaUpdate(); 1112 } catch (RemoteException e) { 1113 Log.e(TAG, "MountService not running?"); 1114 } 1115 } 1116 } break; 1117 case WRITE_SETTINGS: { 1118 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1119 synchronized (mPackages) { 1120 removeMessages(WRITE_SETTINGS); 1121 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1122 mSettings.writeLPr(); 1123 mDirtyUsers.clear(); 1124 } 1125 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1126 } break; 1127 case WRITE_PACKAGE_RESTRICTIONS: { 1128 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1129 synchronized (mPackages) { 1130 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1131 for (int userId : mDirtyUsers) { 1132 mSettings.writePackageRestrictionsLPr(userId); 1133 } 1134 mDirtyUsers.clear(); 1135 } 1136 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1137 } break; 1138 case CHECK_PENDING_VERIFICATION: { 1139 final int verificationId = msg.arg1; 1140 final PackageVerificationState state = mPendingVerification.get(verificationId); 1141 1142 if ((state != null) && !state.timeoutExtended()) { 1143 final InstallArgs args = state.getInstallArgs(); 1144 final Uri originUri = Uri.fromFile(args.originFile); 1145 1146 Slog.i(TAG, "Verification timed out for " + originUri); 1147 mPendingVerification.remove(verificationId); 1148 1149 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1150 1151 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1152 Slog.i(TAG, "Continuing with installation of " + originUri); 1153 state.setVerifierResponse(Binder.getCallingUid(), 1154 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1155 broadcastPackageVerified(verificationId, originUri, 1156 PackageManager.VERIFICATION_ALLOW, 1157 state.getInstallArgs().getUser()); 1158 try { 1159 ret = args.copyApk(mContainerService, true); 1160 } catch (RemoteException e) { 1161 Slog.e(TAG, "Could not contact the ContainerService"); 1162 } 1163 } else { 1164 broadcastPackageVerified(verificationId, originUri, 1165 PackageManager.VERIFICATION_REJECT, 1166 state.getInstallArgs().getUser()); 1167 } 1168 1169 processPendingInstall(args, ret); 1170 mHandler.sendEmptyMessage(MCS_UNBIND); 1171 } 1172 break; 1173 } 1174 case PACKAGE_VERIFIED: { 1175 final int verificationId = msg.arg1; 1176 1177 final PackageVerificationState state = mPendingVerification.get(verificationId); 1178 if (state == null) { 1179 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1180 break; 1181 } 1182 1183 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1184 1185 state.setVerifierResponse(response.callerUid, response.code); 1186 1187 if (state.isVerificationComplete()) { 1188 mPendingVerification.remove(verificationId); 1189 1190 final InstallArgs args = state.getInstallArgs(); 1191 final Uri originUri = Uri.fromFile(args.originFile); 1192 1193 int ret; 1194 if (state.isInstallAllowed()) { 1195 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1196 broadcastPackageVerified(verificationId, originUri, 1197 response.code, state.getInstallArgs().getUser()); 1198 try { 1199 ret = args.copyApk(mContainerService, true); 1200 } catch (RemoteException e) { 1201 Slog.e(TAG, "Could not contact the ContainerService"); 1202 } 1203 } else { 1204 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1205 } 1206 1207 processPendingInstall(args, ret); 1208 1209 mHandler.sendEmptyMessage(MCS_UNBIND); 1210 } 1211 1212 break; 1213 } 1214 } 1215 } 1216 } 1217 1218 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1219 Bundle extras = null; 1220 switch (res.returnCode) { 1221 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1222 extras = new Bundle(); 1223 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1224 res.origPermission); 1225 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1226 res.origPackage); 1227 break; 1228 } 1229 } 1230 return extras; 1231 } 1232 1233 void scheduleWriteSettingsLocked() { 1234 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1235 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1236 } 1237 } 1238 1239 void scheduleWritePackageRestrictionsLocked(int userId) { 1240 if (!sUserManager.exists(userId)) return; 1241 mDirtyUsers.add(userId); 1242 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1243 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1244 } 1245 } 1246 1247 public static final PackageManagerService main(Context context, Installer installer, 1248 boolean factoryTest, boolean onlyCore) { 1249 PackageManagerService m = new PackageManagerService(context, installer, 1250 factoryTest, onlyCore); 1251 ServiceManager.addService("package", m); 1252 return m; 1253 } 1254 1255 static String[] splitString(String str, char sep) { 1256 int count = 1; 1257 int i = 0; 1258 while ((i=str.indexOf(sep, i)) >= 0) { 1259 count++; 1260 i++; 1261 } 1262 1263 String[] res = new String[count]; 1264 i=0; 1265 count = 0; 1266 int lastI=0; 1267 while ((i=str.indexOf(sep, i)) >= 0) { 1268 res[count] = str.substring(lastI, i); 1269 count++; 1270 i++; 1271 lastI = i; 1272 } 1273 res[count] = str.substring(lastI, str.length()); 1274 return res; 1275 } 1276 1277 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1278 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1279 Context.DISPLAY_SERVICE); 1280 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1281 } 1282 1283 public PackageManagerService(Context context, Installer installer, 1284 boolean factoryTest, boolean onlyCore) { 1285 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1286 SystemClock.uptimeMillis()); 1287 1288 if (mSdkVersion <= 0) { 1289 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1290 } 1291 1292 mContext = context; 1293 mFactoryTest = factoryTest; 1294 mOnlyCore = onlyCore; 1295 mMetrics = new DisplayMetrics(); 1296 mSettings = new Settings(context); 1297 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1298 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1299 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1300 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1301 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1302 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1303 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1304 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1305 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1306 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1307 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1308 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1309 1310 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1311 if (separateProcesses != null && separateProcesses.length() > 0) { 1312 if ("*".equals(separateProcesses)) { 1313 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1314 mSeparateProcesses = null; 1315 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1316 } else { 1317 mDefParseFlags = 0; 1318 mSeparateProcesses = separateProcesses.split(","); 1319 Slog.w(TAG, "Running with debug.separate_processes: " 1320 + separateProcesses); 1321 } 1322 } else { 1323 mDefParseFlags = 0; 1324 mSeparateProcesses = null; 1325 } 1326 1327 mInstaller = installer; 1328 1329 getDefaultDisplayMetrics(context, mMetrics); 1330 1331 SystemConfig systemConfig = SystemConfig.getInstance(); 1332 mGlobalGids = systemConfig.getGlobalGids(); 1333 mSystemPermissions = systemConfig.getSystemPermissions(); 1334 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1335 1336 synchronized (mInstallLock) { 1337 // writer 1338 synchronized (mPackages) { 1339 mHandlerThread = new ServiceThread(TAG, 1340 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1341 mHandlerThread.start(); 1342 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1343 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1344 1345 File dataDir = Environment.getDataDirectory(); 1346 mAppDataDir = new File(dataDir, "data"); 1347 mAppInstallDir = new File(dataDir, "app"); 1348 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1349 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1350 mUserAppDataDir = new File(dataDir, "user"); 1351 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1352 1353 sUserManager = new UserManagerService(context, this, 1354 mInstallLock, mPackages); 1355 1356 // Propagate permission configuration in to package manager. 1357 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1358 = systemConfig.getPermissions(); 1359 for (int i=0; i<permConfig.size(); i++) { 1360 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1361 BasePermission bp = mSettings.mPermissions.get(perm.name); 1362 if (bp == null) { 1363 bp = new BasePermission(perm.name, null, BasePermission.TYPE_BUILTIN); 1364 mSettings.mPermissions.put(perm.name, bp); 1365 } 1366 if (perm.gids != null) { 1367 bp.gids = appendInts(bp.gids, perm.gids); 1368 } 1369 } 1370 1371 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1372 for (int i=0; i<libConfig.size(); i++) { 1373 mSharedLibraries.put(libConfig.keyAt(i), 1374 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1375 } 1376 1377 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1378 1379 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1380 mSdkVersion, mOnlyCore); 1381 1382 String customResolverActivity = Resources.getSystem().getString( 1383 R.string.config_customResolverActivity); 1384 if (TextUtils.isEmpty(customResolverActivity)) { 1385 customResolverActivity = null; 1386 } else { 1387 mCustomResolverComponentName = ComponentName.unflattenFromString( 1388 customResolverActivity); 1389 } 1390 1391 long startTime = SystemClock.uptimeMillis(); 1392 1393 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1394 startTime); 1395 1396 // Set flag to monitor and not change apk file paths when 1397 // scanning install directories. 1398 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1399 1400 final HashSet<String> alreadyDexOpted = new HashSet<String>(); 1401 1402 /** 1403 * Add everything in the in the boot class path to the 1404 * list of process files because dexopt will have been run 1405 * if necessary during zygote startup. 1406 */ 1407 String bootClassPath = System.getProperty("java.boot.class.path"); 1408 if (bootClassPath != null) { 1409 String[] paths = splitString(bootClassPath, ':'); 1410 for (int i=0; i<paths.length; i++) { 1411 alreadyDexOpted.add(paths[i]); 1412 } 1413 } else { 1414 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1415 } 1416 1417 boolean didDexOptLibraryOrTool = false; 1418 1419 final List<String> instructionSets = getAllInstructionSets(); 1420 1421 /** 1422 * Ensure all external libraries have had dexopt run on them. 1423 */ 1424 if (mSharedLibraries.size() > 0) { 1425 // NOTE: For now, we're compiling these system "shared libraries" 1426 // (and framework jars) into all available architectures. It's possible 1427 // to compile them only when we come across an app that uses them (there's 1428 // already logic for that in scanPackageLI) but that adds some complexity. 1429 for (String instructionSet : instructionSets) { 1430 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1431 final String lib = libEntry.path; 1432 if (lib == null) { 1433 continue; 1434 } 1435 1436 try { 1437 if (DexFile.isDexOptNeededInternal(lib, null, instructionSet, false)) { 1438 alreadyDexOpted.add(lib); 1439 1440 // The list of "shared libraries" we have at this point is 1441 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, instructionSet); 1442 didDexOptLibraryOrTool = true; 1443 } 1444 } catch (FileNotFoundException e) { 1445 Slog.w(TAG, "Library not found: " + lib); 1446 } catch (IOException e) { 1447 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1448 + e.getMessage()); 1449 } 1450 } 1451 } 1452 } 1453 1454 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1455 1456 // Gross hack for now: we know this file doesn't contain any 1457 // code, so don't dexopt it to avoid the resulting log spew. 1458 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1459 1460 // Gross hack for now: we know this file is only part of 1461 // the boot class path for art, so don't dexopt it to 1462 // avoid the resulting log spew. 1463 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1464 1465 /** 1466 * And there are a number of commands implemented in Java, which 1467 * we currently need to do the dexopt on so that they can be 1468 * run from a non-root shell. 1469 */ 1470 String[] frameworkFiles = frameworkDir.list(); 1471 if (frameworkFiles != null) { 1472 // TODO: We could compile these only for the most preferred ABI. We should 1473 // first double check that the dex files for these commands are not referenced 1474 // by other system apps. 1475 for (String instructionSet : instructionSets) { 1476 for (int i=0; i<frameworkFiles.length; i++) { 1477 File libPath = new File(frameworkDir, frameworkFiles[i]); 1478 String path = libPath.getPath(); 1479 // Skip the file if we already did it. 1480 if (alreadyDexOpted.contains(path)) { 1481 continue; 1482 } 1483 // Skip the file if it is not a type we want to dexopt. 1484 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1485 continue; 1486 } 1487 try { 1488 if (DexFile.isDexOptNeededInternal(path, null, instructionSet, false)) { 1489 mInstaller.dexopt(path, Process.SYSTEM_UID, true, instructionSet); 1490 didDexOptLibraryOrTool = true; 1491 } 1492 } catch (FileNotFoundException e) { 1493 Slog.w(TAG, "Jar not found: " + path); 1494 } catch (IOException e) { 1495 Slog.w(TAG, "Exception reading jar: " + path, e); 1496 } 1497 } 1498 } 1499 } 1500 1501 if (didDexOptLibraryOrTool) { 1502 // If we dexopted a library or tool, then something on the system has 1503 // changed. Consider this significant, and wipe away all other 1504 // existing dexopt files to ensure we don't leave any dangling around. 1505 // 1506 // TODO: This should be revisited because it isn't as good an indicator 1507 // as it used to be. It used to include the boot classpath but at some point 1508 // DexFile.isDexOptNeeded started returning false for the boot 1509 // class path files in all cases. It is very possible in a 1510 // small maintenance release update that the library and tool 1511 // jars may be unchanged but APK could be removed resulting in 1512 // unused dalvik-cache files. 1513 for (String instructionSet : instructionSets) { 1514 mInstaller.pruneDexCache(instructionSet); 1515 } 1516 1517 // Additionally, delete all dex files from the root directory 1518 // since there shouldn't be any there anyway, unless we're upgrading 1519 // from an older OS version or a build that contained the "old" style 1520 // flat scheme. 1521 mInstaller.pruneDexCache("."); 1522 } 1523 1524 // Collect vendor overlay packages. 1525 // (Do this before scanning any apps.) 1526 // For security and version matching reason, only consider 1527 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1528 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1529 mVendorOverlayInstallObserver = new AppDirObserver( 1530 vendorOverlayDir.getPath(), OBSERVER_EVENTS, true, false); 1531 mVendorOverlayInstallObserver.startWatching(); 1532 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1533 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode | SCAN_TRUSTED_OVERLAY, 0); 1534 1535 // Find base frameworks (resource packages without code). 1536 mFrameworkInstallObserver = new AppDirObserver( 1537 frameworkDir.getPath(), OBSERVER_EVENTS, true, false); 1538 mFrameworkInstallObserver.startWatching(); 1539 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1540 | PackageParser.PARSE_IS_SYSTEM_DIR 1541 | PackageParser.PARSE_IS_PRIVILEGED, 1542 scanMode | SCAN_NO_DEX, 0); 1543 1544 // Collected privileged system packages. 1545 File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1546 mPrivilegedInstallObserver = new AppDirObserver( 1547 privilegedAppDir.getPath(), OBSERVER_EVENTS, true, true); 1548 mPrivilegedInstallObserver.startWatching(); 1549 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1550 | PackageParser.PARSE_IS_SYSTEM_DIR 1551 | PackageParser.PARSE_IS_PRIVILEGED, scanMode, 0); 1552 1553 // Collect ordinary system packages. 1554 File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1555 mSystemInstallObserver = new AppDirObserver( 1556 systemAppDir.getPath(), OBSERVER_EVENTS, true, false); 1557 mSystemInstallObserver.startWatching(); 1558 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1559 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1560 1561 // Collect all vendor packages. 1562 File vendorAppDir = new File("/vendor/app"); 1563 try { 1564 vendorAppDir = vendorAppDir.getCanonicalFile(); 1565 } catch (IOException e) { 1566 // failed to look up canonical path, continue with original one 1567 } 1568 mVendorInstallObserver = new AppDirObserver( 1569 vendorAppDir.getPath(), OBSERVER_EVENTS, true, false); 1570 mVendorInstallObserver.startWatching(); 1571 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1572 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1573 1574 // Collect all OEM packages. 1575 File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1576 mOemInstallObserver = new AppDirObserver( 1577 oemAppDir.getPath(), OBSERVER_EVENTS, true, false); 1578 mOemInstallObserver.startWatching(); 1579 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1580 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1581 1582 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1583 mInstaller.moveFiles(); 1584 1585 // Prune any system packages that no longer exist. 1586 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1587 if (!mOnlyCore) { 1588 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1589 while (psit.hasNext()) { 1590 PackageSetting ps = psit.next(); 1591 1592 /* 1593 * If this is not a system app, it can't be a 1594 * disable system app. 1595 */ 1596 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1597 continue; 1598 } 1599 1600 /* 1601 * If the package is scanned, it's not erased. 1602 */ 1603 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1604 if (scannedPkg != null) { 1605 /* 1606 * If the system app is both scanned and in the 1607 * disabled packages list, then it must have been 1608 * added via OTA. Remove it from the currently 1609 * scanned package so the previously user-installed 1610 * application can be scanned. 1611 */ 1612 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1613 Slog.i(TAG, "Expecting better updatd system app for " + ps.name 1614 + "; removing system app"); 1615 removePackageLI(ps, true); 1616 } 1617 1618 continue; 1619 } 1620 1621 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1622 psit.remove(); 1623 String msg = "System package " + ps.name 1624 + " no longer exists; wiping its data"; 1625 reportSettingsProblem(Log.WARN, msg); 1626 removeDataDirsLI(ps.name); 1627 } else { 1628 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1629 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1630 possiblyDeletedUpdatedSystemApps.add(ps.name); 1631 } 1632 } 1633 } 1634 } 1635 1636 //look for any incomplete package installations 1637 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1638 //clean up list 1639 for(int i = 0; i < deletePkgsList.size(); i++) { 1640 //clean up here 1641 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1642 } 1643 //delete tmp files 1644 deleteTempPackageFiles(); 1645 1646 // Remove any shared userIDs that have no associated packages 1647 mSettings.pruneSharedUsersLPw(); 1648 1649 if (!mOnlyCore) { 1650 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 1651 SystemClock.uptimeMillis()); 1652 mAppInstallObserver = new AppDirObserver( 1653 mAppInstallDir.getPath(), OBSERVER_EVENTS, false, false); 1654 mAppInstallObserver.startWatching(); 1655 scanDirLI(mAppInstallDir, 0, scanMode, 0); 1656 1657 mDrmAppInstallObserver = new AppDirObserver( 1658 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false, false); 1659 mDrmAppInstallObserver.startWatching(); 1660 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 1661 scanMode, 0); 1662 1663 /** 1664 * Remove disable package settings for any updated system 1665 * apps that were removed via an OTA. If they're not a 1666 * previously-updated app, remove them completely. 1667 * Otherwise, just revoke their system-level permissions. 1668 */ 1669 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 1670 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 1671 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 1672 1673 String msg; 1674 if (deletedPkg == null) { 1675 msg = "Updated system package " + deletedAppName 1676 + " no longer exists; wiping its data"; 1677 removeDataDirsLI(deletedAppName); 1678 } else { 1679 msg = "Updated system app + " + deletedAppName 1680 + " no longer present; removing system privileges for " 1681 + deletedAppName; 1682 1683 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 1684 1685 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 1686 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 1687 } 1688 reportSettingsProblem(Log.WARN, msg); 1689 } 1690 } else { 1691 mAppInstallObserver = null; 1692 mDrmAppInstallObserver = null; 1693 } 1694 1695 // Now that we know all of the shared libraries, update all clients to have 1696 // the correct library paths. 1697 updateAllSharedLibrariesLPw(); 1698 1699 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 1700 // NOTE: We ignore potential failures here during a system scan (like 1701 // the rest of the commands above) because there's precious little we 1702 // can do about it. A settings error is reported, though. 1703 adjustCpuAbisForSharedUserLPw(setting.packages, null, 1704 false /* force dexopt */, false /* defer dexopt */); 1705 } 1706 1707 // Now that we know all the packages we are keeping, 1708 // read and update their last usage times. 1709 mPackageUsage.readLP(); 1710 1711 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 1712 SystemClock.uptimeMillis()); 1713 Slog.i(TAG, "Time to scan packages: " 1714 + ((SystemClock.uptimeMillis()-startTime)/1000f) 1715 + " seconds"); 1716 1717 // If the platform SDK has changed since the last time we booted, 1718 // we need to re-grant app permission to catch any new ones that 1719 // appear. This is really a hack, and means that apps can in some 1720 // cases get permissions that the user didn't initially explicitly 1721 // allow... it would be nice to have some better way to handle 1722 // this situation. 1723 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 1724 != mSdkVersion; 1725 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 1726 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 1727 + "; regranting permissions for internal storage"); 1728 mSettings.mInternalSdkPlatform = mSdkVersion; 1729 1730 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 1731 | (regrantPermissions 1732 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 1733 : 0)); 1734 1735 // If this is the first boot, and it is a normal boot, then 1736 // we need to initialize the default preferred apps. 1737 if (!mRestoredSettings && !onlyCore) { 1738 mSettings.readDefaultPreferredAppsLPw(this, 0); 1739 } 1740 1741 // All the changes are done during package scanning. 1742 mSettings.updateInternalDatabaseVersion(); 1743 1744 // can downgrade to reader 1745 mSettings.writeLPr(); 1746 1747 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 1748 SystemClock.uptimeMillis()); 1749 1750 1751 mRequiredVerifierPackage = getRequiredVerifierLPr(); 1752 } // synchronized (mPackages) 1753 } // synchronized (mInstallLock) 1754 1755 mInstallerService = new PackageInstallerService(context, this, mAppInstallDir); 1756 1757 // Now after opening every single application zip, make sure they 1758 // are all flushed. Not really needed, but keeps things nice and 1759 // tidy. 1760 Runtime.getRuntime().gc(); 1761 } 1762 1763 @Override 1764 public boolean isFirstBoot() { 1765 return !mRestoredSettings; 1766 } 1767 1768 @Override 1769 public boolean isOnlyCoreApps() { 1770 return mOnlyCore; 1771 } 1772 1773 private String getRequiredVerifierLPr() { 1774 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 1775 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 1776 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 1777 1778 String requiredVerifier = null; 1779 1780 final int N = receivers.size(); 1781 for (int i = 0; i < N; i++) { 1782 final ResolveInfo info = receivers.get(i); 1783 1784 if (info.activityInfo == null) { 1785 continue; 1786 } 1787 1788 final String packageName = info.activityInfo.packageName; 1789 1790 final PackageSetting ps = mSettings.mPackages.get(packageName); 1791 if (ps == null) { 1792 continue; 1793 } 1794 1795 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1796 if (!gp.grantedPermissions 1797 .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) { 1798 continue; 1799 } 1800 1801 if (requiredVerifier != null) { 1802 throw new RuntimeException("There can be only one required verifier"); 1803 } 1804 1805 requiredVerifier = packageName; 1806 } 1807 1808 return requiredVerifier; 1809 } 1810 1811 @Override 1812 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 1813 throws RemoteException { 1814 try { 1815 return super.onTransact(code, data, reply, flags); 1816 } catch (RuntimeException e) { 1817 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 1818 Slog.wtf(TAG, "Package Manager Crash", e); 1819 } 1820 throw e; 1821 } 1822 } 1823 1824 void cleanupInstallFailedPackage(PackageSetting ps) { 1825 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name); 1826 removeDataDirsLI(ps.name); 1827 1828 // TODO: try cleaning up codePath directory contents first, since it 1829 // might be a cluster 1830 1831 if (ps.codePath != null) { 1832 if (!ps.codePath.delete()) { 1833 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath); 1834 } 1835 } 1836 if (ps.resourcePath != null) { 1837 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) { 1838 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath); 1839 } 1840 } 1841 mSettings.removePackageLPw(ps.name); 1842 } 1843 1844 static int[] appendInts(int[] cur, int[] add) { 1845 if (add == null) return cur; 1846 if (cur == null) return add; 1847 final int N = add.length; 1848 for (int i=0; i<N; i++) { 1849 cur = appendInt(cur, add[i]); 1850 } 1851 return cur; 1852 } 1853 1854 static int[] removeInts(int[] cur, int[] rem) { 1855 if (rem == null) return cur; 1856 if (cur == null) return cur; 1857 final int N = rem.length; 1858 for (int i=0; i<N; i++) { 1859 cur = removeInt(cur, rem[i]); 1860 } 1861 return cur; 1862 } 1863 1864 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 1865 if (!sUserManager.exists(userId)) return null; 1866 final PackageSetting ps = (PackageSetting) p.mExtras; 1867 if (ps == null) { 1868 return null; 1869 } 1870 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1871 final PackageUserState state = ps.readUserState(userId); 1872 return PackageParser.generatePackageInfo(p, gp.gids, flags, 1873 ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions, 1874 state, userId); 1875 } 1876 1877 @Override 1878 public boolean isPackageAvailable(String packageName, int userId) { 1879 if (!sUserManager.exists(userId)) return false; 1880 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available"); 1881 synchronized (mPackages) { 1882 PackageParser.Package p = mPackages.get(packageName); 1883 if (p != null) { 1884 final PackageSetting ps = (PackageSetting) p.mExtras; 1885 if (ps != null) { 1886 final PackageUserState state = ps.readUserState(userId); 1887 if (state != null) { 1888 return PackageParser.isAvailable(state); 1889 } 1890 } 1891 } 1892 } 1893 return false; 1894 } 1895 1896 @Override 1897 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 1898 if (!sUserManager.exists(userId)) return null; 1899 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info"); 1900 // reader 1901 synchronized (mPackages) { 1902 PackageParser.Package p = mPackages.get(packageName); 1903 if (DEBUG_PACKAGE_INFO) 1904 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 1905 if (p != null) { 1906 return generatePackageInfo(p, flags, userId); 1907 } 1908 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 1909 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 1910 } 1911 } 1912 return null; 1913 } 1914 1915 @Override 1916 public String[] currentToCanonicalPackageNames(String[] names) { 1917 String[] out = new String[names.length]; 1918 // reader 1919 synchronized (mPackages) { 1920 for (int i=names.length-1; i>=0; i--) { 1921 PackageSetting ps = mSettings.mPackages.get(names[i]); 1922 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 1923 } 1924 } 1925 return out; 1926 } 1927 1928 @Override 1929 public String[] canonicalToCurrentPackageNames(String[] names) { 1930 String[] out = new String[names.length]; 1931 // reader 1932 synchronized (mPackages) { 1933 for (int i=names.length-1; i>=0; i--) { 1934 String cur = mSettings.mRenamedPackages.get(names[i]); 1935 out[i] = cur != null ? cur : names[i]; 1936 } 1937 } 1938 return out; 1939 } 1940 1941 @Override 1942 public int getPackageUid(String packageName, int userId) { 1943 if (!sUserManager.exists(userId)) return -1; 1944 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid"); 1945 // reader 1946 synchronized (mPackages) { 1947 PackageParser.Package p = mPackages.get(packageName); 1948 if(p != null) { 1949 return UserHandle.getUid(userId, p.applicationInfo.uid); 1950 } 1951 PackageSetting ps = mSettings.mPackages.get(packageName); 1952 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 1953 return -1; 1954 } 1955 p = ps.pkg; 1956 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 1957 } 1958 } 1959 1960 @Override 1961 public int[] getPackageGids(String packageName) { 1962 // reader 1963 synchronized (mPackages) { 1964 PackageParser.Package p = mPackages.get(packageName); 1965 if (DEBUG_PACKAGE_INFO) 1966 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 1967 if (p != null) { 1968 final PackageSetting ps = (PackageSetting)p.mExtras; 1969 return ps.getGids(); 1970 } 1971 } 1972 // stupid thing to indicate an error. 1973 return new int[0]; 1974 } 1975 1976 static final PermissionInfo generatePermissionInfo( 1977 BasePermission bp, int flags) { 1978 if (bp.perm != null) { 1979 return PackageParser.generatePermissionInfo(bp.perm, flags); 1980 } 1981 PermissionInfo pi = new PermissionInfo(); 1982 pi.name = bp.name; 1983 pi.packageName = bp.sourcePackage; 1984 pi.nonLocalizedLabel = bp.name; 1985 pi.protectionLevel = bp.protectionLevel; 1986 return pi; 1987 } 1988 1989 @Override 1990 public PermissionInfo getPermissionInfo(String name, int flags) { 1991 // reader 1992 synchronized (mPackages) { 1993 final BasePermission p = mSettings.mPermissions.get(name); 1994 if (p != null) { 1995 return generatePermissionInfo(p, flags); 1996 } 1997 return null; 1998 } 1999 } 2000 2001 @Override 2002 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2003 // reader 2004 synchronized (mPackages) { 2005 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2006 for (BasePermission p : mSettings.mPermissions.values()) { 2007 if (group == null) { 2008 if (p.perm == null || p.perm.info.group == null) { 2009 out.add(generatePermissionInfo(p, flags)); 2010 } 2011 } else { 2012 if (p.perm != null && group.equals(p.perm.info.group)) { 2013 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2014 } 2015 } 2016 } 2017 2018 if (out.size() > 0) { 2019 return out; 2020 } 2021 return mPermissionGroups.containsKey(group) ? out : null; 2022 } 2023 } 2024 2025 @Override 2026 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2027 // reader 2028 synchronized (mPackages) { 2029 return PackageParser.generatePermissionGroupInfo( 2030 mPermissionGroups.get(name), flags); 2031 } 2032 } 2033 2034 @Override 2035 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2036 // reader 2037 synchronized (mPackages) { 2038 final int N = mPermissionGroups.size(); 2039 ArrayList<PermissionGroupInfo> out 2040 = new ArrayList<PermissionGroupInfo>(N); 2041 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2042 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2043 } 2044 return out; 2045 } 2046 } 2047 2048 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2049 int userId) { 2050 if (!sUserManager.exists(userId)) return null; 2051 PackageSetting ps = mSettings.mPackages.get(packageName); 2052 if (ps != null) { 2053 if (ps.pkg == null) { 2054 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2055 flags, userId); 2056 if (pInfo != null) { 2057 return pInfo.applicationInfo; 2058 } 2059 return null; 2060 } 2061 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2062 ps.readUserState(userId), userId); 2063 } 2064 return null; 2065 } 2066 2067 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2068 int userId) { 2069 if (!sUserManager.exists(userId)) return null; 2070 PackageSetting ps = mSettings.mPackages.get(packageName); 2071 if (ps != null) { 2072 PackageParser.Package pkg = ps.pkg; 2073 if (pkg == null) { 2074 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2075 return null; 2076 } 2077 // Only data remains, so we aren't worried about code paths 2078 pkg = new PackageParser.Package(packageName); 2079 pkg.applicationInfo.packageName = packageName; 2080 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2081 pkg.applicationInfo.dataDir = 2082 getDataPathForPackage(packageName, 0).getPath(); 2083 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2084 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2085 } 2086 return generatePackageInfo(pkg, flags, userId); 2087 } 2088 return null; 2089 } 2090 2091 @Override 2092 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2093 if (!sUserManager.exists(userId)) return null; 2094 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info"); 2095 // writer 2096 synchronized (mPackages) { 2097 PackageParser.Package p = mPackages.get(packageName); 2098 if (DEBUG_PACKAGE_INFO) Log.v( 2099 TAG, "getApplicationInfo " + packageName 2100 + ": " + p); 2101 if (p != null) { 2102 PackageSetting ps = mSettings.mPackages.get(packageName); 2103 if (ps == null) return null; 2104 // Note: isEnabledLP() does not apply here - always return info 2105 return PackageParser.generateApplicationInfo( 2106 p, flags, ps.readUserState(userId), userId); 2107 } 2108 if ("android".equals(packageName)||"system".equals(packageName)) { 2109 return mAndroidApplication; 2110 } 2111 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2112 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2113 } 2114 } 2115 return null; 2116 } 2117 2118 2119 @Override 2120 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2121 mContext.enforceCallingOrSelfPermission( 2122 android.Manifest.permission.CLEAR_APP_CACHE, null); 2123 // Queue up an async operation since clearing cache may take a little while. 2124 mHandler.post(new Runnable() { 2125 public void run() { 2126 mHandler.removeCallbacks(this); 2127 int retCode = -1; 2128 synchronized (mInstallLock) { 2129 retCode = mInstaller.freeCache(freeStorageSize); 2130 if (retCode < 0) { 2131 Slog.w(TAG, "Couldn't clear application caches"); 2132 } 2133 } 2134 if (observer != null) { 2135 try { 2136 observer.onRemoveCompleted(null, (retCode >= 0)); 2137 } catch (RemoteException e) { 2138 Slog.w(TAG, "RemoveException when invoking call back"); 2139 } 2140 } 2141 } 2142 }); 2143 } 2144 2145 @Override 2146 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2147 mContext.enforceCallingOrSelfPermission( 2148 android.Manifest.permission.CLEAR_APP_CACHE, null); 2149 // Queue up an async operation since clearing cache may take a little while. 2150 mHandler.post(new Runnable() { 2151 public void run() { 2152 mHandler.removeCallbacks(this); 2153 int retCode = -1; 2154 synchronized (mInstallLock) { 2155 retCode = mInstaller.freeCache(freeStorageSize); 2156 if (retCode < 0) { 2157 Slog.w(TAG, "Couldn't clear application caches"); 2158 } 2159 } 2160 if(pi != null) { 2161 try { 2162 // Callback via pending intent 2163 int code = (retCode >= 0) ? 1 : 0; 2164 pi.sendIntent(null, code, null, 2165 null, null); 2166 } catch (SendIntentException e1) { 2167 Slog.i(TAG, "Failed to send pending intent"); 2168 } 2169 } 2170 } 2171 }); 2172 } 2173 2174 void freeStorage(long freeStorageSize) throws IOException { 2175 synchronized (mInstallLock) { 2176 if (mInstaller.freeCache(freeStorageSize) < 0) { 2177 throw new IOException("Failed to free enough space"); 2178 } 2179 } 2180 } 2181 2182 @Override 2183 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2184 if (!sUserManager.exists(userId)) return null; 2185 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info"); 2186 synchronized (mPackages) { 2187 PackageParser.Activity a = mActivities.mActivities.get(component); 2188 2189 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2190 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2191 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2192 if (ps == null) return null; 2193 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2194 userId); 2195 } 2196 if (mResolveComponentName.equals(component)) { 2197 return mResolveActivity; 2198 } 2199 } 2200 return null; 2201 } 2202 2203 @Override 2204 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2205 String resolvedType) { 2206 synchronized (mPackages) { 2207 PackageParser.Activity a = mActivities.mActivities.get(component); 2208 if (a == null) { 2209 return false; 2210 } 2211 for (int i=0; i<a.intents.size(); i++) { 2212 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2213 intent.getData(), intent.getCategories(), TAG) >= 0) { 2214 return true; 2215 } 2216 } 2217 return false; 2218 } 2219 } 2220 2221 @Override 2222 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2223 if (!sUserManager.exists(userId)) return null; 2224 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info"); 2225 synchronized (mPackages) { 2226 PackageParser.Activity a = mReceivers.mActivities.get(component); 2227 if (DEBUG_PACKAGE_INFO) Log.v( 2228 TAG, "getReceiverInfo " + component + ": " + a); 2229 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2230 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2231 if (ps == null) return null; 2232 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2233 userId); 2234 } 2235 } 2236 return null; 2237 } 2238 2239 @Override 2240 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2241 if (!sUserManager.exists(userId)) return null; 2242 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info"); 2243 synchronized (mPackages) { 2244 PackageParser.Service s = mServices.mServices.get(component); 2245 if (DEBUG_PACKAGE_INFO) Log.v( 2246 TAG, "getServiceInfo " + component + ": " + s); 2247 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2248 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2249 if (ps == null) return null; 2250 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2251 userId); 2252 } 2253 } 2254 return null; 2255 } 2256 2257 @Override 2258 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2259 if (!sUserManager.exists(userId)) return null; 2260 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info"); 2261 synchronized (mPackages) { 2262 PackageParser.Provider p = mProviders.mProviders.get(component); 2263 if (DEBUG_PACKAGE_INFO) Log.v( 2264 TAG, "getProviderInfo " + component + ": " + p); 2265 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2266 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2267 if (ps == null) return null; 2268 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2269 userId); 2270 } 2271 } 2272 return null; 2273 } 2274 2275 @Override 2276 public String[] getSystemSharedLibraryNames() { 2277 Set<String> libSet; 2278 synchronized (mPackages) { 2279 libSet = mSharedLibraries.keySet(); 2280 int size = libSet.size(); 2281 if (size > 0) { 2282 String[] libs = new String[size]; 2283 libSet.toArray(libs); 2284 return libs; 2285 } 2286 } 2287 return null; 2288 } 2289 2290 @Override 2291 public FeatureInfo[] getSystemAvailableFeatures() { 2292 Collection<FeatureInfo> featSet; 2293 synchronized (mPackages) { 2294 featSet = mAvailableFeatures.values(); 2295 int size = featSet.size(); 2296 if (size > 0) { 2297 FeatureInfo[] features = new FeatureInfo[size+1]; 2298 featSet.toArray(features); 2299 FeatureInfo fi = new FeatureInfo(); 2300 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2301 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2302 features[size] = fi; 2303 return features; 2304 } 2305 } 2306 return null; 2307 } 2308 2309 @Override 2310 public boolean hasSystemFeature(String name) { 2311 synchronized (mPackages) { 2312 return mAvailableFeatures.containsKey(name); 2313 } 2314 } 2315 2316 private void checkValidCaller(int uid, int userId) { 2317 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2318 return; 2319 2320 throw new SecurityException("Caller uid=" + uid 2321 + " is not privileged to communicate with user=" + userId); 2322 } 2323 2324 @Override 2325 public int checkPermission(String permName, String pkgName) { 2326 synchronized (mPackages) { 2327 PackageParser.Package p = mPackages.get(pkgName); 2328 if (p != null && p.mExtras != null) { 2329 PackageSetting ps = (PackageSetting)p.mExtras; 2330 if (ps.sharedUser != null) { 2331 if (ps.sharedUser.grantedPermissions.contains(permName)) { 2332 return PackageManager.PERMISSION_GRANTED; 2333 } 2334 } else if (ps.grantedPermissions.contains(permName)) { 2335 return PackageManager.PERMISSION_GRANTED; 2336 } 2337 } 2338 } 2339 return PackageManager.PERMISSION_DENIED; 2340 } 2341 2342 @Override 2343 public int checkUidPermission(String permName, int uid) { 2344 synchronized (mPackages) { 2345 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2346 if (obj != null) { 2347 GrantedPermissions gp = (GrantedPermissions)obj; 2348 if (gp.grantedPermissions.contains(permName)) { 2349 return PackageManager.PERMISSION_GRANTED; 2350 } 2351 } else { 2352 HashSet<String> perms = mSystemPermissions.get(uid); 2353 if (perms != null && perms.contains(permName)) { 2354 return PackageManager.PERMISSION_GRANTED; 2355 } 2356 } 2357 } 2358 return PackageManager.PERMISSION_DENIED; 2359 } 2360 2361 /** 2362 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2363 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2364 * @param message the message to log on security exception 2365 */ 2366 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2367 String message) { 2368 if (userId < 0) { 2369 throw new IllegalArgumentException("Invalid userId " + userId); 2370 } 2371 if (userId == UserHandle.getUserId(callingUid)) return; 2372 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2373 if (requireFullPermission) { 2374 mContext.enforceCallingOrSelfPermission( 2375 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2376 } else { 2377 try { 2378 mContext.enforceCallingOrSelfPermission( 2379 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2380 } catch (SecurityException se) { 2381 mContext.enforceCallingOrSelfPermission( 2382 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2383 } 2384 } 2385 } 2386 } 2387 2388 private BasePermission findPermissionTreeLP(String permName) { 2389 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2390 if (permName.startsWith(bp.name) && 2391 permName.length() > bp.name.length() && 2392 permName.charAt(bp.name.length()) == '.') { 2393 return bp; 2394 } 2395 } 2396 return null; 2397 } 2398 2399 private BasePermission checkPermissionTreeLP(String permName) { 2400 if (permName != null) { 2401 BasePermission bp = findPermissionTreeLP(permName); 2402 if (bp != null) { 2403 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2404 return bp; 2405 } 2406 throw new SecurityException("Calling uid " 2407 + Binder.getCallingUid() 2408 + " is not allowed to add to permission tree " 2409 + bp.name + " owned by uid " + bp.uid); 2410 } 2411 } 2412 throw new SecurityException("No permission tree found for " + permName); 2413 } 2414 2415 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2416 if (s1 == null) { 2417 return s2 == null; 2418 } 2419 if (s2 == null) { 2420 return false; 2421 } 2422 if (s1.getClass() != s2.getClass()) { 2423 return false; 2424 } 2425 return s1.equals(s2); 2426 } 2427 2428 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2429 if (pi1.icon != pi2.icon) return false; 2430 if (pi1.logo != pi2.logo) return false; 2431 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2432 if (!compareStrings(pi1.name, pi2.name)) return false; 2433 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2434 // We'll take care of setting this one. 2435 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2436 // These are not currently stored in settings. 2437 //if (!compareStrings(pi1.group, pi2.group)) return false; 2438 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2439 //if (pi1.labelRes != pi2.labelRes) return false; 2440 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2441 return true; 2442 } 2443 2444 int permissionInfoFootprint(PermissionInfo info) { 2445 int size = info.name.length(); 2446 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2447 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2448 return size; 2449 } 2450 2451 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2452 int size = 0; 2453 for (BasePermission perm : mSettings.mPermissions.values()) { 2454 if (perm.uid == tree.uid) { 2455 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2456 } 2457 } 2458 return size; 2459 } 2460 2461 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2462 // We calculate the max size of permissions defined by this uid and throw 2463 // if that plus the size of 'info' would exceed our stated maximum. 2464 if (tree.uid != Process.SYSTEM_UID) { 2465 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2466 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2467 throw new SecurityException("Permission tree size cap exceeded"); 2468 } 2469 } 2470 } 2471 2472 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2473 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2474 throw new SecurityException("Label must be specified in permission"); 2475 } 2476 BasePermission tree = checkPermissionTreeLP(info.name); 2477 BasePermission bp = mSettings.mPermissions.get(info.name); 2478 boolean added = bp == null; 2479 boolean changed = true; 2480 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2481 if (added) { 2482 enforcePermissionCapLocked(info, tree); 2483 bp = new BasePermission(info.name, tree.sourcePackage, 2484 BasePermission.TYPE_DYNAMIC); 2485 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2486 throw new SecurityException( 2487 "Not allowed to modify non-dynamic permission " 2488 + info.name); 2489 } else { 2490 if (bp.protectionLevel == fixedLevel 2491 && bp.perm.owner.equals(tree.perm.owner) 2492 && bp.uid == tree.uid 2493 && comparePermissionInfos(bp.perm.info, info)) { 2494 changed = false; 2495 } 2496 } 2497 bp.protectionLevel = fixedLevel; 2498 info = new PermissionInfo(info); 2499 info.protectionLevel = fixedLevel; 2500 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 2501 bp.perm.info.packageName = tree.perm.info.packageName; 2502 bp.uid = tree.uid; 2503 if (added) { 2504 mSettings.mPermissions.put(info.name, bp); 2505 } 2506 if (changed) { 2507 if (!async) { 2508 mSettings.writeLPr(); 2509 } else { 2510 scheduleWriteSettingsLocked(); 2511 } 2512 } 2513 return added; 2514 } 2515 2516 @Override 2517 public boolean addPermission(PermissionInfo info) { 2518 synchronized (mPackages) { 2519 return addPermissionLocked(info, false); 2520 } 2521 } 2522 2523 @Override 2524 public boolean addPermissionAsync(PermissionInfo info) { 2525 synchronized (mPackages) { 2526 return addPermissionLocked(info, true); 2527 } 2528 } 2529 2530 @Override 2531 public void removePermission(String name) { 2532 synchronized (mPackages) { 2533 checkPermissionTreeLP(name); 2534 BasePermission bp = mSettings.mPermissions.get(name); 2535 if (bp != null) { 2536 if (bp.type != BasePermission.TYPE_DYNAMIC) { 2537 throw new SecurityException( 2538 "Not allowed to modify non-dynamic permission " 2539 + name); 2540 } 2541 mSettings.mPermissions.remove(name); 2542 mSettings.writeLPr(); 2543 } 2544 } 2545 } 2546 2547 private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) { 2548 int index = pkg.requestedPermissions.indexOf(bp.name); 2549 if (index == -1) { 2550 throw new SecurityException("Package " + pkg.packageName 2551 + " has not requested permission " + bp.name); 2552 } 2553 boolean isNormal = 2554 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2555 == PermissionInfo.PROTECTION_NORMAL); 2556 boolean isDangerous = 2557 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2558 == PermissionInfo.PROTECTION_DANGEROUS); 2559 boolean isDevelopment = 2560 ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0); 2561 2562 if (!isNormal && !isDangerous && !isDevelopment) { 2563 throw new SecurityException("Permission " + bp.name 2564 + " is not a changeable permission type"); 2565 } 2566 2567 if (isNormal || isDangerous) { 2568 if (pkg.requestedPermissionsRequired.get(index)) { 2569 throw new SecurityException("Can't change " + bp.name 2570 + ". It is required by the application"); 2571 } 2572 } 2573 } 2574 2575 @Override 2576 public void grantPermission(String packageName, String permissionName) { 2577 mContext.enforceCallingOrSelfPermission( 2578 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2579 synchronized (mPackages) { 2580 final PackageParser.Package pkg = mPackages.get(packageName); 2581 if (pkg == null) { 2582 throw new IllegalArgumentException("Unknown package: " + packageName); 2583 } 2584 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2585 if (bp == null) { 2586 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2587 } 2588 2589 checkGrantRevokePermissions(pkg, bp); 2590 2591 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2592 if (ps == null) { 2593 return; 2594 } 2595 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2596 if (gp.grantedPermissions.add(permissionName)) { 2597 if (ps.haveGids) { 2598 gp.gids = appendInts(gp.gids, bp.gids); 2599 } 2600 mSettings.writeLPr(); 2601 } 2602 } 2603 } 2604 2605 @Override 2606 public void revokePermission(String packageName, String permissionName) { 2607 int changedAppId = -1; 2608 2609 synchronized (mPackages) { 2610 final PackageParser.Package pkg = mPackages.get(packageName); 2611 if (pkg == null) { 2612 throw new IllegalArgumentException("Unknown package: " + packageName); 2613 } 2614 if (pkg.applicationInfo.uid != Binder.getCallingUid()) { 2615 mContext.enforceCallingOrSelfPermission( 2616 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2617 } 2618 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2619 if (bp == null) { 2620 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2621 } 2622 2623 checkGrantRevokePermissions(pkg, bp); 2624 2625 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2626 if (ps == null) { 2627 return; 2628 } 2629 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2630 if (gp.grantedPermissions.remove(permissionName)) { 2631 gp.grantedPermissions.remove(permissionName); 2632 if (ps.haveGids) { 2633 gp.gids = removeInts(gp.gids, bp.gids); 2634 } 2635 mSettings.writeLPr(); 2636 changedAppId = ps.appId; 2637 } 2638 } 2639 2640 if (changedAppId >= 0) { 2641 // We changed the perm on someone, kill its processes. 2642 IActivityManager am = ActivityManagerNative.getDefault(); 2643 if (am != null) { 2644 final int callingUserId = UserHandle.getCallingUserId(); 2645 final long ident = Binder.clearCallingIdentity(); 2646 try { 2647 //XXX we should only revoke for the calling user's app permissions, 2648 // but for now we impact all users. 2649 //am.killUid(UserHandle.getUid(callingUserId, changedAppId), 2650 // "revoke " + permissionName); 2651 int[] users = sUserManager.getUserIds(); 2652 for (int user : users) { 2653 am.killUid(UserHandle.getUid(user, changedAppId), 2654 "revoke " + permissionName); 2655 } 2656 } catch (RemoteException e) { 2657 } finally { 2658 Binder.restoreCallingIdentity(ident); 2659 } 2660 } 2661 } 2662 } 2663 2664 @Override 2665 public boolean isProtectedBroadcast(String actionName) { 2666 synchronized (mPackages) { 2667 return mProtectedBroadcasts.contains(actionName); 2668 } 2669 } 2670 2671 @Override 2672 public int checkSignatures(String pkg1, String pkg2) { 2673 synchronized (mPackages) { 2674 final PackageParser.Package p1 = mPackages.get(pkg1); 2675 final PackageParser.Package p2 = mPackages.get(pkg2); 2676 if (p1 == null || p1.mExtras == null 2677 || p2 == null || p2.mExtras == null) { 2678 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2679 } 2680 return compareSignatures(p1.mSignatures, p2.mSignatures); 2681 } 2682 } 2683 2684 @Override 2685 public int checkUidSignatures(int uid1, int uid2) { 2686 // Map to base uids. 2687 uid1 = UserHandle.getAppId(uid1); 2688 uid2 = UserHandle.getAppId(uid2); 2689 // reader 2690 synchronized (mPackages) { 2691 Signature[] s1; 2692 Signature[] s2; 2693 Object obj = mSettings.getUserIdLPr(uid1); 2694 if (obj != null) { 2695 if (obj instanceof SharedUserSetting) { 2696 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 2697 } else if (obj instanceof PackageSetting) { 2698 s1 = ((PackageSetting)obj).signatures.mSignatures; 2699 } else { 2700 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2701 } 2702 } else { 2703 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2704 } 2705 obj = mSettings.getUserIdLPr(uid2); 2706 if (obj != null) { 2707 if (obj instanceof SharedUserSetting) { 2708 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 2709 } else if (obj instanceof PackageSetting) { 2710 s2 = ((PackageSetting)obj).signatures.mSignatures; 2711 } else { 2712 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2713 } 2714 } else { 2715 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2716 } 2717 return compareSignatures(s1, s2); 2718 } 2719 } 2720 2721 /** 2722 * Compares two sets of signatures. Returns: 2723 * <br /> 2724 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 2725 * <br /> 2726 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 2727 * <br /> 2728 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 2729 * <br /> 2730 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 2731 * <br /> 2732 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 2733 */ 2734 static int compareSignatures(Signature[] s1, Signature[] s2) { 2735 if (s1 == null) { 2736 return s2 == null 2737 ? PackageManager.SIGNATURE_NEITHER_SIGNED 2738 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 2739 } 2740 2741 if (s2 == null) { 2742 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 2743 } 2744 2745 if (s1.length != s2.length) { 2746 return PackageManager.SIGNATURE_NO_MATCH; 2747 } 2748 2749 // Since both signature sets are of size 1, we can compare without HashSets. 2750 if (s1.length == 1) { 2751 return s1[0].equals(s2[0]) ? 2752 PackageManager.SIGNATURE_MATCH : 2753 PackageManager.SIGNATURE_NO_MATCH; 2754 } 2755 2756 HashSet<Signature> set1 = new HashSet<Signature>(); 2757 for (Signature sig : s1) { 2758 set1.add(sig); 2759 } 2760 HashSet<Signature> set2 = new HashSet<Signature>(); 2761 for (Signature sig : s2) { 2762 set2.add(sig); 2763 } 2764 // Make sure s2 contains all signatures in s1. 2765 if (set1.equals(set2)) { 2766 return PackageManager.SIGNATURE_MATCH; 2767 } 2768 return PackageManager.SIGNATURE_NO_MATCH; 2769 } 2770 2771 /** 2772 * If the database version for this type of package (internal storage or 2773 * external storage) is less than the version where package signatures 2774 * were updated, return true. 2775 */ 2776 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2777 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 2778 DatabaseVersion.SIGNATURE_END_ENTITY)) 2779 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 2780 DatabaseVersion.SIGNATURE_END_ENTITY)); 2781 } 2782 2783 /** 2784 * Used for backward compatibility to make sure any packages with 2785 * certificate chains get upgraded to the new style. {@code existingSigs} 2786 * will be in the old format (since they were stored on disk from before the 2787 * system upgrade) and {@code scannedSigs} will be in the newer format. 2788 */ 2789 private int compareSignaturesCompat(PackageSignatures existingSigs, 2790 PackageParser.Package scannedPkg) { 2791 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 2792 return PackageManager.SIGNATURE_NO_MATCH; 2793 } 2794 2795 HashSet<Signature> existingSet = new HashSet<Signature>(); 2796 for (Signature sig : existingSigs.mSignatures) { 2797 existingSet.add(sig); 2798 } 2799 HashSet<Signature> scannedCompatSet = new HashSet<Signature>(); 2800 for (Signature sig : scannedPkg.mSignatures) { 2801 try { 2802 Signature[] chainSignatures = sig.getChainSignatures(); 2803 for (Signature chainSig : chainSignatures) { 2804 scannedCompatSet.add(chainSig); 2805 } 2806 } catch (CertificateEncodingException e) { 2807 scannedCompatSet.add(sig); 2808 } 2809 } 2810 /* 2811 * Make sure the expanded scanned set contains all signatures in the 2812 * existing one. 2813 */ 2814 if (scannedCompatSet.equals(existingSet)) { 2815 // Migrate the old signatures to the new scheme. 2816 existingSigs.assignSignatures(scannedPkg.mSignatures); 2817 // The new KeySets will be re-added later in the scanning process. 2818 mSettings.mKeySetManagerService.removeAppKeySetData(scannedPkg.packageName); 2819 return PackageManager.SIGNATURE_MATCH; 2820 } 2821 return PackageManager.SIGNATURE_NO_MATCH; 2822 } 2823 2824 @Override 2825 public String[] getPackagesForUid(int uid) { 2826 uid = UserHandle.getAppId(uid); 2827 // reader 2828 synchronized (mPackages) { 2829 Object obj = mSettings.getUserIdLPr(uid); 2830 if (obj instanceof SharedUserSetting) { 2831 final SharedUserSetting sus = (SharedUserSetting) obj; 2832 final int N = sus.packages.size(); 2833 final String[] res = new String[N]; 2834 final Iterator<PackageSetting> it = sus.packages.iterator(); 2835 int i = 0; 2836 while (it.hasNext()) { 2837 res[i++] = it.next().name; 2838 } 2839 return res; 2840 } else if (obj instanceof PackageSetting) { 2841 final PackageSetting ps = (PackageSetting) obj; 2842 return new String[] { ps.name }; 2843 } 2844 } 2845 return null; 2846 } 2847 2848 @Override 2849 public String getNameForUid(int uid) { 2850 // reader 2851 synchronized (mPackages) { 2852 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2853 if (obj instanceof SharedUserSetting) { 2854 final SharedUserSetting sus = (SharedUserSetting) obj; 2855 return sus.name + ":" + sus.userId; 2856 } else if (obj instanceof PackageSetting) { 2857 final PackageSetting ps = (PackageSetting) obj; 2858 return ps.name; 2859 } 2860 } 2861 return null; 2862 } 2863 2864 @Override 2865 public int getUidForSharedUser(String sharedUserName) { 2866 if(sharedUserName == null) { 2867 return -1; 2868 } 2869 // reader 2870 synchronized (mPackages) { 2871 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false); 2872 if (suid == null) { 2873 return -1; 2874 } 2875 return suid.userId; 2876 } 2877 } 2878 2879 @Override 2880 public int getFlagsForUid(int uid) { 2881 synchronized (mPackages) { 2882 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2883 if (obj instanceof SharedUserSetting) { 2884 final SharedUserSetting sus = (SharedUserSetting) obj; 2885 return sus.pkgFlags; 2886 } else if (obj instanceof PackageSetting) { 2887 final PackageSetting ps = (PackageSetting) obj; 2888 return ps.pkgFlags; 2889 } 2890 } 2891 return 0; 2892 } 2893 2894 @Override 2895 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 2896 int flags, int userId) { 2897 if (!sUserManager.exists(userId)) return null; 2898 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent"); 2899 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2900 return chooseBestActivity(intent, resolvedType, flags, query, userId); 2901 } 2902 2903 @Override 2904 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 2905 IntentFilter filter, int match, ComponentName activity) { 2906 final int userId = UserHandle.getCallingUserId(); 2907 if (DEBUG_PREFERRED) { 2908 Log.v(TAG, "setLastChosenActivity intent=" + intent 2909 + " resolvedType=" + resolvedType 2910 + " flags=" + flags 2911 + " filter=" + filter 2912 + " match=" + match 2913 + " activity=" + activity); 2914 filter.dump(new PrintStreamPrinter(System.out), " "); 2915 } 2916 intent.setComponent(null); 2917 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2918 // Find any earlier preferred or last chosen entries and nuke them 2919 findPreferredActivity(intent, resolvedType, 2920 flags, query, 0, false, true, false, userId); 2921 // Add the new activity as the last chosen for this filter 2922 addPreferredActivityInternal(filter, match, null, activity, false, userId); 2923 } 2924 2925 @Override 2926 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 2927 final int userId = UserHandle.getCallingUserId(); 2928 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 2929 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2930 return findPreferredActivity(intent, resolvedType, flags, query, 0, 2931 false, false, false, userId); 2932 } 2933 2934 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 2935 int flags, List<ResolveInfo> query, int userId) { 2936 if (query != null) { 2937 final int N = query.size(); 2938 if (N == 1) { 2939 return query.get(0); 2940 } else if (N > 1) { 2941 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 2942 // If there is more than one activity with the same priority, 2943 // then let the user decide between them. 2944 ResolveInfo r0 = query.get(0); 2945 ResolveInfo r1 = query.get(1); 2946 if (DEBUG_INTENT_MATCHING || debug) { 2947 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 2948 + r1.activityInfo.name + "=" + r1.priority); 2949 } 2950 // If the first activity has a higher priority, or a different 2951 // default, then it is always desireable to pick it. 2952 if (r0.priority != r1.priority 2953 || r0.preferredOrder != r1.preferredOrder 2954 || r0.isDefault != r1.isDefault) { 2955 return query.get(0); 2956 } 2957 // If we have saved a preference for a preferred activity for 2958 // this Intent, use that. 2959 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 2960 flags, query, r0.priority, true, false, debug, userId); 2961 if (ri != null) { 2962 return ri; 2963 } 2964 if (userId != 0) { 2965 ri = new ResolveInfo(mResolveInfo); 2966 ri.activityInfo = new ActivityInfo(ri.activityInfo); 2967 ri.activityInfo.applicationInfo = new ApplicationInfo( 2968 ri.activityInfo.applicationInfo); 2969 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 2970 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 2971 return ri; 2972 } 2973 return mResolveInfo; 2974 } 2975 } 2976 return null; 2977 } 2978 2979 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 2980 int flags, List<ResolveInfo> query, boolean debug, int userId) { 2981 final int N = query.size(); 2982 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 2983 .get(userId); 2984 // Get the list of persistent preferred activities that handle the intent 2985 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 2986 List<PersistentPreferredActivity> pprefs = ppir != null 2987 ? ppir.queryIntent(intent, resolvedType, 2988 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 2989 : null; 2990 if (pprefs != null && pprefs.size() > 0) { 2991 final int M = pprefs.size(); 2992 for (int i=0; i<M; i++) { 2993 final PersistentPreferredActivity ppa = pprefs.get(i); 2994 if (DEBUG_PREFERRED || debug) { 2995 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 2996 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 2997 + "\n component=" + ppa.mComponent); 2998 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 2999 } 3000 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3001 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3002 if (DEBUG_PREFERRED || debug) { 3003 Slog.v(TAG, "Found persistent preferred activity:"); 3004 if (ai != null) { 3005 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3006 } else { 3007 Slog.v(TAG, " null"); 3008 } 3009 } 3010 if (ai == null) { 3011 // This previously registered persistent preferred activity 3012 // component is no longer known. Ignore it and do NOT remove it. 3013 continue; 3014 } 3015 for (int j=0; j<N; j++) { 3016 final ResolveInfo ri = query.get(j); 3017 if (!ri.activityInfo.applicationInfo.packageName 3018 .equals(ai.applicationInfo.packageName)) { 3019 continue; 3020 } 3021 if (!ri.activityInfo.name.equals(ai.name)) { 3022 continue; 3023 } 3024 // Found a persistent preference that can handle the intent. 3025 if (DEBUG_PREFERRED || debug) { 3026 Slog.v(TAG, "Returning persistent preferred activity: " + 3027 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3028 } 3029 return ri; 3030 } 3031 } 3032 } 3033 return null; 3034 } 3035 3036 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3037 List<ResolveInfo> query, int priority, boolean always, 3038 boolean removeMatches, boolean debug, int userId) { 3039 if (!sUserManager.exists(userId)) return null; 3040 // writer 3041 synchronized (mPackages) { 3042 if (intent.getSelector() != null) { 3043 intent = intent.getSelector(); 3044 } 3045 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3046 3047 // Try to find a matching persistent preferred activity. 3048 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3049 debug, userId); 3050 3051 // If a persistent preferred activity matched, use it. 3052 if (pri != null) { 3053 return pri; 3054 } 3055 3056 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3057 // Get the list of preferred activities that handle the intent 3058 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3059 List<PreferredActivity> prefs = pir != null 3060 ? pir.queryIntent(intent, resolvedType, 3061 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3062 : null; 3063 if (prefs != null && prefs.size() > 0) { 3064 // First figure out how good the original match set is. 3065 // We will only allow preferred activities that came 3066 // from the same match quality. 3067 int match = 0; 3068 3069 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3070 3071 final int N = query.size(); 3072 for (int j=0; j<N; j++) { 3073 final ResolveInfo ri = query.get(j); 3074 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3075 + ": 0x" + Integer.toHexString(match)); 3076 if (ri.match > match) { 3077 match = ri.match; 3078 } 3079 } 3080 3081 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3082 + Integer.toHexString(match)); 3083 3084 match &= IntentFilter.MATCH_CATEGORY_MASK; 3085 final int M = prefs.size(); 3086 for (int i=0; i<M; i++) { 3087 final PreferredActivity pa = prefs.get(i); 3088 if (DEBUG_PREFERRED || debug) { 3089 Slog.v(TAG, "Checking PreferredActivity ds=" 3090 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3091 + "\n component=" + pa.mPref.mComponent); 3092 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3093 } 3094 if (pa.mPref.mMatch != match) { 3095 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3096 + Integer.toHexString(pa.mPref.mMatch)); 3097 continue; 3098 } 3099 // If it's not an "always" type preferred activity and that's what we're 3100 // looking for, skip it. 3101 if (always && !pa.mPref.mAlways) { 3102 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3103 continue; 3104 } 3105 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3106 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3107 if (DEBUG_PREFERRED || debug) { 3108 Slog.v(TAG, "Found preferred activity:"); 3109 if (ai != null) { 3110 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3111 } else { 3112 Slog.v(TAG, " null"); 3113 } 3114 } 3115 if (ai == null) { 3116 // This previously registered preferred activity 3117 // component is no longer known. Most likely an update 3118 // to the app was installed and in the new version this 3119 // component no longer exists. Clean it up by removing 3120 // it from the preferred activities list, and skip it. 3121 Slog.w(TAG, "Removing dangling preferred activity: " 3122 + pa.mPref.mComponent); 3123 pir.removeFilter(pa); 3124 continue; 3125 } 3126 for (int j=0; j<N; j++) { 3127 final ResolveInfo ri = query.get(j); 3128 if (!ri.activityInfo.applicationInfo.packageName 3129 .equals(ai.applicationInfo.packageName)) { 3130 continue; 3131 } 3132 if (!ri.activityInfo.name.equals(ai.name)) { 3133 continue; 3134 } 3135 3136 if (removeMatches) { 3137 pir.removeFilter(pa); 3138 if (DEBUG_PREFERRED) { 3139 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3140 } 3141 break; 3142 } 3143 3144 // Okay we found a previously set preferred or last chosen app. 3145 // If the result set is different from when this 3146 // was created, we need to clear it and re-ask the 3147 // user their preference, if we're looking for an "always" type entry. 3148 if (always && !pa.mPref.sameSet(query, priority)) { 3149 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3150 + intent + " type " + resolvedType); 3151 if (DEBUG_PREFERRED) { 3152 Slog.v(TAG, "Removing preferred activity since set changed " 3153 + pa.mPref.mComponent); 3154 } 3155 pir.removeFilter(pa); 3156 // Re-add the filter as a "last chosen" entry (!always) 3157 PreferredActivity lastChosen = new PreferredActivity( 3158 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3159 pir.addFilter(lastChosen); 3160 mSettings.writePackageRestrictionsLPr(userId); 3161 return null; 3162 } 3163 3164 // Yay! Either the set matched or we're looking for the last chosen 3165 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3166 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3167 mSettings.writePackageRestrictionsLPr(userId); 3168 return ri; 3169 } 3170 } 3171 } 3172 mSettings.writePackageRestrictionsLPr(userId); 3173 } 3174 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3175 return null; 3176 } 3177 3178 /* 3179 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3180 */ 3181 @Override 3182 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3183 int targetUserId) { 3184 mContext.enforceCallingOrSelfPermission( 3185 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3186 List<CrossProfileIntentFilter> matches = 3187 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3188 if (matches != null) { 3189 int size = matches.size(); 3190 for (int i = 0; i < size; i++) { 3191 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3192 } 3193 } 3194 3195 ArrayList<String> packageNames = null; 3196 SparseArray<ArrayList<String>> fromSource = 3197 mSettings.mCrossProfilePackageInfo.get(sourceUserId); 3198 if (fromSource != null) { 3199 packageNames = fromSource.get(targetUserId); 3200 } 3201 if (packageNames.contains(intent.getPackage())) { 3202 return true; 3203 } 3204 // We need the package name, so we try to resolve with the loosest flags possible 3205 List<ResolveInfo> resolveInfos = mActivities.queryIntent( 3206 intent, resolvedType, PackageManager.GET_UNINSTALLED_PACKAGES, targetUserId); 3207 int count = resolveInfos.size(); 3208 for (int i = 0; i < count; i++) { 3209 ResolveInfo resolveInfo = resolveInfos.get(i); 3210 if (packageNames.contains(resolveInfo.activityInfo.packageName)) { 3211 return true; 3212 } 3213 } 3214 return false; 3215 } 3216 3217 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3218 String resolvedType, int userId) { 3219 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3220 if (resolver != null) { 3221 return resolver.queryIntent(intent, resolvedType, false, userId); 3222 } 3223 return null; 3224 } 3225 3226 @Override 3227 public List<ResolveInfo> queryIntentActivities(Intent intent, 3228 String resolvedType, int flags, int userId) { 3229 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3230 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities"); 3231 ComponentName comp = intent.getComponent(); 3232 if (comp == null) { 3233 if (intent.getSelector() != null) { 3234 intent = intent.getSelector(); 3235 comp = intent.getComponent(); 3236 } 3237 } 3238 3239 if (comp != null) { 3240 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3241 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3242 if (ai != null) { 3243 final ResolveInfo ri = new ResolveInfo(); 3244 ri.activityInfo = ai; 3245 list.add(ri); 3246 } 3247 return list; 3248 } 3249 3250 // reader 3251 synchronized (mPackages) { 3252 final String pkgName = intent.getPackage(); 3253 boolean queryCrossProfile = (flags & PackageManager.NO_CROSS_PROFILE) == 0; 3254 if (pkgName == null) { 3255 ResolveInfo resolveInfo = null; 3256 if (queryCrossProfile) { 3257 // Check if the intent needs to be forwarded to another user for this package 3258 ArrayList<ResolveInfo> crossProfileResult = 3259 queryIntentActivitiesCrossProfilePackage( 3260 intent, resolvedType, flags, userId); 3261 if (!crossProfileResult.isEmpty()) { 3262 // Skip the current profile 3263 return crossProfileResult; 3264 } 3265 List<CrossProfileIntentFilter> matchingFilters = 3266 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3267 // Check for results that need to skip the current profile. 3268 resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3269 resolvedType, flags, userId); 3270 if (resolveInfo != null) { 3271 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3272 result.add(resolveInfo); 3273 return result; 3274 } 3275 // Check for cross profile results. 3276 resolveInfo = queryCrossProfileIntents( 3277 matchingFilters, intent, resolvedType, flags, userId); 3278 } 3279 // Check for results in the current profile. 3280 List<ResolveInfo> result = mActivities.queryIntent( 3281 intent, resolvedType, flags, userId); 3282 if (resolveInfo != null) { 3283 result.add(resolveInfo); 3284 } 3285 return result; 3286 } 3287 final PackageParser.Package pkg = mPackages.get(pkgName); 3288 if (pkg != null) { 3289 if (queryCrossProfile) { 3290 ArrayList<ResolveInfo> crossProfileResult = 3291 queryIntentActivitiesCrossProfilePackage( 3292 intent, resolvedType, flags, userId, pkg, pkgName); 3293 if (!crossProfileResult.isEmpty()) { 3294 // Skip the current profile 3295 return crossProfileResult; 3296 } 3297 } 3298 return mActivities.queryIntentForPackage(intent, resolvedType, flags, 3299 pkg.activities, userId); 3300 } 3301 return new ArrayList<ResolveInfo>(); 3302 } 3303 } 3304 3305 private ResolveInfo querySkipCurrentProfileIntents( 3306 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3307 int flags, int sourceUserId) { 3308 if (matchingFilters != null) { 3309 int size = matchingFilters.size(); 3310 for (int i = 0; i < size; i ++) { 3311 CrossProfileIntentFilter filter = matchingFilters.get(i); 3312 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 3313 // Checking if there are activities in the target user that can handle the 3314 // intent. 3315 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3316 flags, sourceUserId); 3317 if (resolveInfo != null) { 3318 return resolveInfo; 3319 } 3320 } 3321 } 3322 } 3323 return null; 3324 } 3325 3326 private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage( 3327 Intent intent, String resolvedType, int flags, int userId) { 3328 ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>(); 3329 SparseArray<ArrayList<String>> sourceForwardingInfo = 3330 mSettings.mCrossProfilePackageInfo.get(userId); 3331 if (sourceForwardingInfo != null) { 3332 int NI = sourceForwardingInfo.size(); 3333 for (int i = 0; i < NI; i++) { 3334 int targetUserId = sourceForwardingInfo.keyAt(i); 3335 ArrayList<String> packageNames = sourceForwardingInfo.valueAt(i); 3336 List<ResolveInfo> resolveInfos = mActivities.queryIntent( 3337 intent, resolvedType, flags, targetUserId); 3338 int NJ = resolveInfos.size(); 3339 for (int j = 0; j < NJ; j++) { 3340 ResolveInfo resolveInfo = resolveInfos.get(j); 3341 if (packageNames.contains(resolveInfo.activityInfo.packageName)) { 3342 matchingResolveInfos.add(createForwardingResolveInfo( 3343 resolveInfo.filter, userId, targetUserId)); 3344 } 3345 } 3346 } 3347 } 3348 return matchingResolveInfos; 3349 } 3350 3351 private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage( 3352 Intent intent, String resolvedType, int flags, int userId, PackageParser.Package pkg, 3353 String packageName) { 3354 ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>(); 3355 SparseArray<ArrayList<String>> sourceForwardingInfo = 3356 mSettings.mCrossProfilePackageInfo.get(userId); 3357 if (sourceForwardingInfo != null) { 3358 int NI = sourceForwardingInfo.size(); 3359 for (int i = 0; i < NI; i++) { 3360 int targetUserId = sourceForwardingInfo.keyAt(i); 3361 if (sourceForwardingInfo.valueAt(i).contains(packageName)) { 3362 List<ResolveInfo> resolveInfos = mActivities.queryIntentForPackage( 3363 intent, resolvedType, flags, pkg.activities, targetUserId); 3364 int NJ = resolveInfos.size(); 3365 for (int j = 0; j < NJ; j++) { 3366 ResolveInfo resolveInfo = resolveInfos.get(j); 3367 matchingResolveInfos.add(createForwardingResolveInfo( 3368 resolveInfo.filter, userId, targetUserId)); 3369 } 3370 } 3371 } 3372 } 3373 return matchingResolveInfos; 3374 } 3375 3376 // Return matching ResolveInfo if any for skip current profile intent filters. 3377 private ResolveInfo queryCrossProfileIntents( 3378 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3379 int flags, int sourceUserId) { 3380 if (matchingFilters != null) { 3381 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 3382 // match the same intent. For performance reasons, it is better not to 3383 // run queryIntent twice for the same userId 3384 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 3385 int size = matchingFilters.size(); 3386 for (int i = 0; i < size; i++) { 3387 CrossProfileIntentFilter filter = matchingFilters.get(i); 3388 int targetUserId = filter.getTargetUserId(); 3389 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 3390 && !alreadyTriedUserIds.get(targetUserId)) { 3391 // Checking if there are activities in the target user that can handle the 3392 // intent. 3393 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3394 flags, sourceUserId); 3395 if (resolveInfo != null) return resolveInfo; 3396 alreadyTriedUserIds.put(targetUserId, true); 3397 } 3398 } 3399 } 3400 return null; 3401 } 3402 3403 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 3404 String resolvedType, int flags, int sourceUserId) { 3405 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 3406 resolvedType, flags, filter.getTargetUserId()); 3407 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 3408 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 3409 } 3410 return null; 3411 } 3412 3413 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 3414 int sourceUserId, int targetUserId) { 3415 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 3416 String className; 3417 if (targetUserId == UserHandle.USER_OWNER) { 3418 className = FORWARD_INTENT_TO_USER_OWNER; 3419 } else { 3420 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 3421 } 3422 ComponentName forwardingActivityComponentName = new ComponentName( 3423 mAndroidApplication.packageName, className); 3424 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 3425 sourceUserId); 3426 if (targetUserId == UserHandle.USER_OWNER) { 3427 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 3428 forwardingResolveInfo.noResourceId = true; 3429 } 3430 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 3431 forwardingResolveInfo.priority = 0; 3432 forwardingResolveInfo.preferredOrder = 0; 3433 forwardingResolveInfo.match = 0; 3434 forwardingResolveInfo.isDefault = true; 3435 forwardingResolveInfo.filter = filter; 3436 forwardingResolveInfo.targetUserId = targetUserId; 3437 return forwardingResolveInfo; 3438 } 3439 3440 @Override 3441 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 3442 Intent[] specifics, String[] specificTypes, Intent intent, 3443 String resolvedType, int flags, int userId) { 3444 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3445 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 3446 "query intent activity options"); 3447 final String resultsAction = intent.getAction(); 3448 3449 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 3450 | PackageManager.GET_RESOLVED_FILTER, userId); 3451 3452 if (DEBUG_INTENT_MATCHING) { 3453 Log.v(TAG, "Query " + intent + ": " + results); 3454 } 3455 3456 int specificsPos = 0; 3457 int N; 3458 3459 // todo: note that the algorithm used here is O(N^2). This 3460 // isn't a problem in our current environment, but if we start running 3461 // into situations where we have more than 5 or 10 matches then this 3462 // should probably be changed to something smarter... 3463 3464 // First we go through and resolve each of the specific items 3465 // that were supplied, taking care of removing any corresponding 3466 // duplicate items in the generic resolve list. 3467 if (specifics != null) { 3468 for (int i=0; i<specifics.length; i++) { 3469 final Intent sintent = specifics[i]; 3470 if (sintent == null) { 3471 continue; 3472 } 3473 3474 if (DEBUG_INTENT_MATCHING) { 3475 Log.v(TAG, "Specific #" + i + ": " + sintent); 3476 } 3477 3478 String action = sintent.getAction(); 3479 if (resultsAction != null && resultsAction.equals(action)) { 3480 // If this action was explicitly requested, then don't 3481 // remove things that have it. 3482 action = null; 3483 } 3484 3485 ResolveInfo ri = null; 3486 ActivityInfo ai = null; 3487 3488 ComponentName comp = sintent.getComponent(); 3489 if (comp == null) { 3490 ri = resolveIntent( 3491 sintent, 3492 specificTypes != null ? specificTypes[i] : null, 3493 flags, userId); 3494 if (ri == null) { 3495 continue; 3496 } 3497 if (ri == mResolveInfo) { 3498 // ACK! Must do something better with this. 3499 } 3500 ai = ri.activityInfo; 3501 comp = new ComponentName(ai.applicationInfo.packageName, 3502 ai.name); 3503 } else { 3504 ai = getActivityInfo(comp, flags, userId); 3505 if (ai == null) { 3506 continue; 3507 } 3508 } 3509 3510 // Look for any generic query activities that are duplicates 3511 // of this specific one, and remove them from the results. 3512 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 3513 N = results.size(); 3514 int j; 3515 for (j=specificsPos; j<N; j++) { 3516 ResolveInfo sri = results.get(j); 3517 if ((sri.activityInfo.name.equals(comp.getClassName()) 3518 && sri.activityInfo.applicationInfo.packageName.equals( 3519 comp.getPackageName())) 3520 || (action != null && sri.filter.matchAction(action))) { 3521 results.remove(j); 3522 if (DEBUG_INTENT_MATCHING) Log.v( 3523 TAG, "Removing duplicate item from " + j 3524 + " due to specific " + specificsPos); 3525 if (ri == null) { 3526 ri = sri; 3527 } 3528 j--; 3529 N--; 3530 } 3531 } 3532 3533 // Add this specific item to its proper place. 3534 if (ri == null) { 3535 ri = new ResolveInfo(); 3536 ri.activityInfo = ai; 3537 } 3538 results.add(specificsPos, ri); 3539 ri.specificIndex = i; 3540 specificsPos++; 3541 } 3542 } 3543 3544 // Now we go through the remaining generic results and remove any 3545 // duplicate actions that are found here. 3546 N = results.size(); 3547 for (int i=specificsPos; i<N-1; i++) { 3548 final ResolveInfo rii = results.get(i); 3549 if (rii.filter == null) { 3550 continue; 3551 } 3552 3553 // Iterate over all of the actions of this result's intent 3554 // filter... typically this should be just one. 3555 final Iterator<String> it = rii.filter.actionsIterator(); 3556 if (it == null) { 3557 continue; 3558 } 3559 while (it.hasNext()) { 3560 final String action = it.next(); 3561 if (resultsAction != null && resultsAction.equals(action)) { 3562 // If this action was explicitly requested, then don't 3563 // remove things that have it. 3564 continue; 3565 } 3566 for (int j=i+1; j<N; j++) { 3567 final ResolveInfo rij = results.get(j); 3568 if (rij.filter != null && rij.filter.hasAction(action)) { 3569 results.remove(j); 3570 if (DEBUG_INTENT_MATCHING) Log.v( 3571 TAG, "Removing duplicate item from " + j 3572 + " due to action " + action + " at " + i); 3573 j--; 3574 N--; 3575 } 3576 } 3577 } 3578 3579 // If the caller didn't request filter information, drop it now 3580 // so we don't have to marshall/unmarshall it. 3581 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3582 rii.filter = null; 3583 } 3584 } 3585 3586 // Filter out the caller activity if so requested. 3587 if (caller != null) { 3588 N = results.size(); 3589 for (int i=0; i<N; i++) { 3590 ActivityInfo ainfo = results.get(i).activityInfo; 3591 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 3592 && caller.getClassName().equals(ainfo.name)) { 3593 results.remove(i); 3594 break; 3595 } 3596 } 3597 } 3598 3599 // If the caller didn't request filter information, 3600 // drop them now so we don't have to 3601 // marshall/unmarshall it. 3602 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3603 N = results.size(); 3604 for (int i=0; i<N; i++) { 3605 results.get(i).filter = null; 3606 } 3607 } 3608 3609 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 3610 return results; 3611 } 3612 3613 @Override 3614 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 3615 int userId) { 3616 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3617 ComponentName comp = intent.getComponent(); 3618 if (comp == null) { 3619 if (intent.getSelector() != null) { 3620 intent = intent.getSelector(); 3621 comp = intent.getComponent(); 3622 } 3623 } 3624 if (comp != null) { 3625 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3626 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 3627 if (ai != null) { 3628 ResolveInfo ri = new ResolveInfo(); 3629 ri.activityInfo = ai; 3630 list.add(ri); 3631 } 3632 return list; 3633 } 3634 3635 // reader 3636 synchronized (mPackages) { 3637 String pkgName = intent.getPackage(); 3638 if (pkgName == null) { 3639 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 3640 } 3641 final PackageParser.Package pkg = mPackages.get(pkgName); 3642 if (pkg != null) { 3643 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 3644 userId); 3645 } 3646 return null; 3647 } 3648 } 3649 3650 @Override 3651 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 3652 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 3653 if (!sUserManager.exists(userId)) return null; 3654 if (query != null) { 3655 if (query.size() >= 1) { 3656 // If there is more than one service with the same priority, 3657 // just arbitrarily pick the first one. 3658 return query.get(0); 3659 } 3660 } 3661 return null; 3662 } 3663 3664 @Override 3665 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 3666 int userId) { 3667 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3668 ComponentName comp = intent.getComponent(); 3669 if (comp == null) { 3670 if (intent.getSelector() != null) { 3671 intent = intent.getSelector(); 3672 comp = intent.getComponent(); 3673 } 3674 } 3675 if (comp != null) { 3676 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3677 final ServiceInfo si = getServiceInfo(comp, flags, userId); 3678 if (si != null) { 3679 final ResolveInfo ri = new ResolveInfo(); 3680 ri.serviceInfo = si; 3681 list.add(ri); 3682 } 3683 return list; 3684 } 3685 3686 // reader 3687 synchronized (mPackages) { 3688 String pkgName = intent.getPackage(); 3689 if (pkgName == null) { 3690 return mServices.queryIntent(intent, resolvedType, flags, userId); 3691 } 3692 final PackageParser.Package pkg = mPackages.get(pkgName); 3693 if (pkg != null) { 3694 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 3695 userId); 3696 } 3697 return null; 3698 } 3699 } 3700 3701 @Override 3702 public List<ResolveInfo> queryIntentContentProviders( 3703 Intent intent, String resolvedType, int flags, int userId) { 3704 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3705 ComponentName comp = intent.getComponent(); 3706 if (comp == null) { 3707 if (intent.getSelector() != null) { 3708 intent = intent.getSelector(); 3709 comp = intent.getComponent(); 3710 } 3711 } 3712 if (comp != null) { 3713 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3714 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 3715 if (pi != null) { 3716 final ResolveInfo ri = new ResolveInfo(); 3717 ri.providerInfo = pi; 3718 list.add(ri); 3719 } 3720 return list; 3721 } 3722 3723 // reader 3724 synchronized (mPackages) { 3725 String pkgName = intent.getPackage(); 3726 if (pkgName == null) { 3727 return mProviders.queryIntent(intent, resolvedType, flags, userId); 3728 } 3729 final PackageParser.Package pkg = mPackages.get(pkgName); 3730 if (pkg != null) { 3731 return mProviders.queryIntentForPackage( 3732 intent, resolvedType, flags, pkg.providers, userId); 3733 } 3734 return null; 3735 } 3736 } 3737 3738 @Override 3739 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 3740 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3741 3742 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages"); 3743 3744 // writer 3745 synchronized (mPackages) { 3746 ArrayList<PackageInfo> list; 3747 if (listUninstalled) { 3748 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 3749 for (PackageSetting ps : mSettings.mPackages.values()) { 3750 PackageInfo pi; 3751 if (ps.pkg != null) { 3752 pi = generatePackageInfo(ps.pkg, flags, userId); 3753 } else { 3754 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3755 } 3756 if (pi != null) { 3757 list.add(pi); 3758 } 3759 } 3760 } else { 3761 list = new ArrayList<PackageInfo>(mPackages.size()); 3762 for (PackageParser.Package p : mPackages.values()) { 3763 PackageInfo pi = generatePackageInfo(p, flags, userId); 3764 if (pi != null) { 3765 list.add(pi); 3766 } 3767 } 3768 } 3769 3770 return new ParceledListSlice<PackageInfo>(list); 3771 } 3772 } 3773 3774 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 3775 String[] permissions, boolean[] tmp, int flags, int userId) { 3776 int numMatch = 0; 3777 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 3778 for (int i=0; i<permissions.length; i++) { 3779 if (gp.grantedPermissions.contains(permissions[i])) { 3780 tmp[i] = true; 3781 numMatch++; 3782 } else { 3783 tmp[i] = false; 3784 } 3785 } 3786 if (numMatch == 0) { 3787 return; 3788 } 3789 PackageInfo pi; 3790 if (ps.pkg != null) { 3791 pi = generatePackageInfo(ps.pkg, flags, userId); 3792 } else { 3793 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3794 } 3795 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 3796 if (numMatch == permissions.length) { 3797 pi.requestedPermissions = permissions; 3798 } else { 3799 pi.requestedPermissions = new String[numMatch]; 3800 numMatch = 0; 3801 for (int i=0; i<permissions.length; i++) { 3802 if (tmp[i]) { 3803 pi.requestedPermissions[numMatch] = permissions[i]; 3804 numMatch++; 3805 } 3806 } 3807 } 3808 } 3809 list.add(pi); 3810 } 3811 3812 @Override 3813 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 3814 String[] permissions, int flags, int userId) { 3815 if (!sUserManager.exists(userId)) return null; 3816 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3817 3818 // writer 3819 synchronized (mPackages) { 3820 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 3821 boolean[] tmpBools = new boolean[permissions.length]; 3822 if (listUninstalled) { 3823 for (PackageSetting ps : mSettings.mPackages.values()) { 3824 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 3825 } 3826 } else { 3827 for (PackageParser.Package pkg : mPackages.values()) { 3828 PackageSetting ps = (PackageSetting)pkg.mExtras; 3829 if (ps != null) { 3830 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 3831 userId); 3832 } 3833 } 3834 } 3835 3836 return new ParceledListSlice<PackageInfo>(list); 3837 } 3838 } 3839 3840 @Override 3841 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 3842 if (!sUserManager.exists(userId)) return null; 3843 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3844 3845 // writer 3846 synchronized (mPackages) { 3847 ArrayList<ApplicationInfo> list; 3848 if (listUninstalled) { 3849 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 3850 for (PackageSetting ps : mSettings.mPackages.values()) { 3851 ApplicationInfo ai; 3852 if (ps.pkg != null) { 3853 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3854 ps.readUserState(userId), userId); 3855 } else { 3856 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 3857 } 3858 if (ai != null) { 3859 list.add(ai); 3860 } 3861 } 3862 } else { 3863 list = new ArrayList<ApplicationInfo>(mPackages.size()); 3864 for (PackageParser.Package p : mPackages.values()) { 3865 if (p.mExtras != null) { 3866 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3867 ((PackageSetting)p.mExtras).readUserState(userId), userId); 3868 if (ai != null) { 3869 list.add(ai); 3870 } 3871 } 3872 } 3873 } 3874 3875 return new ParceledListSlice<ApplicationInfo>(list); 3876 } 3877 } 3878 3879 public List<ApplicationInfo> getPersistentApplications(int flags) { 3880 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 3881 3882 // reader 3883 synchronized (mPackages) { 3884 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 3885 final int userId = UserHandle.getCallingUserId(); 3886 while (i.hasNext()) { 3887 final PackageParser.Package p = i.next(); 3888 if (p.applicationInfo != null 3889 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 3890 && (!mSafeMode || isSystemApp(p))) { 3891 PackageSetting ps = mSettings.mPackages.get(p.packageName); 3892 if (ps != null) { 3893 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3894 ps.readUserState(userId), userId); 3895 if (ai != null) { 3896 finalList.add(ai); 3897 } 3898 } 3899 } 3900 } 3901 } 3902 3903 return finalList; 3904 } 3905 3906 @Override 3907 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 3908 if (!sUserManager.exists(userId)) return null; 3909 // reader 3910 synchronized (mPackages) { 3911 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 3912 PackageSetting ps = provider != null 3913 ? mSettings.mPackages.get(provider.owner.packageName) 3914 : null; 3915 return ps != null 3916 && mSettings.isEnabledLPr(provider.info, flags, userId) 3917 && (!mSafeMode || (provider.info.applicationInfo.flags 3918 &ApplicationInfo.FLAG_SYSTEM) != 0) 3919 ? PackageParser.generateProviderInfo(provider, flags, 3920 ps.readUserState(userId), userId) 3921 : null; 3922 } 3923 } 3924 3925 /** 3926 * @deprecated 3927 */ 3928 @Deprecated 3929 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 3930 // reader 3931 synchronized (mPackages) { 3932 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 3933 .entrySet().iterator(); 3934 final int userId = UserHandle.getCallingUserId(); 3935 while (i.hasNext()) { 3936 Map.Entry<String, PackageParser.Provider> entry = i.next(); 3937 PackageParser.Provider p = entry.getValue(); 3938 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3939 3940 if (ps != null && p.syncable 3941 && (!mSafeMode || (p.info.applicationInfo.flags 3942 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 3943 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 3944 ps.readUserState(userId), userId); 3945 if (info != null) { 3946 outNames.add(entry.getKey()); 3947 outInfo.add(info); 3948 } 3949 } 3950 } 3951 } 3952 } 3953 3954 @Override 3955 public List<ProviderInfo> queryContentProviders(String processName, 3956 int uid, int flags) { 3957 ArrayList<ProviderInfo> finalList = null; 3958 // reader 3959 synchronized (mPackages) { 3960 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 3961 final int userId = processName != null ? 3962 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 3963 while (i.hasNext()) { 3964 final PackageParser.Provider p = i.next(); 3965 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3966 if (ps != null && p.info.authority != null 3967 && (processName == null 3968 || (p.info.processName.equals(processName) 3969 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 3970 && mSettings.isEnabledLPr(p.info, flags, userId) 3971 && (!mSafeMode 3972 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 3973 if (finalList == null) { 3974 finalList = new ArrayList<ProviderInfo>(3); 3975 } 3976 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 3977 ps.readUserState(userId), userId); 3978 if (info != null) { 3979 finalList.add(info); 3980 } 3981 } 3982 } 3983 } 3984 3985 if (finalList != null) { 3986 Collections.sort(finalList, mProviderInitOrderSorter); 3987 } 3988 3989 return finalList; 3990 } 3991 3992 @Override 3993 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 3994 int flags) { 3995 // reader 3996 synchronized (mPackages) { 3997 final PackageParser.Instrumentation i = mInstrumentation.get(name); 3998 return PackageParser.generateInstrumentationInfo(i, flags); 3999 } 4000 } 4001 4002 @Override 4003 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4004 int flags) { 4005 ArrayList<InstrumentationInfo> finalList = 4006 new ArrayList<InstrumentationInfo>(); 4007 4008 // reader 4009 synchronized (mPackages) { 4010 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4011 while (i.hasNext()) { 4012 final PackageParser.Instrumentation p = i.next(); 4013 if (targetPackage == null 4014 || targetPackage.equals(p.info.targetPackage)) { 4015 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4016 flags); 4017 if (ii != null) { 4018 finalList.add(ii); 4019 } 4020 } 4021 } 4022 } 4023 4024 return finalList; 4025 } 4026 4027 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4028 HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4029 if (overlays == null) { 4030 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4031 return; 4032 } 4033 for (PackageParser.Package opkg : overlays.values()) { 4034 // Not much to do if idmap fails: we already logged the error 4035 // and we certainly don't want to abort installation of pkg simply 4036 // because an overlay didn't fit properly. For these reasons, 4037 // ignore the return value of createIdmapForPackagePairLI. 4038 createIdmapForPackagePairLI(pkg, opkg); 4039 } 4040 } 4041 4042 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4043 PackageParser.Package opkg) { 4044 if (!opkg.mTrustedOverlay) { 4045 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4046 opkg.baseCodePath + ": overlay not trusted"); 4047 return false; 4048 } 4049 HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4050 if (overlaySet == null) { 4051 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4052 opkg.baseCodePath + " but target package has no known overlays"); 4053 return false; 4054 } 4055 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4056 // TODO: generate idmap for split APKs 4057 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4058 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4059 + opkg.baseCodePath); 4060 return false; 4061 } 4062 PackageParser.Package[] overlayArray = 4063 overlaySet.values().toArray(new PackageParser.Package[0]); 4064 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4065 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4066 return p1.mOverlayPriority - p2.mOverlayPriority; 4067 } 4068 }; 4069 Arrays.sort(overlayArray, cmp); 4070 4071 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4072 int i = 0; 4073 for (PackageParser.Package p : overlayArray) { 4074 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4075 } 4076 return true; 4077 } 4078 4079 private void scanDirLI(File dir, int flags, int scanMode, long currentTime) { 4080 final File[] files = dir.listFiles(); 4081 if (ArrayUtils.isEmpty(files)) { 4082 Log.d(TAG, "No files in app dir " + dir); 4083 return; 4084 } 4085 4086 if (DEBUG_PACKAGE_SCANNING) { 4087 Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode 4088 + " flags=0x" + Integer.toHexString(flags)); 4089 } 4090 4091 for (File file : files) { 4092 final boolean isPackage = isApkFile(file) || file.isDirectory(); 4093 if (!isPackage) { 4094 // Ignore entries which are not apk's 4095 continue; 4096 } 4097 PackageParser.Package pkg = scanPackageLI(file, 4098 flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, null, null); 4099 // Don't mess around with apps in system partition. 4100 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4101 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) { 4102 // Delete the apk 4103 Slog.w(TAG, "Cleaning up failed install of " + file); 4104 file.delete(); 4105 } 4106 } 4107 } 4108 4109 private static File getSettingsProblemFile() { 4110 File dataDir = Environment.getDataDirectory(); 4111 File systemDir = new File(dataDir, "system"); 4112 File fname = new File(systemDir, "uiderrors.txt"); 4113 return fname; 4114 } 4115 4116 static void reportSettingsProblem(int priority, String msg) { 4117 try { 4118 File fname = getSettingsProblemFile(); 4119 FileOutputStream out = new FileOutputStream(fname, true); 4120 PrintWriter pw = new FastPrintWriter(out); 4121 SimpleDateFormat formatter = new SimpleDateFormat(); 4122 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4123 pw.println(dateString + ": " + msg); 4124 pw.close(); 4125 FileUtils.setPermissions( 4126 fname.toString(), 4127 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4128 -1, -1); 4129 } catch (java.io.IOException e) { 4130 } 4131 Slog.println(priority, TAG, msg); 4132 } 4133 4134 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps, 4135 PackageParser.Package pkg, File srcFile, int parseFlags) { 4136 if (ps != null 4137 && ps.codePath.equals(srcFile) 4138 && ps.timeStamp == srcFile.lastModified() 4139 && !isCompatSignatureUpdateNeeded(pkg)) { 4140 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4141 if (ps.signatures.mSignatures != null 4142 && ps.signatures.mSignatures.length != 0 4143 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4144 // Optimization: reuse the existing cached certificates 4145 // if the package appears to be unchanged. 4146 pkg.mSignatures = ps.signatures.mSignatures; 4147 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4148 pkg.mSigningKeys = ksms.getPublicKeysFromKeySet(mSigningKeySetId); 4149 return true; 4150 } 4151 4152 Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them."); 4153 } else { 4154 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4155 } 4156 4157 try { 4158 pp.collectCertificates(pkg, parseFlags); 4159 pp.collectManifestDigest(pkg); 4160 } catch (PackageParserException e) { 4161 Slog.e(TAG, "Failed during collect: " + e); 4162 mLastScanError = e.error; 4163 return false; 4164 } 4165 return true; 4166 } 4167 4168 /* 4169 * Scan a package and return the newly parsed package. 4170 * Returns null in case of errors and the error code is stored in mLastScanError 4171 */ 4172 private PackageParser.Package scanPackageLI(File scanFile, 4173 int parseFlags, int scanMode, long currentTime, UserHandle user, String abiOverride) { 4174 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 4175 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4176 parseFlags |= mDefParseFlags; 4177 PackageParser pp = new PackageParser(); 4178 pp.setSeparateProcesses(mSeparateProcesses); 4179 pp.setOnlyCoreApps(mOnlyCore); 4180 pp.setDisplayMetrics(mMetrics); 4181 4182 if ((scanMode & SCAN_TRUSTED_OVERLAY) != 0) { 4183 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4184 } 4185 4186 final PackageParser.Package pkg; 4187 try { 4188 pkg = pp.parsePackage(scanFile, parseFlags); 4189 } catch (PackageParserException e) { 4190 Slog.e(TAG, "Failed during scan: " + e); 4191 mLastScanError = e.error; 4192 return null; 4193 } 4194 4195 PackageSetting ps = null; 4196 PackageSetting updatedPkg; 4197 // reader 4198 synchronized (mPackages) { 4199 // Look to see if we already know about this package. 4200 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4201 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4202 // This package has been renamed to its original name. Let's 4203 // use that. 4204 ps = mSettings.peekPackageLPr(oldName); 4205 } 4206 // If there was no original package, see one for the real package name. 4207 if (ps == null) { 4208 ps = mSettings.peekPackageLPr(pkg.packageName); 4209 } 4210 // Check to see if this package could be hiding/updating a system 4211 // package. Must look for it either under the original or real 4212 // package name depending on our state. 4213 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4214 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4215 } 4216 boolean updatedPkgBetter = false; 4217 // First check if this is a system package that may involve an update 4218 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4219 if (ps != null && !ps.codePath.equals(scanFile)) { 4220 // The path has changed from what was last scanned... check the 4221 // version of the new path against what we have stored to determine 4222 // what to do. 4223 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4224 if (pkg.mVersionCode < ps.versionCode) { 4225 // The system package has been updated and the code path does not match 4226 // Ignore entry. Skip it. 4227 Log.i(TAG, "Package " + ps.name + " at " + scanFile 4228 + " ignored: updated version " + ps.versionCode 4229 + " better than this " + pkg.mVersionCode); 4230 if (!updatedPkg.codePath.equals(scanFile)) { 4231 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4232 + ps.name + " changing from " + updatedPkg.codePathString 4233 + " to " + scanFile); 4234 updatedPkg.codePath = scanFile; 4235 updatedPkg.codePathString = scanFile.toString(); 4236 // This is the point at which we know that the system-disk APK 4237 // for this package has moved during a reboot (e.g. due to an OTA), 4238 // so we need to reevaluate it for privilege policy. 4239 if (locationIsPrivileged(scanFile)) { 4240 updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED; 4241 } 4242 } 4243 updatedPkg.pkg = pkg; 4244 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 4245 return null; 4246 } else { 4247 // The current app on the system partition is better than 4248 // what we have updated to on the data partition; switch 4249 // back to the system partition version. 4250 // At this point, its safely assumed that package installation for 4251 // apps in system partition will go through. If not there won't be a working 4252 // version of the app 4253 // writer 4254 synchronized (mPackages) { 4255 // Just remove the loaded entries from package lists. 4256 mPackages.remove(ps.name); 4257 } 4258 Slog.w(TAG, "Package " + ps.name + " at " + scanFile 4259 + "reverting from " + ps.codePathString 4260 + ": new version " + pkg.mVersionCode 4261 + " better than installed " + ps.versionCode); 4262 4263 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4264 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4265 getAppDexInstructionSets(ps), isMultiArch(ps)); 4266 synchronized (mInstallLock) { 4267 args.cleanUpResourcesLI(); 4268 } 4269 synchronized (mPackages) { 4270 mSettings.enableSystemPackageLPw(ps.name); 4271 } 4272 updatedPkgBetter = true; 4273 } 4274 } 4275 } 4276 4277 if (updatedPkg != null) { 4278 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4279 // initially 4280 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4281 4282 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4283 // flag set initially 4284 if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) { 4285 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4286 } 4287 } 4288 // Verify certificates against what was last scanned 4289 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) { 4290 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName); 4291 return null; 4292 } 4293 4294 /* 4295 * A new system app appeared, but we already had a non-system one of the 4296 * same name installed earlier. 4297 */ 4298 boolean shouldHideSystemApp = false; 4299 if (updatedPkg == null && ps != null 4300 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4301 /* 4302 * Check to make sure the signatures match first. If they don't, 4303 * wipe the installed application and its data. 4304 */ 4305 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4306 != PackageManager.SIGNATURE_MATCH) { 4307 if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!"); 4308 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4309 ps = null; 4310 } else { 4311 /* 4312 * If the newly-added system app is an older version than the 4313 * already installed version, hide it. It will be scanned later 4314 * and re-added like an update. 4315 */ 4316 if (pkg.mVersionCode < ps.versionCode) { 4317 shouldHideSystemApp = true; 4318 } else { 4319 /* 4320 * The newly found system app is a newer version that the 4321 * one previously installed. Simply remove the 4322 * already-installed application and replace it with our own 4323 * while keeping the application data. 4324 */ 4325 Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from " 4326 + ps.codePathString + ": new version " + pkg.mVersionCode 4327 + " better than installed " + ps.versionCode); 4328 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4329 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4330 getAppDexInstructionSets(ps), isMultiArch(ps)); 4331 synchronized (mInstallLock) { 4332 args.cleanUpResourcesLI(); 4333 } 4334 } 4335 } 4336 } 4337 4338 // The apk is forward locked (not public) if its code and resources 4339 // are kept in different files. (except for app in either system or 4340 // vendor path). 4341 // TODO grab this value from PackageSettings 4342 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4343 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4344 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 4345 } 4346 } 4347 4348 // TODO: extend to support forward-locked splits 4349 String resourcePath = null; 4350 String baseResourcePath = null; 4351 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 4352 if (ps != null && ps.resourcePathString != null) { 4353 resourcePath = ps.resourcePathString; 4354 baseResourcePath = ps.resourcePathString; 4355 } else { 4356 // Should not happen at all. Just log an error. 4357 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 4358 } 4359 } else { 4360 resourcePath = pkg.codePath; 4361 baseResourcePath = pkg.baseCodePath; 4362 } 4363 4364 // Set application objects path explicitly. 4365 pkg.applicationInfo.setCodePath(pkg.codePath); 4366 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 4367 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 4368 pkg.applicationInfo.setResourcePath(resourcePath); 4369 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 4370 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 4371 4372 // Note that we invoke the following method only if we are about to unpack an application 4373 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode 4374 | SCAN_UPDATE_SIGNATURE, currentTime, user, abiOverride); 4375 4376 /* 4377 * If the system app should be overridden by a previously installed 4378 * data, hide the system app now and let the /data/app scan pick it up 4379 * again. 4380 */ 4381 if (shouldHideSystemApp) { 4382 synchronized (mPackages) { 4383 /* 4384 * We have to grant systems permissions before we hide, because 4385 * grantPermissions will assume the package update is trying to 4386 * expand its permissions. 4387 */ 4388 grantPermissionsLPw(pkg, true); 4389 mSettings.disableSystemPackageLPw(pkg.packageName); 4390 } 4391 } 4392 4393 return scannedPkg; 4394 } 4395 4396 private static String fixProcessName(String defProcessName, 4397 String processName, int uid) { 4398 if (processName == null) { 4399 return defProcessName; 4400 } 4401 return processName; 4402 } 4403 4404 private boolean verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) { 4405 if (pkgSetting.signatures.mSignatures != null) { 4406 // Already existing package. Make sure signatures match 4407 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 4408 == PackageManager.SIGNATURE_MATCH; 4409 if (!match) { 4410 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 4411 == PackageManager.SIGNATURE_MATCH; 4412 } 4413 if (!match) { 4414 Slog.e(TAG, "Package " + pkg.packageName 4415 + " signatures do not match the previously installed version; ignoring!"); 4416 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 4417 return false; 4418 } 4419 } 4420 4421 // Check for shared user signatures 4422 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 4423 // Already existing package. Make sure signatures match 4424 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4425 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 4426 if (!match) { 4427 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 4428 == PackageManager.SIGNATURE_MATCH; 4429 } 4430 if (!match) { 4431 Slog.e(TAG, "Package " + pkg.packageName 4432 + " has no signatures that match those in shared user " 4433 + pkgSetting.sharedUser.name + "; ignoring!"); 4434 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 4435 return false; 4436 } 4437 } 4438 return true; 4439 } 4440 4441 /** 4442 * Enforces that only the system UID or root's UID can call a method exposed 4443 * via Binder. 4444 * 4445 * @param message used as message if SecurityException is thrown 4446 * @throws SecurityException if the caller is not system or root 4447 */ 4448 private static final void enforceSystemOrRoot(String message) { 4449 final int uid = Binder.getCallingUid(); 4450 if (uid != Process.SYSTEM_UID && uid != 0) { 4451 throw new SecurityException(message); 4452 } 4453 } 4454 4455 @Override 4456 public void performBootDexOpt() { 4457 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4458 4459 final HashSet<PackageParser.Package> pkgs; 4460 synchronized (mPackages) { 4461 pkgs = mDeferredDexOpt; 4462 mDeferredDexOpt = null; 4463 } 4464 4465 if (pkgs != null) { 4466 // Filter out packages that aren't recently used. 4467 // 4468 // The exception is first boot of a non-eng device, which 4469 // should do a full dexopt. 4470 boolean eng = "eng".equals(SystemProperties.get("ro.build.type")); 4471 if (eng || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 4472 // TODO: add a property to control this? 4473 long dexOptLRUThresholdInMinutes; 4474 if (eng) { 4475 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 4476 } else { 4477 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 4478 } 4479 long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 4480 4481 int total = pkgs.size(); 4482 int skipped = 0; 4483 long now = System.currentTimeMillis(); 4484 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 4485 PackageParser.Package pkg = i.next(); 4486 long then = pkg.mLastPackageUsageTimeInMills; 4487 if (then + dexOptLRUThresholdInMills < now) { 4488 if (DEBUG_DEXOPT) { 4489 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 4490 ((then == 0) ? "never" : new Date(then))); 4491 } 4492 i.remove(); 4493 skipped++; 4494 } 4495 } 4496 if (DEBUG_DEXOPT) { 4497 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 4498 } 4499 } 4500 4501 int i = 0; 4502 for (PackageParser.Package pkg : pkgs) { 4503 i++; 4504 if (DEBUG_DEXOPT) { 4505 Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size() 4506 + ": " + pkg.packageName); 4507 } 4508 if (!isFirstBoot()) { 4509 try { 4510 ActivityManagerNative.getDefault().showBootMessage( 4511 mContext.getResources().getString( 4512 R.string.android_upgrading_apk, 4513 i, pkgs.size()), true); 4514 } catch (RemoteException e) { 4515 } 4516 } 4517 PackageParser.Package p = pkg; 4518 synchronized (mInstallLock) { 4519 if (p.mDexOptNeeded) { 4520 performDexOptLI(p, false /* force dex */, false /* defer */, 4521 true /* include dependencies */); 4522 } 4523 } 4524 } 4525 } 4526 } 4527 4528 @Override 4529 public boolean performDexOpt(String packageName) { 4530 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4531 return performDexOpt(packageName, true); 4532 } 4533 4534 public boolean performDexOpt(String packageName, boolean updateUsage) { 4535 4536 PackageParser.Package p; 4537 synchronized (mPackages) { 4538 p = mPackages.get(packageName); 4539 if (p == null) { 4540 return false; 4541 } 4542 if (updateUsage) { 4543 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 4544 } 4545 mPackageUsage.write(false); 4546 if (!p.mDexOptNeeded) { 4547 return false; 4548 } 4549 } 4550 4551 synchronized (mInstallLock) { 4552 return performDexOptLI(p, false /* force dex */, false /* defer */, 4553 true /* include dependencies */) == DEX_OPT_PERFORMED; 4554 } 4555 } 4556 4557 public HashSet<String> getPackagesThatNeedDexOpt() { 4558 HashSet<String> pkgs = null; 4559 synchronized (mPackages) { 4560 for (PackageParser.Package p : mPackages.values()) { 4561 if (DEBUG_DEXOPT) { 4562 Log.i(TAG, p.packageName + " mDexOptNeeded=" + p.mDexOptNeeded); 4563 } 4564 if (!p.mDexOptNeeded) { 4565 continue; 4566 } 4567 if (pkgs == null) { 4568 pkgs = new HashSet<String>(); 4569 } 4570 pkgs.add(p.packageName); 4571 } 4572 } 4573 return pkgs; 4574 } 4575 4576 public void shutdown() { 4577 mPackageUsage.write(true); 4578 } 4579 4580 private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets, 4581 boolean forceDex, boolean defer, HashSet<String> done) { 4582 for (int i=0; i<libs.size(); i++) { 4583 PackageParser.Package libPkg; 4584 String libName; 4585 synchronized (mPackages) { 4586 libName = libs.get(i); 4587 SharedLibraryEntry lib = mSharedLibraries.get(libName); 4588 if (lib != null && lib.apk != null) { 4589 libPkg = mPackages.get(lib.apk); 4590 } else { 4591 libPkg = null; 4592 } 4593 } 4594 if (libPkg != null && !done.contains(libName)) { 4595 performDexOptLI(libPkg, instructionSets, forceDex, defer, done); 4596 } 4597 } 4598 } 4599 4600 static final int DEX_OPT_SKIPPED = 0; 4601 static final int DEX_OPT_PERFORMED = 1; 4602 static final int DEX_OPT_DEFERRED = 2; 4603 static final int DEX_OPT_FAILED = -1; 4604 4605 private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets, 4606 boolean forceDex, boolean defer, HashSet<String> done) { 4607 final String[] instructionSets = targetInstructionSets != null ? 4608 targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo); 4609 4610 if (done != null) { 4611 done.add(pkg.packageName); 4612 if (pkg.usesLibraries != null) { 4613 performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done); 4614 } 4615 if (pkg.usesOptionalLibraries != null) { 4616 performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done); 4617 } 4618 } 4619 4620 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) { 4621 return DEX_OPT_SKIPPED; 4622 } 4623 4624 final Collection<String> paths = pkg.getAllCodePaths(); 4625 boolean performedDexOpt = false; 4626 // There are three basic cases here: 4627 // 1.) we need to dexopt, either because we are forced or it is needed 4628 // 2.) we are defering a needed dexopt 4629 // 3.) we are skipping an unneeded dexopt 4630 for (String path : paths) { 4631 for (String instructionSet : instructionSets) { 4632 try { 4633 final boolean isDexOptNeeded = DexFile.isDexOptNeededInternal(path, 4634 pkg.packageName, instructionSet, defer); 4635 if (forceDex || (!defer && isDexOptNeeded)) { 4636 Log.i(TAG, "Running dexopt on: " + pkg.applicationInfo.packageName + " isa=" + instructionSet); 4637 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4638 final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg), 4639 pkg.packageName, instructionSet); 4640 4641 if (ret < 0) { 4642 // Don't bother running dexopt again if we failed, it will probably 4643 // just result in an error again. Also, don't bother dexopting for other 4644 // paths & ISAs. 4645 pkg.mDexOptNeeded = false; 4646 return DEX_OPT_FAILED; 4647 } else { 4648 performedDexOpt = true; 4649 } 4650 } 4651 4652 // We're deciding to defer a needed dexopt. Don't bother dexopting for other 4653 // paths and instruction sets. We'll deal with them all together when we process 4654 // our list of deferred dexopts. 4655 if (defer && isDexOptNeeded) { 4656 if (mDeferredDexOpt == null) { 4657 mDeferredDexOpt = new HashSet<PackageParser.Package>(); 4658 } 4659 mDeferredDexOpt.add(pkg); 4660 return DEX_OPT_DEFERRED; 4661 } 4662 } catch (FileNotFoundException e) { 4663 Slog.w(TAG, "Apk not found for dexopt: " + path); 4664 return DEX_OPT_FAILED; 4665 } catch (IOException e) { 4666 Slog.w(TAG, "IOException reading apk: " + path, e); 4667 return DEX_OPT_FAILED; 4668 } catch (StaleDexCacheError e) { 4669 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e); 4670 return DEX_OPT_FAILED; 4671 } catch (Exception e) { 4672 Slog.w(TAG, "Exception when doing dexopt : ", e); 4673 return DEX_OPT_FAILED; 4674 } 4675 } 4676 } 4677 4678 // If we've gotten here, we're sure that no error occurred and that we haven't 4679 // deferred dex-opt. We've either dex-opted one more paths or instruction sets or 4680 // we've skipped all of them because they are up to date. In both cases this 4681 // package doesn't need dexopt any longer. 4682 pkg.mDexOptNeeded = false; 4683 return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED; 4684 } 4685 4686 private static String[] getAppDexInstructionSets(ApplicationInfo info) { 4687 if (info.primaryCpuAbi != null) { 4688 if (info.secondaryCpuAbi != null) { 4689 return new String[] { 4690 VMRuntime.getInstructionSet(info.primaryCpuAbi), 4691 VMRuntime.getInstructionSet(info.secondaryCpuAbi) }; 4692 } else { 4693 return new String[] { 4694 VMRuntime.getInstructionSet(info.primaryCpuAbi) }; 4695 } 4696 } 4697 4698 return new String[] { getPreferredInstructionSet() }; 4699 } 4700 4701 private static String[] getAppDexInstructionSets(PackageSetting ps) { 4702 if (ps.primaryCpuAbiString != null) { 4703 if (ps.secondaryCpuAbiString != null) { 4704 return new String[] { 4705 VMRuntime.getInstructionSet(ps.primaryCpuAbiString), 4706 VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) }; 4707 } else { 4708 return new String[] { 4709 VMRuntime.getInstructionSet(ps.primaryCpuAbiString) }; 4710 } 4711 } 4712 4713 return new String[] { getPreferredInstructionSet() }; 4714 } 4715 4716 private static String getPreferredInstructionSet() { 4717 if (sPreferredInstructionSet == null) { 4718 sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]); 4719 } 4720 4721 return sPreferredInstructionSet; 4722 } 4723 4724 private static List<String> getAllInstructionSets() { 4725 final String[] allAbis = Build.SUPPORTED_ABIS; 4726 final List<String> allInstructionSets = new ArrayList<String>(allAbis.length); 4727 4728 for (String abi : allAbis) { 4729 final String instructionSet = VMRuntime.getInstructionSet(abi); 4730 if (!allInstructionSets.contains(instructionSet)) { 4731 allInstructionSets.add(instructionSet); 4732 } 4733 } 4734 4735 return allInstructionSets; 4736 } 4737 4738 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer, 4739 boolean inclDependencies) { 4740 HashSet<String> done; 4741 if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) { 4742 done = new HashSet<String>(); 4743 done.add(pkg.packageName); 4744 } else { 4745 done = null; 4746 } 4747 return performDexOptLI(pkg, null /* target instruction sets */, forceDex, defer, done); 4748 } 4749 4750 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 4751 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 4752 Slog.w(TAG, "Unable to update from " + oldPkg.name 4753 + " to " + newPkg.packageName 4754 + ": old package not in system partition"); 4755 return false; 4756 } else if (mPackages.get(oldPkg.name) != null) { 4757 Slog.w(TAG, "Unable to update from " + oldPkg.name 4758 + " to " + newPkg.packageName 4759 + ": old package still exists"); 4760 return false; 4761 } 4762 return true; 4763 } 4764 4765 File getDataPathForUser(int userId) { 4766 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId); 4767 } 4768 4769 private File getDataPathForPackage(String packageName, int userId) { 4770 /* 4771 * Until we fully support multiple users, return the directory we 4772 * previously would have. The PackageManagerTests will need to be 4773 * revised when this is changed back.. 4774 */ 4775 if (userId == 0) { 4776 return new File(mAppDataDir, packageName); 4777 } else { 4778 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 4779 + File.separator + packageName); 4780 } 4781 } 4782 4783 private int createDataDirsLI(String packageName, int uid, String seinfo) { 4784 int[] users = sUserManager.getUserIds(); 4785 int res = mInstaller.install(packageName, uid, uid, seinfo); 4786 if (res < 0) { 4787 return res; 4788 } 4789 for (int user : users) { 4790 if (user != 0) { 4791 res = mInstaller.createUserData(packageName, 4792 UserHandle.getUid(user, uid), user, seinfo); 4793 if (res < 0) { 4794 return res; 4795 } 4796 } 4797 } 4798 return res; 4799 } 4800 4801 private int removeDataDirsLI(String packageName) { 4802 int[] users = sUserManager.getUserIds(); 4803 int res = 0; 4804 for (int user : users) { 4805 int resInner = mInstaller.remove(packageName, user); 4806 if (resInner < 0) { 4807 res = resInner; 4808 } 4809 } 4810 4811 return res; 4812 } 4813 4814 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 4815 PackageParser.Package changingLib) { 4816 if (file.path != null) { 4817 usesLibraryFiles.add(file.path); 4818 return; 4819 } 4820 PackageParser.Package p = mPackages.get(file.apk); 4821 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 4822 // If we are doing this while in the middle of updating a library apk, 4823 // then we need to make sure to use that new apk for determining the 4824 // dependencies here. (We haven't yet finished committing the new apk 4825 // to the package manager state.) 4826 if (p == null || p.packageName.equals(changingLib.packageName)) { 4827 p = changingLib; 4828 } 4829 } 4830 if (p != null) { 4831 usesLibraryFiles.addAll(p.getAllCodePaths()); 4832 } 4833 } 4834 4835 private boolean updateSharedLibrariesLPw(PackageParser.Package pkg, 4836 PackageParser.Package changingLib) { 4837 // We might be upgrading from a version of the platform that did not 4838 // provide per-package native library directories for system apps. 4839 // Fix that up here. 4840 if (isSystemApp(pkg)) { 4841 PackageSetting ps = mSettings.mPackages.get(pkg.applicationInfo.packageName); 4842 if (!isUpdatedSystemApp(pkg)) { 4843 setBundledAppAbisAndRoots(pkg, ps); 4844 } 4845 } 4846 4847 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 4848 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 4849 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 4850 for (int i=0; i<N; i++) { 4851 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 4852 if (file == null) { 4853 Slog.e(TAG, "Package " + pkg.packageName 4854 + " requires unavailable shared library " 4855 + pkg.usesLibraries.get(i) + "; failing!"); 4856 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 4857 return false; 4858 } 4859 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4860 } 4861 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 4862 for (int i=0; i<N; i++) { 4863 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 4864 if (file == null) { 4865 Slog.w(TAG, "Package " + pkg.packageName 4866 + " desires unavailable shared library " 4867 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 4868 } else { 4869 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4870 } 4871 } 4872 N = usesLibraryFiles.size(); 4873 if (N > 0) { 4874 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 4875 } else { 4876 pkg.usesLibraryFiles = null; 4877 } 4878 } 4879 return true; 4880 } 4881 4882 private static boolean hasString(List<String> list, List<String> which) { 4883 if (list == null) { 4884 return false; 4885 } 4886 for (int i=list.size()-1; i>=0; i--) { 4887 for (int j=which.size()-1; j>=0; j--) { 4888 if (which.get(j).equals(list.get(i))) { 4889 return true; 4890 } 4891 } 4892 } 4893 return false; 4894 } 4895 4896 private void updateAllSharedLibrariesLPw() { 4897 for (PackageParser.Package pkg : mPackages.values()) { 4898 updateSharedLibrariesLPw(pkg, null); 4899 } 4900 } 4901 4902 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 4903 PackageParser.Package changingPkg) { 4904 ArrayList<PackageParser.Package> res = null; 4905 for (PackageParser.Package pkg : mPackages.values()) { 4906 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 4907 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 4908 if (res == null) { 4909 res = new ArrayList<PackageParser.Package>(); 4910 } 4911 res.add(pkg); 4912 updateSharedLibrariesLPw(pkg, changingPkg); 4913 } 4914 } 4915 return res; 4916 } 4917 4918 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, 4919 int parseFlags, int scanMode, long currentTime, UserHandle user, String abiOverride) { 4920 final File scanFile = new File(pkg.codePath); 4921 if (pkg.applicationInfo.getCodePath() == null || 4922 pkg.applicationInfo.getResourcePath() == null) { 4923 // Bail out. The resource and code paths haven't been set. 4924 Slog.w(TAG, " Code and resource paths haven't been set correctly"); 4925 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK; 4926 return null; 4927 } 4928 4929 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4930 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 4931 } 4932 4933 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 4934 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED; 4935 } 4936 4937 if (mCustomResolverComponentName != null && 4938 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 4939 setUpCustomResolverActivity(pkg); 4940 } 4941 4942 if (pkg.packageName.equals("android")) { 4943 synchronized (mPackages) { 4944 if (mAndroidApplication != null) { 4945 Slog.w(TAG, "*************************************************"); 4946 Slog.w(TAG, "Core android package being redefined. Skipping."); 4947 Slog.w(TAG, " file=" + scanFile); 4948 Slog.w(TAG, "*************************************************"); 4949 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 4950 return null; 4951 } 4952 4953 // Set up information for our fall-back user intent resolution activity. 4954 mPlatformPackage = pkg; 4955 pkg.mVersionCode = mSdkVersion; 4956 mAndroidApplication = pkg.applicationInfo; 4957 4958 if (!mResolverReplaced) { 4959 mResolveActivity.applicationInfo = mAndroidApplication; 4960 mResolveActivity.name = ResolverActivity.class.getName(); 4961 mResolveActivity.packageName = mAndroidApplication.packageName; 4962 mResolveActivity.processName = "system:ui"; 4963 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 4964 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 4965 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 4966 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 4967 mResolveActivity.exported = true; 4968 mResolveActivity.enabled = true; 4969 mResolveInfo.activityInfo = mResolveActivity; 4970 mResolveInfo.priority = 0; 4971 mResolveInfo.preferredOrder = 0; 4972 mResolveInfo.match = 0; 4973 mResolveComponentName = new ComponentName( 4974 mAndroidApplication.packageName, mResolveActivity.name); 4975 } 4976 } 4977 } 4978 4979 if (DEBUG_PACKAGE_SCANNING) { 4980 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 4981 Log.d(TAG, "Scanning package " + pkg.packageName); 4982 } 4983 4984 if (mPackages.containsKey(pkg.packageName) 4985 || mSharedLibraries.containsKey(pkg.packageName)) { 4986 Slog.w(TAG, "Application package " + pkg.packageName 4987 + " already installed. Skipping duplicate."); 4988 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 4989 return null; 4990 } 4991 4992 // Initialize package source and resource directories 4993 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 4994 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 4995 4996 SharedUserSetting suid = null; 4997 PackageSetting pkgSetting = null; 4998 4999 if (!isSystemApp(pkg)) { 5000 // Only system apps can use these features. 5001 pkg.mOriginalPackages = null; 5002 pkg.mRealPackage = null; 5003 pkg.mAdoptPermissions = null; 5004 } 5005 5006 // writer 5007 synchronized (mPackages) { 5008 if (pkg.mSharedUserId != null) { 5009 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true); 5010 if (suid == null) { 5011 Slog.w(TAG, "Creating application package " + pkg.packageName 5012 + " for shared user failed"); 5013 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 5014 return null; 5015 } 5016 if (DEBUG_PACKAGE_SCANNING) { 5017 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5018 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5019 + "): packages=" + suid.packages); 5020 } 5021 } 5022 5023 // Check if we are renaming from an original package name. 5024 PackageSetting origPackage = null; 5025 String realName = null; 5026 if (pkg.mOriginalPackages != null) { 5027 // This package may need to be renamed to a previously 5028 // installed name. Let's check on that... 5029 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5030 if (pkg.mOriginalPackages.contains(renamed)) { 5031 // This package had originally been installed as the 5032 // original name, and we have already taken care of 5033 // transitioning to the new one. Just update the new 5034 // one to continue using the old name. 5035 realName = pkg.mRealPackage; 5036 if (!pkg.packageName.equals(renamed)) { 5037 // Callers into this function may have already taken 5038 // care of renaming the package; only do it here if 5039 // it is not already done. 5040 pkg.setPackageName(renamed); 5041 } 5042 5043 } else { 5044 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5045 if ((origPackage = mSettings.peekPackageLPr( 5046 pkg.mOriginalPackages.get(i))) != null) { 5047 // We do have the package already installed under its 5048 // original name... should we use it? 5049 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5050 // New package is not compatible with original. 5051 origPackage = null; 5052 continue; 5053 } else if (origPackage.sharedUser != null) { 5054 // Make sure uid is compatible between packages. 5055 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5056 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5057 + " to " + pkg.packageName + ": old uid " 5058 + origPackage.sharedUser.name 5059 + " differs from " + pkg.mSharedUserId); 5060 origPackage = null; 5061 continue; 5062 } 5063 } else { 5064 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5065 + pkg.packageName + " to old name " + origPackage.name); 5066 } 5067 break; 5068 } 5069 } 5070 } 5071 } 5072 5073 if (mTransferedPackages.contains(pkg.packageName)) { 5074 Slog.w(TAG, "Package " + pkg.packageName 5075 + " was transferred to another, but its .apk remains"); 5076 } 5077 5078 // Just create the setting, don't add it yet. For already existing packages 5079 // the PkgSetting exists already and doesn't have to be created. 5080 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5081 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 5082 pkg.applicationInfo.primaryCpuAbi, 5083 pkg.applicationInfo.secondaryCpuAbi, 5084 pkg.applicationInfo.flags, user, false); 5085 if (pkgSetting == null) { 5086 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed"); 5087 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 5088 return null; 5089 } 5090 5091 if (pkgSetting.origPackage != null) { 5092 // If we are first transitioning from an original package, 5093 // fix up the new package's name now. We need to do this after 5094 // looking up the package under its new name, so getPackageLP 5095 // can take care of fiddling things correctly. 5096 pkg.setPackageName(origPackage.name); 5097 5098 // File a report about this. 5099 String msg = "New package " + pkgSetting.realName 5100 + " renamed to replace old package " + pkgSetting.name; 5101 reportSettingsProblem(Log.WARN, msg); 5102 5103 // Make a note of it. 5104 mTransferedPackages.add(origPackage.name); 5105 5106 // No longer need to retain this. 5107 pkgSetting.origPackage = null; 5108 } 5109 5110 if (realName != null) { 5111 // Make a note of it. 5112 mTransferedPackages.add(pkg.packageName); 5113 } 5114 5115 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5116 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5117 } 5118 5119 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5120 // Check all shared libraries and map to their actual file path. 5121 // We only do this here for apps not on a system dir, because those 5122 // are the only ones that can fail an install due to this. We 5123 // will take care of the system apps by updating all of their 5124 // library paths after the scan is done. 5125 if (!updateSharedLibrariesLPw(pkg, null)) { 5126 return null; 5127 } 5128 } 5129 5130 if (mFoundPolicyFile) { 5131 SELinuxMMAC.assignSeinfoValue(pkg); 5132 } 5133 5134 pkg.applicationInfo.uid = pkgSetting.appId; 5135 pkg.mExtras = pkgSetting; 5136 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5137 if (!verifySignaturesLP(pkgSetting, pkg)) { 5138 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5139 return null; 5140 } 5141 // The signature has changed, but this package is in the system 5142 // image... let's recover! 5143 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5144 // However... if this package is part of a shared user, but it 5145 // doesn't match the signature of the shared user, let's fail. 5146 // What this means is that you can't change the signatures 5147 // associated with an overall shared user, which doesn't seem all 5148 // that unreasonable. 5149 if (pkgSetting.sharedUser != null) { 5150 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5151 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5152 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser); 5153 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 5154 return null; 5155 } 5156 } 5157 // File a report about this. 5158 String msg = "System package " + pkg.packageName 5159 + " signature changed; retaining data."; 5160 reportSettingsProblem(Log.WARN, msg); 5161 } 5162 } else { 5163 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 5164 Slog.e(TAG, "Package " + pkg.packageName 5165 + " upgrade keys do not match the previously installed version; "); 5166 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 5167 return null; 5168 } else { 5169 // signatures may have changed as result of upgrade 5170 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5171 } 5172 } 5173 // Verify that this new package doesn't have any content providers 5174 // that conflict with existing packages. Only do this if the 5175 // package isn't already installed, since we don't want to break 5176 // things that are installed. 5177 if ((scanMode&SCAN_NEW_INSTALL) != 0) { 5178 final int N = pkg.providers.size(); 5179 int i; 5180 for (i=0; i<N; i++) { 5181 PackageParser.Provider p = pkg.providers.get(i); 5182 if (p.info.authority != null) { 5183 String names[] = p.info.authority.split(";"); 5184 for (int j = 0; j < names.length; j++) { 5185 if (mProvidersByAuthority.containsKey(names[j])) { 5186 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5187 Slog.w(TAG, "Can't install because provider name " + names[j] + 5188 " (in package " + pkg.applicationInfo.packageName + 5189 ") is already used by " 5190 + ((other != null && other.getComponentName() != null) 5191 ? other.getComponentName().getPackageName() : "?")); 5192 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 5193 return null; 5194 } 5195 } 5196 } 5197 } 5198 } 5199 5200 if (pkg.mAdoptPermissions != null) { 5201 // This package wants to adopt ownership of permissions from 5202 // another package. 5203 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 5204 final String origName = pkg.mAdoptPermissions.get(i); 5205 final PackageSetting orig = mSettings.peekPackageLPr(origName); 5206 if (orig != null) { 5207 if (verifyPackageUpdateLPr(orig, pkg)) { 5208 Slog.i(TAG, "Adopting permissions from " + origName + " to " 5209 + pkg.packageName); 5210 mSettings.transferPermissionsLPw(origName, pkg.packageName); 5211 } 5212 } 5213 } 5214 } 5215 } 5216 5217 final String pkgName = pkg.packageName; 5218 5219 final long scanFileTime = scanFile.lastModified(); 5220 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0; 5221 pkg.applicationInfo.processName = fixProcessName( 5222 pkg.applicationInfo.packageName, 5223 pkg.applicationInfo.processName, 5224 pkg.applicationInfo.uid); 5225 5226 File dataPath; 5227 if (mPlatformPackage == pkg) { 5228 // The system package is special. 5229 dataPath = new File (Environment.getDataDirectory(), "system"); 5230 pkg.applicationInfo.dataDir = dataPath.getPath(); 5231 } else { 5232 // This is a normal package, need to make its data directory. 5233 dataPath = getDataPathForPackage(pkg.packageName, 0); 5234 5235 boolean uidError = false; 5236 5237 if (dataPath.exists()) { 5238 int currentUid = 0; 5239 try { 5240 StructStat stat = Os.stat(dataPath.getPath()); 5241 currentUid = stat.st_uid; 5242 } catch (ErrnoException e) { 5243 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 5244 } 5245 5246 // If we have mismatched owners for the data path, we have a problem. 5247 if (currentUid != pkg.applicationInfo.uid) { 5248 boolean recovered = false; 5249 if (currentUid == 0) { 5250 // The directory somehow became owned by root. Wow. 5251 // This is probably because the system was stopped while 5252 // installd was in the middle of messing with its libs 5253 // directory. Ask installd to fix that. 5254 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 5255 pkg.applicationInfo.uid); 5256 if (ret >= 0) { 5257 recovered = true; 5258 String msg = "Package " + pkg.packageName 5259 + " unexpectedly changed to uid 0; recovered to " + 5260 + pkg.applicationInfo.uid; 5261 reportSettingsProblem(Log.WARN, msg); 5262 } 5263 } 5264 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5265 || (scanMode&SCAN_BOOTING) != 0)) { 5266 // If this is a system app, we can at least delete its 5267 // current data so the application will still work. 5268 int ret = removeDataDirsLI(pkgName); 5269 if (ret >= 0) { 5270 // TODO: Kill the processes first 5271 // Old data gone! 5272 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5273 ? "System package " : "Third party package "; 5274 String msg = prefix + pkg.packageName 5275 + " has changed from uid: " 5276 + currentUid + " to " 5277 + pkg.applicationInfo.uid + "; old data erased"; 5278 reportSettingsProblem(Log.WARN, msg); 5279 recovered = true; 5280 5281 // And now re-install the app. 5282 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5283 pkg.applicationInfo.seinfo); 5284 if (ret == -1) { 5285 // Ack should not happen! 5286 msg = prefix + pkg.packageName 5287 + " could not have data directory re-created after delete."; 5288 reportSettingsProblem(Log.WARN, msg); 5289 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 5290 return null; 5291 } 5292 } 5293 if (!recovered) { 5294 mHasSystemUidErrors = true; 5295 } 5296 } else if (!recovered) { 5297 // If we allow this install to proceed, we will be broken. 5298 // Abort, abort! 5299 mLastScanError = PackageManager.INSTALL_FAILED_UID_CHANGED; 5300 return null; 5301 } 5302 if (!recovered) { 5303 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 5304 + pkg.applicationInfo.uid + "/fs_" 5305 + currentUid; 5306 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 5307 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 5308 String msg = "Package " + pkg.packageName 5309 + " has mismatched uid: " 5310 + currentUid + " on disk, " 5311 + pkg.applicationInfo.uid + " in settings"; 5312 // writer 5313 synchronized (mPackages) { 5314 mSettings.mReadMessages.append(msg); 5315 mSettings.mReadMessages.append('\n'); 5316 uidError = true; 5317 if (!pkgSetting.uidError) { 5318 reportSettingsProblem(Log.ERROR, msg); 5319 } 5320 } 5321 } 5322 } 5323 pkg.applicationInfo.dataDir = dataPath.getPath(); 5324 if (mShouldRestoreconData) { 5325 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 5326 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 5327 pkg.applicationInfo.uid); 5328 } 5329 } else { 5330 if (DEBUG_PACKAGE_SCANNING) { 5331 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5332 Log.v(TAG, "Want this data dir: " + dataPath); 5333 } 5334 //invoke installer to do the actual installation 5335 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5336 pkg.applicationInfo.seinfo); 5337 if (ret < 0) { 5338 // Error from installer 5339 Slog.w(TAG, "Unable to create data dirs [errorCode=" + ret + "]"); 5340 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 5341 return null; 5342 } 5343 5344 if (dataPath.exists()) { 5345 pkg.applicationInfo.dataDir = dataPath.getPath(); 5346 } else { 5347 Slog.w(TAG, "Unable to create data directory: " + dataPath); 5348 pkg.applicationInfo.dataDir = null; 5349 } 5350 } 5351 5352 pkgSetting.uidError = uidError; 5353 } 5354 5355 final String path = scanFile.getPath(); 5356 final String codePath = pkg.applicationInfo.getCodePath(); 5357 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 5358 // For the case where we had previously uninstalled an update, get rid 5359 // of any native binaries we might have unpackaged. Note that this assumes 5360 // that system app updates were not installed via ASEC. 5361 // 5362 // TODO(multiArch): Is this cleanup really necessary ? 5363 NativeLibraryHelper.removeNativeBinariesFromDirLI( 5364 new File(codePath, LIB_DIR_NAME), false /* delete dirs */); 5365 setBundledAppAbisAndRoots(pkg, pkgSetting); 5366 setNativeLibraryPaths(pkg); 5367 } else { 5368 // TODO: We can probably be smarter about this stuff. For installed apps, 5369 // we can calculate this information at install time once and for all. For 5370 // system apps, we can probably assume that this information doesn't change 5371 // after the first boot scan. As things stand, we do lots of unnecessary work. 5372 5373 // Give ourselves some initial paths; we'll come back for another 5374 // pass once we've determined ABI below. 5375 setNativeLibraryPaths(pkg); 5376 5377 final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg); 5378 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 5379 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 5380 5381 NativeLibraryHelper.Handle handle = null; 5382 try { 5383 handle = NativeLibraryHelper.Handle.create(scanFile); 5384 // TODO(multiArch): This can be null for apps that didn't go through the 5385 // usual installation process. We can calculate it again, like we 5386 // do during install time. 5387 // 5388 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 5389 // unnecessary. 5390 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 5391 5392 // Null out the abis so that they can be recalculated. 5393 pkg.applicationInfo.primaryCpuAbi = null; 5394 pkg.applicationInfo.secondaryCpuAbi = null; 5395 if (isMultiArch(pkg.applicationInfo)) { 5396 // Warn if we've set an abiOverride for multi-lib packages.. 5397 // By definition, we need to copy both 32 and 64 bit libraries for 5398 // such packages. 5399 if (abiOverride != null) { 5400 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 5401 } 5402 5403 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 5404 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 5405 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 5406 if (isAsec) { 5407 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 5408 } else { 5409 abi32 = copyNativeLibrariesForInternalApp(handle, 5410 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, useIsaSpecificSubdirs); 5411 } 5412 } 5413 5414 if (abi32 < 0 && abi32 != PackageManager.NO_NATIVE_LIBRARIES) { 5415 Slog.w(TAG, "Error unpackaging 32 bit native libs for multiarch app, errorCode=" + abi32); 5416 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5417 return null; 5418 } 5419 5420 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5421 if (isAsec) { 5422 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 5423 } else { 5424 abi64 = copyNativeLibrariesForInternalApp(handle, 5425 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, useIsaSpecificSubdirs); 5426 } 5427 } 5428 5429 if (abi64 < 0 && abi64 != PackageManager.NO_NATIVE_LIBRARIES) { 5430 Slog.w(TAG, "Error unpackaging 64 bit native libs for multiarch app, errorCode=" + abi32); 5431 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5432 return null; 5433 } 5434 5435 5436 if (abi64 >= 0) { 5437 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 5438 } 5439 5440 if (abi32 >= 0) { 5441 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 5442 if (abi64 >= 0) { 5443 pkg.applicationInfo.secondaryCpuAbi = abi; 5444 } else { 5445 pkg.applicationInfo.primaryCpuAbi = abi; 5446 } 5447 } 5448 } else { 5449 String[] abiList = (abiOverride != null) ? 5450 new String[] { abiOverride } : Build.SUPPORTED_ABIS; 5451 5452 // Enable gross and lame hacks for apps that are built with old 5453 // SDK tools. We must scan their APKs for renderscript bitcode and 5454 // not launch them if it's present. Don't bother checking on devices 5455 // that don't have 64 bit support. 5456 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && abiOverride == null && 5457 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5458 abiList = Build.SUPPORTED_32_BIT_ABIS; 5459 } 5460 5461 final int copyRet; 5462 if (isAsec) { 5463 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 5464 } else { 5465 copyRet = copyNativeLibrariesForInternalApp(handle, nativeLibraryRoot, abiList, 5466 useIsaSpecificSubdirs); 5467 } 5468 5469 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5470 Slog.w(TAG, "Error unpackaging native libs for app, errorCode=" + copyRet); 5471 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5472 return null; 5473 } 5474 5475 if (copyRet >= 0) { 5476 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 5477 } 5478 } 5479 } catch (IOException ioe) { 5480 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 5481 } finally { 5482 IoUtils.closeQuietly(handle); 5483 } 5484 5485 // Now that we've calculated the ABIs and determined if it's an internal app, 5486 // we will go ahead and populate the nativeLibraryPath. 5487 setNativeLibraryPaths(pkg); 5488 5489 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 5490 final int[] userIds = sUserManager.getUserIds(); 5491 synchronized (mInstallLock) { 5492 // Create a native library symlink only if we have native libraries 5493 // and if the native libraries are 32 bit libraries. We do not provide 5494 // this symlink for 64 bit libraries. 5495 if (pkg.applicationInfo.primaryCpuAbi != null && 5496 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 5497 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 5498 for (int userId : userIds) { 5499 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 5500 Slog.w(TAG, "Failed linking native library dir (user=" + userId 5501 + ")"); 5502 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5503 return null; 5504 } 5505 } 5506 } 5507 } 5508 5509 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 5510 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 5511 } 5512 5513 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 5514 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 5515 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 5516 5517 // Push the derived path down into PackageSettings so we know what to 5518 // clean up at uninstall time. 5519 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 5520 5521 if (DEBUG_ABI_SELECTION) { 5522 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 5523 " primary=" + pkg.applicationInfo.primaryCpuAbi + 5524 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 5525 } 5526 5527 if ((scanMode&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 5528 // We don't do this here during boot because we can do it all 5529 // at once after scanning all existing packages. 5530 // 5531 // We also do this *before* we perform dexopt on this package, so that 5532 // we can avoid redundant dexopts, and also to make sure we've got the 5533 // code and package path correct. 5534 if (!adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 5535 pkg, forceDex, (scanMode & SCAN_DEFER_DEX) != 0)) { 5536 mLastScanError = PackageManager.INSTALL_FAILED_CPU_ABI_INCOMPATIBLE; 5537 return null; 5538 } 5539 } 5540 5541 if ((scanMode&SCAN_NO_DEX) == 0) { 5542 if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5543 == DEX_OPT_FAILED) { 5544 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5545 removeDataDirsLI(pkg.packageName); 5546 } 5547 5548 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT; 5549 return null; 5550 } 5551 } 5552 5553 if (mFactoryTest && pkg.requestedPermissions.contains( 5554 android.Manifest.permission.FACTORY_TEST)) { 5555 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 5556 } 5557 5558 ArrayList<PackageParser.Package> clientLibPkgs = null; 5559 5560 // writer 5561 synchronized (mPackages) { 5562 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5563 // Only system apps can add new shared libraries. 5564 if (pkg.libraryNames != null) { 5565 for (int i=0; i<pkg.libraryNames.size(); i++) { 5566 String name = pkg.libraryNames.get(i); 5567 boolean allowed = false; 5568 if (isUpdatedSystemApp(pkg)) { 5569 // New library entries can only be added through the 5570 // system image. This is important to get rid of a lot 5571 // of nasty edge cases: for example if we allowed a non- 5572 // system update of the app to add a library, then uninstalling 5573 // the update would make the library go away, and assumptions 5574 // we made such as through app install filtering would now 5575 // have allowed apps on the device which aren't compatible 5576 // with it. Better to just have the restriction here, be 5577 // conservative, and create many fewer cases that can negatively 5578 // impact the user experience. 5579 final PackageSetting sysPs = mSettings 5580 .getDisabledSystemPkgLPr(pkg.packageName); 5581 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 5582 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 5583 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 5584 allowed = true; 5585 allowed = true; 5586 break; 5587 } 5588 } 5589 } 5590 } else { 5591 allowed = true; 5592 } 5593 if (allowed) { 5594 if (!mSharedLibraries.containsKey(name)) { 5595 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 5596 } else if (!name.equals(pkg.packageName)) { 5597 Slog.w(TAG, "Package " + pkg.packageName + " library " 5598 + name + " already exists; skipping"); 5599 } 5600 } else { 5601 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 5602 + name + " that is not declared on system image; skipping"); 5603 } 5604 } 5605 if ((scanMode&SCAN_BOOTING) == 0) { 5606 // If we are not booting, we need to update any applications 5607 // that are clients of our shared library. If we are booting, 5608 // this will all be done once the scan is complete. 5609 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 5610 } 5611 } 5612 } 5613 } 5614 5615 // We also need to dexopt any apps that are dependent on this library. Note that 5616 // if these fail, we should abort the install since installing the library will 5617 // result in some apps being broken. 5618 if (clientLibPkgs != null) { 5619 if ((scanMode&SCAN_NO_DEX) == 0) { 5620 for (int i=0; i<clientLibPkgs.size(); i++) { 5621 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5622 if (performDexOptLI(clientPkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5623 == DEX_OPT_FAILED) { 5624 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5625 removeDataDirsLI(pkg.packageName); 5626 } 5627 5628 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT; 5629 return null; 5630 } 5631 } 5632 } 5633 } 5634 5635 // Request the ActivityManager to kill the process(only for existing packages) 5636 // so that we do not end up in a confused state while the user is still using the older 5637 // version of the application while the new one gets installed. 5638 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 5639 // If the package lives in an asec, tell everyone that the container is going 5640 // away so they can clean up any references to its resources (which would prevent 5641 // vold from being able to unmount the asec) 5642 if (isForwardLocked(pkg) || isExternal(pkg)) { 5643 if (DEBUG_INSTALL) { 5644 Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE"); 5645 } 5646 final int[] uidArray = new int[] { pkg.applicationInfo.uid }; 5647 final ArrayList<String> pkgList = new ArrayList<String>(1); 5648 pkgList.add(pkg.applicationInfo.packageName); 5649 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 5650 } 5651 5652 // Post the request that it be killed now that the going-away broadcast is en route 5653 killApplication(pkg.applicationInfo.packageName, 5654 pkg.applicationInfo.uid, "update pkg"); 5655 } 5656 5657 // Also need to kill any apps that are dependent on the library. 5658 if (clientLibPkgs != null) { 5659 for (int i=0; i<clientLibPkgs.size(); i++) { 5660 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5661 killApplication(clientPkg.applicationInfo.packageName, 5662 clientPkg.applicationInfo.uid, "update lib"); 5663 } 5664 } 5665 5666 // writer 5667 synchronized (mPackages) { 5668 // We don't expect installation to fail beyond this point, 5669 if ((scanMode&SCAN_MONITOR) != 0) { 5670 mAppDirs.put(pkg.codePath, pkg); 5671 } 5672 // Add the new setting to mSettings 5673 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 5674 // Add the new setting to mPackages 5675 mPackages.put(pkg.applicationInfo.packageName, pkg); 5676 // Make sure we don't accidentally delete its data. 5677 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 5678 while (iter.hasNext()) { 5679 PackageCleanItem item = iter.next(); 5680 if (pkgName.equals(item.packageName)) { 5681 iter.remove(); 5682 } 5683 } 5684 5685 // Take care of first install / last update times. 5686 if (currentTime != 0) { 5687 if (pkgSetting.firstInstallTime == 0) { 5688 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 5689 } else if ((scanMode&SCAN_UPDATE_TIME) != 0) { 5690 pkgSetting.lastUpdateTime = currentTime; 5691 } 5692 } else if (pkgSetting.firstInstallTime == 0) { 5693 // We need *something*. Take time time stamp of the file. 5694 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 5695 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 5696 if (scanFileTime != pkgSetting.timeStamp) { 5697 // A package on the system image has changed; consider this 5698 // to be an update. 5699 pkgSetting.lastUpdateTime = scanFileTime; 5700 } 5701 } 5702 5703 // Add the package's KeySets to the global KeySetManagerService 5704 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5705 try { 5706 // Old KeySetData no longer valid. 5707 ksms.removeAppKeySetData(pkg.packageName); 5708 ksms.addSigningKeySetToPackage(pkg.packageName, pkg.mSigningKeys); 5709 if (pkg.mKeySetMapping != null) { 5710 for (Map.Entry<String, ArraySet<PublicKey>> entry : 5711 pkg.mKeySetMapping.entrySet()) { 5712 if (entry.getValue() != null) { 5713 ksms.addDefinedKeySetToPackage(pkg.packageName, 5714 entry.getValue(), entry.getKey()); 5715 } 5716 } 5717 if (pkg.mUpgradeKeySets != null) { 5718 for (String upgradeAlias : pkg.mUpgradeKeySets) { 5719 ksms.addUpgradeKeySetToPackage(pkg.packageName, upgradeAlias); 5720 } 5721 } 5722 } 5723 } catch (NullPointerException e) { 5724 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 5725 } catch (IllegalArgumentException e) { 5726 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 5727 } 5728 5729 int N = pkg.providers.size(); 5730 StringBuilder r = null; 5731 int i; 5732 for (i=0; i<N; i++) { 5733 PackageParser.Provider p = pkg.providers.get(i); 5734 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 5735 p.info.processName, pkg.applicationInfo.uid); 5736 mProviders.addProvider(p); 5737 p.syncable = p.info.isSyncable; 5738 if (p.info.authority != null) { 5739 String names[] = p.info.authority.split(";"); 5740 p.info.authority = null; 5741 for (int j = 0; j < names.length; j++) { 5742 if (j == 1 && p.syncable) { 5743 // We only want the first authority for a provider to possibly be 5744 // syncable, so if we already added this provider using a different 5745 // authority clear the syncable flag. We copy the provider before 5746 // changing it because the mProviders object contains a reference 5747 // to a provider that we don't want to change. 5748 // Only do this for the second authority since the resulting provider 5749 // object can be the same for all future authorities for this provider. 5750 p = new PackageParser.Provider(p); 5751 p.syncable = false; 5752 } 5753 if (!mProvidersByAuthority.containsKey(names[j])) { 5754 mProvidersByAuthority.put(names[j], p); 5755 if (p.info.authority == null) { 5756 p.info.authority = names[j]; 5757 } else { 5758 p.info.authority = p.info.authority + ";" + names[j]; 5759 } 5760 if (DEBUG_PACKAGE_SCANNING) { 5761 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5762 Log.d(TAG, "Registered content provider: " + names[j] 5763 + ", className = " + p.info.name + ", isSyncable = " 5764 + p.info.isSyncable); 5765 } 5766 } else { 5767 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5768 Slog.w(TAG, "Skipping provider name " + names[j] + 5769 " (in package " + pkg.applicationInfo.packageName + 5770 "): name already used by " 5771 + ((other != null && other.getComponentName() != null) 5772 ? other.getComponentName().getPackageName() : "?")); 5773 } 5774 } 5775 } 5776 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5777 if (r == null) { 5778 r = new StringBuilder(256); 5779 } else { 5780 r.append(' '); 5781 } 5782 r.append(p.info.name); 5783 } 5784 } 5785 if (r != null) { 5786 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 5787 } 5788 5789 N = pkg.services.size(); 5790 r = null; 5791 for (i=0; i<N; i++) { 5792 PackageParser.Service s = pkg.services.get(i); 5793 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 5794 s.info.processName, pkg.applicationInfo.uid); 5795 mServices.addService(s); 5796 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5797 if (r == null) { 5798 r = new StringBuilder(256); 5799 } else { 5800 r.append(' '); 5801 } 5802 r.append(s.info.name); 5803 } 5804 } 5805 if (r != null) { 5806 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 5807 } 5808 5809 N = pkg.receivers.size(); 5810 r = null; 5811 for (i=0; i<N; i++) { 5812 PackageParser.Activity a = pkg.receivers.get(i); 5813 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5814 a.info.processName, pkg.applicationInfo.uid); 5815 mReceivers.addActivity(a, "receiver"); 5816 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5817 if (r == null) { 5818 r = new StringBuilder(256); 5819 } else { 5820 r.append(' '); 5821 } 5822 r.append(a.info.name); 5823 } 5824 } 5825 if (r != null) { 5826 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 5827 } 5828 5829 N = pkg.activities.size(); 5830 r = null; 5831 for (i=0; i<N; i++) { 5832 PackageParser.Activity a = pkg.activities.get(i); 5833 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5834 a.info.processName, pkg.applicationInfo.uid); 5835 mActivities.addActivity(a, "activity"); 5836 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5837 if (r == null) { 5838 r = new StringBuilder(256); 5839 } else { 5840 r.append(' '); 5841 } 5842 r.append(a.info.name); 5843 } 5844 } 5845 if (r != null) { 5846 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 5847 } 5848 5849 N = pkg.permissionGroups.size(); 5850 r = null; 5851 for (i=0; i<N; i++) { 5852 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 5853 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 5854 if (cur == null) { 5855 mPermissionGroups.put(pg.info.name, pg); 5856 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5857 if (r == null) { 5858 r = new StringBuilder(256); 5859 } else { 5860 r.append(' '); 5861 } 5862 r.append(pg.info.name); 5863 } 5864 } else { 5865 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 5866 + pg.info.packageName + " ignored: original from " 5867 + cur.info.packageName); 5868 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5869 if (r == null) { 5870 r = new StringBuilder(256); 5871 } else { 5872 r.append(' '); 5873 } 5874 r.append("DUP:"); 5875 r.append(pg.info.name); 5876 } 5877 } 5878 } 5879 if (r != null) { 5880 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 5881 } 5882 5883 N = pkg.permissions.size(); 5884 r = null; 5885 for (i=0; i<N; i++) { 5886 PackageParser.Permission p = pkg.permissions.get(i); 5887 HashMap<String, BasePermission> permissionMap = 5888 p.tree ? mSettings.mPermissionTrees 5889 : mSettings.mPermissions; 5890 p.group = mPermissionGroups.get(p.info.group); 5891 if (p.info.group == null || p.group != null) { 5892 BasePermission bp = permissionMap.get(p.info.name); 5893 if (bp == null) { 5894 bp = new BasePermission(p.info.name, p.info.packageName, 5895 BasePermission.TYPE_NORMAL); 5896 permissionMap.put(p.info.name, bp); 5897 } 5898 if (bp.perm == null) { 5899 if (bp.sourcePackage != null 5900 && !bp.sourcePackage.equals(p.info.packageName)) { 5901 // If this is a permission that was formerly defined by a non-system 5902 // app, but is now defined by a system app (following an upgrade), 5903 // discard the previous declaration and consider the system's to be 5904 // canonical. 5905 if (isSystemApp(p.owner)) { 5906 String msg = "New decl " + p.owner + " of permission " 5907 + p.info.name + " is system"; 5908 reportSettingsProblem(Log.WARN, msg); 5909 bp.sourcePackage = null; 5910 } 5911 } 5912 if (bp.sourcePackage == null 5913 || bp.sourcePackage.equals(p.info.packageName)) { 5914 BasePermission tree = findPermissionTreeLP(p.info.name); 5915 if (tree == null 5916 || tree.sourcePackage.equals(p.info.packageName)) { 5917 bp.packageSetting = pkgSetting; 5918 bp.perm = p; 5919 bp.uid = pkg.applicationInfo.uid; 5920 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5921 if (r == null) { 5922 r = new StringBuilder(256); 5923 } else { 5924 r.append(' '); 5925 } 5926 r.append(p.info.name); 5927 } 5928 } else { 5929 Slog.w(TAG, "Permission " + p.info.name + " from package " 5930 + p.info.packageName + " ignored: base tree " 5931 + tree.name + " is from package " 5932 + tree.sourcePackage); 5933 } 5934 } else { 5935 Slog.w(TAG, "Permission " + p.info.name + " from package " 5936 + p.info.packageName + " ignored: original from " 5937 + bp.sourcePackage); 5938 } 5939 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5940 if (r == null) { 5941 r = new StringBuilder(256); 5942 } else { 5943 r.append(' '); 5944 } 5945 r.append("DUP:"); 5946 r.append(p.info.name); 5947 } 5948 if (bp.perm == p) { 5949 bp.protectionLevel = p.info.protectionLevel; 5950 } 5951 } else { 5952 Slog.w(TAG, "Permission " + p.info.name + " from package " 5953 + p.info.packageName + " ignored: no group " 5954 + p.group); 5955 } 5956 } 5957 if (r != null) { 5958 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 5959 } 5960 5961 N = pkg.instrumentation.size(); 5962 r = null; 5963 for (i=0; i<N; i++) { 5964 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 5965 a.info.packageName = pkg.applicationInfo.packageName; 5966 a.info.sourceDir = pkg.applicationInfo.sourceDir; 5967 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 5968 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 5969 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 5970 a.info.dataDir = pkg.applicationInfo.dataDir; 5971 5972 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 5973 // need other information about the application, like the ABI and what not ? 5974 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 5975 mInstrumentation.put(a.getComponentName(), a); 5976 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5977 if (r == null) { 5978 r = new StringBuilder(256); 5979 } else { 5980 r.append(' '); 5981 } 5982 r.append(a.info.name); 5983 } 5984 } 5985 if (r != null) { 5986 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 5987 } 5988 5989 if (pkg.protectedBroadcasts != null) { 5990 N = pkg.protectedBroadcasts.size(); 5991 for (i=0; i<N; i++) { 5992 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 5993 } 5994 } 5995 5996 pkgSetting.setTimeStamp(scanFileTime); 5997 5998 // Create idmap files for pairs of (packages, overlay packages). 5999 // Note: "android", ie framework-res.apk, is handled by native layers. 6000 if (pkg.mOverlayTarget != null) { 6001 // This is an overlay package. 6002 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6003 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6004 mOverlays.put(pkg.mOverlayTarget, 6005 new HashMap<String, PackageParser.Package>()); 6006 } 6007 HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6008 map.put(pkg.packageName, pkg); 6009 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6010 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6011 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 6012 return null; 6013 } 6014 } 6015 } else if (mOverlays.containsKey(pkg.packageName) && 6016 !pkg.packageName.equals("android")) { 6017 // This is a regular package, with one or more known overlay packages. 6018 createIdmapsForPackageLI(pkg); 6019 } 6020 } 6021 6022 return pkg; 6023 } 6024 6025 /** 6026 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6027 * i.e, so that all packages can be run inside a single process if required. 6028 * 6029 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6030 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6031 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6032 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6033 * updating a package that belongs to a shared user. 6034 * 6035 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6036 * adds unnecessary complexity. 6037 */ 6038 private boolean adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6039 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6040 String requiredInstructionSet = null; 6041 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6042 requiredInstructionSet = VMRuntime.getInstructionSet( 6043 scannedPackage.applicationInfo.primaryCpuAbi); 6044 } 6045 6046 PackageSetting requirer = null; 6047 for (PackageSetting ps : packagesForUser) { 6048 // If packagesForUser contains scannedPackage, we skip it. This will happen 6049 // when scannedPackage is an update of an existing package. Without this check, 6050 // we will never be able to change the ABI of any package belonging to a shared 6051 // user, even if it's compatible with other packages. 6052 if (scannedPackage == null || ! scannedPackage.packageName.equals(ps.name)) { 6053 if (ps.primaryCpuAbiString == null) { 6054 continue; 6055 } 6056 6057 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6058 if (requiredInstructionSet != null) { 6059 if (!instructionSet.equals(requiredInstructionSet)) { 6060 // We have a mismatch between instruction sets (say arm vs arm64). 6061 // bail out. 6062 String errorMessage = "Instruction set mismatch, " 6063 + ((requirer == null) ? "[caller]" : requirer) 6064 + " requires " + requiredInstructionSet + " whereas " + ps 6065 + " requires " + instructionSet; 6066 Slog.e(TAG, errorMessage); 6067 6068 reportSettingsProblem(Log.WARN, errorMessage); 6069 // Give up, don't bother making any other changes to the package settings. 6070 return false; 6071 } 6072 } else { 6073 requiredInstructionSet = instructionSet; 6074 requirer = ps; 6075 } 6076 } 6077 } 6078 6079 if (requiredInstructionSet != null) { 6080 String adjustedAbi; 6081 if (requirer != null) { 6082 // requirer != null implies that either scannedPackage was null or that scannedPackage 6083 // did not require an ABI, in which case we have to adjust scannedPackage to match 6084 // the ABI of the set (which is the same as requirer's ABI) 6085 adjustedAbi = requirer.primaryCpuAbiString; 6086 if (scannedPackage != null) { 6087 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6088 } 6089 } else { 6090 // requirer == null implies that we're updating all ABIs in the set to 6091 // match scannedPackage. 6092 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6093 } 6094 6095 for (PackageSetting ps : packagesForUser) { 6096 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6097 if (ps.primaryCpuAbiString != null) { 6098 continue; 6099 } 6100 6101 ps.primaryCpuAbiString = adjustedAbi; 6102 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6103 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6104 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6105 6106 if (performDexOptLI(ps.pkg, forceDexOpt, deferDexOpt, true) == DEX_OPT_FAILED) { 6107 ps.primaryCpuAbiString = null; 6108 ps.pkg.applicationInfo.primaryCpuAbi = null; 6109 return false; 6110 } else { 6111 mInstaller.rmdex(ps.codePathString, getPreferredInstructionSet()); 6112 } 6113 } 6114 } 6115 } 6116 } 6117 6118 return true; 6119 } 6120 6121 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6122 synchronized (mPackages) { 6123 mResolverReplaced = true; 6124 // Set up information for custom user intent resolution activity. 6125 mResolveActivity.applicationInfo = pkg.applicationInfo; 6126 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6127 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6128 mResolveActivity.processName = null; 6129 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6130 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6131 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6132 mResolveActivity.theme = 0; 6133 mResolveActivity.exported = true; 6134 mResolveActivity.enabled = true; 6135 mResolveInfo.activityInfo = mResolveActivity; 6136 mResolveInfo.priority = 0; 6137 mResolveInfo.preferredOrder = 0; 6138 mResolveInfo.match = 0; 6139 mResolveComponentName = mCustomResolverComponentName; 6140 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6141 mResolveComponentName); 6142 } 6143 } 6144 6145 private static String calculateApkRoot(final String codePathString) { 6146 final File codePath = new File(codePathString); 6147 final File codeRoot; 6148 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6149 codeRoot = Environment.getRootDirectory(); 6150 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6151 codeRoot = Environment.getOemDirectory(); 6152 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6153 codeRoot = Environment.getVendorDirectory(); 6154 } else { 6155 // Unrecognized code path; take its top real segment as the apk root: 6156 // e.g. /something/app/blah.apk => /something 6157 try { 6158 File f = codePath.getCanonicalFile(); 6159 File parent = f.getParentFile(); // non-null because codePath is a file 6160 File tmp; 6161 while ((tmp = parent.getParentFile()) != null) { 6162 f = parent; 6163 parent = tmp; 6164 } 6165 codeRoot = f; 6166 Slog.w(TAG, "Unrecognized code path " 6167 + codePath + " - using " + codeRoot); 6168 } catch (IOException e) { 6169 // Can't canonicalize the code path -- shenanigans? 6170 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6171 return Environment.getRootDirectory().getPath(); 6172 } 6173 } 6174 return codeRoot.getPath(); 6175 } 6176 6177 /** 6178 * Derive and set the location of native libraries for the given package, 6179 * which varies depending on where and how the package was installed. 6180 */ 6181 private void setNativeLibraryPaths(PackageParser.Package pkg) { 6182 final ApplicationInfo info = pkg.applicationInfo; 6183 final String codePath = pkg.codePath; 6184 final File codeFile = new File(codePath); 6185 6186 final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info); 6187 final boolean asecApp = isForwardLocked(info) || isExternal(info); 6188 6189 info.nativeLibraryRootDir = null; 6190 info.nativeLibraryRootRequiresIsa = false; 6191 info.nativeLibraryDir = null; 6192 6193 if (bundledApp) { 6194 // Monolithic bundled install 6195 // TODO: support cluster bundled installs? 6196 6197 final boolean is64Bit = (info.primaryCpuAbi != null) 6198 && VMRuntime.is64BitAbi(info.primaryCpuAbi); 6199 6200 // This is a bundled system app so choose the path based on the ABI. 6201 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 6202 // is just the default path. 6203 final String apkName = deriveCodePathName(codePath); 6204 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 6205 info.nativeLibraryRootDir = Environment.buildPath(new File(info.apkRoot), libDir, 6206 apkName).getAbsolutePath(); 6207 info.nativeLibraryRootRequiresIsa = false; 6208 6209 } else if (isApkFile(codeFile)) { 6210 // Monolithic install 6211 if (asecApp) { 6212 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 6213 .getAbsolutePath(); 6214 info.nativeLibraryRootRequiresIsa = false; 6215 } else { 6216 final String apkName = deriveCodePathName(codePath); 6217 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 6218 .getAbsolutePath(); 6219 info.nativeLibraryRootRequiresIsa = false; 6220 } 6221 } else { 6222 // Cluster install 6223 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 6224 info.nativeLibraryRootRequiresIsa = true; 6225 } 6226 6227 if (info.nativeLibraryRootRequiresIsa) { 6228 if (info.primaryCpuAbi != null) { 6229 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 6230 VMRuntime.getInstructionSet(info.primaryCpuAbi)).getAbsolutePath(); 6231 } else { 6232 Slog.w(TAG, "Package " + info.packageName 6233 + " missing ABI; unable to derive nativeLibraryDir"); 6234 } 6235 } else { 6236 info.nativeLibraryDir = info.nativeLibraryRootDir; 6237 } 6238 } 6239 6240 /** 6241 * Calculate the abis and roots for a bundled app. These can uniquely 6242 * be determined from the contents of the system partition, i.e whether 6243 * it contains 64 or 32 bit shared libraries etc. We do not validate any 6244 * of this information, and instead assume that the system was built 6245 * sensibly. 6246 */ 6247 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 6248 PackageSetting pkgSetting) { 6249 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 6250 6251 // If "/system/lib64/apkname" exists, assume that is the per-package 6252 // native library directory to use; otherwise use "/system/lib/apkname". 6253 final String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir); 6254 pkg.applicationInfo.apkRoot = apkRoot; 6255 setBundledAppAbi(pkg, apkRoot, apkName); 6256 // pkgSetting might be null during rescan following uninstall of updates 6257 // to a bundled app, so accommodate that possibility. The settings in 6258 // that case will be established later from the parsed package. 6259 // 6260 // If the settings aren't null, sync them up with what we've just derived. 6261 // note that apkRoot isn't stored in the package settings. 6262 if (pkgSetting != null) { 6263 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6264 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6265 } 6266 } 6267 6268 /** 6269 * Deduces the ABI of a bundled app and sets the relevant fields on the 6270 * parsed pkg object. 6271 * 6272 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 6273 * under which system libraries are installed. 6274 * @param apkName the name of the installed package. 6275 */ 6276 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 6277 // This is of the form "/system/lib64/<packagename>", "/vendor/lib64/<packagename>" 6278 // or similar. 6279 final boolean has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 6280 final boolean has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 6281 6282 if (has64BitLibs && !has32BitLibs) { 6283 // The package has 64 bit libs, but not 32 bit libs. Its primary 6284 // ABI should be 64 bit. We can safely assume here that the bundled 6285 // native libraries correspond to the most preferred ABI in the list. 6286 6287 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6288 pkg.applicationInfo.secondaryCpuAbi = null; 6289 } else if (has32BitLibs && !has64BitLibs) { 6290 // The package has 32 bit libs but not 64 bit libs. Its primary 6291 // ABI should be 32 bit. 6292 6293 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6294 pkg.applicationInfo.secondaryCpuAbi = null; 6295 } else if (has32BitLibs && has64BitLibs) { 6296 // The application has both 64 and 32 bit bundled libraries. We check 6297 // here that the app declares multiArch support, and warn if it doesn't. 6298 // 6299 // We will be lenient here and record both ABIs. The primary will be the 6300 // ABI that's higher on the list, i.e, a device that's configured to prefer 6301 // 64 bit apps will see a 64 bit primary ABI, 6302 6303 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 6304 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 6305 } 6306 6307 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 6308 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6309 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6310 } else { 6311 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6312 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6313 } 6314 } else { 6315 pkg.applicationInfo.primaryCpuAbi = null; 6316 pkg.applicationInfo.secondaryCpuAbi = null; 6317 } 6318 } 6319 6320 private static void createNativeLibrarySubdir(File path) throws IOException { 6321 if (!path.isDirectory()) { 6322 path.delete(); 6323 6324 if (!path.mkdir()) { 6325 throw new IOException("Cannot create " + path.getPath()); 6326 } 6327 6328 try { 6329 Os.chmod(path.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); 6330 } catch (ErrnoException e) { 6331 throw new IOException("Cannot chmod native library directory " 6332 + path.getPath(), e); 6333 } 6334 } else if (!SELinux.restorecon(path)) { 6335 throw new IOException("Cannot set SELinux context for " + path.getPath()); 6336 } 6337 } 6338 6339 private static int copyNativeLibrariesForInternalApp(NativeLibraryHelper.Handle handle, 6340 final File nativeLibraryRoot, String[] abiList, boolean useIsaSubdir) throws IOException { 6341 createNativeLibrarySubdir(nativeLibraryRoot); 6342 6343 /* 6344 * If this is an internal application or our nativeLibraryPath points to 6345 * the app-lib directory, unpack the libraries if necessary. 6346 */ 6347 int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList); 6348 if (abi >= 0) { 6349 /* 6350 * If we have a matching instruction set, construct a subdir under the native 6351 * library root that corresponds to this instruction set. 6352 */ 6353 final String instructionSet = VMRuntime.getInstructionSet(abiList[abi]); 6354 final File subDir; 6355 if (useIsaSubdir) { 6356 final File isaSubdir = new File(nativeLibraryRoot, instructionSet); 6357 createNativeLibrarySubdir(isaSubdir); 6358 subDir = isaSubdir; 6359 } else { 6360 subDir = nativeLibraryRoot; 6361 } 6362 6363 int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle, subDir, abiList[abi]); 6364 if (copyRet != PackageManager.INSTALL_SUCCEEDED) { 6365 return copyRet; 6366 } 6367 } 6368 6369 return abi; 6370 } 6371 6372 private void killApplication(String pkgName, int appId, String reason) { 6373 // Request the ActivityManager to kill the process(only for existing packages) 6374 // so that we do not end up in a confused state while the user is still using the older 6375 // version of the application while the new one gets installed. 6376 IActivityManager am = ActivityManagerNative.getDefault(); 6377 if (am != null) { 6378 try { 6379 am.killApplicationWithAppId(pkgName, appId, reason); 6380 } catch (RemoteException e) { 6381 } 6382 } 6383 } 6384 6385 void removePackageLI(PackageSetting ps, boolean chatty) { 6386 if (DEBUG_INSTALL) { 6387 if (chatty) 6388 Log.d(TAG, "Removing package " + ps.name); 6389 } 6390 6391 // writer 6392 synchronized (mPackages) { 6393 mPackages.remove(ps.name); 6394 if (ps.codePathString != null) { 6395 mAppDirs.remove(ps.codePathString); 6396 } 6397 6398 final PackageParser.Package pkg = ps.pkg; 6399 if (pkg != null) { 6400 cleanPackageDataStructuresLILPw(pkg, chatty); 6401 } 6402 } 6403 } 6404 6405 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 6406 if (DEBUG_INSTALL) { 6407 if (chatty) 6408 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 6409 } 6410 6411 // writer 6412 synchronized (mPackages) { 6413 mPackages.remove(pkg.applicationInfo.packageName); 6414 if (pkg.codePath != null) { 6415 mAppDirs.remove(pkg.codePath); 6416 } 6417 cleanPackageDataStructuresLILPw(pkg, chatty); 6418 } 6419 } 6420 6421 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 6422 int N = pkg.providers.size(); 6423 StringBuilder r = null; 6424 int i; 6425 for (i=0; i<N; i++) { 6426 PackageParser.Provider p = pkg.providers.get(i); 6427 mProviders.removeProvider(p); 6428 if (p.info.authority == null) { 6429 6430 /* There was another ContentProvider with this authority when 6431 * this app was installed so this authority is null, 6432 * Ignore it as we don't have to unregister the provider. 6433 */ 6434 continue; 6435 } 6436 String names[] = p.info.authority.split(";"); 6437 for (int j = 0; j < names.length; j++) { 6438 if (mProvidersByAuthority.get(names[j]) == p) { 6439 mProvidersByAuthority.remove(names[j]); 6440 if (DEBUG_REMOVE) { 6441 if (chatty) 6442 Log.d(TAG, "Unregistered content provider: " + names[j] 6443 + ", className = " + p.info.name + ", isSyncable = " 6444 + p.info.isSyncable); 6445 } 6446 } 6447 } 6448 if (DEBUG_REMOVE && chatty) { 6449 if (r == null) { 6450 r = new StringBuilder(256); 6451 } else { 6452 r.append(' '); 6453 } 6454 r.append(p.info.name); 6455 } 6456 } 6457 if (r != null) { 6458 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 6459 } 6460 6461 N = pkg.services.size(); 6462 r = null; 6463 for (i=0; i<N; i++) { 6464 PackageParser.Service s = pkg.services.get(i); 6465 mServices.removeService(s); 6466 if (chatty) { 6467 if (r == null) { 6468 r = new StringBuilder(256); 6469 } else { 6470 r.append(' '); 6471 } 6472 r.append(s.info.name); 6473 } 6474 } 6475 if (r != null) { 6476 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 6477 } 6478 6479 N = pkg.receivers.size(); 6480 r = null; 6481 for (i=0; i<N; i++) { 6482 PackageParser.Activity a = pkg.receivers.get(i); 6483 mReceivers.removeActivity(a, "receiver"); 6484 if (DEBUG_REMOVE && chatty) { 6485 if (r == null) { 6486 r = new StringBuilder(256); 6487 } else { 6488 r.append(' '); 6489 } 6490 r.append(a.info.name); 6491 } 6492 } 6493 if (r != null) { 6494 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 6495 } 6496 6497 N = pkg.activities.size(); 6498 r = null; 6499 for (i=0; i<N; i++) { 6500 PackageParser.Activity a = pkg.activities.get(i); 6501 mActivities.removeActivity(a, "activity"); 6502 if (DEBUG_REMOVE && chatty) { 6503 if (r == null) { 6504 r = new StringBuilder(256); 6505 } else { 6506 r.append(' '); 6507 } 6508 r.append(a.info.name); 6509 } 6510 } 6511 if (r != null) { 6512 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 6513 } 6514 6515 N = pkg.permissions.size(); 6516 r = null; 6517 for (i=0; i<N; i++) { 6518 PackageParser.Permission p = pkg.permissions.get(i); 6519 BasePermission bp = mSettings.mPermissions.get(p.info.name); 6520 if (bp == null) { 6521 bp = mSettings.mPermissionTrees.get(p.info.name); 6522 } 6523 if (bp != null && bp.perm == p) { 6524 bp.perm = null; 6525 if (DEBUG_REMOVE && chatty) { 6526 if (r == null) { 6527 r = new StringBuilder(256); 6528 } else { 6529 r.append(' '); 6530 } 6531 r.append(p.info.name); 6532 } 6533 } 6534 } 6535 if (r != null) { 6536 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6537 } 6538 6539 N = pkg.instrumentation.size(); 6540 r = null; 6541 for (i=0; i<N; i++) { 6542 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6543 mInstrumentation.remove(a.getComponentName()); 6544 if (DEBUG_REMOVE && chatty) { 6545 if (r == null) { 6546 r = new StringBuilder(256); 6547 } else { 6548 r.append(' '); 6549 } 6550 r.append(a.info.name); 6551 } 6552 } 6553 if (r != null) { 6554 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 6555 } 6556 6557 r = null; 6558 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6559 // Only system apps can hold shared libraries. 6560 if (pkg.libraryNames != null) { 6561 for (i=0; i<pkg.libraryNames.size(); i++) { 6562 String name = pkg.libraryNames.get(i); 6563 SharedLibraryEntry cur = mSharedLibraries.get(name); 6564 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 6565 mSharedLibraries.remove(name); 6566 if (DEBUG_REMOVE && chatty) { 6567 if (r == null) { 6568 r = new StringBuilder(256); 6569 } else { 6570 r.append(' '); 6571 } 6572 r.append(name); 6573 } 6574 } 6575 } 6576 } 6577 } 6578 if (r != null) { 6579 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 6580 } 6581 } 6582 6583 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 6584 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 6585 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 6586 return true; 6587 } 6588 } 6589 return false; 6590 } 6591 6592 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 6593 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 6594 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 6595 6596 private void updatePermissionsLPw(String changingPkg, 6597 PackageParser.Package pkgInfo, int flags) { 6598 // Make sure there are no dangling permission trees. 6599 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 6600 while (it.hasNext()) { 6601 final BasePermission bp = it.next(); 6602 if (bp.packageSetting == null) { 6603 // We may not yet have parsed the package, so just see if 6604 // we still know about its settings. 6605 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6606 } 6607 if (bp.packageSetting == null) { 6608 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 6609 + " from package " + bp.sourcePackage); 6610 it.remove(); 6611 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6612 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6613 Slog.i(TAG, "Removing old permission tree: " + bp.name 6614 + " from package " + bp.sourcePackage); 6615 flags |= UPDATE_PERMISSIONS_ALL; 6616 it.remove(); 6617 } 6618 } 6619 } 6620 6621 // Make sure all dynamic permissions have been assigned to a package, 6622 // and make sure there are no dangling permissions. 6623 it = mSettings.mPermissions.values().iterator(); 6624 while (it.hasNext()) { 6625 final BasePermission bp = it.next(); 6626 if (bp.type == BasePermission.TYPE_DYNAMIC) { 6627 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 6628 + bp.name + " pkg=" + bp.sourcePackage 6629 + " info=" + bp.pendingInfo); 6630 if (bp.packageSetting == null && bp.pendingInfo != null) { 6631 final BasePermission tree = findPermissionTreeLP(bp.name); 6632 if (tree != null && tree.perm != null) { 6633 bp.packageSetting = tree.packageSetting; 6634 bp.perm = new PackageParser.Permission(tree.perm.owner, 6635 new PermissionInfo(bp.pendingInfo)); 6636 bp.perm.info.packageName = tree.perm.info.packageName; 6637 bp.perm.info.name = bp.name; 6638 bp.uid = tree.uid; 6639 } 6640 } 6641 } 6642 if (bp.packageSetting == null) { 6643 // We may not yet have parsed the package, so just see if 6644 // we still know about its settings. 6645 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6646 } 6647 if (bp.packageSetting == null) { 6648 Slog.w(TAG, "Removing dangling permission: " + bp.name 6649 + " from package " + bp.sourcePackage); 6650 it.remove(); 6651 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6652 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6653 Slog.i(TAG, "Removing old permission: " + bp.name 6654 + " from package " + bp.sourcePackage); 6655 flags |= UPDATE_PERMISSIONS_ALL; 6656 it.remove(); 6657 } 6658 } 6659 } 6660 6661 // Now update the permissions for all packages, in particular 6662 // replace the granted permissions of the system packages. 6663 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 6664 for (PackageParser.Package pkg : mPackages.values()) { 6665 if (pkg != pkgInfo) { 6666 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0); 6667 } 6668 } 6669 } 6670 6671 if (pkgInfo != null) { 6672 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0); 6673 } 6674 } 6675 6676 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) { 6677 final PackageSetting ps = (PackageSetting) pkg.mExtras; 6678 if (ps == null) { 6679 return; 6680 } 6681 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 6682 HashSet<String> origPermissions = gp.grantedPermissions; 6683 boolean changedPermission = false; 6684 6685 if (replace) { 6686 ps.permissionsFixed = false; 6687 if (gp == ps) { 6688 origPermissions = new HashSet<String>(gp.grantedPermissions); 6689 gp.grantedPermissions.clear(); 6690 gp.gids = mGlobalGids; 6691 } 6692 } 6693 6694 if (gp.gids == null) { 6695 gp.gids = mGlobalGids; 6696 } 6697 6698 final int N = pkg.requestedPermissions.size(); 6699 for (int i=0; i<N; i++) { 6700 final String name = pkg.requestedPermissions.get(i); 6701 final boolean required = pkg.requestedPermissionsRequired.get(i); 6702 final BasePermission bp = mSettings.mPermissions.get(name); 6703 if (DEBUG_INSTALL) { 6704 if (gp != ps) { 6705 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 6706 } 6707 } 6708 6709 if (bp == null || bp.packageSetting == null) { 6710 Slog.w(TAG, "Unknown permission " + name 6711 + " in package " + pkg.packageName); 6712 continue; 6713 } 6714 6715 final String perm = bp.name; 6716 boolean allowed; 6717 boolean allowedSig = false; 6718 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 6719 if (level == PermissionInfo.PROTECTION_NORMAL 6720 || level == PermissionInfo.PROTECTION_DANGEROUS) { 6721 // We grant a normal or dangerous permission if any of the following 6722 // are true: 6723 // 1) The permission is required 6724 // 2) The permission is optional, but was granted in the past 6725 // 3) The permission is optional, but was requested by an 6726 // app in /system (not /data) 6727 // 6728 // Otherwise, reject the permission. 6729 allowed = (required || origPermissions.contains(perm) 6730 || (isSystemApp(ps) && !isUpdatedSystemApp(ps))); 6731 } else if (bp.packageSetting == null) { 6732 // This permission is invalid; skip it. 6733 allowed = false; 6734 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 6735 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions); 6736 if (allowed) { 6737 allowedSig = true; 6738 } 6739 } else { 6740 allowed = false; 6741 } 6742 if (DEBUG_INSTALL) { 6743 if (gp != ps) { 6744 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 6745 } 6746 } 6747 if (allowed) { 6748 if (!isSystemApp(ps) && ps.permissionsFixed) { 6749 // If this is an existing, non-system package, then 6750 // we can't add any new permissions to it. 6751 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 6752 // Except... if this is a permission that was added 6753 // to the platform (note: need to only do this when 6754 // updating the platform). 6755 allowed = isNewPlatformPermissionForPackage(perm, pkg); 6756 } 6757 } 6758 if (allowed) { 6759 if (!gp.grantedPermissions.contains(perm)) { 6760 changedPermission = true; 6761 gp.grantedPermissions.add(perm); 6762 gp.gids = appendInts(gp.gids, bp.gids); 6763 } else if (!ps.haveGids) { 6764 gp.gids = appendInts(gp.gids, bp.gids); 6765 } 6766 } else { 6767 Slog.w(TAG, "Not granting permission " + perm 6768 + " to package " + pkg.packageName 6769 + " because it was previously installed without"); 6770 } 6771 } else { 6772 if (gp.grantedPermissions.remove(perm)) { 6773 changedPermission = true; 6774 gp.gids = removeInts(gp.gids, bp.gids); 6775 Slog.i(TAG, "Un-granting permission " + perm 6776 + " from package " + pkg.packageName 6777 + " (protectionLevel=" + bp.protectionLevel 6778 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6779 + ")"); 6780 } else { 6781 Slog.w(TAG, "Not granting permission " + perm 6782 + " to package " + pkg.packageName 6783 + " (protectionLevel=" + bp.protectionLevel 6784 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6785 + ")"); 6786 } 6787 } 6788 } 6789 6790 if ((changedPermission || replace) && !ps.permissionsFixed && 6791 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 6792 // This is the first that we have heard about this package, so the 6793 // permissions we have now selected are fixed until explicitly 6794 // changed. 6795 ps.permissionsFixed = true; 6796 } 6797 ps.haveGids = true; 6798 } 6799 6800 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 6801 boolean allowed = false; 6802 final int NP = PackageParser.NEW_PERMISSIONS.length; 6803 for (int ip=0; ip<NP; ip++) { 6804 final PackageParser.NewPermissionInfo npi 6805 = PackageParser.NEW_PERMISSIONS[ip]; 6806 if (npi.name.equals(perm) 6807 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 6808 allowed = true; 6809 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 6810 + pkg.packageName); 6811 break; 6812 } 6813 } 6814 return allowed; 6815 } 6816 6817 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 6818 BasePermission bp, HashSet<String> origPermissions) { 6819 boolean allowed; 6820 allowed = (compareSignatures( 6821 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 6822 == PackageManager.SIGNATURE_MATCH) 6823 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 6824 == PackageManager.SIGNATURE_MATCH); 6825 if (!allowed && (bp.protectionLevel 6826 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 6827 if (isSystemApp(pkg)) { 6828 // For updated system applications, a system permission 6829 // is granted only if it had been defined by the original application. 6830 if (isUpdatedSystemApp(pkg)) { 6831 final PackageSetting sysPs = mSettings 6832 .getDisabledSystemPkgLPr(pkg.packageName); 6833 final GrantedPermissions origGp = sysPs.sharedUser != null 6834 ? sysPs.sharedUser : sysPs; 6835 6836 if (origGp.grantedPermissions.contains(perm)) { 6837 // If the original was granted this permission, we take 6838 // that grant decision as read and propagate it to the 6839 // update. 6840 allowed = true; 6841 } else { 6842 // The system apk may have been updated with an older 6843 // version of the one on the data partition, but which 6844 // granted a new system permission that it didn't have 6845 // before. In this case we do want to allow the app to 6846 // now get the new permission if the ancestral apk is 6847 // privileged to get it. 6848 if (sysPs.pkg != null && sysPs.isPrivileged()) { 6849 for (int j=0; 6850 j<sysPs.pkg.requestedPermissions.size(); j++) { 6851 if (perm.equals( 6852 sysPs.pkg.requestedPermissions.get(j))) { 6853 allowed = true; 6854 break; 6855 } 6856 } 6857 } 6858 } 6859 } else { 6860 allowed = isPrivilegedApp(pkg); 6861 } 6862 } 6863 } 6864 if (!allowed && (bp.protectionLevel 6865 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 6866 // For development permissions, a development permission 6867 // is granted only if it was already granted. 6868 allowed = origPermissions.contains(perm); 6869 } 6870 return allowed; 6871 } 6872 6873 final class ActivityIntentResolver 6874 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 6875 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 6876 boolean defaultOnly, int userId) { 6877 if (!sUserManager.exists(userId)) return null; 6878 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 6879 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 6880 } 6881 6882 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 6883 int userId) { 6884 if (!sUserManager.exists(userId)) return null; 6885 mFlags = flags; 6886 return super.queryIntent(intent, resolvedType, 6887 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 6888 } 6889 6890 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 6891 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 6892 if (!sUserManager.exists(userId)) return null; 6893 if (packageActivities == null) { 6894 return null; 6895 } 6896 mFlags = flags; 6897 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 6898 final int N = packageActivities.size(); 6899 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 6900 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 6901 6902 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 6903 for (int i = 0; i < N; ++i) { 6904 intentFilters = packageActivities.get(i).intents; 6905 if (intentFilters != null && intentFilters.size() > 0) { 6906 PackageParser.ActivityIntentInfo[] array = 6907 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 6908 intentFilters.toArray(array); 6909 listCut.add(array); 6910 } 6911 } 6912 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 6913 } 6914 6915 public final void addActivity(PackageParser.Activity a, String type) { 6916 final boolean systemApp = isSystemApp(a.info.applicationInfo); 6917 mActivities.put(a.getComponentName(), a); 6918 if (DEBUG_SHOW_INFO) 6919 Log.v( 6920 TAG, " " + type + " " + 6921 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 6922 if (DEBUG_SHOW_INFO) 6923 Log.v(TAG, " Class=" + a.info.name); 6924 final int NI = a.intents.size(); 6925 for (int j=0; j<NI; j++) { 6926 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 6927 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 6928 intent.setPriority(0); 6929 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 6930 + a.className + " with priority > 0, forcing to 0"); 6931 } 6932 if (DEBUG_SHOW_INFO) { 6933 Log.v(TAG, " IntentFilter:"); 6934 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6935 } 6936 if (!intent.debugCheck()) { 6937 Log.w(TAG, "==> For Activity " + a.info.name); 6938 } 6939 addFilter(intent); 6940 } 6941 } 6942 6943 public final void removeActivity(PackageParser.Activity a, String type) { 6944 mActivities.remove(a.getComponentName()); 6945 if (DEBUG_SHOW_INFO) { 6946 Log.v(TAG, " " + type + " " 6947 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 6948 : a.info.name) + ":"); 6949 Log.v(TAG, " Class=" + a.info.name); 6950 } 6951 final int NI = a.intents.size(); 6952 for (int j=0; j<NI; j++) { 6953 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 6954 if (DEBUG_SHOW_INFO) { 6955 Log.v(TAG, " IntentFilter:"); 6956 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6957 } 6958 removeFilter(intent); 6959 } 6960 } 6961 6962 @Override 6963 protected boolean allowFilterResult( 6964 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 6965 ActivityInfo filterAi = filter.activity.info; 6966 for (int i=dest.size()-1; i>=0; i--) { 6967 ActivityInfo destAi = dest.get(i).activityInfo; 6968 if (destAi.name == filterAi.name 6969 && destAi.packageName == filterAi.packageName) { 6970 return false; 6971 } 6972 } 6973 return true; 6974 } 6975 6976 @Override 6977 protected ActivityIntentInfo[] newArray(int size) { 6978 return new ActivityIntentInfo[size]; 6979 } 6980 6981 @Override 6982 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 6983 if (!sUserManager.exists(userId)) return true; 6984 PackageParser.Package p = filter.activity.owner; 6985 if (p != null) { 6986 PackageSetting ps = (PackageSetting)p.mExtras; 6987 if (ps != null) { 6988 // System apps are never considered stopped for purposes of 6989 // filtering, because there may be no way for the user to 6990 // actually re-launch them. 6991 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 6992 && ps.getStopped(userId); 6993 } 6994 } 6995 return false; 6996 } 6997 6998 @Override 6999 protected boolean isPackageForFilter(String packageName, 7000 PackageParser.ActivityIntentInfo info) { 7001 return packageName.equals(info.activity.owner.packageName); 7002 } 7003 7004 @Override 7005 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7006 int match, int userId) { 7007 if (!sUserManager.exists(userId)) return null; 7008 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7009 return null; 7010 } 7011 final PackageParser.Activity activity = info.activity; 7012 if (mSafeMode && (activity.info.applicationInfo.flags 7013 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7014 return null; 7015 } 7016 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7017 if (ps == null) { 7018 return null; 7019 } 7020 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7021 ps.readUserState(userId), userId); 7022 if (ai == null) { 7023 return null; 7024 } 7025 final ResolveInfo res = new ResolveInfo(); 7026 res.activityInfo = ai; 7027 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7028 res.filter = info; 7029 } 7030 res.priority = info.getPriority(); 7031 res.preferredOrder = activity.owner.mPreferredOrder; 7032 //System.out.println("Result: " + res.activityInfo.className + 7033 // " = " + res.priority); 7034 res.match = match; 7035 res.isDefault = info.hasDefault; 7036 res.labelRes = info.labelRes; 7037 res.nonLocalizedLabel = info.nonLocalizedLabel; 7038 if (userNeedsBadging(userId)) { 7039 res.noResourceId = true; 7040 } else { 7041 res.icon = info.icon; 7042 } 7043 res.system = isSystemApp(res.activityInfo.applicationInfo); 7044 return res; 7045 } 7046 7047 @Override 7048 protected void sortResults(List<ResolveInfo> results) { 7049 Collections.sort(results, mResolvePrioritySorter); 7050 } 7051 7052 @Override 7053 protected void dumpFilter(PrintWriter out, String prefix, 7054 PackageParser.ActivityIntentInfo filter) { 7055 out.print(prefix); out.print( 7056 Integer.toHexString(System.identityHashCode(filter.activity))); 7057 out.print(' '); 7058 filter.activity.printComponentShortName(out); 7059 out.print(" filter "); 7060 out.println(Integer.toHexString(System.identityHashCode(filter))); 7061 } 7062 7063// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7064// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7065// final List<ResolveInfo> retList = Lists.newArrayList(); 7066// while (i.hasNext()) { 7067// final ResolveInfo resolveInfo = i.next(); 7068// if (isEnabledLP(resolveInfo.activityInfo)) { 7069// retList.add(resolveInfo); 7070// } 7071// } 7072// return retList; 7073// } 7074 7075 // Keys are String (activity class name), values are Activity. 7076 private final HashMap<ComponentName, PackageParser.Activity> mActivities 7077 = new HashMap<ComponentName, PackageParser.Activity>(); 7078 private int mFlags; 7079 } 7080 7081 private final class ServiceIntentResolver 7082 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 7083 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7084 boolean defaultOnly, int userId) { 7085 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7086 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7087 } 7088 7089 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7090 int userId) { 7091 if (!sUserManager.exists(userId)) return null; 7092 mFlags = flags; 7093 return super.queryIntent(intent, resolvedType, 7094 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7095 } 7096 7097 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7098 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 7099 if (!sUserManager.exists(userId)) return null; 7100 if (packageServices == null) { 7101 return null; 7102 } 7103 mFlags = flags; 7104 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7105 final int N = packageServices.size(); 7106 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 7107 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 7108 7109 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 7110 for (int i = 0; i < N; ++i) { 7111 intentFilters = packageServices.get(i).intents; 7112 if (intentFilters != null && intentFilters.size() > 0) { 7113 PackageParser.ServiceIntentInfo[] array = 7114 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 7115 intentFilters.toArray(array); 7116 listCut.add(array); 7117 } 7118 } 7119 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7120 } 7121 7122 public final void addService(PackageParser.Service s) { 7123 mServices.put(s.getComponentName(), s); 7124 if (DEBUG_SHOW_INFO) { 7125 Log.v(TAG, " " 7126 + (s.info.nonLocalizedLabel != null 7127 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7128 Log.v(TAG, " Class=" + s.info.name); 7129 } 7130 final int NI = s.intents.size(); 7131 int j; 7132 for (j=0; j<NI; j++) { 7133 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7134 if (DEBUG_SHOW_INFO) { 7135 Log.v(TAG, " IntentFilter:"); 7136 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7137 } 7138 if (!intent.debugCheck()) { 7139 Log.w(TAG, "==> For Service " + s.info.name); 7140 } 7141 addFilter(intent); 7142 } 7143 } 7144 7145 public final void removeService(PackageParser.Service s) { 7146 mServices.remove(s.getComponentName()); 7147 if (DEBUG_SHOW_INFO) { 7148 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 7149 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7150 Log.v(TAG, " Class=" + s.info.name); 7151 } 7152 final int NI = s.intents.size(); 7153 int j; 7154 for (j=0; j<NI; j++) { 7155 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7156 if (DEBUG_SHOW_INFO) { 7157 Log.v(TAG, " IntentFilter:"); 7158 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7159 } 7160 removeFilter(intent); 7161 } 7162 } 7163 7164 @Override 7165 protected boolean allowFilterResult( 7166 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 7167 ServiceInfo filterSi = filter.service.info; 7168 for (int i=dest.size()-1; i>=0; i--) { 7169 ServiceInfo destAi = dest.get(i).serviceInfo; 7170 if (destAi.name == filterSi.name 7171 && destAi.packageName == filterSi.packageName) { 7172 return false; 7173 } 7174 } 7175 return true; 7176 } 7177 7178 @Override 7179 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 7180 return new PackageParser.ServiceIntentInfo[size]; 7181 } 7182 7183 @Override 7184 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 7185 if (!sUserManager.exists(userId)) return true; 7186 PackageParser.Package p = filter.service.owner; 7187 if (p != null) { 7188 PackageSetting ps = (PackageSetting)p.mExtras; 7189 if (ps != null) { 7190 // System apps are never considered stopped for purposes of 7191 // filtering, because there may be no way for the user to 7192 // actually re-launch them. 7193 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7194 && ps.getStopped(userId); 7195 } 7196 } 7197 return false; 7198 } 7199 7200 @Override 7201 protected boolean isPackageForFilter(String packageName, 7202 PackageParser.ServiceIntentInfo info) { 7203 return packageName.equals(info.service.owner.packageName); 7204 } 7205 7206 @Override 7207 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 7208 int match, int userId) { 7209 if (!sUserManager.exists(userId)) return null; 7210 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 7211 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 7212 return null; 7213 } 7214 final PackageParser.Service service = info.service; 7215 if (mSafeMode && (service.info.applicationInfo.flags 7216 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7217 return null; 7218 } 7219 PackageSetting ps = (PackageSetting) service.owner.mExtras; 7220 if (ps == null) { 7221 return null; 7222 } 7223 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 7224 ps.readUserState(userId), userId); 7225 if (si == null) { 7226 return null; 7227 } 7228 final ResolveInfo res = new ResolveInfo(); 7229 res.serviceInfo = si; 7230 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7231 res.filter = filter; 7232 } 7233 res.priority = info.getPriority(); 7234 res.preferredOrder = service.owner.mPreferredOrder; 7235 //System.out.println("Result: " + res.activityInfo.className + 7236 // " = " + res.priority); 7237 res.match = match; 7238 res.isDefault = info.hasDefault; 7239 res.labelRes = info.labelRes; 7240 res.nonLocalizedLabel = info.nonLocalizedLabel; 7241 res.icon = info.icon; 7242 res.system = isSystemApp(res.serviceInfo.applicationInfo); 7243 return res; 7244 } 7245 7246 @Override 7247 protected void sortResults(List<ResolveInfo> results) { 7248 Collections.sort(results, mResolvePrioritySorter); 7249 } 7250 7251 @Override 7252 protected void dumpFilter(PrintWriter out, String prefix, 7253 PackageParser.ServiceIntentInfo filter) { 7254 out.print(prefix); out.print( 7255 Integer.toHexString(System.identityHashCode(filter.service))); 7256 out.print(' '); 7257 filter.service.printComponentShortName(out); 7258 out.print(" filter "); 7259 out.println(Integer.toHexString(System.identityHashCode(filter))); 7260 } 7261 7262// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7263// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7264// final List<ResolveInfo> retList = Lists.newArrayList(); 7265// while (i.hasNext()) { 7266// final ResolveInfo resolveInfo = (ResolveInfo) i; 7267// if (isEnabledLP(resolveInfo.serviceInfo)) { 7268// retList.add(resolveInfo); 7269// } 7270// } 7271// return retList; 7272// } 7273 7274 // Keys are String (activity class name), values are Activity. 7275 private final HashMap<ComponentName, PackageParser.Service> mServices 7276 = new HashMap<ComponentName, PackageParser.Service>(); 7277 private int mFlags; 7278 }; 7279 7280 private final class ProviderIntentResolver 7281 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 7282 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7283 boolean defaultOnly, int userId) { 7284 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7285 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7286 } 7287 7288 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7289 int userId) { 7290 if (!sUserManager.exists(userId)) 7291 return null; 7292 mFlags = flags; 7293 return super.queryIntent(intent, resolvedType, 7294 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7295 } 7296 7297 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7298 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 7299 if (!sUserManager.exists(userId)) 7300 return null; 7301 if (packageProviders == null) { 7302 return null; 7303 } 7304 mFlags = flags; 7305 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 7306 final int N = packageProviders.size(); 7307 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 7308 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 7309 7310 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 7311 for (int i = 0; i < N; ++i) { 7312 intentFilters = packageProviders.get(i).intents; 7313 if (intentFilters != null && intentFilters.size() > 0) { 7314 PackageParser.ProviderIntentInfo[] array = 7315 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 7316 intentFilters.toArray(array); 7317 listCut.add(array); 7318 } 7319 } 7320 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7321 } 7322 7323 public final void addProvider(PackageParser.Provider p) { 7324 if (mProviders.containsKey(p.getComponentName())) { 7325 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 7326 return; 7327 } 7328 7329 mProviders.put(p.getComponentName(), p); 7330 if (DEBUG_SHOW_INFO) { 7331 Log.v(TAG, " " 7332 + (p.info.nonLocalizedLabel != null 7333 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7334 Log.v(TAG, " Class=" + p.info.name); 7335 } 7336 final int NI = p.intents.size(); 7337 int j; 7338 for (j = 0; j < NI; j++) { 7339 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7340 if (DEBUG_SHOW_INFO) { 7341 Log.v(TAG, " IntentFilter:"); 7342 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7343 } 7344 if (!intent.debugCheck()) { 7345 Log.w(TAG, "==> For Provider " + p.info.name); 7346 } 7347 addFilter(intent); 7348 } 7349 } 7350 7351 public final void removeProvider(PackageParser.Provider p) { 7352 mProviders.remove(p.getComponentName()); 7353 if (DEBUG_SHOW_INFO) { 7354 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 7355 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7356 Log.v(TAG, " Class=" + p.info.name); 7357 } 7358 final int NI = p.intents.size(); 7359 int j; 7360 for (j = 0; j < NI; j++) { 7361 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7362 if (DEBUG_SHOW_INFO) { 7363 Log.v(TAG, " IntentFilter:"); 7364 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7365 } 7366 removeFilter(intent); 7367 } 7368 } 7369 7370 @Override 7371 protected boolean allowFilterResult( 7372 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 7373 ProviderInfo filterPi = filter.provider.info; 7374 for (int i = dest.size() - 1; i >= 0; i--) { 7375 ProviderInfo destPi = dest.get(i).providerInfo; 7376 if (destPi.name == filterPi.name 7377 && destPi.packageName == filterPi.packageName) { 7378 return false; 7379 } 7380 } 7381 return true; 7382 } 7383 7384 @Override 7385 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 7386 return new PackageParser.ProviderIntentInfo[size]; 7387 } 7388 7389 @Override 7390 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 7391 if (!sUserManager.exists(userId)) 7392 return true; 7393 PackageParser.Package p = filter.provider.owner; 7394 if (p != null) { 7395 PackageSetting ps = (PackageSetting) p.mExtras; 7396 if (ps != null) { 7397 // System apps are never considered stopped for purposes of 7398 // filtering, because there may be no way for the user to 7399 // actually re-launch them. 7400 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7401 && ps.getStopped(userId); 7402 } 7403 } 7404 return false; 7405 } 7406 7407 @Override 7408 protected boolean isPackageForFilter(String packageName, 7409 PackageParser.ProviderIntentInfo info) { 7410 return packageName.equals(info.provider.owner.packageName); 7411 } 7412 7413 @Override 7414 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 7415 int match, int userId) { 7416 if (!sUserManager.exists(userId)) 7417 return null; 7418 final PackageParser.ProviderIntentInfo info = filter; 7419 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 7420 return null; 7421 } 7422 final PackageParser.Provider provider = info.provider; 7423 if (mSafeMode && (provider.info.applicationInfo.flags 7424 & ApplicationInfo.FLAG_SYSTEM) == 0) { 7425 return null; 7426 } 7427 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 7428 if (ps == null) { 7429 return null; 7430 } 7431 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 7432 ps.readUserState(userId), userId); 7433 if (pi == null) { 7434 return null; 7435 } 7436 final ResolveInfo res = new ResolveInfo(); 7437 res.providerInfo = pi; 7438 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 7439 res.filter = filter; 7440 } 7441 res.priority = info.getPriority(); 7442 res.preferredOrder = provider.owner.mPreferredOrder; 7443 res.match = match; 7444 res.isDefault = info.hasDefault; 7445 res.labelRes = info.labelRes; 7446 res.nonLocalizedLabel = info.nonLocalizedLabel; 7447 res.icon = info.icon; 7448 res.system = isSystemApp(res.providerInfo.applicationInfo); 7449 return res; 7450 } 7451 7452 @Override 7453 protected void sortResults(List<ResolveInfo> results) { 7454 Collections.sort(results, mResolvePrioritySorter); 7455 } 7456 7457 @Override 7458 protected void dumpFilter(PrintWriter out, String prefix, 7459 PackageParser.ProviderIntentInfo filter) { 7460 out.print(prefix); 7461 out.print( 7462 Integer.toHexString(System.identityHashCode(filter.provider))); 7463 out.print(' '); 7464 filter.provider.printComponentShortName(out); 7465 out.print(" filter "); 7466 out.println(Integer.toHexString(System.identityHashCode(filter))); 7467 } 7468 7469 private final HashMap<ComponentName, PackageParser.Provider> mProviders 7470 = new HashMap<ComponentName, PackageParser.Provider>(); 7471 private int mFlags; 7472 }; 7473 7474 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 7475 new Comparator<ResolveInfo>() { 7476 public int compare(ResolveInfo r1, ResolveInfo r2) { 7477 int v1 = r1.priority; 7478 int v2 = r2.priority; 7479 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 7480 if (v1 != v2) { 7481 return (v1 > v2) ? -1 : 1; 7482 } 7483 v1 = r1.preferredOrder; 7484 v2 = r2.preferredOrder; 7485 if (v1 != v2) { 7486 return (v1 > v2) ? -1 : 1; 7487 } 7488 if (r1.isDefault != r2.isDefault) { 7489 return r1.isDefault ? -1 : 1; 7490 } 7491 v1 = r1.match; 7492 v2 = r2.match; 7493 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 7494 if (v1 != v2) { 7495 return (v1 > v2) ? -1 : 1; 7496 } 7497 if (r1.system != r2.system) { 7498 return r1.system ? -1 : 1; 7499 } 7500 return 0; 7501 } 7502 }; 7503 7504 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 7505 new Comparator<ProviderInfo>() { 7506 public int compare(ProviderInfo p1, ProviderInfo p2) { 7507 final int v1 = p1.initOrder; 7508 final int v2 = p2.initOrder; 7509 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 7510 } 7511 }; 7512 7513 static final void sendPackageBroadcast(String action, String pkg, 7514 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 7515 int[] userIds) { 7516 IActivityManager am = ActivityManagerNative.getDefault(); 7517 if (am != null) { 7518 try { 7519 if (userIds == null) { 7520 userIds = am.getRunningUserIds(); 7521 } 7522 for (int id : userIds) { 7523 final Intent intent = new Intent(action, 7524 pkg != null ? Uri.fromParts("package", pkg, null) : null); 7525 if (extras != null) { 7526 intent.putExtras(extras); 7527 } 7528 if (targetPkg != null) { 7529 intent.setPackage(targetPkg); 7530 } 7531 // Modify the UID when posting to other users 7532 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 7533 if (uid > 0 && UserHandle.getUserId(uid) != id) { 7534 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 7535 intent.putExtra(Intent.EXTRA_UID, uid); 7536 } 7537 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 7538 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 7539 if (DEBUG_BROADCASTS) { 7540 RuntimeException here = new RuntimeException("here"); 7541 here.fillInStackTrace(); 7542 Slog.d(TAG, "Sending to user " + id + ": " 7543 + intent.toShortString(false, true, false, false) 7544 + " " + intent.getExtras(), here); 7545 } 7546 am.broadcastIntent(null, intent, null, finishedReceiver, 7547 0, null, null, null, android.app.AppOpsManager.OP_NONE, 7548 finishedReceiver != null, false, id); 7549 } 7550 } catch (RemoteException ex) { 7551 } 7552 } 7553 } 7554 7555 /** 7556 * Check if the external storage media is available. This is true if there 7557 * is a mounted external storage medium or if the external storage is 7558 * emulated. 7559 */ 7560 private boolean isExternalMediaAvailable() { 7561 return mMediaMounted || Environment.isExternalStorageEmulated(); 7562 } 7563 7564 @Override 7565 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 7566 // writer 7567 synchronized (mPackages) { 7568 if (!isExternalMediaAvailable()) { 7569 // If the external storage is no longer mounted at this point, 7570 // the caller may not have been able to delete all of this 7571 // packages files and can not delete any more. Bail. 7572 return null; 7573 } 7574 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 7575 if (lastPackage != null) { 7576 pkgs.remove(lastPackage); 7577 } 7578 if (pkgs.size() > 0) { 7579 return pkgs.get(0); 7580 } 7581 } 7582 return null; 7583 } 7584 7585 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 7586 if (false) { 7587 RuntimeException here = new RuntimeException("here"); 7588 here.fillInStackTrace(); 7589 Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId 7590 + " andCode=" + andCode, here); 7591 } 7592 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, 7593 userId, andCode ? 1 : 0, packageName)); 7594 } 7595 7596 void startCleaningPackages() { 7597 // reader 7598 synchronized (mPackages) { 7599 if (!isExternalMediaAvailable()) { 7600 return; 7601 } 7602 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 7603 return; 7604 } 7605 } 7606 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 7607 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 7608 IActivityManager am = ActivityManagerNative.getDefault(); 7609 if (am != null) { 7610 try { 7611 am.startService(null, intent, null, UserHandle.USER_OWNER); 7612 } catch (RemoteException e) { 7613 } 7614 } 7615 } 7616 7617 private final class AppDirObserver extends FileObserver { 7618 public AppDirObserver(String path, int mask, boolean isrom, boolean isPrivileged) { 7619 super(path, mask); 7620 mRootDir = path; 7621 mIsRom = isrom; 7622 mIsPrivileged = isPrivileged; 7623 } 7624 7625 public void onEvent(int event, String path) { 7626 String removedPackage = null; 7627 int removedAppId = -1; 7628 int[] removedUsers = null; 7629 String addedPackage = null; 7630 int addedAppId = -1; 7631 int[] addedUsers = null; 7632 7633 // TODO post a message to the handler to obtain serial ordering 7634 synchronized (mInstallLock) { 7635 String fullPathStr = null; 7636 File fullPath = null; 7637 if (path != null) { 7638 fullPath = new File(mRootDir, path); 7639 fullPathStr = fullPath.getPath(); 7640 } 7641 7642 if (DEBUG_APP_DIR_OBSERVER) 7643 Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event)); 7644 7645 if (!isApkFile(fullPath)) { 7646 if (DEBUG_APP_DIR_OBSERVER) 7647 Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr); 7648 return; 7649 } 7650 7651 // Ignore packages that are being installed or 7652 // have just been installed. 7653 if (ignoreCodePath(fullPathStr)) { 7654 return; 7655 } 7656 PackageParser.Package p = null; 7657 PackageSetting ps = null; 7658 // reader 7659 synchronized (mPackages) { 7660 p = mAppDirs.get(fullPathStr); 7661 if (p != null) { 7662 ps = mSettings.mPackages.get(p.applicationInfo.packageName); 7663 if (ps != null) { 7664 removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 7665 } else { 7666 removedUsers = sUserManager.getUserIds(); 7667 } 7668 } 7669 addedUsers = sUserManager.getUserIds(); 7670 } 7671 if ((event&REMOVE_EVENTS) != 0) { 7672 if (ps != null) { 7673 if (DEBUG_REMOVE) Slog.d(TAG, "Package disappeared: " + ps); 7674 removePackageLI(ps, true); 7675 removedPackage = ps.name; 7676 removedAppId = ps.appId; 7677 } 7678 } 7679 7680 if ((event&ADD_EVENTS) != 0) { 7681 if (p == null) { 7682 if (DEBUG_INSTALL) Slog.d(TAG, "New file appeared: " + fullPath); 7683 int flags = PackageParser.PARSE_CHATTY | PackageParser.PARSE_MUST_BE_APK; 7684 if (mIsRom) { 7685 flags |= PackageParser.PARSE_IS_SYSTEM 7686 | PackageParser.PARSE_IS_SYSTEM_DIR; 7687 if (mIsPrivileged) { 7688 flags |= PackageParser.PARSE_IS_PRIVILEGED; 7689 } 7690 } 7691 p = scanPackageLI(fullPath, flags, 7692 SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME, 7693 System.currentTimeMillis(), UserHandle.ALL, null); 7694 if (p != null) { 7695 /* 7696 * TODO this seems dangerous as the package may have 7697 * changed since we last acquired the mPackages 7698 * lock. 7699 */ 7700 // writer 7701 synchronized (mPackages) { 7702 updatePermissionsLPw(p.packageName, p, 7703 p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0); 7704 } 7705 addedPackage = p.applicationInfo.packageName; 7706 addedAppId = UserHandle.getAppId(p.applicationInfo.uid); 7707 } 7708 } 7709 } 7710 7711 // reader 7712 synchronized (mPackages) { 7713 mSettings.writeLPr(); 7714 } 7715 } 7716 7717 if (removedPackage != null) { 7718 Bundle extras = new Bundle(1); 7719 extras.putInt(Intent.EXTRA_UID, removedAppId); 7720 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false); 7721 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 7722 extras, null, null, removedUsers); 7723 } 7724 if (addedPackage != null) { 7725 Bundle extras = new Bundle(1); 7726 extras.putInt(Intent.EXTRA_UID, addedAppId); 7727 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, 7728 extras, null, null, addedUsers); 7729 } 7730 } 7731 7732 private final String mRootDir; 7733 private final boolean mIsRom; 7734 private final boolean mIsPrivileged; 7735 } 7736 7737 @Override 7738 public void installPackage(String originPath, IPackageInstallObserver2 observer, int flags, 7739 String installerPackageName, VerificationParams verificationParams, 7740 String packageAbiOverride) { 7741 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7742 null); 7743 7744 final File originFile = new File(originPath); 7745 final int uid = Binder.getCallingUid(); 7746 if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) { 7747 try { 7748 if (observer != null) { 7749 observer.packageInstalled("", null, INSTALL_FAILED_USER_RESTRICTED); 7750 } 7751 } catch (RemoteException re) { 7752 } 7753 return; 7754 } 7755 7756 UserHandle user; 7757 if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) { 7758 user = UserHandle.ALL; 7759 } else { 7760 user = new UserHandle(UserHandle.getUserId(uid)); 7761 } 7762 7763 final int filteredFlags; 7764 if (uid == Process.SHELL_UID || uid == 0) { 7765 if (DEBUG_INSTALL) { 7766 Slog.v(TAG, "Install from ADB"); 7767 } 7768 filteredFlags = flags | PackageManager.INSTALL_FROM_ADB; 7769 } else { 7770 filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB; 7771 } 7772 7773 verificationParams.setInstallerUid(uid); 7774 7775 final Message msg = mHandler.obtainMessage(INIT_COPY); 7776 msg.obj = new InstallParams(originFile, false, observer, filteredFlags, 7777 installerPackageName, verificationParams, user, packageAbiOverride); 7778 mHandler.sendMessage(msg); 7779 } 7780 7781 void installStage(String packageName, File stageDir, IPackageInstallObserver2 observer, 7782 PackageInstallerParams params, String installerPackageName, int installerUid, 7783 UserHandle user) { 7784 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 7785 params.referrerUri, installerUid, null); 7786 7787 final Message msg = mHandler.obtainMessage(INIT_COPY); 7788 msg.obj = new InstallParams(stageDir, true, observer, params.installFlags, 7789 installerPackageName, verifParams, user, params.abiOverride); 7790 mHandler.sendMessage(msg); 7791 } 7792 7793 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 7794 Bundle extras = new Bundle(1); 7795 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 7796 7797 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 7798 packageName, extras, null, null, new int[] {userId}); 7799 try { 7800 IActivityManager am = ActivityManagerNative.getDefault(); 7801 final boolean isSystem = 7802 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 7803 if (isSystem && am.isUserRunning(userId, false)) { 7804 // The just-installed/enabled app is bundled on the system, so presumed 7805 // to be able to run automatically without needing an explicit launch. 7806 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 7807 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 7808 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 7809 .setPackage(packageName); 7810 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 7811 android.app.AppOpsManager.OP_NONE, false, false, userId); 7812 } 7813 } catch (RemoteException e) { 7814 // shouldn't happen 7815 Slog.w(TAG, "Unable to bootstrap installed package", e); 7816 } 7817 } 7818 7819 @Override 7820 public boolean setApplicationBlockedSettingAsUser(String packageName, boolean blocked, 7821 int userId) { 7822 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7823 PackageSetting pkgSetting; 7824 final int uid = Binder.getCallingUid(); 7825 if (UserHandle.getUserId(uid) != userId) { 7826 mContext.enforceCallingOrSelfPermission( 7827 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 7828 "setApplicationBlockedSetting for user " + userId); 7829 } 7830 7831 if (blocked && isPackageDeviceAdmin(packageName, userId)) { 7832 Slog.w(TAG, "Not blocking package " + packageName + ": has active device admin"); 7833 return false; 7834 } 7835 7836 long callingId = Binder.clearCallingIdentity(); 7837 try { 7838 boolean sendAdded = false; 7839 boolean sendRemoved = false; 7840 // writer 7841 synchronized (mPackages) { 7842 pkgSetting = mSettings.mPackages.get(packageName); 7843 if (pkgSetting == null) { 7844 return false; 7845 } 7846 if (pkgSetting.getBlocked(userId) != blocked) { 7847 pkgSetting.setBlocked(blocked, userId); 7848 mSettings.writePackageRestrictionsLPr(userId); 7849 if (blocked) { 7850 sendRemoved = true; 7851 } else { 7852 sendAdded = true; 7853 } 7854 } 7855 } 7856 if (sendAdded) { 7857 sendPackageAddedForUser(packageName, pkgSetting, userId); 7858 return true; 7859 } 7860 if (sendRemoved) { 7861 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 7862 "blocking pkg"); 7863 sendPackageBlockedForUser(packageName, pkgSetting, userId); 7864 } 7865 } finally { 7866 Binder.restoreCallingIdentity(callingId); 7867 } 7868 return false; 7869 } 7870 7871 private void sendPackageBlockedForUser(String packageName, PackageSetting pkgSetting, 7872 int userId) { 7873 final PackageRemovedInfo info = new PackageRemovedInfo(); 7874 info.removedPackage = packageName; 7875 info.removedUsers = new int[] {userId}; 7876 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 7877 info.sendBroadcast(false, false, false); 7878 } 7879 7880 /** 7881 * Returns true if application is not found or there was an error. Otherwise it returns 7882 * the blocked state of the package for the given user. 7883 */ 7884 @Override 7885 public boolean getApplicationBlockedSettingAsUser(String packageName, int userId) { 7886 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7887 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 7888 "getApplicationBlocked for user " + userId); 7889 PackageSetting pkgSetting; 7890 long callingId = Binder.clearCallingIdentity(); 7891 try { 7892 // writer 7893 synchronized (mPackages) { 7894 pkgSetting = mSettings.mPackages.get(packageName); 7895 if (pkgSetting == null) { 7896 return true; 7897 } 7898 return pkgSetting.getBlocked(userId); 7899 } 7900 } finally { 7901 Binder.restoreCallingIdentity(callingId); 7902 } 7903 } 7904 7905 /** 7906 * @hide 7907 */ 7908 @Override 7909 public int installExistingPackageAsUser(String packageName, int userId) { 7910 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7911 null); 7912 PackageSetting pkgSetting; 7913 final int uid = Binder.getCallingUid(); 7914 enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId); 7915 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 7916 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 7917 } 7918 7919 long callingId = Binder.clearCallingIdentity(); 7920 try { 7921 boolean sendAdded = false; 7922 Bundle extras = new Bundle(1); 7923 7924 // writer 7925 synchronized (mPackages) { 7926 pkgSetting = mSettings.mPackages.get(packageName); 7927 if (pkgSetting == null) { 7928 return PackageManager.INSTALL_FAILED_INVALID_URI; 7929 } 7930 if (!pkgSetting.getInstalled(userId)) { 7931 pkgSetting.setInstalled(true, userId); 7932 pkgSetting.setBlocked(false, userId); 7933 mSettings.writePackageRestrictionsLPr(userId); 7934 sendAdded = true; 7935 } 7936 } 7937 7938 if (sendAdded) { 7939 sendPackageAddedForUser(packageName, pkgSetting, userId); 7940 } 7941 } finally { 7942 Binder.restoreCallingIdentity(callingId); 7943 } 7944 7945 return PackageManager.INSTALL_SUCCEEDED; 7946 } 7947 7948 boolean isUserRestricted(int userId, String restrictionKey) { 7949 Bundle restrictions = sUserManager.getUserRestrictions(userId); 7950 if (restrictions.getBoolean(restrictionKey, false)) { 7951 Log.w(TAG, "User is restricted: " + restrictionKey); 7952 return true; 7953 } 7954 return false; 7955 } 7956 7957 @Override 7958 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 7959 mContext.enforceCallingOrSelfPermission( 7960 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7961 "Only package verification agents can verify applications"); 7962 7963 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7964 final PackageVerificationResponse response = new PackageVerificationResponse( 7965 verificationCode, Binder.getCallingUid()); 7966 msg.arg1 = id; 7967 msg.obj = response; 7968 mHandler.sendMessage(msg); 7969 } 7970 7971 @Override 7972 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 7973 long millisecondsToDelay) { 7974 mContext.enforceCallingOrSelfPermission( 7975 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7976 "Only package verification agents can extend verification timeouts"); 7977 7978 final PackageVerificationState state = mPendingVerification.get(id); 7979 final PackageVerificationResponse response = new PackageVerificationResponse( 7980 verificationCodeAtTimeout, Binder.getCallingUid()); 7981 7982 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 7983 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 7984 } 7985 if (millisecondsToDelay < 0) { 7986 millisecondsToDelay = 0; 7987 } 7988 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 7989 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 7990 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 7991 } 7992 7993 if ((state != null) && !state.timeoutExtended()) { 7994 state.extendTimeout(); 7995 7996 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7997 msg.arg1 = id; 7998 msg.obj = response; 7999 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 8000 } 8001 } 8002 8003 private void broadcastPackageVerified(int verificationId, Uri packageUri, 8004 int verificationCode, UserHandle user) { 8005 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 8006 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 8007 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8008 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8009 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 8010 8011 mContext.sendBroadcastAsUser(intent, user, 8012 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 8013 } 8014 8015 private ComponentName matchComponentForVerifier(String packageName, 8016 List<ResolveInfo> receivers) { 8017 ActivityInfo targetReceiver = null; 8018 8019 final int NR = receivers.size(); 8020 for (int i = 0; i < NR; i++) { 8021 final ResolveInfo info = receivers.get(i); 8022 if (info.activityInfo == null) { 8023 continue; 8024 } 8025 8026 if (packageName.equals(info.activityInfo.packageName)) { 8027 targetReceiver = info.activityInfo; 8028 break; 8029 } 8030 } 8031 8032 if (targetReceiver == null) { 8033 return null; 8034 } 8035 8036 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8037 } 8038 8039 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8040 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8041 if (pkgInfo.verifiers.length == 0) { 8042 return null; 8043 } 8044 8045 final int N = pkgInfo.verifiers.length; 8046 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8047 for (int i = 0; i < N; i++) { 8048 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8049 8050 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8051 receivers); 8052 if (comp == null) { 8053 continue; 8054 } 8055 8056 final int verifierUid = getUidForVerifier(verifierInfo); 8057 if (verifierUid == -1) { 8058 continue; 8059 } 8060 8061 if (DEBUG_VERIFY) { 8062 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8063 + " with the correct signature"); 8064 } 8065 sufficientVerifiers.add(comp); 8066 verificationState.addSufficientVerifier(verifierUid); 8067 } 8068 8069 return sufficientVerifiers; 8070 } 8071 8072 private int getUidForVerifier(VerifierInfo verifierInfo) { 8073 synchronized (mPackages) { 8074 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8075 if (pkg == null) { 8076 return -1; 8077 } else if (pkg.mSignatures.length != 1) { 8078 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8079 + " has more than one signature; ignoring"); 8080 return -1; 8081 } 8082 8083 /* 8084 * If the public key of the package's signature does not match 8085 * our expected public key, then this is a different package and 8086 * we should skip. 8087 */ 8088 8089 final byte[] expectedPublicKey; 8090 try { 8091 final Signature verifierSig = pkg.mSignatures[0]; 8092 final PublicKey publicKey = verifierSig.getPublicKey(); 8093 expectedPublicKey = publicKey.getEncoded(); 8094 } catch (CertificateException e) { 8095 return -1; 8096 } 8097 8098 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8099 8100 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8101 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8102 + " does not have the expected public key; ignoring"); 8103 return -1; 8104 } 8105 8106 return pkg.applicationInfo.uid; 8107 } 8108 } 8109 8110 @Override 8111 public void finishPackageInstall(int token) { 8112 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8113 8114 if (DEBUG_INSTALL) { 8115 Slog.v(TAG, "BM finishing package install for " + token); 8116 } 8117 8118 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8119 mHandler.sendMessage(msg); 8120 } 8121 8122 /** 8123 * Get the verification agent timeout. 8124 * 8125 * @return verification timeout in milliseconds 8126 */ 8127 private long getVerificationTimeout() { 8128 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8129 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8130 DEFAULT_VERIFICATION_TIMEOUT); 8131 } 8132 8133 /** 8134 * Get the default verification agent response code. 8135 * 8136 * @return default verification response code 8137 */ 8138 private int getDefaultVerificationResponse() { 8139 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8140 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8141 DEFAULT_VERIFICATION_RESPONSE); 8142 } 8143 8144 /** 8145 * Check whether or not package verification has been enabled. 8146 * 8147 * @return true if verification should be performed 8148 */ 8149 private boolean isVerificationEnabled(int userId, int flags) { 8150 if (!DEFAULT_VERIFY_ENABLE) { 8151 return false; 8152 } 8153 8154 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 8155 8156 // Check if installing from ADB 8157 if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) { 8158 // Do not run verification in a test harness environment 8159 if (ActivityManager.isRunningInTestHarness()) { 8160 return false; 8161 } 8162 if (ensureVerifyAppsEnabled) { 8163 return true; 8164 } 8165 // Check if the developer does not want package verification for ADB installs 8166 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8167 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8168 return false; 8169 } 8170 } 8171 8172 if (ensureVerifyAppsEnabled) { 8173 return true; 8174 } 8175 8176 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8177 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8178 } 8179 8180 /** 8181 * Get the "allow unknown sources" setting. 8182 * 8183 * @return the current "allow unknown sources" setting 8184 */ 8185 private int getUnknownSourcesSettings() { 8186 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8187 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 8188 -1); 8189 } 8190 8191 @Override 8192 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 8193 final int uid = Binder.getCallingUid(); 8194 // writer 8195 synchronized (mPackages) { 8196 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 8197 if (targetPackageSetting == null) { 8198 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 8199 } 8200 8201 PackageSetting installerPackageSetting; 8202 if (installerPackageName != null) { 8203 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 8204 if (installerPackageSetting == null) { 8205 throw new IllegalArgumentException("Unknown installer package: " 8206 + installerPackageName); 8207 } 8208 } else { 8209 installerPackageSetting = null; 8210 } 8211 8212 Signature[] callerSignature; 8213 Object obj = mSettings.getUserIdLPr(uid); 8214 if (obj != null) { 8215 if (obj instanceof SharedUserSetting) { 8216 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 8217 } else if (obj instanceof PackageSetting) { 8218 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 8219 } else { 8220 throw new SecurityException("Bad object " + obj + " for uid " + uid); 8221 } 8222 } else { 8223 throw new SecurityException("Unknown calling uid " + uid); 8224 } 8225 8226 // Verify: can't set installerPackageName to a package that is 8227 // not signed with the same cert as the caller. 8228 if (installerPackageSetting != null) { 8229 if (compareSignatures(callerSignature, 8230 installerPackageSetting.signatures.mSignatures) 8231 != PackageManager.SIGNATURE_MATCH) { 8232 throw new SecurityException( 8233 "Caller does not have same cert as new installer package " 8234 + installerPackageName); 8235 } 8236 } 8237 8238 // Verify: if target already has an installer package, it must 8239 // be signed with the same cert as the caller. 8240 if (targetPackageSetting.installerPackageName != null) { 8241 PackageSetting setting = mSettings.mPackages.get( 8242 targetPackageSetting.installerPackageName); 8243 // If the currently set package isn't valid, then it's always 8244 // okay to change it. 8245 if (setting != null) { 8246 if (compareSignatures(callerSignature, 8247 setting.signatures.mSignatures) 8248 != PackageManager.SIGNATURE_MATCH) { 8249 throw new SecurityException( 8250 "Caller does not have same cert as old installer package " 8251 + targetPackageSetting.installerPackageName); 8252 } 8253 } 8254 } 8255 8256 // Okay! 8257 targetPackageSetting.installerPackageName = installerPackageName; 8258 scheduleWriteSettingsLocked(); 8259 } 8260 } 8261 8262 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 8263 // Queue up an async operation since the package installation may take a little while. 8264 mHandler.post(new Runnable() { 8265 public void run() { 8266 mHandler.removeCallbacks(this); 8267 // Result object to be returned 8268 PackageInstalledInfo res = new PackageInstalledInfo(); 8269 res.returnCode = currentStatus; 8270 res.uid = -1; 8271 res.pkg = null; 8272 res.removedInfo = new PackageRemovedInfo(); 8273 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 8274 args.doPreInstall(res.returnCode); 8275 synchronized (mInstallLock) { 8276 installPackageLI(args, true, res); 8277 } 8278 args.doPostInstall(res.returnCode, res.uid); 8279 } 8280 8281 // A restore should be performed at this point if (a) the install 8282 // succeeded, (b) the operation is not an update, and (c) the new 8283 // package has a backupAgent defined. 8284 final boolean update = res.removedInfo.removedPackage != null; 8285 boolean doRestore = (!update 8286 && res.pkg != null 8287 && res.pkg.applicationInfo.backupAgentName != null); 8288 8289 // Set up the post-install work request bookkeeping. This will be used 8290 // and cleaned up by the post-install event handling regardless of whether 8291 // there's a restore pass performed. Token values are >= 1. 8292 int token; 8293 if (mNextInstallToken < 0) mNextInstallToken = 1; 8294 token = mNextInstallToken++; 8295 8296 PostInstallData data = new PostInstallData(args, res); 8297 mRunningInstalls.put(token, data); 8298 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 8299 8300 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 8301 // Pass responsibility to the Backup Manager. It will perform a 8302 // restore if appropriate, then pass responsibility back to the 8303 // Package Manager to run the post-install observer callbacks 8304 // and broadcasts. 8305 IBackupManager bm = IBackupManager.Stub.asInterface( 8306 ServiceManager.getService(Context.BACKUP_SERVICE)); 8307 if (bm != null) { 8308 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 8309 + " to BM for possible restore"); 8310 try { 8311 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 8312 } catch (RemoteException e) { 8313 // can't happen; the backup manager is local 8314 } catch (Exception e) { 8315 Slog.e(TAG, "Exception trying to enqueue restore", e); 8316 doRestore = false; 8317 } 8318 } else { 8319 Slog.e(TAG, "Backup Manager not found!"); 8320 doRestore = false; 8321 } 8322 } 8323 8324 if (!doRestore) { 8325 // No restore possible, or the Backup Manager was mysteriously not 8326 // available -- just fire the post-install work request directly. 8327 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 8328 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8329 mHandler.sendMessage(msg); 8330 } 8331 } 8332 }); 8333 } 8334 8335 private abstract class HandlerParams { 8336 private static final int MAX_RETRIES = 4; 8337 8338 /** 8339 * Number of times startCopy() has been attempted and had a non-fatal 8340 * error. 8341 */ 8342 private int mRetries = 0; 8343 8344 /** User handle for the user requesting the information or installation. */ 8345 private final UserHandle mUser; 8346 8347 HandlerParams(UserHandle user) { 8348 mUser = user; 8349 } 8350 8351 UserHandle getUser() { 8352 return mUser; 8353 } 8354 8355 final boolean startCopy() { 8356 boolean res; 8357 try { 8358 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 8359 8360 if (++mRetries > MAX_RETRIES) { 8361 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 8362 mHandler.sendEmptyMessage(MCS_GIVE_UP); 8363 handleServiceError(); 8364 return false; 8365 } else { 8366 handleStartCopy(); 8367 res = true; 8368 } 8369 } catch (RemoteException e) { 8370 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 8371 mHandler.sendEmptyMessage(MCS_RECONNECT); 8372 res = false; 8373 } 8374 handleReturnCode(); 8375 return res; 8376 } 8377 8378 final void serviceError() { 8379 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 8380 handleServiceError(); 8381 handleReturnCode(); 8382 } 8383 8384 abstract void handleStartCopy() throws RemoteException; 8385 abstract void handleServiceError(); 8386 abstract void handleReturnCode(); 8387 } 8388 8389 class MeasureParams extends HandlerParams { 8390 private final PackageStats mStats; 8391 private boolean mSuccess; 8392 8393 private final IPackageStatsObserver mObserver; 8394 8395 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 8396 super(new UserHandle(stats.userHandle)); 8397 mObserver = observer; 8398 mStats = stats; 8399 } 8400 8401 @Override 8402 public String toString() { 8403 return "MeasureParams{" 8404 + Integer.toHexString(System.identityHashCode(this)) 8405 + " " + mStats.packageName + "}"; 8406 } 8407 8408 @Override 8409 void handleStartCopy() throws RemoteException { 8410 synchronized (mInstallLock) { 8411 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 8412 } 8413 8414 if (mSuccess) { 8415 final boolean mounted; 8416 if (Environment.isExternalStorageEmulated()) { 8417 mounted = true; 8418 } else { 8419 final String status = Environment.getExternalStorageState(); 8420 mounted = (Environment.MEDIA_MOUNTED.equals(status) 8421 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 8422 } 8423 8424 if (mounted) { 8425 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 8426 8427 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 8428 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 8429 8430 mStats.externalDataSize = calculateDirectorySize(mContainerService, 8431 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 8432 8433 // Always subtract cache size, since it's a subdirectory 8434 mStats.externalDataSize -= mStats.externalCacheSize; 8435 8436 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 8437 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 8438 8439 mStats.externalObbSize = calculateDirectorySize(mContainerService, 8440 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 8441 } 8442 } 8443 } 8444 8445 @Override 8446 void handleReturnCode() { 8447 if (mObserver != null) { 8448 try { 8449 mObserver.onGetStatsCompleted(mStats, mSuccess); 8450 } catch (RemoteException e) { 8451 Slog.i(TAG, "Observer no longer exists."); 8452 } 8453 } 8454 } 8455 8456 @Override 8457 void handleServiceError() { 8458 Slog.e(TAG, "Could not measure application " + mStats.packageName 8459 + " external storage"); 8460 } 8461 } 8462 8463 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 8464 throws RemoteException { 8465 long result = 0; 8466 for (File path : paths) { 8467 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 8468 } 8469 return result; 8470 } 8471 8472 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 8473 for (File path : paths) { 8474 try { 8475 mcs.clearDirectory(path.getAbsolutePath()); 8476 } catch (RemoteException e) { 8477 } 8478 } 8479 } 8480 8481 class InstallParams extends HandlerParams { 8482 /** 8483 * Location where install is coming from, before it has been 8484 * copied/renamed into place. This could be a single monolithic APK 8485 * file, or a cluster directory. This location may be untrusted. 8486 */ 8487 final File originFile; 8488 8489 /** 8490 * Flag indicating that {@link #originFile} has already been staged, 8491 * meaning downstream users don't need to defensively copy the contents. 8492 */ 8493 boolean originStaged; 8494 8495 final IPackageInstallObserver2 observer; 8496 int flags; 8497 final String installerPackageName; 8498 final VerificationParams verificationParams; 8499 private InstallArgs mArgs; 8500 private int mRet; 8501 final String packageAbiOverride; 8502 boolean multiArch; 8503 8504 InstallParams(File originFile, boolean originStaged, IPackageInstallObserver2 observer, 8505 int flags, String installerPackageName, VerificationParams verificationParams, 8506 UserHandle user, String packageAbiOverride) { 8507 super(user); 8508 this.originFile = Preconditions.checkNotNull(originFile); 8509 this.originStaged = originStaged; 8510 this.observer = observer; 8511 this.flags = flags; 8512 this.installerPackageName = installerPackageName; 8513 this.verificationParams = verificationParams; 8514 this.packageAbiOverride = packageAbiOverride; 8515 } 8516 8517 @Override 8518 public String toString() { 8519 return "InstallParams{" 8520 + Integer.toHexString(System.identityHashCode(this)) 8521 + " " + originFile + "}"; 8522 } 8523 8524 public ManifestDigest getManifestDigest() { 8525 if (verificationParams == null) { 8526 return null; 8527 } 8528 return verificationParams.getManifestDigest(); 8529 } 8530 8531 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) { 8532 String packageName = pkgLite.packageName; 8533 int installLocation = pkgLite.installLocation; 8534 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8535 // reader 8536 synchronized (mPackages) { 8537 PackageParser.Package pkg = mPackages.get(packageName); 8538 if (pkg != null) { 8539 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 8540 // Check for downgrading. 8541 if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 8542 if (pkgLite.versionCode < pkg.mVersionCode) { 8543 Slog.w(TAG, "Can't install update of " + packageName 8544 + " update version " + pkgLite.versionCode 8545 + " is older than installed version " 8546 + pkg.mVersionCode); 8547 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 8548 } 8549 } 8550 // Check for updated system application. 8551 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8552 if (onSd) { 8553 Slog.w(TAG, "Cannot install update to system app on sdcard"); 8554 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 8555 } 8556 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8557 } else { 8558 if (onSd) { 8559 // Install flag overrides everything. 8560 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8561 } 8562 // If current upgrade specifies particular preference 8563 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 8564 // Application explicitly specified internal. 8565 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8566 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 8567 // App explictly prefers external. Let policy decide 8568 } else { 8569 // Prefer previous location 8570 if (isExternal(pkg)) { 8571 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8572 } 8573 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8574 } 8575 } 8576 } else { 8577 // Invalid install. Return error code 8578 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 8579 } 8580 } 8581 } 8582 // All the special cases have been taken care of. 8583 // Return result based on recommended install location. 8584 if (onSd) { 8585 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8586 } 8587 return pkgLite.recommendedInstallLocation; 8588 } 8589 8590 private long getMemoryLowThreshold() { 8591 final DeviceStorageMonitorInternal 8592 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 8593 if (dsm == null) { 8594 return 0L; 8595 } 8596 return dsm.getMemoryLowThreshold(); 8597 } 8598 8599 /* 8600 * Invoke remote method to get package information and install 8601 * location values. Override install location based on default 8602 * policy if needed and then create install arguments based 8603 * on the install location. 8604 */ 8605 public void handleStartCopy() throws RemoteException { 8606 int ret = PackageManager.INSTALL_SUCCEEDED; 8607 final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8608 final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0; 8609 PackageInfoLite pkgLite = null; 8610 8611 if (onInt && onSd) { 8612 // Check if both bits are set. 8613 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 8614 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8615 } else { 8616 final long lowThreshold = getMemoryLowThreshold(); 8617 if (lowThreshold == 0L) { 8618 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 8619 } 8620 8621 // Remote call to find out default install location 8622 final String originPath = originFile.getAbsolutePath(); 8623 pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags, lowThreshold, 8624 packageAbiOverride); 8625 // Keep track of whether this package is a multiArch package until 8626 // we perform a full scan of it. We need to do this because we might 8627 // end up extracting the package shared libraries before we perform 8628 // a full scan. 8629 multiArch = pkgLite.multiArch; 8630 8631 /* 8632 * If we have too little free space, try to free cache 8633 * before giving up. 8634 */ 8635 if (pkgLite.recommendedInstallLocation 8636 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8637 final long size = mContainerService.calculateInstalledSize( 8638 originPath, isForwardLocked(), packageAbiOverride); 8639 if (mInstaller.freeCache(size + lowThreshold) >= 0) { 8640 pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags, 8641 lowThreshold, packageAbiOverride); 8642 } 8643 /* 8644 * The cache free must have deleted the file we 8645 * downloaded to install. 8646 * 8647 * TODO: fix the "freeCache" call to not delete 8648 * the file we care about. 8649 */ 8650 if (pkgLite.recommendedInstallLocation 8651 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8652 pkgLite.recommendedInstallLocation 8653 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 8654 } 8655 } 8656 } 8657 8658 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8659 int loc = pkgLite.recommendedInstallLocation; 8660 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 8661 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8662 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 8663 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 8664 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8665 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8666 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 8667 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 8668 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8669 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 8670 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 8671 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 8672 } else { 8673 // Override with defaults if needed. 8674 loc = installLocationPolicy(pkgLite, flags); 8675 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 8676 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 8677 } else if (!onSd && !onInt) { 8678 // Override install location with flags 8679 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 8680 // Set the flag to install on external media. 8681 flags |= PackageManager.INSTALL_EXTERNAL; 8682 flags &= ~PackageManager.INSTALL_INTERNAL; 8683 } else { 8684 // Make sure the flag for installing on external 8685 // media is unset 8686 flags |= PackageManager.INSTALL_INTERNAL; 8687 flags &= ~PackageManager.INSTALL_EXTERNAL; 8688 } 8689 } 8690 } 8691 } 8692 8693 final InstallArgs args = createInstallArgs(this); 8694 mArgs = args; 8695 8696 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8697 /* 8698 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 8699 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 8700 */ 8701 int userIdentifier = getUser().getIdentifier(); 8702 if (userIdentifier == UserHandle.USER_ALL 8703 && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) { 8704 userIdentifier = UserHandle.USER_OWNER; 8705 } 8706 8707 /* 8708 * Determine if we have any installed package verifiers. If we 8709 * do, then we'll defer to them to verify the packages. 8710 */ 8711 final int requiredUid = mRequiredVerifierPackage == null ? -1 8712 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 8713 if (requiredUid != -1 && isVerificationEnabled(userIdentifier, flags)) { 8714 // TODO: send verifier the install session instead of uri 8715 final Intent verification = new Intent( 8716 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 8717 verification.setDataAndType(Uri.fromFile(originFile), PACKAGE_MIME_TYPE); 8718 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8719 8720 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 8721 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 8722 0 /* TODO: Which userId? */); 8723 8724 if (DEBUG_VERIFY) { 8725 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 8726 + verification.toString() + " with " + pkgLite.verifiers.length 8727 + " optional verifiers"); 8728 } 8729 8730 final int verificationId = mPendingVerificationToken++; 8731 8732 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8733 8734 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 8735 installerPackageName); 8736 8737 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags); 8738 8739 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 8740 pkgLite.packageName); 8741 8742 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 8743 pkgLite.versionCode); 8744 8745 if (verificationParams != null) { 8746 if (verificationParams.getVerificationURI() != null) { 8747 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 8748 verificationParams.getVerificationURI()); 8749 } 8750 if (verificationParams.getOriginatingURI() != null) { 8751 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 8752 verificationParams.getOriginatingURI()); 8753 } 8754 if (verificationParams.getReferrer() != null) { 8755 verification.putExtra(Intent.EXTRA_REFERRER, 8756 verificationParams.getReferrer()); 8757 } 8758 if (verificationParams.getOriginatingUid() >= 0) { 8759 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 8760 verificationParams.getOriginatingUid()); 8761 } 8762 if (verificationParams.getInstallerUid() >= 0) { 8763 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 8764 verificationParams.getInstallerUid()); 8765 } 8766 } 8767 8768 final PackageVerificationState verificationState = new PackageVerificationState( 8769 requiredUid, args); 8770 8771 mPendingVerification.append(verificationId, verificationState); 8772 8773 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 8774 receivers, verificationState); 8775 8776 /* 8777 * If any sufficient verifiers were listed in the package 8778 * manifest, attempt to ask them. 8779 */ 8780 if (sufficientVerifiers != null) { 8781 final int N = sufficientVerifiers.size(); 8782 if (N == 0) { 8783 Slog.i(TAG, "Additional verifiers required, but none installed."); 8784 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 8785 } else { 8786 for (int i = 0; i < N; i++) { 8787 final ComponentName verifierComponent = sufficientVerifiers.get(i); 8788 8789 final Intent sufficientIntent = new Intent(verification); 8790 sufficientIntent.setComponent(verifierComponent); 8791 8792 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 8793 } 8794 } 8795 } 8796 8797 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 8798 mRequiredVerifierPackage, receivers); 8799 if (ret == PackageManager.INSTALL_SUCCEEDED 8800 && mRequiredVerifierPackage != null) { 8801 /* 8802 * Send the intent to the required verification agent, 8803 * but only start the verification timeout after the 8804 * target BroadcastReceivers have run. 8805 */ 8806 verification.setComponent(requiredVerifierComponent); 8807 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 8808 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8809 new BroadcastReceiver() { 8810 @Override 8811 public void onReceive(Context context, Intent intent) { 8812 final Message msg = mHandler 8813 .obtainMessage(CHECK_PENDING_VERIFICATION); 8814 msg.arg1 = verificationId; 8815 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 8816 } 8817 }, null, 0, null, null); 8818 8819 /* 8820 * We don't want the copy to proceed until verification 8821 * succeeds, so null out this field. 8822 */ 8823 mArgs = null; 8824 } 8825 } else { 8826 /* 8827 * No package verification is enabled, so immediately start 8828 * the remote call to initiate copy using temporary file. 8829 */ 8830 ret = args.copyApk(mContainerService, true); 8831 } 8832 } 8833 8834 mRet = ret; 8835 } 8836 8837 @Override 8838 void handleReturnCode() { 8839 // If mArgs is null, then MCS couldn't be reached. When it 8840 // reconnects, it will try again to install. At that point, this 8841 // will succeed. 8842 if (mArgs != null) { 8843 processPendingInstall(mArgs, mRet); 8844 } 8845 } 8846 8847 @Override 8848 void handleServiceError() { 8849 mArgs = createInstallArgs(this); 8850 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8851 } 8852 8853 public boolean isForwardLocked() { 8854 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8855 } 8856 } 8857 8858 /* 8859 * Utility class used in movePackage api. 8860 * srcArgs and targetArgs are not set for invalid flags and make 8861 * sure to do null checks when invoking methods on them. 8862 * We probably want to return ErrorPrams for both failed installs 8863 * and moves. 8864 */ 8865 class MoveParams extends HandlerParams { 8866 final IPackageMoveObserver observer; 8867 final int flags; 8868 final String packageName; 8869 final InstallArgs srcArgs; 8870 final InstallArgs targetArgs; 8871 int uid; 8872 int mRet; 8873 8874 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags, 8875 String packageName, String[] instructionSets, int uid, UserHandle user, 8876 boolean isMultiArch) { 8877 super(user); 8878 this.srcArgs = srcArgs; 8879 this.observer = observer; 8880 this.flags = flags; 8881 this.packageName = packageName; 8882 this.uid = uid; 8883 if (srcArgs != null) { 8884 final String codePath = srcArgs.getCodePath(); 8885 targetArgs = createInstallArgsForMoveTarget(codePath, flags, packageName, 8886 instructionSets, isMultiArch); 8887 } else { 8888 targetArgs = null; 8889 } 8890 } 8891 8892 @Override 8893 public String toString() { 8894 return "MoveParams{" 8895 + Integer.toHexString(System.identityHashCode(this)) 8896 + " " + packageName + "}"; 8897 } 8898 8899 public void handleStartCopy() throws RemoteException { 8900 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8901 // Check for storage space on target medium 8902 if (!targetArgs.checkFreeStorage(mContainerService)) { 8903 Log.w(TAG, "Insufficient storage to install"); 8904 return; 8905 } 8906 8907 mRet = srcArgs.doPreCopy(); 8908 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8909 return; 8910 } 8911 8912 mRet = targetArgs.copyApk(mContainerService, false); 8913 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8914 srcArgs.doPostCopy(uid); 8915 return; 8916 } 8917 8918 mRet = srcArgs.doPostCopy(uid); 8919 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8920 return; 8921 } 8922 8923 mRet = targetArgs.doPreInstall(mRet); 8924 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8925 return; 8926 } 8927 8928 if (DEBUG_SD_INSTALL) { 8929 StringBuilder builder = new StringBuilder(); 8930 if (srcArgs != null) { 8931 builder.append("src: "); 8932 builder.append(srcArgs.getCodePath()); 8933 } 8934 if (targetArgs != null) { 8935 builder.append(" target : "); 8936 builder.append(targetArgs.getCodePath()); 8937 } 8938 Log.i(TAG, builder.toString()); 8939 } 8940 } 8941 8942 @Override 8943 void handleReturnCode() { 8944 targetArgs.doPostInstall(mRet, uid); 8945 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 8946 if (mRet == PackageManager.INSTALL_SUCCEEDED) { 8947 currentStatus = PackageManager.MOVE_SUCCEEDED; 8948 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){ 8949 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 8950 } 8951 processPendingMove(this, currentStatus); 8952 } 8953 8954 @Override 8955 void handleServiceError() { 8956 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8957 } 8958 } 8959 8960 /** 8961 * Used during creation of InstallArgs 8962 * 8963 * @param flags package installation flags 8964 * @return true if should be installed on external storage 8965 */ 8966 private static boolean installOnSd(int flags) { 8967 if ((flags & PackageManager.INSTALL_INTERNAL) != 0) { 8968 return false; 8969 } 8970 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) { 8971 return true; 8972 } 8973 return false; 8974 } 8975 8976 /** 8977 * Used during creation of InstallArgs 8978 * 8979 * @param flags package installation flags 8980 * @return true if should be installed as forward locked 8981 */ 8982 private static boolean installForwardLocked(int flags) { 8983 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8984 } 8985 8986 private InstallArgs createInstallArgs(InstallParams params) { 8987 // TODO: extend to support incoming zero-copy locations 8988 8989 if (installOnSd(params.flags) || params.isForwardLocked()) { 8990 return new AsecInstallArgs(params); 8991 } else { 8992 return new FileInstallArgs(params); 8993 } 8994 } 8995 8996 /** 8997 * Create args that describe an existing installed package. Typically used 8998 * when cleaning up old installs, or used as a move source. 8999 */ 9000 private InstallArgs createInstallArgsForExisting(int flags, String codePath, 9001 String resourcePath, String nativeLibraryRoot, String[] instructionSets, 9002 boolean isMultiArch) { 9003 final boolean isInAsec; 9004 if (installOnSd(flags)) { 9005 /* Apps on SD card are always in ASEC containers. */ 9006 isInAsec = true; 9007 } else if (installForwardLocked(flags) 9008 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 9009 /* 9010 * Forward-locked apps are only in ASEC containers if they're the 9011 * new style 9012 */ 9013 isInAsec = true; 9014 } else { 9015 isInAsec = false; 9016 } 9017 9018 if (isInAsec) { 9019 return new AsecInstallArgs(codePath, instructionSets, 9020 installOnSd(flags), installForwardLocked(flags), isMultiArch); 9021 } else { 9022 return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot, 9023 instructionSets, isMultiArch); 9024 } 9025 } 9026 9027 private InstallArgs createInstallArgsForMoveTarget(String codePath, int flags, String pkgName, 9028 String[] instructionSets, boolean isMultiArch) { 9029 final File codeFile = new File(codePath); 9030 if (installOnSd(flags) || installForwardLocked(flags)) { 9031 String cid = getNextCodePath(codePath, pkgName, "/" 9032 + AsecInstallArgs.RES_FILE_NAME); 9033 return new AsecInstallArgs(codeFile, cid, instructionSets, installOnSd(flags), 9034 installForwardLocked(flags), isMultiArch); 9035 } else { 9036 return new FileInstallArgs(codeFile, instructionSets, isMultiArch); 9037 } 9038 } 9039 9040 static abstract class InstallArgs { 9041 /** @see InstallParams#originFile */ 9042 final File originFile; 9043 /** @see InstallParams#originStaged */ 9044 final boolean originStaged; 9045 9046 // TODO: define inherit location 9047 9048 final IPackageInstallObserver2 observer; 9049 // Always refers to PackageManager flags only 9050 final int flags; 9051 final String installerPackageName; 9052 final ManifestDigest manifestDigest; 9053 final UserHandle user; 9054 final String abiOverride; 9055 final boolean multiArch; 9056 9057 // The list of instruction sets supported by this app. This is currently 9058 // only used during the rmdex() phase to clean up resources. We can get rid of this 9059 // if we move dex files under the common app path. 9060 /* nullable */ String[] instructionSets; 9061 9062 InstallArgs(File originFile, boolean originStaged, IPackageInstallObserver2 observer, 9063 int flags, String installerPackageName, ManifestDigest manifestDigest, 9064 UserHandle user, String[] instructionSets, 9065 String abiOverride, boolean multiArch) { 9066 this.originFile = originFile; 9067 this.originStaged = originStaged; 9068 this.flags = flags; 9069 this.observer = observer; 9070 this.installerPackageName = installerPackageName; 9071 this.manifestDigest = manifestDigest; 9072 this.user = user; 9073 this.instructionSets = instructionSets; 9074 this.abiOverride = abiOverride; 9075 this.multiArch = multiArch; 9076 } 9077 9078 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 9079 abstract int doPreInstall(int status); 9080 9081 /** 9082 * Rename package into final resting place. All paths on the given 9083 * scanned package should be updated to reflect the rename. 9084 */ 9085 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 9086 abstract int doPostInstall(int status, int uid); 9087 9088 /** @see PackageSettingBase#codePathString */ 9089 abstract String getCodePath(); 9090 /** @see PackageSettingBase#resourcePathString */ 9091 abstract String getResourcePath(); 9092 abstract String getLegacyNativeLibraryPath(); 9093 9094 // Need installer lock especially for dex file removal. 9095 abstract void cleanUpResourcesLI(); 9096 abstract boolean doPostDeleteLI(boolean delete); 9097 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9098 9099 /** 9100 * Called before the source arguments are copied. This is used mostly 9101 * for MoveParams when it needs to read the source file to put it in the 9102 * destination. 9103 */ 9104 int doPreCopy() { 9105 return PackageManager.INSTALL_SUCCEEDED; 9106 } 9107 9108 /** 9109 * Called after the source arguments are copied. This is used mostly for 9110 * MoveParams when it needs to read the source file to put it in the 9111 * destination. 9112 * 9113 * @return 9114 */ 9115 int doPostCopy(int uid) { 9116 return PackageManager.INSTALL_SUCCEEDED; 9117 } 9118 9119 protected boolean isFwdLocked() { 9120 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9121 } 9122 9123 UserHandle getUser() { 9124 return user; 9125 } 9126 } 9127 9128 /** 9129 * Logic to handle installation of non-ASEC applications, including copying 9130 * and renaming logic. 9131 */ 9132 class FileInstallArgs extends InstallArgs { 9133 private File codeFile; 9134 private File resourceFile; 9135 private File legacyNativeLibraryPath; 9136 9137 // Example topology: 9138 // /data/app/com.example/base.apk 9139 // /data/app/com.example/split_foo.apk 9140 // /data/app/com.example/lib/arm/libfoo.so 9141 // /data/app/com.example/lib/arm64/libfoo.so 9142 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 9143 9144 /** New install */ 9145 FileInstallArgs(InstallParams params) { 9146 super(params.originFile, params.originStaged, params.observer, params.flags, 9147 params.installerPackageName, params.getManifestDigest(), params.getUser(), 9148 null /* instruction sets */, params.packageAbiOverride, 9149 params.multiArch); 9150 if (isFwdLocked()) { 9151 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 9152 } 9153 } 9154 9155 /** Existing install */ 9156 FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath, 9157 String[] instructionSets, boolean isMultiArch) { 9158 super(null, false, null, 0, null, null, null, instructionSets, null, isMultiArch); 9159 this.codeFile = (codePath != null) ? new File(codePath) : null; 9160 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 9161 this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ? 9162 new File(legacyNativeLibraryPath) : null; 9163 } 9164 9165 /** New install from existing */ 9166 FileInstallArgs(File originFile, String[] instructionSets, boolean isMultiArch) { 9167 super(originFile, false, null, 0, null, null, null, instructionSets, null, 9168 isMultiArch); 9169 } 9170 9171 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9172 final long lowThreshold; 9173 9174 final DeviceStorageMonitorInternal 9175 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 9176 if (dsm == null) { 9177 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 9178 lowThreshold = 0L; 9179 } else { 9180 if (dsm.isMemoryLow()) { 9181 Log.w(TAG, "Memory is reported as being too low; aborting package install"); 9182 return false; 9183 } 9184 9185 lowThreshold = dsm.getMemoryLowThreshold(); 9186 } 9187 9188 return imcs.checkInternalFreeStorage(originFile.getAbsolutePath(), isFwdLocked(), 9189 lowThreshold); 9190 } 9191 9192 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9193 int ret = PackageManager.INSTALL_SUCCEEDED; 9194 9195 if (originStaged) { 9196 Slog.d(TAG, originFile + " already staged; skipping copy"); 9197 codeFile = originFile; 9198 resourceFile = originFile; 9199 } else { 9200 try { 9201 final File tempDir = mInstallerService.allocateSessionDir(); 9202 codeFile = tempDir; 9203 resourceFile = tempDir; 9204 } catch (IOException e) { 9205 Slog.w(TAG, "Failed to create copy file: " + e); 9206 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9207 } 9208 9209 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 9210 @Override 9211 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 9212 if (!FileUtils.isValidExtFilename(name)) { 9213 throw new IllegalArgumentException("Invalid filename: " + name); 9214 } 9215 try { 9216 final File file = new File(codeFile, name); 9217 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 9218 O_RDWR | O_CREAT, 0644); 9219 Os.chmod(file.getAbsolutePath(), 0644); 9220 return new ParcelFileDescriptor(fd); 9221 } catch (ErrnoException e) { 9222 throw new RemoteException("Failed to open: " + e.getMessage()); 9223 } 9224 } 9225 }; 9226 9227 ret = imcs.copyPackage(originFile.getAbsolutePath(), target); 9228 if (ret != PackageManager.INSTALL_SUCCEEDED) { 9229 Slog.e(TAG, "Failed to copy package"); 9230 return ret; 9231 } 9232 } 9233 9234 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 9235 NativeLibraryHelper.Handle handle = null; 9236 try { 9237 handle = NativeLibraryHelper.Handle.create(codeFile); 9238 if (multiArch) { 9239 // Warn if we've set an abiOverride for multi-lib packages.. 9240 // By definition, we need to copy both 32 and 64 bit libraries for 9241 // such packages. 9242 if (abiOverride != null) { 9243 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 9244 } 9245 9246 int copyRet = PackageManager.NO_NATIVE_LIBRARIES; 9247 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 9248 copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot, 9249 Build.SUPPORTED_32_BIT_ABIS, true /* use isa specific subdirs */); 9250 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9251 Slog.w(TAG, "Failure copying 32 bit native libraries [errorCode=" + copyRet + "]"); 9252 return copyRet; 9253 } 9254 } 9255 9256 if (DEBUG_ABI_SELECTION && copyRet >= 0) { 9257 Log.d(TAG, "Installed 32 bit libraries under: " + codeFile + " abi=" + 9258 Build.SUPPORTED_32_BIT_ABIS[copyRet]); 9259 } 9260 9261 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 9262 copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot, 9263 Build.SUPPORTED_64_BIT_ABIS, true /* use isa specific subdirs */); 9264 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9265 Slog.w(TAG, "Failure copying 64 bit native libraries [errorCode=" + copyRet + "]"); 9266 return copyRet; 9267 } 9268 } 9269 9270 if (DEBUG_ABI_SELECTION && copyRet >= 0) { 9271 Log.d(TAG, "Installed 64 bit libraries under: " + codeFile + " abi=" + 9272 Build.SUPPORTED_64_BIT_ABIS[copyRet]); 9273 } 9274 } else { 9275 String[] abiList = (abiOverride != null) ? 9276 new String[] { abiOverride } : Build.SUPPORTED_ABIS; 9277 9278 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && abiOverride == null && 9279 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9280 abiList = Build.SUPPORTED_32_BIT_ABIS; 9281 } 9282 9283 int copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot, abiList, 9284 true /* use isa specific subdirs */); 9285 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9286 Slog.w(TAG, "Failure copying native libraries [errorCode=" + copyRet + "]"); 9287 return copyRet; 9288 } 9289 9290 if (DEBUG_ABI_SELECTION && copyRet >= 0) { 9291 Log.d(TAG, "Installed libraries under: " + codeFile + " abi=" + abiList[copyRet]); 9292 } 9293 } 9294 } catch (IOException e) { 9295 Slog.e(TAG, "Copying native libraries failed", e); 9296 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9297 } finally { 9298 IoUtils.closeQuietly(handle); 9299 } 9300 9301 return ret; 9302 } 9303 9304 int doPreInstall(int status) { 9305 if (status != PackageManager.INSTALL_SUCCEEDED) { 9306 cleanUp(); 9307 } 9308 return status; 9309 } 9310 9311 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9312 if (status != PackageManager.INSTALL_SUCCEEDED) { 9313 cleanUp(); 9314 return false; 9315 } else { 9316 final File beforeCodeFile = codeFile; 9317 final File afterCodeFile = new File(mAppInstallDir, 9318 getNextCodePath(oldCodePath, pkg.packageName, null)); 9319 9320 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 9321 if (!beforeCodeFile.renameTo(afterCodeFile)) { 9322 return false; 9323 } 9324 if (!SELinux.restoreconRecursive(afterCodeFile)) { 9325 return false; 9326 } 9327 9328 // Reflect the rename internally 9329 codeFile = afterCodeFile; 9330 resourceFile = afterCodeFile; 9331 9332 // Reflect the rename in scanned details 9333 pkg.codePath = afterCodeFile.getAbsolutePath(); 9334 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9335 pkg.baseCodePath); 9336 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9337 pkg.splitCodePaths); 9338 9339 // Reflect the rename in app info 9340 pkg.applicationInfo.setCodePath(pkg.codePath); 9341 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9342 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9343 pkg.applicationInfo.setResourcePath(pkg.codePath); 9344 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9345 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9346 9347 return true; 9348 } 9349 } 9350 9351 int doPostInstall(int status, int uid) { 9352 if (status != PackageManager.INSTALL_SUCCEEDED) { 9353 cleanUp(); 9354 } 9355 return status; 9356 } 9357 9358 @Override 9359 String getCodePath() { 9360 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 9361 } 9362 9363 @Override 9364 String getResourcePath() { 9365 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 9366 } 9367 9368 @Override 9369 String getLegacyNativeLibraryPath() { 9370 return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null; 9371 } 9372 9373 private boolean cleanUp() { 9374 if (codeFile == null || !codeFile.exists()) { 9375 return false; 9376 } 9377 9378 if (codeFile.isDirectory()) { 9379 FileUtils.deleteContents(codeFile); 9380 } 9381 codeFile.delete(); 9382 9383 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 9384 resourceFile.delete(); 9385 } 9386 9387 if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) { 9388 if (!FileUtils.deleteContents(legacyNativeLibraryPath)) { 9389 Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath); 9390 } 9391 legacyNativeLibraryPath.delete(); 9392 } 9393 9394 return true; 9395 } 9396 9397 void cleanUpResourcesLI() { 9398 // Try enumerating all code paths before deleting 9399 List<String> allCodePaths = Collections.EMPTY_LIST; 9400 if (codeFile != null && codeFile.exists()) { 9401 try { 9402 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9403 allCodePaths = pkg.getAllCodePaths(); 9404 } catch (PackageParserException e) { 9405 // Ignored; we tried our best 9406 } 9407 } 9408 9409 cleanUp(); 9410 9411 if (!allCodePaths.isEmpty()) { 9412 if (instructionSets == null) { 9413 throw new IllegalStateException("instructionSet == null"); 9414 } 9415 9416 for (String codePath : allCodePaths) { 9417 for (String instructionSet : instructionSets) { 9418 int retCode = mInstaller.rmdex(codePath, instructionSet); 9419 if (retCode < 0) { 9420 Slog.w(TAG, "Couldn't remove dex file for package: " 9421 + " at location " + codePath + ", retcode=" + retCode); 9422 // we don't consider this to be a failure of the core package deletion 9423 } 9424 } 9425 } 9426 } 9427 } 9428 9429 boolean doPostDeleteLI(boolean delete) { 9430 // XXX err, shouldn't we respect the delete flag? 9431 cleanUpResourcesLI(); 9432 return true; 9433 } 9434 } 9435 9436 private boolean isAsecExternal(String cid) { 9437 final String asecPath = PackageHelper.getSdFilesystem(cid); 9438 return !asecPath.startsWith(mAsecInternalPath); 9439 } 9440 9441 /** 9442 * Extract the MountService "container ID" from the full code path of an 9443 * .apk. 9444 */ 9445 static String cidFromCodePath(String fullCodePath) { 9446 int eidx = fullCodePath.lastIndexOf("/"); 9447 String subStr1 = fullCodePath.substring(0, eidx); 9448 int sidx = subStr1.lastIndexOf("/"); 9449 return subStr1.substring(sidx+1, eidx); 9450 } 9451 9452 /** 9453 * Logic to handle installation of ASEC applications, including copying and 9454 * renaming logic. 9455 */ 9456 class AsecInstallArgs extends InstallArgs { 9457 // TODO: teach about handling cluster directories 9458 9459 static final String RES_FILE_NAME = "pkg.apk"; 9460 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 9461 9462 String cid; 9463 String packagePath; 9464 String resourcePath; 9465 String legacyNativeLibraryDir; 9466 9467 /** New install */ 9468 AsecInstallArgs(InstallParams params) { 9469 super(params.originFile, params.originStaged, params.observer, params.flags, 9470 params.installerPackageName, params.getManifestDigest(), 9471 params.getUser(), null /* instruction sets */, 9472 params.packageAbiOverride, params.multiArch); 9473 } 9474 9475 /** Existing install */ 9476 AsecInstallArgs(String fullCodePath, String[] instructionSets, 9477 boolean isExternal, boolean isForwardLocked, boolean isMultiArch) { 9478 super(null, false, null, (isExternal ? INSTALL_EXTERNAL : 0) 9479 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9480 instructionSets, null, isMultiArch); 9481 // Extract cid from fullCodePath 9482 int eidx = fullCodePath.lastIndexOf("/"); 9483 String subStr1 = fullCodePath.substring(0, eidx); 9484 int sidx = subStr1.lastIndexOf("/"); 9485 cid = subStr1.substring(sidx+1, eidx); 9486 setCachePath(subStr1); 9487 } 9488 9489 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked, 9490 boolean isMultiArch) { 9491 super(null, false, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 9492 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9493 instructionSets, null, isMultiArch); 9494 this.cid = cid; 9495 setCachePath(PackageHelper.getSdDir(cid)); 9496 } 9497 9498 /** New install from existing */ 9499 AsecInstallArgs(File originPackageFile, String cid, String[] instructionSets, 9500 boolean isExternal, boolean isForwardLocked, boolean isMultiArch) { 9501 super(originPackageFile, false, null, (isExternal ? INSTALL_EXTERNAL : 0) 9502 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9503 instructionSets, null, isMultiArch); 9504 this.cid = cid; 9505 } 9506 9507 void createCopyFile() { 9508 cid = getTempContainerId(); 9509 } 9510 9511 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9512 return imcs.checkExternalFreeStorage(originFile.getAbsolutePath(), isFwdLocked(), 9513 abiOverride); 9514 } 9515 9516 private final boolean isExternal() { 9517 return (flags & PackageManager.INSTALL_EXTERNAL) != 0; 9518 } 9519 9520 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9521 if (temp) { 9522 createCopyFile(); 9523 } else { 9524 /* 9525 * Pre-emptively destroy the container since it's destroyed if 9526 * copying fails due to it existing anyway. 9527 */ 9528 PackageHelper.destroySdDir(cid); 9529 } 9530 9531 final String newCachePath = imcs.copyPackageToContainer( 9532 originFile.getAbsolutePath(), cid, getEncryptKey(), isExternal(), 9533 isFwdLocked(), abiOverride); 9534 9535 if (newCachePath != null) { 9536 setCachePath(newCachePath); 9537 return PackageManager.INSTALL_SUCCEEDED; 9538 } else { 9539 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9540 } 9541 } 9542 9543 @Override 9544 String getCodePath() { 9545 return packagePath; 9546 } 9547 9548 @Override 9549 String getResourcePath() { 9550 return resourcePath; 9551 } 9552 9553 @Override 9554 String getLegacyNativeLibraryPath() { 9555 return legacyNativeLibraryDir; 9556 } 9557 9558 int doPreInstall(int status) { 9559 if (status != PackageManager.INSTALL_SUCCEEDED) { 9560 // Destroy container 9561 PackageHelper.destroySdDir(cid); 9562 } else { 9563 boolean mounted = PackageHelper.isContainerMounted(cid); 9564 if (!mounted) { 9565 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), 9566 Process.SYSTEM_UID); 9567 if (newCachePath != null) { 9568 setCachePath(newCachePath); 9569 } else { 9570 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9571 } 9572 } 9573 } 9574 return status; 9575 } 9576 9577 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9578 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 9579 String newCachePath = null; 9580 if (PackageHelper.isContainerMounted(cid)) { 9581 // Unmount the container 9582 if (!PackageHelper.unMountSdDir(cid)) { 9583 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9584 return false; 9585 } 9586 } 9587 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9588 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9589 " which might be stale. Will try to clean up."); 9590 // Clean up the stale container and proceed to recreate. 9591 if (!PackageHelper.destroySdDir(newCacheId)) { 9592 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9593 return false; 9594 } 9595 // Successfully cleaned up stale container. Try to rename again. 9596 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9597 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9598 + " inspite of cleaning it up."); 9599 return false; 9600 } 9601 } 9602 if (!PackageHelper.isContainerMounted(newCacheId)) { 9603 Slog.w(TAG, "Mounting container " + newCacheId); 9604 newCachePath = PackageHelper.mountSdDir(newCacheId, 9605 getEncryptKey(), Process.SYSTEM_UID); 9606 } else { 9607 newCachePath = PackageHelper.getSdDir(newCacheId); 9608 } 9609 if (newCachePath == null) { 9610 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9611 return false; 9612 } 9613 Log.i(TAG, "Succesfully renamed " + cid + 9614 " to " + newCacheId + 9615 " at new path: " + newCachePath); 9616 cid = newCacheId; 9617 setCachePath(newCachePath); 9618 9619 // TODO: extend to support split APKs 9620 pkg.codePath = getCodePath(); 9621 pkg.baseCodePath = getCodePath(); 9622 pkg.splitCodePaths = null; 9623 9624 pkg.applicationInfo.setCodePath(getCodePath()); 9625 pkg.applicationInfo.setBaseCodePath(getCodePath()); 9626 pkg.applicationInfo.setSplitCodePaths(null); 9627 pkg.applicationInfo.setResourcePath(getResourcePath()); 9628 pkg.applicationInfo.setBaseResourcePath(getResourcePath()); 9629 pkg.applicationInfo.setSplitResourcePaths(null); 9630 9631 return true; 9632 } 9633 9634 private void setCachePath(String newCachePath) { 9635 File cachePath = new File(newCachePath); 9636 legacyNativeLibraryDir = new File(cachePath, LIB_DIR_NAME).getPath(); 9637 packagePath = new File(cachePath, RES_FILE_NAME).getPath(); 9638 9639 if (isFwdLocked()) { 9640 resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath(); 9641 } else { 9642 resourcePath = packagePath; 9643 } 9644 } 9645 9646 int doPostInstall(int status, int uid) { 9647 if (status != PackageManager.INSTALL_SUCCEEDED) { 9648 cleanUp(); 9649 } else { 9650 final int groupOwner; 9651 final String protectedFile; 9652 if (isFwdLocked()) { 9653 groupOwner = UserHandle.getSharedAppGid(uid); 9654 protectedFile = RES_FILE_NAME; 9655 } else { 9656 groupOwner = -1; 9657 protectedFile = null; 9658 } 9659 9660 if (uid < Process.FIRST_APPLICATION_UID 9661 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9662 Slog.e(TAG, "Failed to finalize " + cid); 9663 PackageHelper.destroySdDir(cid); 9664 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9665 } 9666 9667 boolean mounted = PackageHelper.isContainerMounted(cid); 9668 if (!mounted) { 9669 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9670 } 9671 } 9672 return status; 9673 } 9674 9675 private void cleanUp() { 9676 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9677 9678 // Destroy secure container 9679 PackageHelper.destroySdDir(cid); 9680 } 9681 9682 void cleanUpResourcesLI() { 9683 String sourceFile = getCodePath(); 9684 // Remove dex file 9685 if (instructionSets == null) { 9686 throw new IllegalStateException("instructionSet == null"); 9687 } 9688 for (String instructionSet : instructionSets) { 9689 int retCode = mInstaller.rmdex(sourceFile, instructionSet); 9690 if (retCode < 0) { 9691 Slog.w(TAG, "Couldn't remove dex file for package: " 9692 + " at location " 9693 + sourceFile.toString() + ", retcode=" + retCode); 9694 // we don't consider this to be a failure of the core package deletion 9695 } 9696 } 9697 cleanUp(); 9698 } 9699 9700 boolean matchContainer(String app) { 9701 if (cid.startsWith(app)) { 9702 return true; 9703 } 9704 return false; 9705 } 9706 9707 String getPackageName() { 9708 return getAsecPackageName(cid); 9709 } 9710 9711 boolean doPostDeleteLI(boolean delete) { 9712 boolean ret = false; 9713 boolean mounted = PackageHelper.isContainerMounted(cid); 9714 if (mounted) { 9715 // Unmount first 9716 ret = PackageHelper.unMountSdDir(cid); 9717 } 9718 if (ret && delete) { 9719 cleanUpResourcesLI(); 9720 } 9721 return ret; 9722 } 9723 9724 @Override 9725 int doPreCopy() { 9726 if (isFwdLocked()) { 9727 if (!PackageHelper.fixSdPermissions(cid, 9728 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 9729 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9730 } 9731 } 9732 9733 return PackageManager.INSTALL_SUCCEEDED; 9734 } 9735 9736 @Override 9737 int doPostCopy(int uid) { 9738 if (isFwdLocked()) { 9739 if (uid < Process.FIRST_APPLICATION_UID 9740 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 9741 RES_FILE_NAME)) { 9742 Slog.e(TAG, "Failed to finalize " + cid); 9743 PackageHelper.destroySdDir(cid); 9744 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9745 } 9746 } 9747 9748 return PackageManager.INSTALL_SUCCEEDED; 9749 } 9750 } 9751 9752 static String getAsecPackageName(String packageCid) { 9753 int idx = packageCid.lastIndexOf("-"); 9754 if (idx == -1) { 9755 return packageCid; 9756 } 9757 return packageCid.substring(0, idx); 9758 } 9759 9760 // Utility method used to create code paths based on package name and available index. 9761 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 9762 String idxStr = ""; 9763 int idx = 1; 9764 // Fall back to default value of idx=1 if prefix is not 9765 // part of oldCodePath 9766 if (oldCodePath != null) { 9767 String subStr = oldCodePath; 9768 // Drop the suffix right away 9769 if (suffix != null && subStr.endsWith(suffix)) { 9770 subStr = subStr.substring(0, subStr.length() - suffix.length()); 9771 } 9772 // If oldCodePath already contains prefix find out the 9773 // ending index to either increment or decrement. 9774 int sidx = subStr.lastIndexOf(prefix); 9775 if (sidx != -1) { 9776 subStr = subStr.substring(sidx + prefix.length()); 9777 if (subStr != null) { 9778 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 9779 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 9780 } 9781 try { 9782 idx = Integer.parseInt(subStr); 9783 if (idx <= 1) { 9784 idx++; 9785 } else { 9786 idx--; 9787 } 9788 } catch(NumberFormatException e) { 9789 } 9790 } 9791 } 9792 } 9793 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 9794 return prefix + idxStr; 9795 } 9796 9797 // Utility method used to ignore ADD/REMOVE events 9798 // by directory observer. 9799 private static boolean ignoreCodePath(String fullPathStr) { 9800 String apkName = deriveCodePathName(fullPathStr); 9801 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 9802 if (idx != -1 && ((idx+1) < apkName.length())) { 9803 // Make sure the package ends with a numeral 9804 String version = apkName.substring(idx+1); 9805 try { 9806 Integer.parseInt(version); 9807 return true; 9808 } catch (NumberFormatException e) {} 9809 } 9810 return false; 9811 } 9812 9813 // Utility method that returns the relative package path with respect 9814 // to the installation directory. Like say for /data/data/com.test-1.apk 9815 // string com.test-1 is returned. 9816 static String deriveCodePathName(String codePath) { 9817 if (codePath == null) { 9818 return null; 9819 } 9820 final File codeFile = new File(codePath); 9821 final String name = codeFile.getName(); 9822 if (codeFile.isDirectory()) { 9823 return name; 9824 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 9825 final int lastDot = name.lastIndexOf('.'); 9826 return name.substring(0, lastDot); 9827 } else { 9828 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 9829 return null; 9830 } 9831 } 9832 9833 class PackageInstalledInfo { 9834 String name; 9835 int uid; 9836 // The set of users that originally had this package installed. 9837 int[] origUsers; 9838 // The set of users that now have this package installed. 9839 int[] newUsers; 9840 PackageParser.Package pkg; 9841 int returnCode; 9842 PackageRemovedInfo removedInfo; 9843 9844 // In some error cases we want to convey more info back to the observer 9845 String origPackage; 9846 String origPermission; 9847 } 9848 9849 /* 9850 * Install a non-existing package. 9851 */ 9852 private void installNewPackageLI(PackageParser.Package pkg, 9853 int parseFlags, int scanMode, UserHandle user, 9854 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9855 // Remember this for later, in case we need to rollback this install 9856 String pkgName = pkg.packageName; 9857 9858 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 9859 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 9860 synchronized(mPackages) { 9861 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 9862 // A package with the same name is already installed, though 9863 // it has been renamed to an older name. The package we 9864 // are trying to install should be installed as an update to 9865 // the existing one, but that has not been requested, so bail. 9866 Slog.w(TAG, "Attempt to re-install " + pkgName 9867 + " without first uninstalling package running as " 9868 + mSettings.mRenamedPackages.get(pkgName)); 9869 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9870 return; 9871 } 9872 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.codePath)) { 9873 // Don't allow installation over an existing package with the same name. 9874 Slog.w(TAG, "Attempt to re-install " + pkgName 9875 + " without first uninstalling."); 9876 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9877 return; 9878 } 9879 } 9880 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 9881 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode, 9882 System.currentTimeMillis(), user, abiOverride); 9883 if (newPackage == null) { 9884 Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath); 9885 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 9886 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 9887 } 9888 } else { 9889 updateSettingsLI(newPackage, installerPackageName, null, null, res); 9890 // delete the partially installed application. the data directory will have to be 9891 // restored if it was already existing 9892 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9893 // remove package from internal structures. Note that we want deletePackageX to 9894 // delete the package data and cache directories that it created in 9895 // scanPackageLocked, unless those directories existed before we even tried to 9896 // install. 9897 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 9898 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 9899 res.removedInfo, true); 9900 } 9901 } 9902 } 9903 9904 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 9905 // Upgrade keysets are being used. Determine if new package has a superset of the 9906 // required keys. 9907 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 9908 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9909 Set<Long> newSigningKeyIds = new ArraySet<Long>(); 9910 for (PublicKey pk : newPkg.mSigningKeys) { 9911 newSigningKeyIds.add(ksms.getIdForPublicKey(pk)); 9912 } 9913 //remove PUBLIC_KEY_NOT_FOUND, although not necessary 9914 newSigningKeyIds.remove(ksms.PUBLIC_KEY_NOT_FOUND); 9915 for (int i = 0; i < upgradeKeySets.length; i++) { 9916 if (newSigningKeyIds.containsAll(ksms.mKeySetMapping.get(upgradeKeySets[i]))) { 9917 return true; 9918 } 9919 } 9920 return false; 9921 } 9922 9923 private void replacePackageLI(PackageParser.Package pkg, 9924 int parseFlags, int scanMode, UserHandle user, 9925 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9926 PackageParser.Package oldPackage; 9927 String pkgName = pkg.packageName; 9928 int[] allUsers; 9929 boolean[] perUserInstalled; 9930 9931 // First find the old package info and check signatures 9932 synchronized(mPackages) { 9933 oldPackage = mPackages.get(pkgName); 9934 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 9935 PackageSetting ps = mSettings.mPackages.get(pkgName); 9936 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 9937 // default to original signature matching 9938 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 9939 != PackageManager.SIGNATURE_MATCH) { 9940 Slog.w(TAG, "New package has a different signature: " + pkgName); 9941 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 9942 return; 9943 } 9944 } else { 9945 if(!checkUpgradeKeySetLP(ps, pkg)) { 9946 Slog.w(TAG, "New package not signed by keys specified by upgrade-keysets: " 9947 + pkgName); 9948 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 9949 return; 9950 } 9951 } 9952 9953 // In case of rollback, remember per-user/profile install state 9954 allUsers = sUserManager.getUserIds(); 9955 perUserInstalled = new boolean[allUsers.length]; 9956 for (int i = 0; i < allUsers.length; i++) { 9957 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 9958 } 9959 } 9960 boolean sysPkg = (isSystemApp(oldPackage)); 9961 if (sysPkg) { 9962 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 9963 user, allUsers, perUserInstalled, installerPackageName, res, 9964 abiOverride); 9965 } else { 9966 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 9967 user, allUsers, perUserInstalled, installerPackageName, res, 9968 abiOverride); 9969 } 9970 } 9971 9972 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 9973 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 9974 int[] allUsers, boolean[] perUserInstalled, 9975 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9976 PackageParser.Package newPackage = null; 9977 String pkgName = deletedPackage.packageName; 9978 boolean deletedPkg = true; 9979 boolean updatedSettings = false; 9980 9981 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 9982 + deletedPackage); 9983 long origUpdateTime; 9984 if (pkg.mExtras != null) { 9985 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 9986 } else { 9987 origUpdateTime = 0; 9988 } 9989 9990 // First delete the existing package while retaining the data directory 9991 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 9992 res.removedInfo, true)) { 9993 // If the existing package wasn't successfully deleted 9994 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 9995 deletedPkg = false; 9996 } else { 9997 // Successfully deleted the old package. Now proceed with re-installation 9998 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 9999 newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME, 10000 System.currentTimeMillis(), user, abiOverride); 10001 if (newPackage == null) { 10002 Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath); 10003 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 10004 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 10005 } 10006 } else { 10007 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10008 updatedSettings = true; 10009 } 10010 } 10011 10012 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10013 // remove package from internal structures. Note that we want deletePackageX to 10014 // delete the package data and cache directories that it created in 10015 // scanPackageLocked, unless those directories existed before we even tried to 10016 // install. 10017 if(updatedSettings) { 10018 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 10019 deletePackageLI( 10020 pkgName, null, true, allUsers, perUserInstalled, 10021 PackageManager.DELETE_KEEP_DATA, 10022 res.removedInfo, true); 10023 } 10024 // Since we failed to install the new package we need to restore the old 10025 // package that we deleted. 10026 if (deletedPkg) { 10027 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 10028 File restoreFile = new File(deletedPackage.codePath); 10029 // Parse old package 10030 boolean oldOnSd = isExternal(deletedPackage); 10031 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 10032 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) | 10033 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 10034 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE 10035 | SCAN_UPDATE_TIME; 10036 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode, 10037 origUpdateTime, null, null) == null) { 10038 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade"); 10039 return; 10040 } 10041 // Restore of old package succeeded. Update permissions. 10042 // writer 10043 synchronized (mPackages) { 10044 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 10045 UPDATE_PERMISSIONS_ALL); 10046 // can downgrade to reader 10047 mSettings.writeLPr(); 10048 } 10049 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 10050 } 10051 } 10052 } 10053 10054 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 10055 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 10056 int[] allUsers, boolean[] perUserInstalled, 10057 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 10058 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 10059 + ", old=" + deletedPackage); 10060 PackageParser.Package newPackage = null; 10061 boolean updatedSettings = false; 10062 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING | 10063 PackageParser.PARSE_IS_SYSTEM; 10064 if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) { 10065 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10066 } 10067 String packageName = deletedPackage.packageName; 10068 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 10069 if (packageName == null) { 10070 Slog.w(TAG, "Attempt to delete null packageName."); 10071 return; 10072 } 10073 PackageParser.Package oldPkg; 10074 PackageSetting oldPkgSetting; 10075 // reader 10076 synchronized (mPackages) { 10077 oldPkg = mPackages.get(packageName); 10078 oldPkgSetting = mSettings.mPackages.get(packageName); 10079 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 10080 (oldPkgSetting == null)) { 10081 Slog.w(TAG, "Couldn't find package:"+packageName+" information"); 10082 return; 10083 } 10084 } 10085 10086 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 10087 10088 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10089 res.removedInfo.removedPackage = packageName; 10090 // Remove existing system package 10091 removePackageLI(oldPkgSetting, true); 10092 // writer 10093 synchronized (mPackages) { 10094 if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) { 10095 // We didn't need to disable the .apk as a current system package, 10096 // which means we are replacing another update that is already 10097 // installed. We need to make sure to delete the older one's .apk. 10098 res.removedInfo.args = createInstallArgsForExisting(0, 10099 deletedPackage.applicationInfo.getCodePath(), 10100 deletedPackage.applicationInfo.getResourcePath(), 10101 deletedPackage.applicationInfo.nativeLibraryRootDir, 10102 getAppDexInstructionSets(deletedPackage.applicationInfo), 10103 isMultiArch(deletedPackage.applicationInfo)); 10104 } else { 10105 res.removedInfo.args = null; 10106 } 10107 } 10108 10109 // Successfully disabled the old package. Now proceed with re-installation 10110 res.returnCode = mLastScanError = PackageManager.INSTALL_SUCCEEDED; 10111 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10112 newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user, abiOverride); 10113 if (newPackage == null) { 10114 Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath); 10115 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 10116 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 10117 } 10118 } else { 10119 if (newPackage.mExtras != null) { 10120 final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras; 10121 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10122 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10123 10124 // is the update attempting to change shared user? that isn't going to work... 10125 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10126 Slog.w(TAG, "Forbidding shared user change from " + oldPkgSetting.sharedUser 10127 + " to " + newPkgSetting.sharedUser); 10128 res.returnCode = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 10129 updatedSettings = true; 10130 } 10131 } 10132 10133 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10134 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10135 updatedSettings = true; 10136 } 10137 } 10138 10139 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10140 // Re installation failed. Restore old information 10141 // Remove new pkg information 10142 if (newPackage != null) { 10143 removeInstalledPackageLI(newPackage, true); 10144 } 10145 // Add back the old system package 10146 scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user, null); 10147 // Restore the old system information in Settings 10148 synchronized(mPackages) { 10149 if (updatedSettings) { 10150 mSettings.enableSystemPackageLPw(packageName); 10151 mSettings.setInstallerPackageName(packageName, 10152 oldPkgSetting.installerPackageName); 10153 } 10154 mSettings.writeLPr(); 10155 } 10156 } 10157 } 10158 10159 // Utility method used to move dex files during install. 10160 private int moveDexFilesLI(String oldCodePath, PackageParser.Package newPackage) { 10161 // TODO: extend to move split APK dex files 10162 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) { 10163 final String[] instructionSets = getAppDexInstructionSets(newPackage.applicationInfo); 10164 for (String instructionSet : instructionSets) { 10165 int retCode = mInstaller.movedex(oldCodePath, newPackage.baseCodePath, 10166 instructionSet); 10167 if (retCode != 0) { 10168 /* 10169 * Programs may be lazily run through dexopt, so the 10170 * source may not exist. However, something seems to 10171 * have gone wrong, so note that dexopt needs to be 10172 * run again and remove the source file. In addition, 10173 * remove the target to make sure there isn't a stale 10174 * file from a previous version of the package. 10175 */ 10176 newPackage.mDexOptNeeded = true; 10177 mInstaller.rmdex(oldCodePath, instructionSet); 10178 mInstaller.rmdex(newPackage.baseCodePath, instructionSet); 10179 } 10180 } 10181 } 10182 return PackageManager.INSTALL_SUCCEEDED; 10183 } 10184 10185 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10186 int[] allUsers, boolean[] perUserInstalled, 10187 PackageInstalledInfo res) { 10188 String pkgName = newPackage.packageName; 10189 synchronized (mPackages) { 10190 //write settings. the installStatus will be incomplete at this stage. 10191 //note that the new package setting would have already been 10192 //added to mPackages. It hasn't been persisted yet. 10193 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10194 mSettings.writeLPr(); 10195 } 10196 10197 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10198 10199 synchronized (mPackages) { 10200 updatePermissionsLPw(newPackage.packageName, newPackage, 10201 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10202 ? UPDATE_PERMISSIONS_ALL : 0)); 10203 // For system-bundled packages, we assume that installing an upgraded version 10204 // of the package implies that the user actually wants to run that new code, 10205 // so we enable the package. 10206 if (isSystemApp(newPackage)) { 10207 // NB: implicit assumption that system package upgrades apply to all users 10208 if (DEBUG_INSTALL) { 10209 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10210 } 10211 PackageSetting ps = mSettings.mPackages.get(pkgName); 10212 if (ps != null) { 10213 if (res.origUsers != null) { 10214 for (int userHandle : res.origUsers) { 10215 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10216 userHandle, installerPackageName); 10217 } 10218 } 10219 // Also convey the prior install/uninstall state 10220 if (allUsers != null && perUserInstalled != null) { 10221 for (int i = 0; i < allUsers.length; i++) { 10222 if (DEBUG_INSTALL) { 10223 Slog.d(TAG, " user " + allUsers[i] 10224 + " => " + perUserInstalled[i]); 10225 } 10226 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10227 } 10228 // these install state changes will be persisted in the 10229 // upcoming call to mSettings.writeLPr(). 10230 } 10231 } 10232 } 10233 res.name = pkgName; 10234 res.uid = newPackage.applicationInfo.uid; 10235 res.pkg = newPackage; 10236 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10237 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10238 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10239 //to update install status 10240 mSettings.writeLPr(); 10241 } 10242 } 10243 10244 private void installPackageLI(InstallArgs args, boolean newInstall, PackageInstalledInfo res) { 10245 int pFlags = args.flags; 10246 String installerPackageName = args.installerPackageName; 10247 File tmpPackageFile = new File(args.getCodePath()); 10248 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10249 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0); 10250 boolean replace = false; 10251 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE 10252 | (newInstall ? SCAN_NEW_INSTALL : 0); 10253 // Result object to be returned 10254 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10255 10256 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10257 // Retrieve PackageSettings and parse package 10258 int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10259 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10260 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 10261 PackageParser pp = new PackageParser(); 10262 pp.setSeparateProcesses(mSeparateProcesses); 10263 pp.setDisplayMetrics(mMetrics); 10264 10265 final PackageParser.Package pkg; 10266 try { 10267 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 10268 } catch (PackageParserException e) { 10269 Slog.e(TAG, "Failed during install: " + e); 10270 res.returnCode = e.error; 10271 return; 10272 } 10273 10274 String pkgName = res.name = pkg.packageName; 10275 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 10276 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) { 10277 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY; 10278 return; 10279 } 10280 } 10281 10282 try { 10283 pp.collectCertificates(pkg, parseFlags); 10284 pp.collectManifestDigest(pkg); 10285 } catch (PackageParserException e) { 10286 Slog.e(TAG, "Failed during install: " + e); 10287 res.returnCode = e.error; 10288 return; 10289 } 10290 10291 /* If the installer passed in a manifest digest, compare it now. */ 10292 if (args.manifestDigest != null) { 10293 if (DEBUG_INSTALL) { 10294 final String parsedManifest = pkg.manifestDigest == null ? "null" 10295 : pkg.manifestDigest.toString(); 10296 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 10297 + parsedManifest); 10298 } 10299 10300 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 10301 res.returnCode = PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 10302 return; 10303 } 10304 } else if (DEBUG_INSTALL) { 10305 final String parsedManifest = pkg.manifestDigest == null 10306 ? "null" : pkg.manifestDigest.toString(); 10307 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 10308 } 10309 10310 // Get rid of all references to package scan path via parser. 10311 pp = null; 10312 String oldCodePath = null; 10313 boolean systemApp = false; 10314 synchronized (mPackages) { 10315 // Check whether the newly-scanned package wants to define an already-defined perm 10316 int N = pkg.permissions.size(); 10317 for (int i = N-1; i >= 0; i--) { 10318 PackageParser.Permission perm = pkg.permissions.get(i); 10319 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 10320 if (bp != null) { 10321 // If the defining package is signed with our cert, it's okay. This 10322 // also includes the "updating the same package" case, of course. 10323 if (compareSignatures(bp.packageSetting.signatures.mSignatures, 10324 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 10325 // If the owning package is the system itself, we log but allow 10326 // install to proceed; we fail the install on all other permission 10327 // redefinitions. 10328 if (!bp.sourcePackage.equals("android")) { 10329 Slog.w(TAG, "Package " + pkg.packageName 10330 + " attempting to redeclare permission " + perm.info.name 10331 + " already owned by " + bp.sourcePackage); 10332 res.returnCode = PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 10333 res.origPermission = perm.info.name; 10334 res.origPackage = bp.sourcePackage; 10335 return; 10336 } else { 10337 Slog.w(TAG, "Package " + pkg.packageName 10338 + " attempting to redeclare system permission " 10339 + perm.info.name + "; ignoring new declaration"); 10340 pkg.permissions.remove(i); 10341 } 10342 } 10343 } 10344 } 10345 10346 // Check if installing already existing package 10347 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10348 String oldName = mSettings.mRenamedPackages.get(pkgName); 10349 if (pkg.mOriginalPackages != null 10350 && pkg.mOriginalPackages.contains(oldName) 10351 && mPackages.containsKey(oldName)) { 10352 // This package is derived from an original package, 10353 // and this device has been updating from that original 10354 // name. We must continue using the original name, so 10355 // rename the new package here. 10356 pkg.setPackageName(oldName); 10357 pkgName = pkg.packageName; 10358 replace = true; 10359 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 10360 + oldName + " pkgName=" + pkgName); 10361 } else if (mPackages.containsKey(pkgName)) { 10362 // This package, under its official name, already exists 10363 // on the device; we should replace it. 10364 replace = true; 10365 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 10366 } 10367 } 10368 PackageSetting ps = mSettings.mPackages.get(pkgName); 10369 if (ps != null) { 10370 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 10371 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 10372 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 10373 systemApp = (ps.pkg.applicationInfo.flags & 10374 ApplicationInfo.FLAG_SYSTEM) != 0; 10375 } 10376 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10377 } 10378 } 10379 10380 if (systemApp && onSd) { 10381 // Disable updates to system apps on sdcard 10382 Slog.w(TAG, "Cannot install updates to system apps on sdcard"); 10383 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 10384 return; 10385 } 10386 10387 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 10388 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 10389 return; 10390 } 10391 10392 if (replace) { 10393 replacePackageLI(pkg, parseFlags, scanMode, args.user, 10394 installerPackageName, res, args.abiOverride); 10395 } else { 10396 installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user, 10397 installerPackageName, res, args.abiOverride); 10398 } 10399 synchronized (mPackages) { 10400 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10401 if (ps != null) { 10402 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10403 } 10404 } 10405 } 10406 10407 private static boolean isForwardLocked(PackageParser.Package pkg) { 10408 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10409 } 10410 10411 private static boolean isForwardLocked(ApplicationInfo info) { 10412 return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10413 } 10414 10415 private boolean isForwardLocked(PackageSetting ps) { 10416 return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10417 } 10418 10419 private static boolean isMultiArch(PackageSetting ps) { 10420 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10421 } 10422 10423 private static boolean isMultiArch(ApplicationInfo info) { 10424 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10425 } 10426 10427 private static boolean isExternal(PackageParser.Package pkg) { 10428 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10429 } 10430 10431 private static boolean isExternal(PackageSetting ps) { 10432 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10433 } 10434 10435 private static boolean isExternal(ApplicationInfo info) { 10436 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10437 } 10438 10439 private static boolean isSystemApp(PackageParser.Package pkg) { 10440 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10441 } 10442 10443 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 10444 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0; 10445 } 10446 10447 private static boolean isSystemApp(ApplicationInfo info) { 10448 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10449 } 10450 10451 private static boolean isSystemApp(PackageSetting ps) { 10452 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 10453 } 10454 10455 private static boolean isUpdatedSystemApp(PackageSetting ps) { 10456 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10457 } 10458 10459 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 10460 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10461 } 10462 10463 private static boolean isUpdatedSystemApp(ApplicationInfo info) { 10464 return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10465 } 10466 10467 private int packageFlagsToInstallFlags(PackageSetting ps) { 10468 int installFlags = 0; 10469 if (isExternal(ps)) { 10470 installFlags |= PackageManager.INSTALL_EXTERNAL; 10471 } 10472 if (isForwardLocked(ps)) { 10473 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 10474 } 10475 return installFlags; 10476 } 10477 10478 private void deleteTempPackageFiles() { 10479 final FilenameFilter filter = new FilenameFilter() { 10480 public boolean accept(File dir, String name) { 10481 return name.startsWith("vmdl") && name.endsWith(".tmp"); 10482 } 10483 }; 10484 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 10485 file.delete(); 10486 } 10487 } 10488 10489 @Override 10490 public void deletePackageAsUser(final String packageName, 10491 final IPackageDeleteObserver observer, 10492 final int userId, final int flags) { 10493 mContext.enforceCallingOrSelfPermission( 10494 android.Manifest.permission.DELETE_PACKAGES, null); 10495 final int uid = Binder.getCallingUid(); 10496 if (UserHandle.getUserId(uid) != userId) { 10497 mContext.enforceCallingPermission( 10498 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 10499 "deletePackage for user " + userId); 10500 } 10501 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 10502 try { 10503 observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_USER_RESTRICTED); 10504 } catch (RemoteException re) { 10505 } 10506 return; 10507 } 10508 10509 boolean blocked = false; 10510 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 10511 int[] users = sUserManager.getUserIds(); 10512 for (int i = 0; i < users.length; ++i) { 10513 if (getBlockUninstallForUser(packageName, users[i])) { 10514 blocked = true; 10515 break; 10516 } 10517 } 10518 } else { 10519 blocked = getBlockUninstallForUser(packageName, userId); 10520 } 10521 if (blocked) { 10522 try { 10523 observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED); 10524 } catch (RemoteException re) { 10525 } 10526 return; 10527 } 10528 10529 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 10530 // Queue up an async operation since the package deletion may take a little while. 10531 mHandler.post(new Runnable() { 10532 public void run() { 10533 mHandler.removeCallbacks(this); 10534 final int returnCode = deletePackageX(packageName, userId, flags); 10535 if (observer != null) { 10536 try { 10537 observer.packageDeleted(packageName, returnCode); 10538 } catch (RemoteException e) { 10539 Log.i(TAG, "Observer no longer exists."); 10540 } //end catch 10541 } //end if 10542 } //end run 10543 }); 10544 } 10545 10546 private boolean isPackageDeviceAdmin(String packageName, int userId) { 10547 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 10548 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 10549 try { 10550 if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId) 10551 || dpm.isDeviceOwner(packageName))) { 10552 return true; 10553 } 10554 } catch (RemoteException e) { 10555 } 10556 return false; 10557 } 10558 10559 /** 10560 * This method is an internal method that could be get invoked either 10561 * to delete an installed package or to clean up a failed installation. 10562 * After deleting an installed package, a broadcast is sent to notify any 10563 * listeners that the package has been installed. For cleaning up a failed 10564 * installation, the broadcast is not necessary since the package's 10565 * installation wouldn't have sent the initial broadcast either 10566 * The key steps in deleting a package are 10567 * deleting the package information in internal structures like mPackages, 10568 * deleting the packages base directories through installd 10569 * updating mSettings to reflect current status 10570 * persisting settings for later use 10571 * sending a broadcast if necessary 10572 */ 10573 private int deletePackageX(String packageName, int userId, int flags) { 10574 final PackageRemovedInfo info = new PackageRemovedInfo(); 10575 final boolean res; 10576 10577 if (isPackageDeviceAdmin(packageName, userId)) { 10578 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 10579 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 10580 } 10581 10582 boolean removedForAllUsers = false; 10583 boolean systemUpdate = false; 10584 10585 // for the uninstall-updates case and restricted profiles, remember the per- 10586 // userhandle installed state 10587 int[] allUsers; 10588 boolean[] perUserInstalled; 10589 synchronized (mPackages) { 10590 PackageSetting ps = mSettings.mPackages.get(packageName); 10591 allUsers = sUserManager.getUserIds(); 10592 perUserInstalled = new boolean[allUsers.length]; 10593 for (int i = 0; i < allUsers.length; i++) { 10594 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10595 } 10596 } 10597 10598 synchronized (mInstallLock) { 10599 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 10600 res = deletePackageLI(packageName, 10601 (flags & PackageManager.DELETE_ALL_USERS) != 0 10602 ? UserHandle.ALL : new UserHandle(userId), 10603 true, allUsers, perUserInstalled, 10604 flags | REMOVE_CHATTY, info, true); 10605 systemUpdate = info.isRemovedPackageSystemUpdate; 10606 if (res && !systemUpdate && mPackages.get(packageName) == null) { 10607 removedForAllUsers = true; 10608 } 10609 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 10610 + " removedForAllUsers=" + removedForAllUsers); 10611 } 10612 10613 if (res) { 10614 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 10615 10616 // If the removed package was a system update, the old system package 10617 // was re-enabled; we need to broadcast this information 10618 if (systemUpdate) { 10619 Bundle extras = new Bundle(1); 10620 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 10621 ? info.removedAppId : info.uid); 10622 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10623 10624 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 10625 extras, null, null, null); 10626 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 10627 extras, null, null, null); 10628 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 10629 null, packageName, null, null); 10630 } 10631 } 10632 // Force a gc here. 10633 Runtime.getRuntime().gc(); 10634 // Delete the resources here after sending the broadcast to let 10635 // other processes clean up before deleting resources. 10636 if (info.args != null) { 10637 synchronized (mInstallLock) { 10638 info.args.doPostDeleteLI(true); 10639 } 10640 } 10641 10642 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10643 } 10644 10645 static class PackageRemovedInfo { 10646 String removedPackage; 10647 int uid = -1; 10648 int removedAppId = -1; 10649 int[] removedUsers = null; 10650 boolean isRemovedPackageSystemUpdate = false; 10651 // Clean up resources deleted packages. 10652 InstallArgs args = null; 10653 10654 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 10655 Bundle extras = new Bundle(1); 10656 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 10657 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 10658 if (replacing) { 10659 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10660 } 10661 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 10662 if (removedPackage != null) { 10663 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 10664 extras, null, null, removedUsers); 10665 if (fullRemove && !replacing) { 10666 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 10667 extras, null, null, removedUsers); 10668 } 10669 } 10670 if (removedAppId >= 0) { 10671 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 10672 removedUsers); 10673 } 10674 } 10675 } 10676 10677 /* 10678 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 10679 * flag is not set, the data directory is removed as well. 10680 * make sure this flag is set for partially installed apps. If not its meaningless to 10681 * delete a partially installed application. 10682 */ 10683 private void removePackageDataLI(PackageSetting ps, 10684 int[] allUserHandles, boolean[] perUserInstalled, 10685 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 10686 String packageName = ps.name; 10687 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 10688 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 10689 // Retrieve object to delete permissions for shared user later on 10690 final PackageSetting deletedPs; 10691 // reader 10692 synchronized (mPackages) { 10693 deletedPs = mSettings.mPackages.get(packageName); 10694 if (outInfo != null) { 10695 outInfo.removedPackage = packageName; 10696 outInfo.removedUsers = deletedPs != null 10697 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 10698 : null; 10699 } 10700 } 10701 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10702 removeDataDirsLI(packageName); 10703 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 10704 } 10705 // writer 10706 synchronized (mPackages) { 10707 if (deletedPs != null) { 10708 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10709 if (outInfo != null) { 10710 mSettings.mKeySetManagerService.removeAppKeySetData(packageName); 10711 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 10712 } 10713 if (deletedPs != null) { 10714 updatePermissionsLPw(deletedPs.name, null, 0); 10715 if (deletedPs.sharedUser != null) { 10716 // remove permissions associated with package 10717 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 10718 } 10719 } 10720 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 10721 } 10722 // make sure to preserve per-user disabled state if this removal was just 10723 // a downgrade of a system app to the factory package 10724 if (allUserHandles != null && perUserInstalled != null) { 10725 if (DEBUG_REMOVE) { 10726 Slog.d(TAG, "Propagating install state across downgrade"); 10727 } 10728 for (int i = 0; i < allUserHandles.length; i++) { 10729 if (DEBUG_REMOVE) { 10730 Slog.d(TAG, " user " + allUserHandles[i] 10731 + " => " + perUserInstalled[i]); 10732 } 10733 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10734 } 10735 } 10736 } 10737 // can downgrade to reader 10738 if (writeSettings) { 10739 // Save settings now 10740 mSettings.writeLPr(); 10741 } 10742 } 10743 if (outInfo != null) { 10744 // A user ID was deleted here. Go through all users and remove it 10745 // from KeyStore. 10746 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 10747 } 10748 } 10749 10750 static boolean locationIsPrivileged(File path) { 10751 try { 10752 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 10753 .getCanonicalPath(); 10754 return path.getCanonicalPath().startsWith(privilegedAppDir); 10755 } catch (IOException e) { 10756 Slog.e(TAG, "Unable to access code path " + path); 10757 } 10758 return false; 10759 } 10760 10761 /* 10762 * Tries to delete system package. 10763 */ 10764 private boolean deleteSystemPackageLI(PackageSetting newPs, 10765 int[] allUserHandles, boolean[] perUserInstalled, 10766 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 10767 final boolean applyUserRestrictions 10768 = (allUserHandles != null) && (perUserInstalled != null); 10769 PackageSetting disabledPs = null; 10770 // Confirm if the system package has been updated 10771 // An updated system app can be deleted. This will also have to restore 10772 // the system pkg from system partition 10773 // reader 10774 synchronized (mPackages) { 10775 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 10776 } 10777 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 10778 + " disabledPs=" + disabledPs); 10779 if (disabledPs == null) { 10780 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 10781 return false; 10782 } else if (DEBUG_REMOVE) { 10783 Slog.d(TAG, "Deleting system pkg from data partition"); 10784 } 10785 if (DEBUG_REMOVE) { 10786 if (applyUserRestrictions) { 10787 Slog.d(TAG, "Remembering install states:"); 10788 for (int i = 0; i < allUserHandles.length; i++) { 10789 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 10790 } 10791 } 10792 } 10793 // Delete the updated package 10794 outInfo.isRemovedPackageSystemUpdate = true; 10795 if (disabledPs.versionCode < newPs.versionCode) { 10796 // Delete data for downgrades 10797 flags &= ~PackageManager.DELETE_KEEP_DATA; 10798 } else { 10799 // Preserve data by setting flag 10800 flags |= PackageManager.DELETE_KEEP_DATA; 10801 } 10802 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 10803 allUserHandles, perUserInstalled, outInfo, writeSettings); 10804 if (!ret) { 10805 return false; 10806 } 10807 // writer 10808 synchronized (mPackages) { 10809 // Reinstate the old system package 10810 mSettings.enableSystemPackageLPw(newPs.name); 10811 // Remove any native libraries from the upgraded package. 10812 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 10813 } 10814 // Install the system package 10815 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 10816 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 10817 if (locationIsPrivileged(disabledPs.codePath)) { 10818 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10819 } 10820 PackageParser.Package newPkg = scanPackageLI(disabledPs.codePath, 10821 parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, null, null); 10822 10823 if (newPkg == null) { 10824 Slog.w(TAG, "Failed to restore system package:" + newPs.name 10825 + " with error:" + mLastScanError); 10826 return false; 10827 } 10828 // writer 10829 synchronized (mPackages) { 10830 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 10831 setBundledAppAbisAndRoots(newPkg, ps); 10832 updatePermissionsLPw(newPkg.packageName, newPkg, 10833 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 10834 if (applyUserRestrictions) { 10835 if (DEBUG_REMOVE) { 10836 Slog.d(TAG, "Propagating install state across reinstall"); 10837 } 10838 for (int i = 0; i < allUserHandles.length; i++) { 10839 if (DEBUG_REMOVE) { 10840 Slog.d(TAG, " user " + allUserHandles[i] 10841 + " => " + perUserInstalled[i]); 10842 } 10843 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10844 } 10845 // Regardless of writeSettings we need to ensure that this restriction 10846 // state propagation is persisted 10847 mSettings.writeAllUsersPackageRestrictionsLPr(); 10848 } 10849 // can downgrade to reader here 10850 if (writeSettings) { 10851 mSettings.writeLPr(); 10852 } 10853 } 10854 return true; 10855 } 10856 10857 private boolean deleteInstalledPackageLI(PackageSetting ps, 10858 boolean deleteCodeAndResources, int flags, 10859 int[] allUserHandles, boolean[] perUserInstalled, 10860 PackageRemovedInfo outInfo, boolean writeSettings) { 10861 if (outInfo != null) { 10862 outInfo.uid = ps.appId; 10863 } 10864 10865 // Delete package data from internal structures and also remove data if flag is set 10866 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 10867 10868 // Delete application code and resources 10869 if (deleteCodeAndResources && (outInfo != null)) { 10870 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 10871 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 10872 getAppDexInstructionSets(ps), isMultiArch(ps)); 10873 } 10874 return true; 10875 } 10876 10877 @Override 10878 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 10879 int userId) { 10880 mContext.enforceCallingOrSelfPermission( 10881 android.Manifest.permission.DELETE_PACKAGES, null); 10882 synchronized (mPackages) { 10883 PackageSetting ps = mSettings.mPackages.get(packageName); 10884 if (ps == null) { 10885 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 10886 return false; 10887 } 10888 if (!ps.getInstalled(userId)) { 10889 // Can't block uninstall for an app that is not installed or enabled. 10890 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 10891 return false; 10892 } 10893 ps.setBlockUninstall(blockUninstall, userId); 10894 mSettings.writePackageRestrictionsLPr(userId); 10895 } 10896 return true; 10897 } 10898 10899 @Override 10900 public boolean getBlockUninstallForUser(String packageName, int userId) { 10901 synchronized (mPackages) { 10902 PackageSetting ps = mSettings.mPackages.get(packageName); 10903 if (ps == null) { 10904 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 10905 return false; 10906 } 10907 return ps.getBlockUninstall(userId); 10908 } 10909 } 10910 10911 /* 10912 * This method handles package deletion in general 10913 */ 10914 private boolean deletePackageLI(String packageName, UserHandle user, 10915 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 10916 int flags, PackageRemovedInfo outInfo, 10917 boolean writeSettings) { 10918 if (packageName == null) { 10919 Slog.w(TAG, "Attempt to delete null packageName."); 10920 return false; 10921 } 10922 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 10923 PackageSetting ps; 10924 boolean dataOnly = false; 10925 int removeUser = -1; 10926 int appId = -1; 10927 synchronized (mPackages) { 10928 ps = mSettings.mPackages.get(packageName); 10929 if (ps == null) { 10930 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 10931 return false; 10932 } 10933 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 10934 && user.getIdentifier() != UserHandle.USER_ALL) { 10935 // The caller is asking that the package only be deleted for a single 10936 // user. To do this, we just mark its uninstalled state and delete 10937 // its data. If this is a system app, we only allow this to happen if 10938 // they have set the special DELETE_SYSTEM_APP which requests different 10939 // semantics than normal for uninstalling system apps. 10940 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 10941 ps.setUserState(user.getIdentifier(), 10942 COMPONENT_ENABLED_STATE_DEFAULT, 10943 false, //installed 10944 true, //stopped 10945 true, //notLaunched 10946 false, //blocked 10947 null, null, null, 10948 false // blockUninstall 10949 ); 10950 if (!isSystemApp(ps)) { 10951 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 10952 // Other user still have this package installed, so all 10953 // we need to do is clear this user's data and save that 10954 // it is uninstalled. 10955 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 10956 removeUser = user.getIdentifier(); 10957 appId = ps.appId; 10958 mSettings.writePackageRestrictionsLPr(removeUser); 10959 } else { 10960 // We need to set it back to 'installed' so the uninstall 10961 // broadcasts will be sent correctly. 10962 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 10963 ps.setInstalled(true, user.getIdentifier()); 10964 } 10965 } else { 10966 // This is a system app, so we assume that the 10967 // other users still have this package installed, so all 10968 // we need to do is clear this user's data and save that 10969 // it is uninstalled. 10970 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 10971 removeUser = user.getIdentifier(); 10972 appId = ps.appId; 10973 mSettings.writePackageRestrictionsLPr(removeUser); 10974 } 10975 } 10976 } 10977 10978 if (removeUser >= 0) { 10979 // From above, we determined that we are deleting this only 10980 // for a single user. Continue the work here. 10981 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 10982 if (outInfo != null) { 10983 outInfo.removedPackage = packageName; 10984 outInfo.removedAppId = appId; 10985 outInfo.removedUsers = new int[] {removeUser}; 10986 } 10987 mInstaller.clearUserData(packageName, removeUser); 10988 removeKeystoreDataIfNeeded(removeUser, appId); 10989 schedulePackageCleaning(packageName, removeUser, false); 10990 return true; 10991 } 10992 10993 if (dataOnly) { 10994 // Delete application data first 10995 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 10996 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 10997 return true; 10998 } 10999 11000 boolean ret = false; 11001 if (isSystemApp(ps)) { 11002 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 11003 // When an updated system application is deleted we delete the existing resources as well and 11004 // fall back to existing code in system partition 11005 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 11006 flags, outInfo, writeSettings); 11007 } else { 11008 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 11009 // Kill application pre-emptively especially for apps on sd. 11010 killApplication(packageName, ps.appId, "uninstall pkg"); 11011 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 11012 allUserHandles, perUserInstalled, 11013 outInfo, writeSettings); 11014 } 11015 11016 return ret; 11017 } 11018 11019 private final class ClearStorageConnection implements ServiceConnection { 11020 IMediaContainerService mContainerService; 11021 11022 @Override 11023 public void onServiceConnected(ComponentName name, IBinder service) { 11024 synchronized (this) { 11025 mContainerService = IMediaContainerService.Stub.asInterface(service); 11026 notifyAll(); 11027 } 11028 } 11029 11030 @Override 11031 public void onServiceDisconnected(ComponentName name) { 11032 } 11033 } 11034 11035 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 11036 final boolean mounted; 11037 if (Environment.isExternalStorageEmulated()) { 11038 mounted = true; 11039 } else { 11040 final String status = Environment.getExternalStorageState(); 11041 11042 mounted = status.equals(Environment.MEDIA_MOUNTED) 11043 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 11044 } 11045 11046 if (!mounted) { 11047 return; 11048 } 11049 11050 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 11051 int[] users; 11052 if (userId == UserHandle.USER_ALL) { 11053 users = sUserManager.getUserIds(); 11054 } else { 11055 users = new int[] { userId }; 11056 } 11057 final ClearStorageConnection conn = new ClearStorageConnection(); 11058 if (mContext.bindServiceAsUser( 11059 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 11060 try { 11061 for (int curUser : users) { 11062 long timeout = SystemClock.uptimeMillis() + 5000; 11063 synchronized (conn) { 11064 long now = SystemClock.uptimeMillis(); 11065 while (conn.mContainerService == null && now < timeout) { 11066 try { 11067 conn.wait(timeout - now); 11068 } catch (InterruptedException e) { 11069 } 11070 } 11071 } 11072 if (conn.mContainerService == null) { 11073 return; 11074 } 11075 11076 final UserEnvironment userEnv = new UserEnvironment(curUser); 11077 clearDirectory(conn.mContainerService, 11078 userEnv.buildExternalStorageAppCacheDirs(packageName)); 11079 if (allData) { 11080 clearDirectory(conn.mContainerService, 11081 userEnv.buildExternalStorageAppDataDirs(packageName)); 11082 clearDirectory(conn.mContainerService, 11083 userEnv.buildExternalStorageAppMediaDirs(packageName)); 11084 } 11085 } 11086 } finally { 11087 mContext.unbindService(conn); 11088 } 11089 } 11090 } 11091 11092 @Override 11093 public void clearApplicationUserData(final String packageName, 11094 final IPackageDataObserver observer, final int userId) { 11095 mContext.enforceCallingOrSelfPermission( 11096 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 11097 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data"); 11098 // Queue up an async operation since the package deletion may take a little while. 11099 mHandler.post(new Runnable() { 11100 public void run() { 11101 mHandler.removeCallbacks(this); 11102 final boolean succeeded; 11103 synchronized (mInstallLock) { 11104 succeeded = clearApplicationUserDataLI(packageName, userId); 11105 } 11106 clearExternalStorageDataSync(packageName, userId, true); 11107 if (succeeded) { 11108 // invoke DeviceStorageMonitor's update method to clear any notifications 11109 DeviceStorageMonitorInternal 11110 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 11111 if (dsm != null) { 11112 dsm.checkMemory(); 11113 } 11114 } 11115 if(observer != null) { 11116 try { 11117 observer.onRemoveCompleted(packageName, succeeded); 11118 } catch (RemoteException e) { 11119 Log.i(TAG, "Observer no longer exists."); 11120 } 11121 } //end if observer 11122 } //end run 11123 }); 11124 } 11125 11126 private boolean clearApplicationUserDataLI(String packageName, int userId) { 11127 if (packageName == null) { 11128 Slog.w(TAG, "Attempt to delete null packageName."); 11129 return false; 11130 } 11131 PackageParser.Package p; 11132 boolean dataOnly = false; 11133 final int appId; 11134 synchronized (mPackages) { 11135 p = mPackages.get(packageName); 11136 if (p == null) { 11137 dataOnly = true; 11138 PackageSetting ps = mSettings.mPackages.get(packageName); 11139 if ((ps == null) || (ps.pkg == null)) { 11140 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11141 return false; 11142 } 11143 p = ps.pkg; 11144 } 11145 if (!dataOnly) { 11146 // need to check this only for fully installed applications 11147 if (p == null) { 11148 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11149 return false; 11150 } 11151 final ApplicationInfo applicationInfo = p.applicationInfo; 11152 if (applicationInfo == null) { 11153 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11154 return false; 11155 } 11156 } 11157 if (p != null && p.applicationInfo != null) { 11158 appId = p.applicationInfo.uid; 11159 } else { 11160 appId = -1; 11161 } 11162 } 11163 int retCode = mInstaller.clearUserData(packageName, userId); 11164 if (retCode < 0) { 11165 Slog.w(TAG, "Couldn't remove cache files for package: " 11166 + packageName); 11167 return false; 11168 } 11169 removeKeystoreDataIfNeeded(userId, appId); 11170 return true; 11171 } 11172 11173 /** 11174 * Remove entries from the keystore daemon. Will only remove it if the 11175 * {@code appId} is valid. 11176 */ 11177 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 11178 if (appId < 0) { 11179 return; 11180 } 11181 11182 final KeyStore keyStore = KeyStore.getInstance(); 11183 if (keyStore != null) { 11184 if (userId == UserHandle.USER_ALL) { 11185 for (final int individual : sUserManager.getUserIds()) { 11186 keyStore.clearUid(UserHandle.getUid(individual, appId)); 11187 } 11188 } else { 11189 keyStore.clearUid(UserHandle.getUid(userId, appId)); 11190 } 11191 } else { 11192 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 11193 } 11194 } 11195 11196 @Override 11197 public void deleteApplicationCacheFiles(final String packageName, 11198 final IPackageDataObserver observer) { 11199 mContext.enforceCallingOrSelfPermission( 11200 android.Manifest.permission.DELETE_CACHE_FILES, null); 11201 // Queue up an async operation since the package deletion may take a little while. 11202 final int userId = UserHandle.getCallingUserId(); 11203 mHandler.post(new Runnable() { 11204 public void run() { 11205 mHandler.removeCallbacks(this); 11206 final boolean succeded; 11207 synchronized (mInstallLock) { 11208 succeded = deleteApplicationCacheFilesLI(packageName, userId); 11209 } 11210 clearExternalStorageDataSync(packageName, userId, false); 11211 if(observer != null) { 11212 try { 11213 observer.onRemoveCompleted(packageName, succeded); 11214 } catch (RemoteException e) { 11215 Log.i(TAG, "Observer no longer exists."); 11216 } 11217 } //end if observer 11218 } //end run 11219 }); 11220 } 11221 11222 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 11223 if (packageName == null) { 11224 Slog.w(TAG, "Attempt to delete null packageName."); 11225 return false; 11226 } 11227 PackageParser.Package p; 11228 synchronized (mPackages) { 11229 p = mPackages.get(packageName); 11230 } 11231 if (p == null) { 11232 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11233 return false; 11234 } 11235 final ApplicationInfo applicationInfo = p.applicationInfo; 11236 if (applicationInfo == null) { 11237 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11238 return false; 11239 } 11240 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 11241 if (retCode < 0) { 11242 Slog.w(TAG, "Couldn't remove cache files for package: " 11243 + packageName + " u" + userId); 11244 return false; 11245 } 11246 return true; 11247 } 11248 11249 @Override 11250 public void getPackageSizeInfo(final String packageName, int userHandle, 11251 final IPackageStatsObserver observer) { 11252 mContext.enforceCallingOrSelfPermission( 11253 android.Manifest.permission.GET_PACKAGE_SIZE, null); 11254 if (packageName == null) { 11255 throw new IllegalArgumentException("Attempt to get size of null packageName"); 11256 } 11257 11258 PackageStats stats = new PackageStats(packageName, userHandle); 11259 11260 /* 11261 * Queue up an async operation since the package measurement may take a 11262 * little while. 11263 */ 11264 Message msg = mHandler.obtainMessage(INIT_COPY); 11265 msg.obj = new MeasureParams(stats, observer); 11266 mHandler.sendMessage(msg); 11267 } 11268 11269 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 11270 PackageStats pStats) { 11271 if (packageName == null) { 11272 Slog.w(TAG, "Attempt to get size of null packageName."); 11273 return false; 11274 } 11275 PackageParser.Package p; 11276 boolean dataOnly = false; 11277 String libDirRoot = null; 11278 String asecPath = null; 11279 PackageSetting ps = null; 11280 synchronized (mPackages) { 11281 p = mPackages.get(packageName); 11282 ps = mSettings.mPackages.get(packageName); 11283 if(p == null) { 11284 dataOnly = true; 11285 if((ps == null) || (ps.pkg == null)) { 11286 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11287 return false; 11288 } 11289 p = ps.pkg; 11290 } 11291 if (ps != null) { 11292 libDirRoot = ps.legacyNativeLibraryPathString; 11293 } 11294 if (p != null && (isExternal(p) || isForwardLocked(p))) { 11295 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 11296 if (secureContainerId != null) { 11297 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 11298 } 11299 } 11300 } 11301 String publicSrcDir = null; 11302 if(!dataOnly) { 11303 final ApplicationInfo applicationInfo = p.applicationInfo; 11304 if (applicationInfo == null) { 11305 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11306 return false; 11307 } 11308 if (isForwardLocked(p)) { 11309 publicSrcDir = applicationInfo.getBaseResourcePath(); 11310 } 11311 } 11312 // TODO: extend to measure size of split APKs 11313 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 11314 // not just the first level. 11315 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 11316 // just the primary. 11317 int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot, 11318 publicSrcDir, asecPath, getAppDexInstructionSets(ps), 11319 pStats); 11320 if (res < 0) { 11321 return false; 11322 } 11323 11324 // Fix-up for forward-locked applications in ASEC containers. 11325 if (!isExternal(p)) { 11326 pStats.codeSize += pStats.externalCodeSize; 11327 pStats.externalCodeSize = 0L; 11328 } 11329 11330 return true; 11331 } 11332 11333 11334 @Override 11335 public void addPackageToPreferred(String packageName) { 11336 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 11337 } 11338 11339 @Override 11340 public void removePackageFromPreferred(String packageName) { 11341 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 11342 } 11343 11344 @Override 11345 public List<PackageInfo> getPreferredPackages(int flags) { 11346 return new ArrayList<PackageInfo>(); 11347 } 11348 11349 private int getUidTargetSdkVersionLockedLPr(int uid) { 11350 Object obj = mSettings.getUserIdLPr(uid); 11351 if (obj instanceof SharedUserSetting) { 11352 final SharedUserSetting sus = (SharedUserSetting) obj; 11353 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 11354 final Iterator<PackageSetting> it = sus.packages.iterator(); 11355 while (it.hasNext()) { 11356 final PackageSetting ps = it.next(); 11357 if (ps.pkg != null) { 11358 int v = ps.pkg.applicationInfo.targetSdkVersion; 11359 if (v < vers) vers = v; 11360 } 11361 } 11362 return vers; 11363 } else if (obj instanceof PackageSetting) { 11364 final PackageSetting ps = (PackageSetting) obj; 11365 if (ps.pkg != null) { 11366 return ps.pkg.applicationInfo.targetSdkVersion; 11367 } 11368 } 11369 return Build.VERSION_CODES.CUR_DEVELOPMENT; 11370 } 11371 11372 @Override 11373 public void addPreferredActivity(IntentFilter filter, int match, 11374 ComponentName[] set, ComponentName activity, int userId) { 11375 addPreferredActivityInternal(filter, match, set, activity, true, userId); 11376 } 11377 11378 private void addPreferredActivityInternal(IntentFilter filter, int match, 11379 ComponentName[] set, ComponentName activity, boolean always, int userId) { 11380 // writer 11381 int callingUid = Binder.getCallingUid(); 11382 enforceCrossUserPermission(callingUid, userId, true, "add preferred activity"); 11383 if (filter.countActions() == 0) { 11384 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11385 return; 11386 } 11387 synchronized (mPackages) { 11388 if (mContext.checkCallingOrSelfPermission( 11389 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11390 != PackageManager.PERMISSION_GRANTED) { 11391 if (getUidTargetSdkVersionLockedLPr(callingUid) 11392 < Build.VERSION_CODES.FROYO) { 11393 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 11394 + callingUid); 11395 return; 11396 } 11397 mContext.enforceCallingOrSelfPermission( 11398 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11399 } 11400 11401 Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :"); 11402 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11403 mSettings.editPreferredActivitiesLPw(userId).addFilter( 11404 new PreferredActivity(filter, match, set, activity, always)); 11405 mSettings.writePackageRestrictionsLPr(userId); 11406 } 11407 } 11408 11409 @Override 11410 public void replacePreferredActivity(IntentFilter filter, int match, 11411 ComponentName[] set, ComponentName activity) { 11412 if (filter.countActions() != 1) { 11413 throw new IllegalArgumentException( 11414 "replacePreferredActivity expects filter to have only 1 action."); 11415 } 11416 if (filter.countDataAuthorities() != 0 11417 || filter.countDataPaths() != 0 11418 || filter.countDataSchemes() > 1 11419 || filter.countDataTypes() != 0) { 11420 throw new IllegalArgumentException( 11421 "replacePreferredActivity expects filter to have no data authorities, " + 11422 "paths, or types; and at most one scheme."); 11423 } 11424 synchronized (mPackages) { 11425 if (mContext.checkCallingOrSelfPermission( 11426 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11427 != PackageManager.PERMISSION_GRANTED) { 11428 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11429 < Build.VERSION_CODES.FROYO) { 11430 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 11431 + Binder.getCallingUid()); 11432 return; 11433 } 11434 mContext.enforceCallingOrSelfPermission( 11435 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11436 } 11437 11438 final int callingUserId = UserHandle.getCallingUserId(); 11439 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId); 11440 if (pir != null) { 11441 Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0)); 11442 if (filter.countDataSchemes() == 1) { 11443 Uri.Builder builder = new Uri.Builder(); 11444 builder.scheme(filter.getDataScheme(0)); 11445 intent.setData(builder.build()); 11446 } 11447 List<PreferredActivity> matches = pir.queryIntent( 11448 intent, null, true, callingUserId); 11449 if (DEBUG_PREFERRED) { 11450 Slog.i(TAG, matches.size() + " preferred matches for " + intent); 11451 } 11452 for (int i = 0; i < matches.size(); i++) { 11453 PreferredActivity pa = matches.get(i); 11454 if (DEBUG_PREFERRED) { 11455 Slog.i(TAG, "Removing preferred activity " 11456 + pa.mPref.mComponent + ":"); 11457 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11458 } 11459 pir.removeFilter(pa); 11460 } 11461 } 11462 addPreferredActivityInternal(filter, match, set, activity, true, callingUserId); 11463 } 11464 } 11465 11466 @Override 11467 public void clearPackagePreferredActivities(String packageName) { 11468 final int uid = Binder.getCallingUid(); 11469 // writer 11470 synchronized (mPackages) { 11471 PackageParser.Package pkg = mPackages.get(packageName); 11472 if (pkg == null || pkg.applicationInfo.uid != uid) { 11473 if (mContext.checkCallingOrSelfPermission( 11474 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11475 != PackageManager.PERMISSION_GRANTED) { 11476 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11477 < Build.VERSION_CODES.FROYO) { 11478 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 11479 + Binder.getCallingUid()); 11480 return; 11481 } 11482 mContext.enforceCallingOrSelfPermission( 11483 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11484 } 11485 } 11486 11487 int user = UserHandle.getCallingUserId(); 11488 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 11489 mSettings.writePackageRestrictionsLPr(user); 11490 scheduleWriteSettingsLocked(); 11491 } 11492 } 11493 } 11494 11495 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 11496 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 11497 ArrayList<PreferredActivity> removed = null; 11498 boolean changed = false; 11499 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11500 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 11501 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11502 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 11503 continue; 11504 } 11505 Iterator<PreferredActivity> it = pir.filterIterator(); 11506 while (it.hasNext()) { 11507 PreferredActivity pa = it.next(); 11508 // Mark entry for removal only if it matches the package name 11509 // and the entry is of type "always". 11510 if (packageName == null || 11511 (pa.mPref.mComponent.getPackageName().equals(packageName) 11512 && pa.mPref.mAlways)) { 11513 if (removed == null) { 11514 removed = new ArrayList<PreferredActivity>(); 11515 } 11516 removed.add(pa); 11517 } 11518 } 11519 if (removed != null) { 11520 for (int j=0; j<removed.size(); j++) { 11521 PreferredActivity pa = removed.get(j); 11522 pir.removeFilter(pa); 11523 } 11524 changed = true; 11525 } 11526 } 11527 return changed; 11528 } 11529 11530 @Override 11531 public void resetPreferredActivities(int userId) { 11532 mContext.enforceCallingOrSelfPermission( 11533 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11534 // writer 11535 synchronized (mPackages) { 11536 int user = UserHandle.getCallingUserId(); 11537 clearPackagePreferredActivitiesLPw(null, user); 11538 mSettings.readDefaultPreferredAppsLPw(this, user); 11539 mSettings.writePackageRestrictionsLPr(user); 11540 scheduleWriteSettingsLocked(); 11541 } 11542 } 11543 11544 @Override 11545 public int getPreferredActivities(List<IntentFilter> outFilters, 11546 List<ComponentName> outActivities, String packageName) { 11547 11548 int num = 0; 11549 final int userId = UserHandle.getCallingUserId(); 11550 // reader 11551 synchronized (mPackages) { 11552 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11553 if (pir != null) { 11554 final Iterator<PreferredActivity> it = pir.filterIterator(); 11555 while (it.hasNext()) { 11556 final PreferredActivity pa = it.next(); 11557 if (packageName == null 11558 || (pa.mPref.mComponent.getPackageName().equals(packageName) 11559 && pa.mPref.mAlways)) { 11560 if (outFilters != null) { 11561 outFilters.add(new IntentFilter(pa)); 11562 } 11563 if (outActivities != null) { 11564 outActivities.add(pa.mPref.mComponent); 11565 } 11566 } 11567 } 11568 } 11569 } 11570 11571 return num; 11572 } 11573 11574 @Override 11575 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 11576 int userId) { 11577 int callingUid = Binder.getCallingUid(); 11578 if (callingUid != Process.SYSTEM_UID) { 11579 throw new SecurityException( 11580 "addPersistentPreferredActivity can only be run by the system"); 11581 } 11582 if (filter.countActions() == 0) { 11583 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11584 return; 11585 } 11586 synchronized (mPackages) { 11587 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 11588 " :"); 11589 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11590 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 11591 new PersistentPreferredActivity(filter, activity)); 11592 mSettings.writePackageRestrictionsLPr(userId); 11593 } 11594 } 11595 11596 @Override 11597 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 11598 int callingUid = Binder.getCallingUid(); 11599 if (callingUid != Process.SYSTEM_UID) { 11600 throw new SecurityException( 11601 "clearPackagePersistentPreferredActivities can only be run by the system"); 11602 } 11603 ArrayList<PersistentPreferredActivity> removed = null; 11604 boolean changed = false; 11605 synchronized (mPackages) { 11606 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 11607 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 11608 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 11609 .valueAt(i); 11610 if (userId != thisUserId) { 11611 continue; 11612 } 11613 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 11614 while (it.hasNext()) { 11615 PersistentPreferredActivity ppa = it.next(); 11616 // Mark entry for removal only if it matches the package name. 11617 if (ppa.mComponent.getPackageName().equals(packageName)) { 11618 if (removed == null) { 11619 removed = new ArrayList<PersistentPreferredActivity>(); 11620 } 11621 removed.add(ppa); 11622 } 11623 } 11624 if (removed != null) { 11625 for (int j=0; j<removed.size(); j++) { 11626 PersistentPreferredActivity ppa = removed.get(j); 11627 ppir.removeFilter(ppa); 11628 } 11629 changed = true; 11630 } 11631 } 11632 11633 if (changed) { 11634 mSettings.writePackageRestrictionsLPr(userId); 11635 } 11636 } 11637 } 11638 11639 @Override 11640 public void addCrossProfileIntentFilter(IntentFilter intentFilter, int sourceUserId, 11641 int targetUserId, int flags) { 11642 mContext.enforceCallingOrSelfPermission( 11643 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11644 if (intentFilter.countActions() == 0) { 11645 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 11646 return; 11647 } 11648 synchronized (mPackages) { 11649 CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter, 11650 targetUserId, flags); 11651 mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter); 11652 mSettings.writePackageRestrictionsLPr(sourceUserId); 11653 } 11654 } 11655 11656 public void addCrossProfileIntentsForPackage(String packageName, 11657 int sourceUserId, int targetUserId) { 11658 mContext.enforceCallingOrSelfPermission( 11659 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11660 mSettings.addCrossProfilePackage(packageName, sourceUserId, targetUserId); 11661 mSettings.writePackageRestrictionsLPr(sourceUserId); 11662 } 11663 11664 public void removeCrossProfileIntentsForPackage(String packageName, 11665 int sourceUserId, int targetUserId) { 11666 mContext.enforceCallingOrSelfPermission( 11667 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11668 mSettings.removeCrossProfilePackage(packageName, sourceUserId, targetUserId); 11669 mSettings.writePackageRestrictionsLPr(sourceUserId); 11670 } 11671 11672 @Override 11673 public void clearCrossProfileIntentFilters(int sourceUserId) { 11674 mContext.enforceCallingOrSelfPermission( 11675 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11676 synchronized (mPackages) { 11677 CrossProfileIntentResolver resolver = 11678 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11679 HashSet<CrossProfileIntentFilter> set = 11680 new HashSet<CrossProfileIntentFilter>(resolver.filterSet()); 11681 for (CrossProfileIntentFilter filter : set) { 11682 if ((filter.getFlags() & PackageManager.SET_BY_PROFILE_OWNER) != 0) { 11683 resolver.removeFilter(filter); 11684 } 11685 } 11686 mSettings.writePackageRestrictionsLPr(sourceUserId); 11687 } 11688 } 11689 11690 @Override 11691 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 11692 Intent intent = new Intent(Intent.ACTION_MAIN); 11693 intent.addCategory(Intent.CATEGORY_HOME); 11694 11695 final int callingUserId = UserHandle.getCallingUserId(); 11696 List<ResolveInfo> list = queryIntentActivities(intent, null, 11697 PackageManager.GET_META_DATA, callingUserId); 11698 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 11699 true, false, false, callingUserId); 11700 11701 allHomeCandidates.clear(); 11702 if (list != null) { 11703 for (ResolveInfo ri : list) { 11704 allHomeCandidates.add(ri); 11705 } 11706 } 11707 return (preferred == null || preferred.activityInfo == null) 11708 ? null 11709 : new ComponentName(preferred.activityInfo.packageName, 11710 preferred.activityInfo.name); 11711 } 11712 11713 @Override 11714 public void setApplicationEnabledSetting(String appPackageName, 11715 int newState, int flags, int userId, String callingPackage) { 11716 if (!sUserManager.exists(userId)) return; 11717 if (callingPackage == null) { 11718 callingPackage = Integer.toString(Binder.getCallingUid()); 11719 } 11720 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 11721 } 11722 11723 @Override 11724 public void setComponentEnabledSetting(ComponentName componentName, 11725 int newState, int flags, int userId) { 11726 if (!sUserManager.exists(userId)) return; 11727 setEnabledSetting(componentName.getPackageName(), 11728 componentName.getClassName(), newState, flags, userId, null); 11729 } 11730 11731 private void setEnabledSetting(final String packageName, String className, int newState, 11732 final int flags, int userId, String callingPackage) { 11733 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 11734 || newState == COMPONENT_ENABLED_STATE_ENABLED 11735 || newState == COMPONENT_ENABLED_STATE_DISABLED 11736 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 11737 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 11738 throw new IllegalArgumentException("Invalid new component state: " 11739 + newState); 11740 } 11741 PackageSetting pkgSetting; 11742 final int uid = Binder.getCallingUid(); 11743 final int permission = mContext.checkCallingOrSelfPermission( 11744 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11745 enforceCrossUserPermission(uid, userId, false, "set enabled"); 11746 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11747 boolean sendNow = false; 11748 boolean isApp = (className == null); 11749 String componentName = isApp ? packageName : className; 11750 int packageUid = -1; 11751 ArrayList<String> components; 11752 11753 // writer 11754 synchronized (mPackages) { 11755 pkgSetting = mSettings.mPackages.get(packageName); 11756 if (pkgSetting == null) { 11757 if (className == null) { 11758 throw new IllegalArgumentException( 11759 "Unknown package: " + packageName); 11760 } 11761 throw new IllegalArgumentException( 11762 "Unknown component: " + packageName 11763 + "/" + className); 11764 } 11765 // Allow root and verify that userId is not being specified by a different user 11766 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 11767 throw new SecurityException( 11768 "Permission Denial: attempt to change component state from pid=" 11769 + Binder.getCallingPid() 11770 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 11771 } 11772 if (className == null) { 11773 // We're dealing with an application/package level state change 11774 if (pkgSetting.getEnabled(userId) == newState) { 11775 // Nothing to do 11776 return; 11777 } 11778 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 11779 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 11780 // Don't care about who enables an app. 11781 callingPackage = null; 11782 } 11783 pkgSetting.setEnabled(newState, userId, callingPackage); 11784 // pkgSetting.pkg.mSetEnabled = newState; 11785 } else { 11786 // We're dealing with a component level state change 11787 // First, verify that this is a valid class name. 11788 PackageParser.Package pkg = pkgSetting.pkg; 11789 if (pkg == null || !pkg.hasComponentClassName(className)) { 11790 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 11791 throw new IllegalArgumentException("Component class " + className 11792 + " does not exist in " + packageName); 11793 } else { 11794 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 11795 + className + " does not exist in " + packageName); 11796 } 11797 } 11798 switch (newState) { 11799 case COMPONENT_ENABLED_STATE_ENABLED: 11800 if (!pkgSetting.enableComponentLPw(className, userId)) { 11801 return; 11802 } 11803 break; 11804 case COMPONENT_ENABLED_STATE_DISABLED: 11805 if (!pkgSetting.disableComponentLPw(className, userId)) { 11806 return; 11807 } 11808 break; 11809 case COMPONENT_ENABLED_STATE_DEFAULT: 11810 if (!pkgSetting.restoreComponentLPw(className, userId)) { 11811 return; 11812 } 11813 break; 11814 default: 11815 Slog.e(TAG, "Invalid new component state: " + newState); 11816 return; 11817 } 11818 } 11819 mSettings.writePackageRestrictionsLPr(userId); 11820 components = mPendingBroadcasts.get(userId, packageName); 11821 final boolean newPackage = components == null; 11822 if (newPackage) { 11823 components = new ArrayList<String>(); 11824 } 11825 if (!components.contains(componentName)) { 11826 components.add(componentName); 11827 } 11828 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 11829 sendNow = true; 11830 // Purge entry from pending broadcast list if another one exists already 11831 // since we are sending one right away. 11832 mPendingBroadcasts.remove(userId, packageName); 11833 } else { 11834 if (newPackage) { 11835 mPendingBroadcasts.put(userId, packageName, components); 11836 } 11837 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 11838 // Schedule a message 11839 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 11840 } 11841 } 11842 } 11843 11844 long callingId = Binder.clearCallingIdentity(); 11845 try { 11846 if (sendNow) { 11847 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 11848 sendPackageChangedBroadcast(packageName, 11849 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 11850 } 11851 } finally { 11852 Binder.restoreCallingIdentity(callingId); 11853 } 11854 } 11855 11856 private void sendPackageChangedBroadcast(String packageName, 11857 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 11858 if (DEBUG_INSTALL) 11859 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 11860 + componentNames); 11861 Bundle extras = new Bundle(4); 11862 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 11863 String nameList[] = new String[componentNames.size()]; 11864 componentNames.toArray(nameList); 11865 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 11866 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 11867 extras.putInt(Intent.EXTRA_UID, packageUid); 11868 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 11869 new int[] {UserHandle.getUserId(packageUid)}); 11870 } 11871 11872 @Override 11873 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 11874 if (!sUserManager.exists(userId)) return; 11875 final int uid = Binder.getCallingUid(); 11876 final int permission = mContext.checkCallingOrSelfPermission( 11877 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11878 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11879 enforceCrossUserPermission(uid, userId, true, "stop package"); 11880 // writer 11881 synchronized (mPackages) { 11882 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 11883 uid, userId)) { 11884 scheduleWritePackageRestrictionsLocked(userId); 11885 } 11886 } 11887 } 11888 11889 @Override 11890 public String getInstallerPackageName(String packageName) { 11891 // reader 11892 synchronized (mPackages) { 11893 return mSettings.getInstallerPackageNameLPr(packageName); 11894 } 11895 } 11896 11897 @Override 11898 public int getApplicationEnabledSetting(String packageName, int userId) { 11899 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11900 int uid = Binder.getCallingUid(); 11901 enforceCrossUserPermission(uid, userId, false, "get enabled"); 11902 // reader 11903 synchronized (mPackages) { 11904 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 11905 } 11906 } 11907 11908 @Override 11909 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 11910 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11911 int uid = Binder.getCallingUid(); 11912 enforceCrossUserPermission(uid, userId, false, "get component enabled"); 11913 // reader 11914 synchronized (mPackages) { 11915 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 11916 } 11917 } 11918 11919 @Override 11920 public void enterSafeMode() { 11921 enforceSystemOrRoot("Only the system can request entering safe mode"); 11922 11923 if (!mSystemReady) { 11924 mSafeMode = true; 11925 } 11926 } 11927 11928 @Override 11929 public void systemReady() { 11930 mSystemReady = true; 11931 11932 // Read the compatibilty setting when the system is ready. 11933 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 11934 mContext.getContentResolver(), 11935 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 11936 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 11937 if (DEBUG_SETTINGS) { 11938 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 11939 } 11940 11941 synchronized (mPackages) { 11942 // Verify that all of the preferred activity components actually 11943 // exist. It is possible for applications to be updated and at 11944 // that point remove a previously declared activity component that 11945 // had been set as a preferred activity. We try to clean this up 11946 // the next time we encounter that preferred activity, but it is 11947 // possible for the user flow to never be able to return to that 11948 // situation so here we do a sanity check to make sure we haven't 11949 // left any junk around. 11950 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 11951 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11952 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11953 removed.clear(); 11954 for (PreferredActivity pa : pir.filterSet()) { 11955 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 11956 removed.add(pa); 11957 } 11958 } 11959 if (removed.size() > 0) { 11960 for (int r=0; r<removed.size(); r++) { 11961 PreferredActivity pa = removed.get(r); 11962 Slog.w(TAG, "Removing dangling preferred activity: " 11963 + pa.mPref.mComponent); 11964 pir.removeFilter(pa); 11965 } 11966 mSettings.writePackageRestrictionsLPr( 11967 mSettings.mPreferredActivities.keyAt(i)); 11968 } 11969 } 11970 } 11971 sUserManager.systemReady(); 11972 } 11973 11974 @Override 11975 public boolean isSafeMode() { 11976 return mSafeMode; 11977 } 11978 11979 @Override 11980 public boolean hasSystemUidErrors() { 11981 return mHasSystemUidErrors; 11982 } 11983 11984 static String arrayToString(int[] array) { 11985 StringBuffer buf = new StringBuffer(128); 11986 buf.append('['); 11987 if (array != null) { 11988 for (int i=0; i<array.length; i++) { 11989 if (i > 0) buf.append(", "); 11990 buf.append(array[i]); 11991 } 11992 } 11993 buf.append(']'); 11994 return buf.toString(); 11995 } 11996 11997 static class DumpState { 11998 public static final int DUMP_LIBS = 1 << 0; 11999 12000 public static final int DUMP_FEATURES = 1 << 1; 12001 12002 public static final int DUMP_RESOLVERS = 1 << 2; 12003 12004 public static final int DUMP_PERMISSIONS = 1 << 3; 12005 12006 public static final int DUMP_PACKAGES = 1 << 4; 12007 12008 public static final int DUMP_SHARED_USERS = 1 << 5; 12009 12010 public static final int DUMP_MESSAGES = 1 << 6; 12011 12012 public static final int DUMP_PROVIDERS = 1 << 7; 12013 12014 public static final int DUMP_VERIFIERS = 1 << 8; 12015 12016 public static final int DUMP_PREFERRED = 1 << 9; 12017 12018 public static final int DUMP_PREFERRED_XML = 1 << 10; 12019 12020 public static final int DUMP_KEYSETS = 1 << 11; 12021 12022 public static final int DUMP_VERSION = 1 << 12; 12023 12024 public static final int OPTION_SHOW_FILTERS = 1 << 0; 12025 12026 private int mTypes; 12027 12028 private int mOptions; 12029 12030 private boolean mTitlePrinted; 12031 12032 private SharedUserSetting mSharedUser; 12033 12034 public boolean isDumping(int type) { 12035 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 12036 return true; 12037 } 12038 12039 return (mTypes & type) != 0; 12040 } 12041 12042 public void setDump(int type) { 12043 mTypes |= type; 12044 } 12045 12046 public boolean isOptionEnabled(int option) { 12047 return (mOptions & option) != 0; 12048 } 12049 12050 public void setOptionEnabled(int option) { 12051 mOptions |= option; 12052 } 12053 12054 public boolean onTitlePrinted() { 12055 final boolean printed = mTitlePrinted; 12056 mTitlePrinted = true; 12057 return printed; 12058 } 12059 12060 public boolean getTitlePrinted() { 12061 return mTitlePrinted; 12062 } 12063 12064 public void setTitlePrinted(boolean enabled) { 12065 mTitlePrinted = enabled; 12066 } 12067 12068 public SharedUserSetting getSharedUser() { 12069 return mSharedUser; 12070 } 12071 12072 public void setSharedUser(SharedUserSetting user) { 12073 mSharedUser = user; 12074 } 12075 } 12076 12077 @Override 12078 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 12079 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 12080 != PackageManager.PERMISSION_GRANTED) { 12081 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 12082 + Binder.getCallingPid() 12083 + ", uid=" + Binder.getCallingUid() 12084 + " without permission " 12085 + android.Manifest.permission.DUMP); 12086 return; 12087 } 12088 12089 DumpState dumpState = new DumpState(); 12090 boolean fullPreferred = false; 12091 boolean checkin = false; 12092 12093 String packageName = null; 12094 12095 int opti = 0; 12096 while (opti < args.length) { 12097 String opt = args[opti]; 12098 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 12099 break; 12100 } 12101 opti++; 12102 if ("-a".equals(opt)) { 12103 // Right now we only know how to print all. 12104 } else if ("-h".equals(opt)) { 12105 pw.println("Package manager dump options:"); 12106 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 12107 pw.println(" --checkin: dump for a checkin"); 12108 pw.println(" -f: print details of intent filters"); 12109 pw.println(" -h: print this help"); 12110 pw.println(" cmd may be one of:"); 12111 pw.println(" l[ibraries]: list known shared libraries"); 12112 pw.println(" f[ibraries]: list device features"); 12113 pw.println(" k[eysets]: print known keysets"); 12114 pw.println(" r[esolvers]: dump intent resolvers"); 12115 pw.println(" perm[issions]: dump permissions"); 12116 pw.println(" pref[erred]: print preferred package settings"); 12117 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 12118 pw.println(" prov[iders]: dump content providers"); 12119 pw.println(" p[ackages]: dump installed packages"); 12120 pw.println(" s[hared-users]: dump shared user IDs"); 12121 pw.println(" m[essages]: print collected runtime messages"); 12122 pw.println(" v[erifiers]: print package verifier info"); 12123 pw.println(" version: print database version info"); 12124 pw.println(" write: write current settings now"); 12125 pw.println(" <package.name>: info about given package"); 12126 return; 12127 } else if ("--checkin".equals(opt)) { 12128 checkin = true; 12129 } else if ("-f".equals(opt)) { 12130 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12131 } else { 12132 pw.println("Unknown argument: " + opt + "; use -h for help"); 12133 } 12134 } 12135 12136 // Is the caller requesting to dump a particular piece of data? 12137 if (opti < args.length) { 12138 String cmd = args[opti]; 12139 opti++; 12140 // Is this a package name? 12141 if ("android".equals(cmd) || cmd.contains(".")) { 12142 packageName = cmd; 12143 // When dumping a single package, we always dump all of its 12144 // filter information since the amount of data will be reasonable. 12145 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12146 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 12147 dumpState.setDump(DumpState.DUMP_LIBS); 12148 } else if ("f".equals(cmd) || "features".equals(cmd)) { 12149 dumpState.setDump(DumpState.DUMP_FEATURES); 12150 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 12151 dumpState.setDump(DumpState.DUMP_RESOLVERS); 12152 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 12153 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 12154 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 12155 dumpState.setDump(DumpState.DUMP_PREFERRED); 12156 } else if ("preferred-xml".equals(cmd)) { 12157 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 12158 if (opti < args.length && "--full".equals(args[opti])) { 12159 fullPreferred = true; 12160 opti++; 12161 } 12162 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 12163 dumpState.setDump(DumpState.DUMP_PACKAGES); 12164 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 12165 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 12166 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 12167 dumpState.setDump(DumpState.DUMP_PROVIDERS); 12168 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 12169 dumpState.setDump(DumpState.DUMP_MESSAGES); 12170 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 12171 dumpState.setDump(DumpState.DUMP_VERIFIERS); 12172 } else if ("version".equals(cmd)) { 12173 dumpState.setDump(DumpState.DUMP_VERSION); 12174 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 12175 dumpState.setDump(DumpState.DUMP_KEYSETS); 12176 } else if ("write".equals(cmd)) { 12177 synchronized (mPackages) { 12178 mSettings.writeLPr(); 12179 pw.println("Settings written."); 12180 return; 12181 } 12182 } 12183 } 12184 12185 if (checkin) { 12186 pw.println("vers,1"); 12187 } 12188 12189 // reader 12190 synchronized (mPackages) { 12191 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 12192 if (!checkin) { 12193 if (dumpState.onTitlePrinted()) 12194 pw.println(); 12195 pw.println("Database versions:"); 12196 pw.print(" SDK Version:"); 12197 pw.print(" internal="); 12198 pw.print(mSettings.mInternalSdkPlatform); 12199 pw.print(" external="); 12200 pw.println(mSettings.mExternalSdkPlatform); 12201 pw.print(" DB Version:"); 12202 pw.print(" internal="); 12203 pw.print(mSettings.mInternalDatabaseVersion); 12204 pw.print(" external="); 12205 pw.println(mSettings.mExternalDatabaseVersion); 12206 } 12207 } 12208 12209 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 12210 if (!checkin) { 12211 if (dumpState.onTitlePrinted()) 12212 pw.println(); 12213 pw.println("Verifiers:"); 12214 pw.print(" Required: "); 12215 pw.print(mRequiredVerifierPackage); 12216 pw.print(" (uid="); 12217 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 12218 pw.println(")"); 12219 } else if (mRequiredVerifierPackage != null) { 12220 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 12221 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 12222 } 12223 } 12224 12225 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 12226 boolean printedHeader = false; 12227 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 12228 while (it.hasNext()) { 12229 String name = it.next(); 12230 SharedLibraryEntry ent = mSharedLibraries.get(name); 12231 if (!checkin) { 12232 if (!printedHeader) { 12233 if (dumpState.onTitlePrinted()) 12234 pw.println(); 12235 pw.println("Libraries:"); 12236 printedHeader = true; 12237 } 12238 pw.print(" "); 12239 } else { 12240 pw.print("lib,"); 12241 } 12242 pw.print(name); 12243 if (!checkin) { 12244 pw.print(" -> "); 12245 } 12246 if (ent.path != null) { 12247 if (!checkin) { 12248 pw.print("(jar) "); 12249 pw.print(ent.path); 12250 } else { 12251 pw.print(",jar,"); 12252 pw.print(ent.path); 12253 } 12254 } else { 12255 if (!checkin) { 12256 pw.print("(apk) "); 12257 pw.print(ent.apk); 12258 } else { 12259 pw.print(",apk,"); 12260 pw.print(ent.apk); 12261 } 12262 } 12263 pw.println(); 12264 } 12265 } 12266 12267 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 12268 if (dumpState.onTitlePrinted()) 12269 pw.println(); 12270 if (!checkin) { 12271 pw.println("Features:"); 12272 } 12273 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 12274 while (it.hasNext()) { 12275 String name = it.next(); 12276 if (!checkin) { 12277 pw.print(" "); 12278 } else { 12279 pw.print("feat,"); 12280 } 12281 pw.println(name); 12282 } 12283 } 12284 12285 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 12286 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 12287 : "Activity Resolver Table:", " ", packageName, 12288 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12289 dumpState.setTitlePrinted(true); 12290 } 12291 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 12292 : "Receiver Resolver Table:", " ", packageName, 12293 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12294 dumpState.setTitlePrinted(true); 12295 } 12296 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 12297 : "Service Resolver Table:", " ", packageName, 12298 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12299 dumpState.setTitlePrinted(true); 12300 } 12301 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 12302 : "Provider Resolver Table:", " ", packageName, 12303 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12304 dumpState.setTitlePrinted(true); 12305 } 12306 } 12307 12308 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 12309 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12310 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12311 int user = mSettings.mPreferredActivities.keyAt(i); 12312 if (pir.dump(pw, 12313 dumpState.getTitlePrinted() 12314 ? "\nPreferred Activities User " + user + ":" 12315 : "Preferred Activities User " + user + ":", " ", 12316 packageName, true)) { 12317 dumpState.setTitlePrinted(true); 12318 } 12319 } 12320 } 12321 12322 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 12323 pw.flush(); 12324 FileOutputStream fout = new FileOutputStream(fd); 12325 BufferedOutputStream str = new BufferedOutputStream(fout); 12326 XmlSerializer serializer = new FastXmlSerializer(); 12327 try { 12328 serializer.setOutput(str, "utf-8"); 12329 serializer.startDocument(null, true); 12330 serializer.setFeature( 12331 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 12332 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 12333 serializer.endDocument(); 12334 serializer.flush(); 12335 } catch (IllegalArgumentException e) { 12336 pw.println("Failed writing: " + e); 12337 } catch (IllegalStateException e) { 12338 pw.println("Failed writing: " + e); 12339 } catch (IOException e) { 12340 pw.println("Failed writing: " + e); 12341 } 12342 } 12343 12344 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 12345 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 12346 } 12347 12348 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 12349 boolean printedSomething = false; 12350 for (PackageParser.Provider p : mProviders.mProviders.values()) { 12351 if (packageName != null && !packageName.equals(p.info.packageName)) { 12352 continue; 12353 } 12354 if (!printedSomething) { 12355 if (dumpState.onTitlePrinted()) 12356 pw.println(); 12357 pw.println("Registered ContentProviders:"); 12358 printedSomething = true; 12359 } 12360 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 12361 pw.print(" "); pw.println(p.toString()); 12362 } 12363 printedSomething = false; 12364 for (Map.Entry<String, PackageParser.Provider> entry : 12365 mProvidersByAuthority.entrySet()) { 12366 PackageParser.Provider p = entry.getValue(); 12367 if (packageName != null && !packageName.equals(p.info.packageName)) { 12368 continue; 12369 } 12370 if (!printedSomething) { 12371 if (dumpState.onTitlePrinted()) 12372 pw.println(); 12373 pw.println("ContentProvider Authorities:"); 12374 printedSomething = true; 12375 } 12376 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 12377 pw.print(" "); pw.println(p.toString()); 12378 if (p.info != null && p.info.applicationInfo != null) { 12379 final String appInfo = p.info.applicationInfo.toString(); 12380 pw.print(" applicationInfo="); pw.println(appInfo); 12381 } 12382 } 12383 } 12384 12385 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 12386 mSettings.mKeySetManagerService.dump(pw, packageName, dumpState); 12387 } 12388 12389 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 12390 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 12391 } 12392 12393 if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 12394 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState); 12395 } 12396 12397 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 12398 if (dumpState.onTitlePrinted()) 12399 pw.println(); 12400 mSettings.dumpReadMessagesLPr(pw, dumpState); 12401 12402 pw.println(); 12403 pw.println("Package warning messages:"); 12404 final File fname = getSettingsProblemFile(); 12405 FileInputStream in = null; 12406 try { 12407 in = new FileInputStream(fname); 12408 final int avail = in.available(); 12409 final byte[] data = new byte[avail]; 12410 in.read(data); 12411 pw.print(new String(data)); 12412 } catch (FileNotFoundException e) { 12413 } catch (IOException e) { 12414 } finally { 12415 if (in != null) { 12416 try { 12417 in.close(); 12418 } catch (IOException e) { 12419 } 12420 } 12421 } 12422 } 12423 } 12424 } 12425 12426 // ------- apps on sdcard specific code ------- 12427 static final boolean DEBUG_SD_INSTALL = false; 12428 12429 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 12430 12431 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 12432 12433 private boolean mMediaMounted = false; 12434 12435 private String getEncryptKey() { 12436 try { 12437 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 12438 SD_ENCRYPTION_KEYSTORE_NAME); 12439 if (sdEncKey == null) { 12440 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 12441 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 12442 if (sdEncKey == null) { 12443 Slog.e(TAG, "Failed to create encryption keys"); 12444 return null; 12445 } 12446 } 12447 return sdEncKey; 12448 } catch (NoSuchAlgorithmException nsae) { 12449 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 12450 return null; 12451 } catch (IOException ioe) { 12452 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 12453 return null; 12454 } 12455 12456 } 12457 12458 /* package */static String getTempContainerId() { 12459 int tmpIdx = 1; 12460 String list[] = PackageHelper.getSecureContainerList(); 12461 if (list != null) { 12462 for (final String name : list) { 12463 // Ignore null and non-temporary container entries 12464 if (name == null || !name.startsWith(mTempContainerPrefix)) { 12465 continue; 12466 } 12467 12468 String subStr = name.substring(mTempContainerPrefix.length()); 12469 try { 12470 int cid = Integer.parseInt(subStr); 12471 if (cid >= tmpIdx) { 12472 tmpIdx = cid + 1; 12473 } 12474 } catch (NumberFormatException e) { 12475 } 12476 } 12477 } 12478 return mTempContainerPrefix + tmpIdx; 12479 } 12480 12481 /* 12482 * Update media status on PackageManager. 12483 */ 12484 @Override 12485 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 12486 int callingUid = Binder.getCallingUid(); 12487 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 12488 throw new SecurityException("Media status can only be updated by the system"); 12489 } 12490 // reader; this apparently protects mMediaMounted, but should probably 12491 // be a different lock in that case. 12492 synchronized (mPackages) { 12493 Log.i(TAG, "Updating external media status from " 12494 + (mMediaMounted ? "mounted" : "unmounted") + " to " 12495 + (mediaStatus ? "mounted" : "unmounted")); 12496 if (DEBUG_SD_INSTALL) 12497 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 12498 + ", mMediaMounted=" + mMediaMounted); 12499 if (mediaStatus == mMediaMounted) { 12500 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 12501 : 0, -1); 12502 mHandler.sendMessage(msg); 12503 return; 12504 } 12505 mMediaMounted = mediaStatus; 12506 } 12507 // Queue up an async operation since the package installation may take a 12508 // little while. 12509 mHandler.post(new Runnable() { 12510 public void run() { 12511 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 12512 } 12513 }); 12514 } 12515 12516 /** 12517 * Called by MountService when the initial ASECs to scan are available. 12518 * Should block until all the ASEC containers are finished being scanned. 12519 */ 12520 public void scanAvailableAsecs() { 12521 updateExternalMediaStatusInner(true, false, false); 12522 if (mShouldRestoreconData) { 12523 SELinuxMMAC.setRestoreconDone(); 12524 mShouldRestoreconData = false; 12525 } 12526 } 12527 12528 /* 12529 * Collect information of applications on external media, map them against 12530 * existing containers and update information based on current mount status. 12531 * Please note that we always have to report status if reportStatus has been 12532 * set to true especially when unloading packages. 12533 */ 12534 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 12535 boolean externalStorage) { 12536 // Collection of uids 12537 int uidArr[] = null; 12538 // Collection of stale containers 12539 HashSet<String> removeCids = new HashSet<String>(); 12540 // Collection of packages on external media with valid containers. 12541 HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>(); 12542 // Get list of secure containers. 12543 final String list[] = PackageHelper.getSecureContainerList(); 12544 if (list == null || list.length == 0) { 12545 Log.i(TAG, "No secure containers on sdcard"); 12546 } else { 12547 // Process list of secure containers and categorize them 12548 // as active or stale based on their package internal state. 12549 int uidList[] = new int[list.length]; 12550 int num = 0; 12551 // reader 12552 synchronized (mPackages) { 12553 for (String cid : list) { 12554 if (DEBUG_SD_INSTALL) 12555 Log.i(TAG, "Processing container " + cid); 12556 String pkgName = getAsecPackageName(cid); 12557 if (pkgName == null) { 12558 if (DEBUG_SD_INSTALL) 12559 Log.i(TAG, "Container : " + cid + " stale"); 12560 removeCids.add(cid); 12561 continue; 12562 } 12563 if (DEBUG_SD_INSTALL) 12564 Log.i(TAG, "Looking for pkg : " + pkgName); 12565 12566 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12567 if (ps == null) { 12568 Log.i(TAG, "Deleting container with no matching settings " + cid); 12569 removeCids.add(cid); 12570 continue; 12571 } 12572 12573 /* 12574 * Skip packages that are not external if we're unmounting 12575 * external storage. 12576 */ 12577 if (externalStorage && !isMounted && !isExternal(ps)) { 12578 continue; 12579 } 12580 12581 final AsecInstallArgs args = new AsecInstallArgs(cid, 12582 getAppDexInstructionSets(ps), isForwardLocked(ps), isMultiArch(ps)); 12583 // The package status is changed only if the code path 12584 // matches between settings and the container id. 12585 if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) { 12586 if (DEBUG_SD_INSTALL) { 12587 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 12588 + " at code path: " + ps.codePathString); 12589 } 12590 12591 // We do have a valid package installed on sdcard 12592 processCids.put(args, ps.codePathString); 12593 final int uid = ps.appId; 12594 if (uid != -1) { 12595 uidList[num++] = uid; 12596 } 12597 } else { 12598 Log.i(TAG, "Deleting stale container for " + cid); 12599 removeCids.add(cid); 12600 } 12601 } 12602 } 12603 12604 if (num > 0) { 12605 // Sort uid list 12606 Arrays.sort(uidList, 0, num); 12607 // Throw away duplicates 12608 uidArr = new int[num]; 12609 uidArr[0] = uidList[0]; 12610 int di = 0; 12611 for (int i = 1; i < num; i++) { 12612 if (uidList[i - 1] != uidList[i]) { 12613 uidArr[di++] = uidList[i]; 12614 } 12615 } 12616 } 12617 } 12618 // Process packages with valid entries. 12619 if (isMounted) { 12620 if (DEBUG_SD_INSTALL) 12621 Log.i(TAG, "Loading packages"); 12622 loadMediaPackages(processCids, uidArr, removeCids); 12623 startCleaningPackages(); 12624 } else { 12625 if (DEBUG_SD_INSTALL) 12626 Log.i(TAG, "Unloading packages"); 12627 unloadMediaPackages(processCids, uidArr, reportStatus); 12628 } 12629 } 12630 12631 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 12632 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 12633 int size = pkgList.size(); 12634 if (size > 0) { 12635 // Send broadcasts here 12636 Bundle extras = new Bundle(); 12637 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 12638 .toArray(new String[size])); 12639 if (uidArr != null) { 12640 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 12641 } 12642 if (replacing) { 12643 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 12644 } 12645 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 12646 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 12647 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 12648 } 12649 } 12650 12651 /* 12652 * Look at potentially valid container ids from processCids If package 12653 * information doesn't match the one on record or package scanning fails, 12654 * the cid is added to list of removeCids. We currently don't delete stale 12655 * containers. 12656 */ 12657 private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 12658 HashSet<String> removeCids) { 12659 ArrayList<String> pkgList = new ArrayList<String>(); 12660 Set<AsecInstallArgs> keys = processCids.keySet(); 12661 boolean doGc = false; 12662 for (AsecInstallArgs args : keys) { 12663 String codePath = processCids.get(args); 12664 if (DEBUG_SD_INSTALL) 12665 Log.i(TAG, "Loading container : " + args.cid); 12666 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12667 try { 12668 // Make sure there are no container errors first. 12669 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 12670 Slog.e(TAG, "Failed to mount cid : " + args.cid 12671 + " when installing from sdcard"); 12672 continue; 12673 } 12674 // Check code path here. 12675 if (codePath == null || !codePath.equals(args.getCodePath())) { 12676 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 12677 + " does not match one in settings " + codePath); 12678 continue; 12679 } 12680 // Parse package 12681 int parseFlags = mDefParseFlags; 12682 if (args.isExternal()) { 12683 parseFlags |= PackageParser.PARSE_ON_SDCARD; 12684 } 12685 if (args.isFwdLocked()) { 12686 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 12687 } 12688 12689 doGc = true; 12690 synchronized (mInstallLock) { 12691 final PackageParser.Package pkg = scanPackageLI(new File(codePath), parseFlags, 12692 0, 0, null, null); 12693 // Scan the package 12694 if (pkg != null) { 12695 /* 12696 * TODO why is the lock being held? doPostInstall is 12697 * called in other places without the lock. This needs 12698 * to be straightened out. 12699 */ 12700 // writer 12701 synchronized (mPackages) { 12702 retCode = PackageManager.INSTALL_SUCCEEDED; 12703 pkgList.add(pkg.packageName); 12704 // Post process args 12705 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 12706 pkg.applicationInfo.uid); 12707 } 12708 } else { 12709 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 12710 } 12711 } 12712 12713 } finally { 12714 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 12715 // Don't destroy container here. Wait till gc clears things 12716 // up. 12717 removeCids.add(args.cid); 12718 } 12719 } 12720 } 12721 // writer 12722 synchronized (mPackages) { 12723 // If the platform SDK has changed since the last time we booted, 12724 // we need to re-grant app permission to catch any new ones that 12725 // appear. This is really a hack, and means that apps can in some 12726 // cases get permissions that the user didn't initially explicitly 12727 // allow... it would be nice to have some better way to handle 12728 // this situation. 12729 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 12730 if (regrantPermissions) 12731 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 12732 + mSdkVersion + "; regranting permissions for external storage"); 12733 mSettings.mExternalSdkPlatform = mSdkVersion; 12734 12735 // Make sure group IDs have been assigned, and any permission 12736 // changes in other apps are accounted for 12737 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 12738 | (regrantPermissions 12739 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 12740 : 0)); 12741 12742 mSettings.updateExternalDatabaseVersion(); 12743 12744 // can downgrade to reader 12745 // Persist settings 12746 mSettings.writeLPr(); 12747 } 12748 // Send a broadcast to let everyone know we are done processing 12749 if (pkgList.size() > 0) { 12750 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12751 } 12752 // Force gc to avoid any stale parser references that we might have. 12753 if (doGc) { 12754 Runtime.getRuntime().gc(); 12755 } 12756 // List stale containers and destroy stale temporary containers. 12757 if (removeCids != null) { 12758 for (String cid : removeCids) { 12759 if (cid.startsWith(mTempContainerPrefix)) { 12760 Log.i(TAG, "Destroying stale temporary container " + cid); 12761 PackageHelper.destroySdDir(cid); 12762 } else { 12763 Log.w(TAG, "Container " + cid + " is stale"); 12764 } 12765 } 12766 } 12767 } 12768 12769 /* 12770 * Utility method to unload a list of specified containers 12771 */ 12772 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 12773 // Just unmount all valid containers. 12774 for (AsecInstallArgs arg : cidArgs) { 12775 synchronized (mInstallLock) { 12776 arg.doPostDeleteLI(false); 12777 } 12778 } 12779 } 12780 12781 /* 12782 * Unload packages mounted on external media. This involves deleting package 12783 * data from internal structures, sending broadcasts about diabled packages, 12784 * gc'ing to free up references, unmounting all secure containers 12785 * corresponding to packages on external media, and posting a 12786 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 12787 * that we always have to post this message if status has been requested no 12788 * matter what. 12789 */ 12790 private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 12791 final boolean reportStatus) { 12792 if (DEBUG_SD_INSTALL) 12793 Log.i(TAG, "unloading media packages"); 12794 ArrayList<String> pkgList = new ArrayList<String>(); 12795 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 12796 final Set<AsecInstallArgs> keys = processCids.keySet(); 12797 for (AsecInstallArgs args : keys) { 12798 String pkgName = args.getPackageName(); 12799 if (DEBUG_SD_INSTALL) 12800 Log.i(TAG, "Trying to unload pkg : " + pkgName); 12801 // Delete package internally 12802 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 12803 synchronized (mInstallLock) { 12804 boolean res = deletePackageLI(pkgName, null, false, null, null, 12805 PackageManager.DELETE_KEEP_DATA, outInfo, false); 12806 if (res) { 12807 pkgList.add(pkgName); 12808 } else { 12809 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 12810 failedList.add(args); 12811 } 12812 } 12813 } 12814 12815 // reader 12816 synchronized (mPackages) { 12817 // We didn't update the settings after removing each package; 12818 // write them now for all packages. 12819 mSettings.writeLPr(); 12820 } 12821 12822 // We have to absolutely send UPDATED_MEDIA_STATUS only 12823 // after confirming that all the receivers processed the ordered 12824 // broadcast when packages get disabled, force a gc to clean things up. 12825 // and unload all the containers. 12826 if (pkgList.size() > 0) { 12827 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 12828 new IIntentReceiver.Stub() { 12829 public void performReceive(Intent intent, int resultCode, String data, 12830 Bundle extras, boolean ordered, boolean sticky, 12831 int sendingUser) throws RemoteException { 12832 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 12833 reportStatus ? 1 : 0, 1, keys); 12834 mHandler.sendMessage(msg); 12835 } 12836 }); 12837 } else { 12838 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 12839 keys); 12840 mHandler.sendMessage(msg); 12841 } 12842 } 12843 12844 /** Binder call */ 12845 @Override 12846 public void movePackage(final String packageName, final IPackageMoveObserver observer, 12847 final int flags) { 12848 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 12849 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 12850 int returnCode = PackageManager.MOVE_SUCCEEDED; 12851 int currFlags = 0; 12852 int newFlags = 0; 12853 // reader 12854 synchronized (mPackages) { 12855 PackageParser.Package pkg = mPackages.get(packageName); 12856 if (pkg == null) { 12857 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12858 } else { 12859 // Disable moving fwd locked apps and system packages 12860 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 12861 Slog.w(TAG, "Cannot move system application"); 12862 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 12863 } else if (pkg.mOperationPending) { 12864 Slog.w(TAG, "Attempt to move package which has pending operations"); 12865 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 12866 } else { 12867 // Find install location first 12868 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 12869 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 12870 Slog.w(TAG, "Ambigous flags specified for move location."); 12871 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12872 } else { 12873 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL 12874 : PackageManager.INSTALL_INTERNAL; 12875 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL 12876 : PackageManager.INSTALL_INTERNAL; 12877 12878 if (newFlags == currFlags) { 12879 Slog.w(TAG, "No move required. Trying to move to same location"); 12880 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12881 } else { 12882 if (isForwardLocked(pkg)) { 12883 currFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12884 newFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12885 } 12886 } 12887 } 12888 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12889 pkg.mOperationPending = true; 12890 } 12891 } 12892 } 12893 12894 /* 12895 * TODO this next block probably shouldn't be inside the lock. We 12896 * can't guarantee these won't change after this is fired off 12897 * anyway. 12898 */ 12899 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 12900 processPendingMove(new MoveParams(null, observer, 0, packageName, null, -1, user, false), 12901 returnCode); 12902 } else { 12903 Message msg = mHandler.obtainMessage(INIT_COPY); 12904 final String[] instructionSets = getAppDexInstructionSets(pkg.applicationInfo); 12905 final boolean multiArch = isMultiArch(pkg.applicationInfo); 12906 InstallArgs srcArgs = createInstallArgsForExisting(currFlags, 12907 pkg.applicationInfo.getCodePath(), pkg.applicationInfo.getResourcePath(), 12908 pkg.applicationInfo.nativeLibraryRootDir, instructionSets, multiArch); 12909 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName, 12910 instructionSets, pkg.applicationInfo.uid, user, multiArch); 12911 msg.obj = mp; 12912 mHandler.sendMessage(msg); 12913 } 12914 } 12915 } 12916 12917 private void processPendingMove(final MoveParams mp, final int currentStatus) { 12918 // Queue up an async operation since the package deletion may take a 12919 // little while. 12920 mHandler.post(new Runnable() { 12921 public void run() { 12922 // TODO fix this; this does nothing. 12923 mHandler.removeCallbacks(this); 12924 int returnCode = currentStatus; 12925 if (currentStatus == PackageManager.MOVE_SUCCEEDED) { 12926 int uidArr[] = null; 12927 ArrayList<String> pkgList = null; 12928 synchronized (mPackages) { 12929 PackageParser.Package pkg = mPackages.get(mp.packageName); 12930 if (pkg == null) { 12931 Slog.w(TAG, " Package " + mp.packageName 12932 + " doesn't exist. Aborting move"); 12933 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12934 } else if (!mp.srcArgs.getCodePath().equals( 12935 pkg.applicationInfo.getCodePath())) { 12936 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " 12937 + mp.srcArgs.getCodePath() + " to " 12938 + pkg.applicationInfo.getCodePath() 12939 + " Aborting move and returning error"); 12940 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 12941 } else { 12942 uidArr = new int[] { 12943 pkg.applicationInfo.uid 12944 }; 12945 pkgList = new ArrayList<String>(); 12946 pkgList.add(mp.packageName); 12947 } 12948 } 12949 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12950 // Send resources unavailable broadcast 12951 sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null); 12952 // Update package code and resource paths 12953 synchronized (mInstallLock) { 12954 synchronized (mPackages) { 12955 PackageParser.Package pkg = mPackages.get(mp.packageName); 12956 // Recheck for package again. 12957 if (pkg == null) { 12958 Slog.w(TAG, " Package " + mp.packageName 12959 + " doesn't exist. Aborting move"); 12960 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12961 } else if (!mp.srcArgs.getCodePath().equals( 12962 pkg.applicationInfo.getCodePath())) { 12963 Slog.w(TAG, "Package " + mp.packageName 12964 + " code path changed from " + mp.srcArgs.getCodePath() 12965 + " to " + pkg.applicationInfo.getCodePath() 12966 + " Aborting move and returning error"); 12967 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 12968 } else { 12969 final String oldCodePath = pkg.codePath; 12970 final String newCodePath = mp.targetArgs.getCodePath(); 12971 final String newResPath = mp.targetArgs.getResourcePath(); 12972 // TODO: This assumes the new style of installation. 12973 // should we look at legacyNativeLibraryPath ? 12974 final String newNativeRoot = new File(pkg.codePath, LIB_DIR_NAME).getAbsolutePath(); 12975 final File newNativeDir = new File(newNativeRoot); 12976 12977 if (!isForwardLocked(pkg) && !isExternal(pkg)) { 12978 // TODO(multiArch): Fix this so that it looks at the existing 12979 // recorded CPU abis from the package. There's no need for a separate 12980 // round of ABI scanning here. 12981 NativeLibraryHelper.Handle handle = null; 12982 try { 12983 handle = NativeLibraryHelper.Handle.create( 12984 new File(newCodePath)); 12985 final int abi = NativeLibraryHelper.findSupportedAbi( 12986 handle, Build.SUPPORTED_ABIS); 12987 if (abi >= 0) { 12988 NativeLibraryHelper.copyNativeBinariesIfNeededLI( 12989 handle, newNativeDir, Build.SUPPORTED_ABIS[abi]); 12990 } 12991 } catch (IOException ioe) { 12992 Slog.w(TAG, "Unable to extract native libs for package :" 12993 + mp.packageName, ioe); 12994 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 12995 } finally { 12996 IoUtils.closeQuietly(handle); 12997 } 12998 } 12999 13000 final int[] users = sUserManager.getUserIds(); 13001 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13002 for (int user : users) { 13003 // TODO(multiArch): Fix this so that it links to the 13004 // correct directory. We're currently pointing to root. but we 13005 // must point to the arch specific subdirectory (if applicable). 13006 // 13007 // TODO(multiArch): Bogus reference to nativeLibraryDir. 13008 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, 13009 newNativeRoot, user) < 0) { 13010 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 13011 } 13012 } 13013 } 13014 13015 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13016 pkg.codePath = newCodePath; 13017 pkg.baseCodePath = newCodePath; 13018 // Move dex files around 13019 if (moveDexFilesLI(oldCodePath, pkg) != PackageManager.INSTALL_SUCCEEDED) { 13020 // Moving of dex files failed. Set 13021 // error code and abort move. 13022 pkg.codePath = oldCodePath; 13023 pkg.baseCodePath = oldCodePath; 13024 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 13025 } 13026 } 13027 13028 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13029 pkg.applicationInfo.setCodePath(newCodePath); 13030 pkg.applicationInfo.setBaseCodePath(newCodePath); 13031 pkg.applicationInfo.setSplitCodePaths(null); 13032 pkg.applicationInfo.setResourcePath(newResPath); 13033 pkg.applicationInfo.setBaseResourcePath(newResPath); 13034 pkg.applicationInfo.setSplitResourcePaths(null); 13035 13036 PackageSetting ps = (PackageSetting) pkg.mExtras; 13037 ps.codePath = new File(pkg.applicationInfo.getCodePath()); 13038 ps.codePathString = ps.codePath.getPath(); 13039 ps.resourcePath = new File(pkg.applicationInfo.getResourcePath()); 13040 ps.resourcePathString = ps.resourcePath.getPath(); 13041 13042 // Note that we don't have to recalculate the primary and secondary 13043 // CPU ABIs because they must already have been calculated during the 13044 // initial install of the app. 13045 ps.legacyNativeLibraryPathString = null; 13046 13047 // Set the application info flag 13048 // correctly. 13049 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) { 13050 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE; 13051 } else { 13052 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE; 13053 } 13054 ps.setFlags(pkg.applicationInfo.flags); 13055 mAppDirs.remove(oldCodePath); 13056 mAppDirs.put(newCodePath, pkg); 13057 // Persist settings 13058 mSettings.writeLPr(); 13059 } 13060 } 13061 } 13062 } 13063 // Send resources available broadcast 13064 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 13065 } 13066 } 13067 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 13068 // Clean up failed installation 13069 if (mp.targetArgs != null) { 13070 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR, 13071 -1); 13072 } 13073 } else { 13074 // Force a gc to clear things up. 13075 Runtime.getRuntime().gc(); 13076 // Delete older code 13077 synchronized (mInstallLock) { 13078 mp.srcArgs.doPostDeleteLI(true); 13079 } 13080 } 13081 13082 // Allow more operations on this file if we didn't fail because 13083 // an operation was already pending for this package. 13084 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) { 13085 synchronized (mPackages) { 13086 PackageParser.Package pkg = mPackages.get(mp.packageName); 13087 if (pkg != null) { 13088 pkg.mOperationPending = false; 13089 } 13090 } 13091 } 13092 13093 IPackageMoveObserver observer = mp.observer; 13094 if (observer != null) { 13095 try { 13096 observer.packageMoved(mp.packageName, returnCode); 13097 } catch (RemoteException e) { 13098 Log.i(TAG, "Observer no longer exists."); 13099 } 13100 } 13101 } 13102 }); 13103 } 13104 13105 @Override 13106 public boolean setInstallLocation(int loc) { 13107 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 13108 null); 13109 if (getInstallLocation() == loc) { 13110 return true; 13111 } 13112 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 13113 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 13114 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 13115 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 13116 return true; 13117 } 13118 return false; 13119 } 13120 13121 @Override 13122 public int getInstallLocation() { 13123 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13124 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 13125 PackageHelper.APP_INSTALL_AUTO); 13126 } 13127 13128 /** Called by UserManagerService */ 13129 void cleanUpUserLILPw(int userHandle) { 13130 mDirtyUsers.remove(userHandle); 13131 mSettings.removeUserLPw(userHandle); 13132 mPendingBroadcasts.remove(userHandle); 13133 if (mInstaller != null) { 13134 // Technically, we shouldn't be doing this with the package lock 13135 // held. However, this is very rare, and there is already so much 13136 // other disk I/O going on, that we'll let it slide for now. 13137 mInstaller.removeUserDataDirs(userHandle); 13138 } 13139 mUserNeedsBadging.delete(userHandle); 13140 } 13141 13142 /** Called by UserManagerService */ 13143 void createNewUserLILPw(int userHandle, File path) { 13144 if (mInstaller != null) { 13145 mInstaller.createUserConfig(userHandle); 13146 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 13147 } 13148 } 13149 13150 @Override 13151 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 13152 mContext.enforceCallingOrSelfPermission( 13153 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13154 "Only package verification agents can read the verifier device identity"); 13155 13156 synchronized (mPackages) { 13157 return mSettings.getVerifierDeviceIdentityLPw(); 13158 } 13159 } 13160 13161 @Override 13162 public void setPermissionEnforced(String permission, boolean enforced) { 13163 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 13164 if (READ_EXTERNAL_STORAGE.equals(permission)) { 13165 synchronized (mPackages) { 13166 if (mSettings.mReadExternalStorageEnforced == null 13167 || mSettings.mReadExternalStorageEnforced != enforced) { 13168 mSettings.mReadExternalStorageEnforced = enforced; 13169 mSettings.writeLPr(); 13170 } 13171 } 13172 // kill any non-foreground processes so we restart them and 13173 // grant/revoke the GID. 13174 final IActivityManager am = ActivityManagerNative.getDefault(); 13175 if (am != null) { 13176 final long token = Binder.clearCallingIdentity(); 13177 try { 13178 am.killProcessesBelowForeground("setPermissionEnforcement"); 13179 } catch (RemoteException e) { 13180 } finally { 13181 Binder.restoreCallingIdentity(token); 13182 } 13183 } 13184 } else { 13185 throw new IllegalArgumentException("No selective enforcement for " + permission); 13186 } 13187 } 13188 13189 @Override 13190 @Deprecated 13191 public boolean isPermissionEnforced(String permission) { 13192 return true; 13193 } 13194 13195 @Override 13196 public boolean isStorageLow() { 13197 final long token = Binder.clearCallingIdentity(); 13198 try { 13199 final DeviceStorageMonitorInternal 13200 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13201 if (dsm != null) { 13202 return dsm.isMemoryLow(); 13203 } else { 13204 return false; 13205 } 13206 } finally { 13207 Binder.restoreCallingIdentity(token); 13208 } 13209 } 13210 13211 @Override 13212 public IPackageInstaller getPackageInstaller() { 13213 return mInstallerService; 13214 } 13215 13216 private boolean userNeedsBadging(int userId) { 13217 int index = mUserNeedsBadging.indexOfKey(userId); 13218 if (index < 0) { 13219 final UserInfo userInfo; 13220 final long token = Binder.clearCallingIdentity(); 13221 try { 13222 userInfo = sUserManager.getUserInfo(userId); 13223 } finally { 13224 Binder.restoreCallingIdentity(token); 13225 } 13226 final boolean b; 13227 if (userInfo != null && userInfo.isManagedProfile()) { 13228 b = true; 13229 } else { 13230 b = false; 13231 } 13232 mUserNeedsBadging.put(userId, b); 13233 return b; 13234 } 13235 return mUserNeedsBadging.valueAt(index); 13236 } 13237} 13238