PackageManagerService.java revision 43327a61eb57839429fbb064f4166a858788779c
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS; 20import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 21import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 26import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 27import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 28import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 29import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 30import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 32import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 33import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 34import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 36import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 37import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 38import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 39import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 41import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 42import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 44import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 45import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 46import static android.content.pm.PackageParser.isApkFile; 47import static android.os.Process.PACKAGE_INFO_GID; 48import static android.os.Process.SYSTEM_UID; 49import static android.system.OsConstants.O_CREAT; 50import static android.system.OsConstants.O_RDWR; 51import static android.system.OsConstants.S_IRGRP; 52import static android.system.OsConstants.S_IROTH; 53import static android.system.OsConstants.S_IRWXU; 54import static android.system.OsConstants.S_IXGRP; 55import static android.system.OsConstants.S_IXOTH; 56import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 57import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 58import static com.android.internal.util.ArrayUtils.appendInt; 59import static com.android.internal.util.ArrayUtils.removeInt; 60 61import android.util.ArrayMap; 62 63import com.android.internal.R; 64import com.android.internal.app.IMediaContainerService; 65import com.android.internal.app.ResolverActivity; 66import com.android.internal.content.NativeLibraryHelper; 67import com.android.internal.content.PackageHelper; 68import com.android.internal.os.IParcelFileDescriptorFactory; 69import com.android.internal.util.ArrayUtils; 70import com.android.internal.util.FastPrintWriter; 71import com.android.internal.util.FastXmlSerializer; 72import com.android.internal.util.IndentingPrintWriter; 73import com.android.internal.util.Preconditions; 74import com.android.server.EventLogTags; 75import com.android.server.IntentResolver; 76import com.android.server.LocalServices; 77import com.android.server.ServiceThread; 78import com.android.server.SystemConfig; 79import com.android.server.Watchdog; 80import com.android.server.pm.Settings.DatabaseVersion; 81import com.android.server.storage.DeviceStorageMonitorInternal; 82 83import org.xmlpull.v1.XmlSerializer; 84 85import android.app.ActivityManager; 86import android.app.ActivityManagerNative; 87import android.app.IActivityManager; 88import android.app.admin.IDevicePolicyManager; 89import android.app.backup.IBackupManager; 90import android.content.BroadcastReceiver; 91import android.content.ComponentName; 92import android.content.Context; 93import android.content.IIntentReceiver; 94import android.content.Intent; 95import android.content.IntentFilter; 96import android.content.IntentSender; 97import android.content.IntentSender.SendIntentException; 98import android.content.ServiceConnection; 99import android.content.pm.ActivityInfo; 100import android.content.pm.ApplicationInfo; 101import android.content.pm.FeatureInfo; 102import android.content.pm.IPackageDataObserver; 103import android.content.pm.IPackageDeleteObserver; 104import android.content.pm.IPackageInstallObserver2; 105import android.content.pm.IPackageInstaller; 106import android.content.pm.IPackageManager; 107import android.content.pm.IPackageMoveObserver; 108import android.content.pm.IPackageStatsObserver; 109import android.content.pm.InstallSessionParams; 110import android.content.pm.InstrumentationInfo; 111import android.content.pm.ManifestDigest; 112import android.content.pm.PackageCleanItem; 113import android.content.pm.PackageInfo; 114import android.content.pm.PackageInfoLite; 115import android.content.pm.PackageManager; 116import android.content.pm.PackageParser.ActivityIntentInfo; 117import android.content.pm.PackageParser.PackageLite; 118import android.content.pm.PackageParser.PackageParserException; 119import android.content.pm.PackageParser; 120import android.content.pm.PackageStats; 121import android.content.pm.PackageUserState; 122import android.content.pm.ParceledListSlice; 123import android.content.pm.PermissionGroupInfo; 124import android.content.pm.PermissionInfo; 125import android.content.pm.ProviderInfo; 126import android.content.pm.ResolveInfo; 127import android.content.pm.ServiceInfo; 128import android.content.pm.Signature; 129import android.content.pm.UserInfo; 130import android.content.pm.VerificationParams; 131import android.content.pm.VerifierDeviceIdentity; 132import android.content.pm.VerifierInfo; 133import android.content.res.Resources; 134import android.hardware.display.DisplayManager; 135import android.net.Uri; 136import android.os.Binder; 137import android.os.Build; 138import android.os.Bundle; 139import android.os.Environment; 140import android.os.Environment.UserEnvironment; 141import android.os.FileUtils; 142import android.os.Handler; 143import android.os.IBinder; 144import android.os.Looper; 145import android.os.Message; 146import android.os.Parcel; 147import android.os.ParcelFileDescriptor; 148import android.os.Process; 149import android.os.RemoteException; 150import android.os.SELinux; 151import android.os.ServiceManager; 152import android.os.SystemClock; 153import android.os.SystemProperties; 154import android.os.UserHandle; 155import android.os.UserManager; 156import android.security.KeyStore; 157import android.security.SystemKeyStore; 158import android.system.ErrnoException; 159import android.system.Os; 160import android.system.StructStat; 161import android.text.TextUtils; 162import android.util.ArraySet; 163import android.util.AtomicFile; 164import android.util.DisplayMetrics; 165import android.util.EventLog; 166import android.util.ExceptionUtils; 167import android.util.Log; 168import android.util.LogPrinter; 169import android.util.PrintStreamPrinter; 170import android.util.Slog; 171import android.util.SparseArray; 172import android.util.SparseBooleanArray; 173import android.view.Display; 174 175import java.io.BufferedInputStream; 176import java.io.BufferedOutputStream; 177import java.io.File; 178import java.io.FileDescriptor; 179import java.io.FileInputStream; 180import java.io.FileNotFoundException; 181import java.io.FileOutputStream; 182import java.io.FilenameFilter; 183import java.io.IOException; 184import java.io.InputStream; 185import java.io.PrintWriter; 186import java.nio.charset.StandardCharsets; 187import java.security.NoSuchAlgorithmException; 188import java.security.PublicKey; 189import java.security.cert.CertificateEncodingException; 190import java.security.cert.CertificateException; 191import java.text.SimpleDateFormat; 192import java.util.ArrayList; 193import java.util.Arrays; 194import java.util.Collection; 195import java.util.Collections; 196import java.util.Comparator; 197import java.util.Date; 198import java.util.HashMap; 199import java.util.HashSet; 200import java.util.Iterator; 201import java.util.List; 202import java.util.Map; 203import java.util.Set; 204import java.util.concurrent.atomic.AtomicBoolean; 205import java.util.concurrent.atomic.AtomicLong; 206 207import dalvik.system.DexFile; 208import dalvik.system.StaleDexCacheError; 209import dalvik.system.VMRuntime; 210 211import libcore.io.IoUtils; 212 213/** 214 * Keep track of all those .apks everywhere. 215 * 216 * This is very central to the platform's security; please run the unit 217 * tests whenever making modifications here: 218 * 219mmm frameworks/base/tests/AndroidTests 220adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 221adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 222 * 223 * {@hide} 224 */ 225public class PackageManagerService extends IPackageManager.Stub { 226 static final String TAG = "PackageManager"; 227 static final boolean DEBUG_SETTINGS = false; 228 static final boolean DEBUG_PREFERRED = false; 229 static final boolean DEBUG_UPGRADE = false; 230 private static final boolean DEBUG_INSTALL = false; 231 private static final boolean DEBUG_REMOVE = false; 232 private static final boolean DEBUG_BROADCASTS = false; 233 private static final boolean DEBUG_SHOW_INFO = false; 234 private static final boolean DEBUG_PACKAGE_INFO = false; 235 private static final boolean DEBUG_INTENT_MATCHING = false; 236 private static final boolean DEBUG_PACKAGE_SCANNING = false; 237 private static final boolean DEBUG_VERIFY = false; 238 private static final boolean DEBUG_DEXOPT = false; 239 private static final boolean DEBUG_ABI_SELECTION = false; 240 241 private static final int RADIO_UID = Process.PHONE_UID; 242 private static final int LOG_UID = Process.LOG_UID; 243 private static final int NFC_UID = Process.NFC_UID; 244 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 245 private static final int SHELL_UID = Process.SHELL_UID; 246 247 // Cap the size of permission trees that 3rd party apps can define 248 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 249 250 // Suffix used during package installation when copying/moving 251 // package apks to install directory. 252 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 253 254 static final int SCAN_MONITOR = 1<<0; 255 static final int SCAN_NO_DEX = 1<<1; 256 static final int SCAN_FORCE_DEX = 1<<2; 257 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 258 static final int SCAN_NEW_INSTALL = 1<<4; 259 static final int SCAN_NO_PATHS = 1<<5; 260 static final int SCAN_UPDATE_TIME = 1<<6; 261 static final int SCAN_DEFER_DEX = 1<<7; 262 static final int SCAN_BOOTING = 1<<8; 263 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 264 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 265 266 static final int REMOVE_CHATTY = 1<<16; 267 268 /** 269 * Timeout (in milliseconds) after which the watchdog should declare that 270 * our handler thread is wedged. The usual default for such things is one 271 * minute but we sometimes do very lengthy I/O operations on this thread, 272 * such as installing multi-gigabyte applications, so ours needs to be longer. 273 */ 274 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 275 276 /** 277 * Whether verification is enabled by default. 278 */ 279 private static final boolean DEFAULT_VERIFY_ENABLE = true; 280 281 /** 282 * The default maximum time to wait for the verification agent to return in 283 * milliseconds. 284 */ 285 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 286 287 /** 288 * The default response for package verification timeout. 289 * 290 * This can be either PackageManager.VERIFICATION_ALLOW or 291 * PackageManager.VERIFICATION_REJECT. 292 */ 293 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 294 295 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 296 297 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 298 DEFAULT_CONTAINER_PACKAGE, 299 "com.android.defcontainer.DefaultContainerService"); 300 301 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 302 303 private static final String LIB_DIR_NAME = "lib"; 304 private static final String LIB64_DIR_NAME = "lib64"; 305 306 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 307 308 static final String mTempContainerPrefix = "smdl2tmp"; 309 310 private static String sPreferredInstructionSet; 311 312 final ServiceThread mHandlerThread; 313 314 private static final String IDMAP_PREFIX = "/data/resource-cache/"; 315 private static final String IDMAP_SUFFIX = "@idmap"; 316 317 final PackageHandler mHandler; 318 319 final int mSdkVersion = Build.VERSION.SDK_INT; 320 321 final Context mContext; 322 final boolean mFactoryTest; 323 final boolean mOnlyCore; 324 final DisplayMetrics mMetrics; 325 final int mDefParseFlags; 326 final String[] mSeparateProcesses; 327 328 // This is where all application persistent data goes. 329 final File mAppDataDir; 330 331 // This is where all application persistent data goes for secondary users. 332 final File mUserAppDataDir; 333 334 /** The location for ASEC container files on internal storage. */ 335 final String mAsecInternalPath; 336 337 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 338 // LOCK HELD. Can be called with mInstallLock held. 339 final Installer mInstaller; 340 341 /** Directory where installed third-party apps stored */ 342 final File mAppInstallDir; 343 344 /** 345 * Directory to which applications installed internally have their 346 * 32 bit native libraries copied. 347 */ 348 private File mAppLib32InstallDir; 349 350 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 351 // apps. 352 final File mDrmAppPrivateInstallDir; 353 354 // ---------------------------------------------------------------- 355 356 // Lock for state used when installing and doing other long running 357 // operations. Methods that must be called with this lock held have 358 // the suffix "LI". 359 final Object mInstallLock = new Object(); 360 361 // These are the directories in the 3rd party applications installed dir 362 // that we have currently loaded packages from. Keys are the application's 363 // installed zip file (absolute codePath), and values are Package. 364 final HashMap<String, PackageParser.Package> mAppDirs = 365 new HashMap<String, PackageParser.Package>(); 366 367 // ---------------------------------------------------------------- 368 369 // Keys are String (package name), values are Package. This also serves 370 // as the lock for the global state. Methods that must be called with 371 // this lock held have the prefix "LP". 372 final HashMap<String, PackageParser.Package> mPackages = 373 new HashMap<String, PackageParser.Package>(); 374 375 // Tracks available target package names -> overlay package paths. 376 final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays = 377 new HashMap<String, HashMap<String, PackageParser.Package>>(); 378 379 final Settings mSettings; 380 boolean mRestoredSettings; 381 382 // System configuration read by SystemConfig. 383 final int[] mGlobalGids; 384 final SparseArray<HashSet<String>> mSystemPermissions; 385 final HashMap<String, FeatureInfo> mAvailableFeatures; 386 387 // If mac_permissions.xml was found for seinfo labeling. 388 boolean mFoundPolicyFile; 389 390 // If a recursive restorecon of /data/data/<pkg> is needed. 391 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 392 393 public static final class SharedLibraryEntry { 394 public final String path; 395 public final String apk; 396 397 SharedLibraryEntry(String _path, String _apk) { 398 path = _path; 399 apk = _apk; 400 } 401 } 402 403 // Currently known shared libraries. 404 final HashMap<String, SharedLibraryEntry> mSharedLibraries = 405 new HashMap<String, SharedLibraryEntry>(); 406 407 // All available activities, for your resolving pleasure. 408 final ActivityIntentResolver mActivities = 409 new ActivityIntentResolver(); 410 411 // All available receivers, for your resolving pleasure. 412 final ActivityIntentResolver mReceivers = 413 new ActivityIntentResolver(); 414 415 // All available services, for your resolving pleasure. 416 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 417 418 // All available providers, for your resolving pleasure. 419 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 420 421 // Mapping from provider base names (first directory in content URI codePath) 422 // to the provider information. 423 final HashMap<String, PackageParser.Provider> mProvidersByAuthority = 424 new HashMap<String, PackageParser.Provider>(); 425 426 // Mapping from instrumentation class names to info about them. 427 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 428 new HashMap<ComponentName, PackageParser.Instrumentation>(); 429 430 // Mapping from permission names to info about them. 431 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups = 432 new HashMap<String, PackageParser.PermissionGroup>(); 433 434 // Packages whose data we have transfered into another package, thus 435 // should no longer exist. 436 final HashSet<String> mTransferedPackages = new HashSet<String>(); 437 438 // Broadcast actions that are only available to the system. 439 final HashSet<String> mProtectedBroadcasts = new HashSet<String>(); 440 441 /** List of packages waiting for verification. */ 442 final SparseArray<PackageVerificationState> mPendingVerification 443 = new SparseArray<PackageVerificationState>(); 444 445 /** Set of packages associated with each app op permission. */ 446 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 447 448 final PackageInstallerService mInstallerService; 449 450 HashSet<PackageParser.Package> mDeferredDexOpt = null; 451 452 // Cache of users who need badging. 453 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 454 455 /** Token for keys in mPendingVerification. */ 456 private int mPendingVerificationToken = 0; 457 458 boolean mSystemReady; 459 boolean mSafeMode; 460 boolean mHasSystemUidErrors; 461 462 ApplicationInfo mAndroidApplication; 463 final ActivityInfo mResolveActivity = new ActivityInfo(); 464 final ResolveInfo mResolveInfo = new ResolveInfo(); 465 ComponentName mResolveComponentName; 466 PackageParser.Package mPlatformPackage; 467 ComponentName mCustomResolverComponentName; 468 469 boolean mResolverReplaced = false; 470 471 // Set of pending broadcasts for aggregating enable/disable of components. 472 static class PendingPackageBroadcasts { 473 // for each user id, a map of <package name -> components within that package> 474 final SparseArray<HashMap<String, ArrayList<String>>> mUidMap; 475 476 public PendingPackageBroadcasts() { 477 mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2); 478 } 479 480 public ArrayList<String> get(int userId, String packageName) { 481 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 482 return packages.get(packageName); 483 } 484 485 public void put(int userId, String packageName, ArrayList<String> components) { 486 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 487 packages.put(packageName, components); 488 } 489 490 public void remove(int userId, String packageName) { 491 HashMap<String, ArrayList<String>> packages = mUidMap.get(userId); 492 if (packages != null) { 493 packages.remove(packageName); 494 } 495 } 496 497 public void remove(int userId) { 498 mUidMap.remove(userId); 499 } 500 501 public int userIdCount() { 502 return mUidMap.size(); 503 } 504 505 public int userIdAt(int n) { 506 return mUidMap.keyAt(n); 507 } 508 509 public HashMap<String, ArrayList<String>> packagesForUserId(int userId) { 510 return mUidMap.get(userId); 511 } 512 513 public int size() { 514 // total number of pending broadcast entries across all userIds 515 int num = 0; 516 for (int i = 0; i< mUidMap.size(); i++) { 517 num += mUidMap.valueAt(i).size(); 518 } 519 return num; 520 } 521 522 public void clear() { 523 mUidMap.clear(); 524 } 525 526 private HashMap<String, ArrayList<String>> getOrAllocate(int userId) { 527 HashMap<String, ArrayList<String>> map = mUidMap.get(userId); 528 if (map == null) { 529 map = new HashMap<String, ArrayList<String>>(); 530 mUidMap.put(userId, map); 531 } 532 return map; 533 } 534 } 535 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 536 537 // Service Connection to remote media container service to copy 538 // package uri's from external media onto secure containers 539 // or internal storage. 540 private IMediaContainerService mContainerService = null; 541 542 static final int SEND_PENDING_BROADCAST = 1; 543 static final int MCS_BOUND = 3; 544 static final int END_COPY = 4; 545 static final int INIT_COPY = 5; 546 static final int MCS_UNBIND = 6; 547 static final int START_CLEANING_PACKAGE = 7; 548 static final int FIND_INSTALL_LOC = 8; 549 static final int POST_INSTALL = 9; 550 static final int MCS_RECONNECT = 10; 551 static final int MCS_GIVE_UP = 11; 552 static final int UPDATED_MEDIA_STATUS = 12; 553 static final int WRITE_SETTINGS = 13; 554 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 555 static final int PACKAGE_VERIFIED = 15; 556 static final int CHECK_PENDING_VERIFICATION = 16; 557 558 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 559 560 // Delay time in millisecs 561 static final int BROADCAST_DELAY = 10 * 1000; 562 563 static UserManagerService sUserManager; 564 565 // Stores a list of users whose package restrictions file needs to be updated 566 private HashSet<Integer> mDirtyUsers = new HashSet<Integer>(); 567 568 final private DefaultContainerConnection mDefContainerConn = 569 new DefaultContainerConnection(); 570 class DefaultContainerConnection implements ServiceConnection { 571 public void onServiceConnected(ComponentName name, IBinder service) { 572 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 573 IMediaContainerService imcs = 574 IMediaContainerService.Stub.asInterface(service); 575 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 576 } 577 578 public void onServiceDisconnected(ComponentName name) { 579 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 580 } 581 }; 582 583 // Recordkeeping of restore-after-install operations that are currently in flight 584 // between the Package Manager and the Backup Manager 585 class PostInstallData { 586 public InstallArgs args; 587 public PackageInstalledInfo res; 588 589 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 590 args = _a; 591 res = _r; 592 } 593 }; 594 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 595 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 596 597 private final String mRequiredVerifierPackage; 598 599 private final PackageUsage mPackageUsage = new PackageUsage(); 600 601 private class PackageUsage { 602 private static final int WRITE_INTERVAL 603 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 604 605 private final Object mFileLock = new Object(); 606 private final AtomicLong mLastWritten = new AtomicLong(0); 607 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 608 609 private boolean mIsHistoricalPackageUsageAvailable = true; 610 611 boolean isHistoricalPackageUsageAvailable() { 612 return mIsHistoricalPackageUsageAvailable; 613 } 614 615 void write(boolean force) { 616 if (force) { 617 writeInternal(); 618 return; 619 } 620 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 621 && !DEBUG_DEXOPT) { 622 return; 623 } 624 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 625 new Thread("PackageUsage_DiskWriter") { 626 @Override 627 public void run() { 628 try { 629 writeInternal(); 630 } finally { 631 mBackgroundWriteRunning.set(false); 632 } 633 } 634 }.start(); 635 } 636 } 637 638 private void writeInternal() { 639 synchronized (mPackages) { 640 synchronized (mFileLock) { 641 AtomicFile file = getFile(); 642 FileOutputStream f = null; 643 try { 644 f = file.startWrite(); 645 BufferedOutputStream out = new BufferedOutputStream(f); 646 FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID); 647 StringBuilder sb = new StringBuilder(); 648 for (PackageParser.Package pkg : mPackages.values()) { 649 if (pkg.mLastPackageUsageTimeInMills == 0) { 650 continue; 651 } 652 sb.setLength(0); 653 sb.append(pkg.packageName); 654 sb.append(' '); 655 sb.append((long)pkg.mLastPackageUsageTimeInMills); 656 sb.append('\n'); 657 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 658 } 659 out.flush(); 660 file.finishWrite(f); 661 } catch (IOException e) { 662 if (f != null) { 663 file.failWrite(f); 664 } 665 Log.e(TAG, "Failed to write package usage times", e); 666 } 667 } 668 } 669 mLastWritten.set(SystemClock.elapsedRealtime()); 670 } 671 672 void readLP() { 673 synchronized (mFileLock) { 674 AtomicFile file = getFile(); 675 BufferedInputStream in = null; 676 try { 677 in = new BufferedInputStream(file.openRead()); 678 StringBuffer sb = new StringBuffer(); 679 while (true) { 680 String packageName = readToken(in, sb, ' '); 681 if (packageName == null) { 682 break; 683 } 684 String timeInMillisString = readToken(in, sb, '\n'); 685 if (timeInMillisString == null) { 686 throw new IOException("Failed to find last usage time for package " 687 + packageName); 688 } 689 PackageParser.Package pkg = mPackages.get(packageName); 690 if (pkg == null) { 691 continue; 692 } 693 long timeInMillis; 694 try { 695 timeInMillis = Long.parseLong(timeInMillisString.toString()); 696 } catch (NumberFormatException e) { 697 throw new IOException("Failed to parse " + timeInMillisString 698 + " as a long.", e); 699 } 700 pkg.mLastPackageUsageTimeInMills = timeInMillis; 701 } 702 } catch (FileNotFoundException expected) { 703 mIsHistoricalPackageUsageAvailable = false; 704 } catch (IOException e) { 705 Log.w(TAG, "Failed to read package usage times", e); 706 } finally { 707 IoUtils.closeQuietly(in); 708 } 709 } 710 mLastWritten.set(SystemClock.elapsedRealtime()); 711 } 712 713 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 714 throws IOException { 715 sb.setLength(0); 716 while (true) { 717 int ch = in.read(); 718 if (ch == -1) { 719 if (sb.length() == 0) { 720 return null; 721 } 722 throw new IOException("Unexpected EOF"); 723 } 724 if (ch == endOfToken) { 725 return sb.toString(); 726 } 727 sb.append((char)ch); 728 } 729 } 730 731 private AtomicFile getFile() { 732 File dataDir = Environment.getDataDirectory(); 733 File systemDir = new File(dataDir, "system"); 734 File fname = new File(systemDir, "package-usage.list"); 735 return new AtomicFile(fname); 736 } 737 } 738 739 class PackageHandler extends Handler { 740 private boolean mBound = false; 741 final ArrayList<HandlerParams> mPendingInstalls = 742 new ArrayList<HandlerParams>(); 743 744 private boolean connectToService() { 745 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 746 " DefaultContainerService"); 747 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 748 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 749 if (mContext.bindServiceAsUser(service, mDefContainerConn, 750 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 751 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 752 mBound = true; 753 return true; 754 } 755 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 756 return false; 757 } 758 759 private void disconnectService() { 760 mContainerService = null; 761 mBound = false; 762 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 763 mContext.unbindService(mDefContainerConn); 764 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 765 } 766 767 PackageHandler(Looper looper) { 768 super(looper); 769 } 770 771 public void handleMessage(Message msg) { 772 try { 773 doHandleMessage(msg); 774 } finally { 775 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 776 } 777 } 778 779 void doHandleMessage(Message msg) { 780 switch (msg.what) { 781 case INIT_COPY: { 782 HandlerParams params = (HandlerParams) msg.obj; 783 int idx = mPendingInstalls.size(); 784 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 785 // If a bind was already initiated we dont really 786 // need to do anything. The pending install 787 // will be processed later on. 788 if (!mBound) { 789 // If this is the only one pending we might 790 // have to bind to the service again. 791 if (!connectToService()) { 792 Slog.e(TAG, "Failed to bind to media container service"); 793 params.serviceError(); 794 return; 795 } else { 796 // Once we bind to the service, the first 797 // pending request will be processed. 798 mPendingInstalls.add(idx, params); 799 } 800 } else { 801 mPendingInstalls.add(idx, params); 802 // Already bound to the service. Just make 803 // sure we trigger off processing the first request. 804 if (idx == 0) { 805 mHandler.sendEmptyMessage(MCS_BOUND); 806 } 807 } 808 break; 809 } 810 case MCS_BOUND: { 811 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 812 if (msg.obj != null) { 813 mContainerService = (IMediaContainerService) msg.obj; 814 } 815 if (mContainerService == null) { 816 // Something seriously wrong. Bail out 817 Slog.e(TAG, "Cannot bind to media container service"); 818 for (HandlerParams params : mPendingInstalls) { 819 // Indicate service bind error 820 params.serviceError(); 821 } 822 mPendingInstalls.clear(); 823 } else if (mPendingInstalls.size() > 0) { 824 HandlerParams params = mPendingInstalls.get(0); 825 if (params != null) { 826 if (params.startCopy()) { 827 // We are done... look for more work or to 828 // go idle. 829 if (DEBUG_SD_INSTALL) Log.i(TAG, 830 "Checking for more work or unbind..."); 831 // Delete pending install 832 if (mPendingInstalls.size() > 0) { 833 mPendingInstalls.remove(0); 834 } 835 if (mPendingInstalls.size() == 0) { 836 if (mBound) { 837 if (DEBUG_SD_INSTALL) Log.i(TAG, 838 "Posting delayed MCS_UNBIND"); 839 removeMessages(MCS_UNBIND); 840 Message ubmsg = obtainMessage(MCS_UNBIND); 841 // Unbind after a little delay, to avoid 842 // continual thrashing. 843 sendMessageDelayed(ubmsg, 10000); 844 } 845 } else { 846 // There are more pending requests in queue. 847 // Just post MCS_BOUND message to trigger processing 848 // of next pending install. 849 if (DEBUG_SD_INSTALL) Log.i(TAG, 850 "Posting MCS_BOUND for next work"); 851 mHandler.sendEmptyMessage(MCS_BOUND); 852 } 853 } 854 } 855 } else { 856 // Should never happen ideally. 857 Slog.w(TAG, "Empty queue"); 858 } 859 break; 860 } 861 case MCS_RECONNECT: { 862 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 863 if (mPendingInstalls.size() > 0) { 864 if (mBound) { 865 disconnectService(); 866 } 867 if (!connectToService()) { 868 Slog.e(TAG, "Failed to bind to media container service"); 869 for (HandlerParams params : mPendingInstalls) { 870 // Indicate service bind error 871 params.serviceError(); 872 } 873 mPendingInstalls.clear(); 874 } 875 } 876 break; 877 } 878 case MCS_UNBIND: { 879 // If there is no actual work left, then time to unbind. 880 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 881 882 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 883 if (mBound) { 884 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 885 886 disconnectService(); 887 } 888 } else if (mPendingInstalls.size() > 0) { 889 // There are more pending requests in queue. 890 // Just post MCS_BOUND message to trigger processing 891 // of next pending install. 892 mHandler.sendEmptyMessage(MCS_BOUND); 893 } 894 895 break; 896 } 897 case MCS_GIVE_UP: { 898 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 899 mPendingInstalls.remove(0); 900 break; 901 } 902 case SEND_PENDING_BROADCAST: { 903 String packages[]; 904 ArrayList<String> components[]; 905 int size = 0; 906 int uids[]; 907 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 908 synchronized (mPackages) { 909 if (mPendingBroadcasts == null) { 910 return; 911 } 912 size = mPendingBroadcasts.size(); 913 if (size <= 0) { 914 // Nothing to be done. Just return 915 return; 916 } 917 packages = new String[size]; 918 components = new ArrayList[size]; 919 uids = new int[size]; 920 int i = 0; // filling out the above arrays 921 922 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 923 int packageUserId = mPendingBroadcasts.userIdAt(n); 924 Iterator<Map.Entry<String, ArrayList<String>>> it 925 = mPendingBroadcasts.packagesForUserId(packageUserId) 926 .entrySet().iterator(); 927 while (it.hasNext() && i < size) { 928 Map.Entry<String, ArrayList<String>> ent = it.next(); 929 packages[i] = ent.getKey(); 930 components[i] = ent.getValue(); 931 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 932 uids[i] = (ps != null) 933 ? UserHandle.getUid(packageUserId, ps.appId) 934 : -1; 935 i++; 936 } 937 } 938 size = i; 939 mPendingBroadcasts.clear(); 940 } 941 // Send broadcasts 942 for (int i = 0; i < size; i++) { 943 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 944 } 945 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 946 break; 947 } 948 case START_CLEANING_PACKAGE: { 949 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 950 final String packageName = (String)msg.obj; 951 final int userId = msg.arg1; 952 final boolean andCode = msg.arg2 != 0; 953 synchronized (mPackages) { 954 if (userId == UserHandle.USER_ALL) { 955 int[] users = sUserManager.getUserIds(); 956 for (int user : users) { 957 mSettings.addPackageToCleanLPw( 958 new PackageCleanItem(user, packageName, andCode)); 959 } 960 } else { 961 mSettings.addPackageToCleanLPw( 962 new PackageCleanItem(userId, packageName, andCode)); 963 } 964 } 965 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 966 startCleaningPackages(); 967 } break; 968 case POST_INSTALL: { 969 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 970 PostInstallData data = mRunningInstalls.get(msg.arg1); 971 mRunningInstalls.delete(msg.arg1); 972 boolean deleteOld = false; 973 974 if (data != null) { 975 InstallArgs args = data.args; 976 PackageInstalledInfo res = data.res; 977 978 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 979 res.removedInfo.sendBroadcast(false, true, false); 980 Bundle extras = new Bundle(1); 981 extras.putInt(Intent.EXTRA_UID, res.uid); 982 // Determine the set of users who are adding this 983 // package for the first time vs. those who are seeing 984 // an update. 985 int[] firstUsers; 986 int[] updateUsers = new int[0]; 987 if (res.origUsers == null || res.origUsers.length == 0) { 988 firstUsers = res.newUsers; 989 } else { 990 firstUsers = new int[0]; 991 for (int i=0; i<res.newUsers.length; i++) { 992 int user = res.newUsers[i]; 993 boolean isNew = true; 994 for (int j=0; j<res.origUsers.length; j++) { 995 if (res.origUsers[j] == user) { 996 isNew = false; 997 break; 998 } 999 } 1000 if (isNew) { 1001 int[] newFirst = new int[firstUsers.length+1]; 1002 System.arraycopy(firstUsers, 0, newFirst, 0, 1003 firstUsers.length); 1004 newFirst[firstUsers.length] = user; 1005 firstUsers = newFirst; 1006 } else { 1007 int[] newUpdate = new int[updateUsers.length+1]; 1008 System.arraycopy(updateUsers, 0, newUpdate, 0, 1009 updateUsers.length); 1010 newUpdate[updateUsers.length] = user; 1011 updateUsers = newUpdate; 1012 } 1013 } 1014 } 1015 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1016 res.pkg.applicationInfo.packageName, 1017 extras, null, null, firstUsers); 1018 final boolean update = res.removedInfo.removedPackage != null; 1019 if (update) { 1020 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1021 } 1022 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1023 res.pkg.applicationInfo.packageName, 1024 extras, null, null, updateUsers); 1025 if (update) { 1026 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1027 res.pkg.applicationInfo.packageName, 1028 extras, null, null, updateUsers); 1029 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1030 null, null, 1031 res.pkg.applicationInfo.packageName, null, updateUsers); 1032 1033 // treat asec-hosted packages like removable media on upgrade 1034 if (isForwardLocked(res.pkg) || isExternal(res.pkg)) { 1035 if (DEBUG_INSTALL) { 1036 Slog.i(TAG, "upgrading pkg " + res.pkg 1037 + " is ASEC-hosted -> AVAILABLE"); 1038 } 1039 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1040 ArrayList<String> pkgList = new ArrayList<String>(1); 1041 pkgList.add(res.pkg.applicationInfo.packageName); 1042 sendResourcesChangedBroadcast(true, true, 1043 pkgList,uidArray, null); 1044 } 1045 } 1046 if (res.removedInfo.args != null) { 1047 // Remove the replaced package's older resources safely now 1048 deleteOld = true; 1049 } 1050 1051 // Log current value of "unknown sources" setting 1052 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1053 getUnknownSourcesSettings()); 1054 } 1055 // Force a gc to clear up things 1056 Runtime.getRuntime().gc(); 1057 // We delete after a gc for applications on sdcard. 1058 if (deleteOld) { 1059 synchronized (mInstallLock) { 1060 res.removedInfo.args.doPostDeleteLI(true); 1061 } 1062 } 1063 if (args.observer != null) { 1064 try { 1065 Bundle extras = extrasForInstallResult(res); 1066 args.observer.packageInstalled(res.name, extras, res.returnCode, 1067 res.returnMsg); 1068 } catch (RemoteException e) { 1069 Slog.i(TAG, "Observer no longer exists."); 1070 } 1071 } 1072 } else { 1073 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1074 } 1075 } break; 1076 case UPDATED_MEDIA_STATUS: { 1077 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1078 boolean reportStatus = msg.arg1 == 1; 1079 boolean doGc = msg.arg2 == 1; 1080 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1081 if (doGc) { 1082 // Force a gc to clear up stale containers. 1083 Runtime.getRuntime().gc(); 1084 } 1085 if (msg.obj != null) { 1086 @SuppressWarnings("unchecked") 1087 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1088 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1089 // Unload containers 1090 unloadAllContainers(args); 1091 } 1092 if (reportStatus) { 1093 try { 1094 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1095 PackageHelper.getMountService().finishMediaUpdate(); 1096 } catch (RemoteException e) { 1097 Log.e(TAG, "MountService not running?"); 1098 } 1099 } 1100 } break; 1101 case WRITE_SETTINGS: { 1102 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1103 synchronized (mPackages) { 1104 removeMessages(WRITE_SETTINGS); 1105 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1106 mSettings.writeLPr(); 1107 mDirtyUsers.clear(); 1108 } 1109 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1110 } break; 1111 case WRITE_PACKAGE_RESTRICTIONS: { 1112 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1113 synchronized (mPackages) { 1114 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1115 for (int userId : mDirtyUsers) { 1116 mSettings.writePackageRestrictionsLPr(userId); 1117 } 1118 mDirtyUsers.clear(); 1119 } 1120 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1121 } break; 1122 case CHECK_PENDING_VERIFICATION: { 1123 final int verificationId = msg.arg1; 1124 final PackageVerificationState state = mPendingVerification.get(verificationId); 1125 1126 if ((state != null) && !state.timeoutExtended()) { 1127 final InstallArgs args = state.getInstallArgs(); 1128 final Uri originUri = Uri.fromFile(args.originFile); 1129 1130 Slog.i(TAG, "Verification timed out for " + originUri); 1131 mPendingVerification.remove(verificationId); 1132 1133 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1134 1135 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1136 Slog.i(TAG, "Continuing with installation of " + originUri); 1137 state.setVerifierResponse(Binder.getCallingUid(), 1138 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1139 broadcastPackageVerified(verificationId, originUri, 1140 PackageManager.VERIFICATION_ALLOW, 1141 state.getInstallArgs().getUser()); 1142 try { 1143 ret = args.copyApk(mContainerService, true); 1144 } catch (RemoteException e) { 1145 Slog.e(TAG, "Could not contact the ContainerService"); 1146 } 1147 } else { 1148 broadcastPackageVerified(verificationId, originUri, 1149 PackageManager.VERIFICATION_REJECT, 1150 state.getInstallArgs().getUser()); 1151 } 1152 1153 processPendingInstall(args, ret); 1154 mHandler.sendEmptyMessage(MCS_UNBIND); 1155 } 1156 break; 1157 } 1158 case PACKAGE_VERIFIED: { 1159 final int verificationId = msg.arg1; 1160 1161 final PackageVerificationState state = mPendingVerification.get(verificationId); 1162 if (state == null) { 1163 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1164 break; 1165 } 1166 1167 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1168 1169 state.setVerifierResponse(response.callerUid, response.code); 1170 1171 if (state.isVerificationComplete()) { 1172 mPendingVerification.remove(verificationId); 1173 1174 final InstallArgs args = state.getInstallArgs(); 1175 final Uri originUri = Uri.fromFile(args.originFile); 1176 1177 int ret; 1178 if (state.isInstallAllowed()) { 1179 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1180 broadcastPackageVerified(verificationId, originUri, 1181 response.code, state.getInstallArgs().getUser()); 1182 try { 1183 ret = args.copyApk(mContainerService, true); 1184 } catch (RemoteException e) { 1185 Slog.e(TAG, "Could not contact the ContainerService"); 1186 } 1187 } else { 1188 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1189 } 1190 1191 processPendingInstall(args, ret); 1192 1193 mHandler.sendEmptyMessage(MCS_UNBIND); 1194 } 1195 1196 break; 1197 } 1198 } 1199 } 1200 } 1201 1202 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1203 Bundle extras = null; 1204 switch (res.returnCode) { 1205 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1206 extras = new Bundle(); 1207 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1208 res.origPermission); 1209 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1210 res.origPackage); 1211 break; 1212 } 1213 } 1214 return extras; 1215 } 1216 1217 void scheduleWriteSettingsLocked() { 1218 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1219 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1220 } 1221 } 1222 1223 void scheduleWritePackageRestrictionsLocked(int userId) { 1224 if (!sUserManager.exists(userId)) return; 1225 mDirtyUsers.add(userId); 1226 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1227 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1228 } 1229 } 1230 1231 public static final PackageManagerService main(Context context, Installer installer, 1232 boolean factoryTest, boolean onlyCore) { 1233 PackageManagerService m = new PackageManagerService(context, installer, 1234 factoryTest, onlyCore); 1235 ServiceManager.addService("package", m); 1236 return m; 1237 } 1238 1239 static String[] splitString(String str, char sep) { 1240 int count = 1; 1241 int i = 0; 1242 while ((i=str.indexOf(sep, i)) >= 0) { 1243 count++; 1244 i++; 1245 } 1246 1247 String[] res = new String[count]; 1248 i=0; 1249 count = 0; 1250 int lastI=0; 1251 while ((i=str.indexOf(sep, i)) >= 0) { 1252 res[count] = str.substring(lastI, i); 1253 count++; 1254 i++; 1255 lastI = i; 1256 } 1257 res[count] = str.substring(lastI, str.length()); 1258 return res; 1259 } 1260 1261 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1262 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1263 Context.DISPLAY_SERVICE); 1264 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1265 } 1266 1267 public PackageManagerService(Context context, Installer installer, 1268 boolean factoryTest, boolean onlyCore) { 1269 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1270 SystemClock.uptimeMillis()); 1271 1272 if (mSdkVersion <= 0) { 1273 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1274 } 1275 1276 mContext = context; 1277 mFactoryTest = factoryTest; 1278 mOnlyCore = onlyCore; 1279 mMetrics = new DisplayMetrics(); 1280 mSettings = new Settings(context); 1281 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1282 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1283 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1284 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1285 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1286 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1287 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1288 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1289 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1290 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1291 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1292 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1293 1294 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1295 if (separateProcesses != null && separateProcesses.length() > 0) { 1296 if ("*".equals(separateProcesses)) { 1297 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1298 mSeparateProcesses = null; 1299 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1300 } else { 1301 mDefParseFlags = 0; 1302 mSeparateProcesses = separateProcesses.split(","); 1303 Slog.w(TAG, "Running with debug.separate_processes: " 1304 + separateProcesses); 1305 } 1306 } else { 1307 mDefParseFlags = 0; 1308 mSeparateProcesses = null; 1309 } 1310 1311 mInstaller = installer; 1312 1313 getDefaultDisplayMetrics(context, mMetrics); 1314 1315 SystemConfig systemConfig = SystemConfig.getInstance(); 1316 mGlobalGids = systemConfig.getGlobalGids(); 1317 mSystemPermissions = systemConfig.getSystemPermissions(); 1318 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1319 1320 synchronized (mInstallLock) { 1321 // writer 1322 synchronized (mPackages) { 1323 mHandlerThread = new ServiceThread(TAG, 1324 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1325 mHandlerThread.start(); 1326 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1327 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1328 1329 File dataDir = Environment.getDataDirectory(); 1330 mAppDataDir = new File(dataDir, "data"); 1331 mAppInstallDir = new File(dataDir, "app"); 1332 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1333 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1334 mUserAppDataDir = new File(dataDir, "user"); 1335 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1336 1337 sUserManager = new UserManagerService(context, this, 1338 mInstallLock, mPackages); 1339 1340 // Propagate permission configuration in to package manager. 1341 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1342 = systemConfig.getPermissions(); 1343 for (int i=0; i<permConfig.size(); i++) { 1344 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1345 BasePermission bp = mSettings.mPermissions.get(perm.name); 1346 if (bp == null) { 1347 bp = new BasePermission(perm.name, null, BasePermission.TYPE_BUILTIN); 1348 mSettings.mPermissions.put(perm.name, bp); 1349 } 1350 if (perm.gids != null) { 1351 bp.gids = appendInts(bp.gids, perm.gids); 1352 } 1353 } 1354 1355 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1356 for (int i=0; i<libConfig.size(); i++) { 1357 mSharedLibraries.put(libConfig.keyAt(i), 1358 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1359 } 1360 1361 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1362 1363 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1364 mSdkVersion, mOnlyCore); 1365 1366 String customResolverActivity = Resources.getSystem().getString( 1367 R.string.config_customResolverActivity); 1368 if (TextUtils.isEmpty(customResolverActivity)) { 1369 customResolverActivity = null; 1370 } else { 1371 mCustomResolverComponentName = ComponentName.unflattenFromString( 1372 customResolverActivity); 1373 } 1374 1375 long startTime = SystemClock.uptimeMillis(); 1376 1377 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1378 startTime); 1379 1380 // Set flag to monitor and not change apk file paths when 1381 // scanning install directories. 1382 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1383 1384 final HashSet<String> alreadyDexOpted = new HashSet<String>(); 1385 1386 /** 1387 * Add everything in the in the boot class path to the 1388 * list of process files because dexopt will have been run 1389 * if necessary during zygote startup. 1390 */ 1391 String bootClassPath = System.getProperty("java.boot.class.path"); 1392 if (bootClassPath != null) { 1393 String[] paths = splitString(bootClassPath, ':'); 1394 for (int i=0; i<paths.length; i++) { 1395 alreadyDexOpted.add(paths[i]); 1396 } 1397 } else { 1398 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1399 } 1400 1401 boolean didDexOptLibraryOrTool = false; 1402 1403 final List<String> instructionSets = getAllInstructionSets(); 1404 1405 /** 1406 * Ensure all external libraries have had dexopt run on them. 1407 */ 1408 if (mSharedLibraries.size() > 0) { 1409 // NOTE: For now, we're compiling these system "shared libraries" 1410 // (and framework jars) into all available architectures. It's possible 1411 // to compile them only when we come across an app that uses them (there's 1412 // already logic for that in scanPackageLI) but that adds some complexity. 1413 for (String instructionSet : instructionSets) { 1414 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1415 final String lib = libEntry.path; 1416 if (lib == null) { 1417 continue; 1418 } 1419 1420 try { 1421 if (DexFile.isDexOptNeededInternal(lib, null, instructionSet, false)) { 1422 alreadyDexOpted.add(lib); 1423 1424 // The list of "shared libraries" we have at this point is 1425 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, instructionSet); 1426 didDexOptLibraryOrTool = true; 1427 } 1428 } catch (FileNotFoundException e) { 1429 Slog.w(TAG, "Library not found: " + lib); 1430 } catch (IOException e) { 1431 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1432 + e.getMessage()); 1433 } 1434 } 1435 } 1436 } 1437 1438 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1439 1440 // Gross hack for now: we know this file doesn't contain any 1441 // code, so don't dexopt it to avoid the resulting log spew. 1442 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1443 1444 // Gross hack for now: we know this file is only part of 1445 // the boot class path for art, so don't dexopt it to 1446 // avoid the resulting log spew. 1447 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1448 1449 /** 1450 * And there are a number of commands implemented in Java, which 1451 * we currently need to do the dexopt on so that they can be 1452 * run from a non-root shell. 1453 */ 1454 String[] frameworkFiles = frameworkDir.list(); 1455 if (frameworkFiles != null) { 1456 // TODO: We could compile these only for the most preferred ABI. We should 1457 // first double check that the dex files for these commands are not referenced 1458 // by other system apps. 1459 for (String instructionSet : instructionSets) { 1460 for (int i=0; i<frameworkFiles.length; i++) { 1461 File libPath = new File(frameworkDir, frameworkFiles[i]); 1462 String path = libPath.getPath(); 1463 // Skip the file if we already did it. 1464 if (alreadyDexOpted.contains(path)) { 1465 continue; 1466 } 1467 // Skip the file if it is not a type we want to dexopt. 1468 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1469 continue; 1470 } 1471 try { 1472 if (DexFile.isDexOptNeededInternal(path, null, instructionSet, false)) { 1473 mInstaller.dexopt(path, Process.SYSTEM_UID, true, instructionSet); 1474 didDexOptLibraryOrTool = true; 1475 } 1476 } catch (FileNotFoundException e) { 1477 Slog.w(TAG, "Jar not found: " + path); 1478 } catch (IOException e) { 1479 Slog.w(TAG, "Exception reading jar: " + path, e); 1480 } 1481 } 1482 } 1483 } 1484 1485 if (didDexOptLibraryOrTool) { 1486 // If we dexopted a library or tool, then something on the system has 1487 // changed. Consider this significant, and wipe away all other 1488 // existing dexopt files to ensure we don't leave any dangling around. 1489 // 1490 // TODO: This should be revisited because it isn't as good an indicator 1491 // as it used to be. It used to include the boot classpath but at some point 1492 // DexFile.isDexOptNeeded started returning false for the boot 1493 // class path files in all cases. It is very possible in a 1494 // small maintenance release update that the library and tool 1495 // jars may be unchanged but APK could be removed resulting in 1496 // unused dalvik-cache files. 1497 for (String instructionSet : instructionSets) { 1498 mInstaller.pruneDexCache(instructionSet); 1499 } 1500 1501 // Additionally, delete all dex files from the root directory 1502 // since there shouldn't be any there anyway, unless we're upgrading 1503 // from an older OS version or a build that contained the "old" style 1504 // flat scheme. 1505 mInstaller.pruneDexCache("."); 1506 } 1507 1508 // Collect vendor overlay packages. 1509 // (Do this before scanning any apps.) 1510 // For security and version matching reason, only consider 1511 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1512 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1513 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1514 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode | SCAN_TRUSTED_OVERLAY, 0); 1515 1516 // Find base frameworks (resource packages without code). 1517 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1518 | PackageParser.PARSE_IS_SYSTEM_DIR 1519 | PackageParser.PARSE_IS_PRIVILEGED, 1520 scanMode | SCAN_NO_DEX, 0); 1521 1522 // Collected privileged system packages. 1523 File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1524 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1525 | PackageParser.PARSE_IS_SYSTEM_DIR 1526 | PackageParser.PARSE_IS_PRIVILEGED, scanMode, 0); 1527 1528 // Collect ordinary system packages. 1529 File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1530 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1531 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1532 1533 // Collect all vendor packages. 1534 File vendorAppDir = new File("/vendor/app"); 1535 try { 1536 vendorAppDir = vendorAppDir.getCanonicalFile(); 1537 } catch (IOException e) { 1538 // failed to look up canonical path, continue with original one 1539 } 1540 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1541 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1542 1543 // Collect all OEM packages. 1544 File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1545 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1546 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1547 1548 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1549 mInstaller.moveFiles(); 1550 1551 // Prune any system packages that no longer exist. 1552 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1553 if (!mOnlyCore) { 1554 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1555 while (psit.hasNext()) { 1556 PackageSetting ps = psit.next(); 1557 1558 /* 1559 * If this is not a system app, it can't be a 1560 * disable system app. 1561 */ 1562 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1563 continue; 1564 } 1565 1566 /* 1567 * If the package is scanned, it's not erased. 1568 */ 1569 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1570 if (scannedPkg != null) { 1571 /* 1572 * If the system app is both scanned and in the 1573 * disabled packages list, then it must have been 1574 * added via OTA. Remove it from the currently 1575 * scanned package so the previously user-installed 1576 * application can be scanned. 1577 */ 1578 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1579 Slog.i(TAG, "Expecting better updatd system app for " + ps.name 1580 + "; removing system app"); 1581 removePackageLI(ps, true); 1582 } 1583 1584 continue; 1585 } 1586 1587 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1588 psit.remove(); 1589 String msg = "System package " + ps.name 1590 + " no longer exists; wiping its data"; 1591 reportSettingsProblem(Log.WARN, msg); 1592 removeDataDirsLI(ps.name); 1593 } else { 1594 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1595 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1596 possiblyDeletedUpdatedSystemApps.add(ps.name); 1597 } 1598 } 1599 } 1600 } 1601 1602 //look for any incomplete package installations 1603 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1604 //clean up list 1605 for(int i = 0; i < deletePkgsList.size(); i++) { 1606 //clean up here 1607 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1608 } 1609 //delete tmp files 1610 deleteTempPackageFiles(); 1611 1612 // Remove any shared userIDs that have no associated packages 1613 mSettings.pruneSharedUsersLPw(); 1614 1615 if (!mOnlyCore) { 1616 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 1617 SystemClock.uptimeMillis()); 1618 scanDirLI(mAppInstallDir, 0, scanMode, 0); 1619 1620 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 1621 scanMode, 0); 1622 1623 /** 1624 * Remove disable package settings for any updated system 1625 * apps that were removed via an OTA. If they're not a 1626 * previously-updated app, remove them completely. 1627 * Otherwise, just revoke their system-level permissions. 1628 */ 1629 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 1630 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 1631 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 1632 1633 String msg; 1634 if (deletedPkg == null) { 1635 msg = "Updated system package " + deletedAppName 1636 + " no longer exists; wiping its data"; 1637 removeDataDirsLI(deletedAppName); 1638 } else { 1639 msg = "Updated system app + " + deletedAppName 1640 + " no longer present; removing system privileges for " 1641 + deletedAppName; 1642 1643 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 1644 1645 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 1646 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 1647 } 1648 reportSettingsProblem(Log.WARN, msg); 1649 } 1650 } 1651 1652 // Now that we know all of the shared libraries, update all clients to have 1653 // the correct library paths. 1654 updateAllSharedLibrariesLPw(); 1655 1656 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 1657 // NOTE: We ignore potential failures here during a system scan (like 1658 // the rest of the commands above) because there's precious little we 1659 // can do about it. A settings error is reported, though. 1660 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 1661 false /* force dexopt */, false /* defer dexopt */); 1662 } 1663 1664 // Now that we know all the packages we are keeping, 1665 // read and update their last usage times. 1666 mPackageUsage.readLP(); 1667 1668 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 1669 SystemClock.uptimeMillis()); 1670 Slog.i(TAG, "Time to scan packages: " 1671 + ((SystemClock.uptimeMillis()-startTime)/1000f) 1672 + " seconds"); 1673 1674 // If the platform SDK has changed since the last time we booted, 1675 // we need to re-grant app permission to catch any new ones that 1676 // appear. This is really a hack, and means that apps can in some 1677 // cases get permissions that the user didn't initially explicitly 1678 // allow... it would be nice to have some better way to handle 1679 // this situation. 1680 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 1681 != mSdkVersion; 1682 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 1683 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 1684 + "; regranting permissions for internal storage"); 1685 mSettings.mInternalSdkPlatform = mSdkVersion; 1686 1687 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 1688 | (regrantPermissions 1689 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 1690 : 0)); 1691 1692 // If this is the first boot, and it is a normal boot, then 1693 // we need to initialize the default preferred apps. 1694 if (!mRestoredSettings && !onlyCore) { 1695 mSettings.readDefaultPreferredAppsLPw(this, 0); 1696 } 1697 1698 // If this is first boot after an OTA, and a normal boot, then 1699 // we need to clear code cache directories. 1700 if (!Build.FINGERPRINT.equals(mSettings.mFingerprint) && !onlyCore) { 1701 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 1702 for (String pkgName : mSettings.mPackages.keySet()) { 1703 deleteCodeCacheDirsLI(pkgName); 1704 } 1705 mSettings.mFingerprint = Build.FINGERPRINT; 1706 } 1707 1708 // All the changes are done during package scanning. 1709 mSettings.updateInternalDatabaseVersion(); 1710 1711 // can downgrade to reader 1712 mSettings.writeLPr(); 1713 1714 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 1715 SystemClock.uptimeMillis()); 1716 1717 1718 mRequiredVerifierPackage = getRequiredVerifierLPr(); 1719 } // synchronized (mPackages) 1720 } // synchronized (mInstallLock) 1721 1722 mInstallerService = new PackageInstallerService(context, this, mAppInstallDir); 1723 1724 // Now after opening every single application zip, make sure they 1725 // are all flushed. Not really needed, but keeps things nice and 1726 // tidy. 1727 Runtime.getRuntime().gc(); 1728 } 1729 1730 @Override 1731 public boolean isFirstBoot() { 1732 return !mRestoredSettings; 1733 } 1734 1735 @Override 1736 public boolean isOnlyCoreApps() { 1737 return mOnlyCore; 1738 } 1739 1740 private String getRequiredVerifierLPr() { 1741 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 1742 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 1743 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 1744 1745 String requiredVerifier = null; 1746 1747 final int N = receivers.size(); 1748 for (int i = 0; i < N; i++) { 1749 final ResolveInfo info = receivers.get(i); 1750 1751 if (info.activityInfo == null) { 1752 continue; 1753 } 1754 1755 final String packageName = info.activityInfo.packageName; 1756 1757 final PackageSetting ps = mSettings.mPackages.get(packageName); 1758 if (ps == null) { 1759 continue; 1760 } 1761 1762 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1763 if (!gp.grantedPermissions 1764 .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) { 1765 continue; 1766 } 1767 1768 if (requiredVerifier != null) { 1769 throw new RuntimeException("There can be only one required verifier"); 1770 } 1771 1772 requiredVerifier = packageName; 1773 } 1774 1775 return requiredVerifier; 1776 } 1777 1778 @Override 1779 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 1780 throws RemoteException { 1781 try { 1782 return super.onTransact(code, data, reply, flags); 1783 } catch (RuntimeException e) { 1784 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 1785 Slog.wtf(TAG, "Package Manager Crash", e); 1786 } 1787 throw e; 1788 } 1789 } 1790 1791 void cleanupInstallFailedPackage(PackageSetting ps) { 1792 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name); 1793 removeDataDirsLI(ps.name); 1794 1795 // TODO: try cleaning up codePath directory contents first, since it 1796 // might be a cluster 1797 1798 if (ps.codePath != null) { 1799 if (!ps.codePath.delete()) { 1800 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath); 1801 } 1802 } 1803 if (ps.resourcePath != null) { 1804 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) { 1805 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath); 1806 } 1807 } 1808 mSettings.removePackageLPw(ps.name); 1809 } 1810 1811 static int[] appendInts(int[] cur, int[] add) { 1812 if (add == null) return cur; 1813 if (cur == null) return add; 1814 final int N = add.length; 1815 for (int i=0; i<N; i++) { 1816 cur = appendInt(cur, add[i]); 1817 } 1818 return cur; 1819 } 1820 1821 static int[] removeInts(int[] cur, int[] rem) { 1822 if (rem == null) return cur; 1823 if (cur == null) return cur; 1824 final int N = rem.length; 1825 for (int i=0; i<N; i++) { 1826 cur = removeInt(cur, rem[i]); 1827 } 1828 return cur; 1829 } 1830 1831 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 1832 if (!sUserManager.exists(userId)) return null; 1833 final PackageSetting ps = (PackageSetting) p.mExtras; 1834 if (ps == null) { 1835 return null; 1836 } 1837 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1838 final PackageUserState state = ps.readUserState(userId); 1839 return PackageParser.generatePackageInfo(p, gp.gids, flags, 1840 ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions, 1841 state, userId); 1842 } 1843 1844 @Override 1845 public boolean isPackageAvailable(String packageName, int userId) { 1846 if (!sUserManager.exists(userId)) return false; 1847 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available"); 1848 synchronized (mPackages) { 1849 PackageParser.Package p = mPackages.get(packageName); 1850 if (p != null) { 1851 final PackageSetting ps = (PackageSetting) p.mExtras; 1852 if (ps != null) { 1853 final PackageUserState state = ps.readUserState(userId); 1854 if (state != null) { 1855 return PackageParser.isAvailable(state); 1856 } 1857 } 1858 } 1859 } 1860 return false; 1861 } 1862 1863 @Override 1864 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 1865 if (!sUserManager.exists(userId)) return null; 1866 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info"); 1867 // reader 1868 synchronized (mPackages) { 1869 PackageParser.Package p = mPackages.get(packageName); 1870 if (DEBUG_PACKAGE_INFO) 1871 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 1872 if (p != null) { 1873 return generatePackageInfo(p, flags, userId); 1874 } 1875 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 1876 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 1877 } 1878 } 1879 return null; 1880 } 1881 1882 @Override 1883 public String[] currentToCanonicalPackageNames(String[] names) { 1884 String[] out = new String[names.length]; 1885 // reader 1886 synchronized (mPackages) { 1887 for (int i=names.length-1; i>=0; i--) { 1888 PackageSetting ps = mSettings.mPackages.get(names[i]); 1889 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 1890 } 1891 } 1892 return out; 1893 } 1894 1895 @Override 1896 public String[] canonicalToCurrentPackageNames(String[] names) { 1897 String[] out = new String[names.length]; 1898 // reader 1899 synchronized (mPackages) { 1900 for (int i=names.length-1; i>=0; i--) { 1901 String cur = mSettings.mRenamedPackages.get(names[i]); 1902 out[i] = cur != null ? cur : names[i]; 1903 } 1904 } 1905 return out; 1906 } 1907 1908 @Override 1909 public int getPackageUid(String packageName, int userId) { 1910 if (!sUserManager.exists(userId)) return -1; 1911 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid"); 1912 // reader 1913 synchronized (mPackages) { 1914 PackageParser.Package p = mPackages.get(packageName); 1915 if(p != null) { 1916 return UserHandle.getUid(userId, p.applicationInfo.uid); 1917 } 1918 PackageSetting ps = mSettings.mPackages.get(packageName); 1919 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 1920 return -1; 1921 } 1922 p = ps.pkg; 1923 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 1924 } 1925 } 1926 1927 @Override 1928 public int[] getPackageGids(String packageName) { 1929 // reader 1930 synchronized (mPackages) { 1931 PackageParser.Package p = mPackages.get(packageName); 1932 if (DEBUG_PACKAGE_INFO) 1933 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 1934 if (p != null) { 1935 final PackageSetting ps = (PackageSetting)p.mExtras; 1936 return ps.getGids(); 1937 } 1938 } 1939 // stupid thing to indicate an error. 1940 return new int[0]; 1941 } 1942 1943 static final PermissionInfo generatePermissionInfo( 1944 BasePermission bp, int flags) { 1945 if (bp.perm != null) { 1946 return PackageParser.generatePermissionInfo(bp.perm, flags); 1947 } 1948 PermissionInfo pi = new PermissionInfo(); 1949 pi.name = bp.name; 1950 pi.packageName = bp.sourcePackage; 1951 pi.nonLocalizedLabel = bp.name; 1952 pi.protectionLevel = bp.protectionLevel; 1953 return pi; 1954 } 1955 1956 @Override 1957 public PermissionInfo getPermissionInfo(String name, int flags) { 1958 // reader 1959 synchronized (mPackages) { 1960 final BasePermission p = mSettings.mPermissions.get(name); 1961 if (p != null) { 1962 return generatePermissionInfo(p, flags); 1963 } 1964 return null; 1965 } 1966 } 1967 1968 @Override 1969 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 1970 // reader 1971 synchronized (mPackages) { 1972 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 1973 for (BasePermission p : mSettings.mPermissions.values()) { 1974 if (group == null) { 1975 if (p.perm == null || p.perm.info.group == null) { 1976 out.add(generatePermissionInfo(p, flags)); 1977 } 1978 } else { 1979 if (p.perm != null && group.equals(p.perm.info.group)) { 1980 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 1981 } 1982 } 1983 } 1984 1985 if (out.size() > 0) { 1986 return out; 1987 } 1988 return mPermissionGroups.containsKey(group) ? out : null; 1989 } 1990 } 1991 1992 @Override 1993 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 1994 // reader 1995 synchronized (mPackages) { 1996 return PackageParser.generatePermissionGroupInfo( 1997 mPermissionGroups.get(name), flags); 1998 } 1999 } 2000 2001 @Override 2002 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2003 // reader 2004 synchronized (mPackages) { 2005 final int N = mPermissionGroups.size(); 2006 ArrayList<PermissionGroupInfo> out 2007 = new ArrayList<PermissionGroupInfo>(N); 2008 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2009 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2010 } 2011 return out; 2012 } 2013 } 2014 2015 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2016 int userId) { 2017 if (!sUserManager.exists(userId)) return null; 2018 PackageSetting ps = mSettings.mPackages.get(packageName); 2019 if (ps != null) { 2020 if (ps.pkg == null) { 2021 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2022 flags, userId); 2023 if (pInfo != null) { 2024 return pInfo.applicationInfo; 2025 } 2026 return null; 2027 } 2028 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2029 ps.readUserState(userId), userId); 2030 } 2031 return null; 2032 } 2033 2034 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2035 int userId) { 2036 if (!sUserManager.exists(userId)) return null; 2037 PackageSetting ps = mSettings.mPackages.get(packageName); 2038 if (ps != null) { 2039 PackageParser.Package pkg = ps.pkg; 2040 if (pkg == null) { 2041 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2042 return null; 2043 } 2044 // Only data remains, so we aren't worried about code paths 2045 pkg = new PackageParser.Package(packageName); 2046 pkg.applicationInfo.packageName = packageName; 2047 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2048 pkg.applicationInfo.dataDir = 2049 getDataPathForPackage(packageName, 0).getPath(); 2050 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2051 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2052 } 2053 return generatePackageInfo(pkg, flags, userId); 2054 } 2055 return null; 2056 } 2057 2058 @Override 2059 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2060 if (!sUserManager.exists(userId)) return null; 2061 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info"); 2062 // writer 2063 synchronized (mPackages) { 2064 PackageParser.Package p = mPackages.get(packageName); 2065 if (DEBUG_PACKAGE_INFO) Log.v( 2066 TAG, "getApplicationInfo " + packageName 2067 + ": " + p); 2068 if (p != null) { 2069 PackageSetting ps = mSettings.mPackages.get(packageName); 2070 if (ps == null) return null; 2071 // Note: isEnabledLP() does not apply here - always return info 2072 return PackageParser.generateApplicationInfo( 2073 p, flags, ps.readUserState(userId), userId); 2074 } 2075 if ("android".equals(packageName)||"system".equals(packageName)) { 2076 return mAndroidApplication; 2077 } 2078 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2079 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2080 } 2081 } 2082 return null; 2083 } 2084 2085 2086 @Override 2087 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2088 mContext.enforceCallingOrSelfPermission( 2089 android.Manifest.permission.CLEAR_APP_CACHE, null); 2090 // Queue up an async operation since clearing cache may take a little while. 2091 mHandler.post(new Runnable() { 2092 public void run() { 2093 mHandler.removeCallbacks(this); 2094 int retCode = -1; 2095 synchronized (mInstallLock) { 2096 retCode = mInstaller.freeCache(freeStorageSize); 2097 if (retCode < 0) { 2098 Slog.w(TAG, "Couldn't clear application caches"); 2099 } 2100 } 2101 if (observer != null) { 2102 try { 2103 observer.onRemoveCompleted(null, (retCode >= 0)); 2104 } catch (RemoteException e) { 2105 Slog.w(TAG, "RemoveException when invoking call back"); 2106 } 2107 } 2108 } 2109 }); 2110 } 2111 2112 @Override 2113 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2114 mContext.enforceCallingOrSelfPermission( 2115 android.Manifest.permission.CLEAR_APP_CACHE, null); 2116 // Queue up an async operation since clearing cache may take a little while. 2117 mHandler.post(new Runnable() { 2118 public void run() { 2119 mHandler.removeCallbacks(this); 2120 int retCode = -1; 2121 synchronized (mInstallLock) { 2122 retCode = mInstaller.freeCache(freeStorageSize); 2123 if (retCode < 0) { 2124 Slog.w(TAG, "Couldn't clear application caches"); 2125 } 2126 } 2127 if(pi != null) { 2128 try { 2129 // Callback via pending intent 2130 int code = (retCode >= 0) ? 1 : 0; 2131 pi.sendIntent(null, code, null, 2132 null, null); 2133 } catch (SendIntentException e1) { 2134 Slog.i(TAG, "Failed to send pending intent"); 2135 } 2136 } 2137 } 2138 }); 2139 } 2140 2141 void freeStorage(long freeStorageSize) throws IOException { 2142 synchronized (mInstallLock) { 2143 if (mInstaller.freeCache(freeStorageSize) < 0) { 2144 throw new IOException("Failed to free enough space"); 2145 } 2146 } 2147 } 2148 2149 @Override 2150 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2151 if (!sUserManager.exists(userId)) return null; 2152 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info"); 2153 synchronized (mPackages) { 2154 PackageParser.Activity a = mActivities.mActivities.get(component); 2155 2156 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2157 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2158 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2159 if (ps == null) return null; 2160 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2161 userId); 2162 } 2163 if (mResolveComponentName.equals(component)) { 2164 return mResolveActivity; 2165 } 2166 } 2167 return null; 2168 } 2169 2170 @Override 2171 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2172 String resolvedType) { 2173 synchronized (mPackages) { 2174 PackageParser.Activity a = mActivities.mActivities.get(component); 2175 if (a == null) { 2176 return false; 2177 } 2178 for (int i=0; i<a.intents.size(); i++) { 2179 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2180 intent.getData(), intent.getCategories(), TAG) >= 0) { 2181 return true; 2182 } 2183 } 2184 return false; 2185 } 2186 } 2187 2188 @Override 2189 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2190 if (!sUserManager.exists(userId)) return null; 2191 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info"); 2192 synchronized (mPackages) { 2193 PackageParser.Activity a = mReceivers.mActivities.get(component); 2194 if (DEBUG_PACKAGE_INFO) Log.v( 2195 TAG, "getReceiverInfo " + component + ": " + a); 2196 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2197 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2198 if (ps == null) return null; 2199 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2200 userId); 2201 } 2202 } 2203 return null; 2204 } 2205 2206 @Override 2207 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2208 if (!sUserManager.exists(userId)) return null; 2209 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info"); 2210 synchronized (mPackages) { 2211 PackageParser.Service s = mServices.mServices.get(component); 2212 if (DEBUG_PACKAGE_INFO) Log.v( 2213 TAG, "getServiceInfo " + component + ": " + s); 2214 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2215 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2216 if (ps == null) return null; 2217 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2218 userId); 2219 } 2220 } 2221 return null; 2222 } 2223 2224 @Override 2225 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2226 if (!sUserManager.exists(userId)) return null; 2227 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info"); 2228 synchronized (mPackages) { 2229 PackageParser.Provider p = mProviders.mProviders.get(component); 2230 if (DEBUG_PACKAGE_INFO) Log.v( 2231 TAG, "getProviderInfo " + component + ": " + p); 2232 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2233 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2234 if (ps == null) return null; 2235 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2236 userId); 2237 } 2238 } 2239 return null; 2240 } 2241 2242 @Override 2243 public String[] getSystemSharedLibraryNames() { 2244 Set<String> libSet; 2245 synchronized (mPackages) { 2246 libSet = mSharedLibraries.keySet(); 2247 int size = libSet.size(); 2248 if (size > 0) { 2249 String[] libs = new String[size]; 2250 libSet.toArray(libs); 2251 return libs; 2252 } 2253 } 2254 return null; 2255 } 2256 2257 @Override 2258 public FeatureInfo[] getSystemAvailableFeatures() { 2259 Collection<FeatureInfo> featSet; 2260 synchronized (mPackages) { 2261 featSet = mAvailableFeatures.values(); 2262 int size = featSet.size(); 2263 if (size > 0) { 2264 FeatureInfo[] features = new FeatureInfo[size+1]; 2265 featSet.toArray(features); 2266 FeatureInfo fi = new FeatureInfo(); 2267 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2268 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2269 features[size] = fi; 2270 return features; 2271 } 2272 } 2273 return null; 2274 } 2275 2276 @Override 2277 public boolean hasSystemFeature(String name) { 2278 synchronized (mPackages) { 2279 return mAvailableFeatures.containsKey(name); 2280 } 2281 } 2282 2283 private void checkValidCaller(int uid, int userId) { 2284 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2285 return; 2286 2287 throw new SecurityException("Caller uid=" + uid 2288 + " is not privileged to communicate with user=" + userId); 2289 } 2290 2291 @Override 2292 public int checkPermission(String permName, String pkgName) { 2293 synchronized (mPackages) { 2294 PackageParser.Package p = mPackages.get(pkgName); 2295 if (p != null && p.mExtras != null) { 2296 PackageSetting ps = (PackageSetting)p.mExtras; 2297 if (ps.sharedUser != null) { 2298 if (ps.sharedUser.grantedPermissions.contains(permName)) { 2299 return PackageManager.PERMISSION_GRANTED; 2300 } 2301 } else if (ps.grantedPermissions.contains(permName)) { 2302 return PackageManager.PERMISSION_GRANTED; 2303 } 2304 } 2305 } 2306 return PackageManager.PERMISSION_DENIED; 2307 } 2308 2309 @Override 2310 public int checkUidPermission(String permName, int uid) { 2311 synchronized (mPackages) { 2312 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2313 if (obj != null) { 2314 GrantedPermissions gp = (GrantedPermissions)obj; 2315 if (gp.grantedPermissions.contains(permName)) { 2316 return PackageManager.PERMISSION_GRANTED; 2317 } 2318 } else { 2319 HashSet<String> perms = mSystemPermissions.get(uid); 2320 if (perms != null && perms.contains(permName)) { 2321 return PackageManager.PERMISSION_GRANTED; 2322 } 2323 } 2324 } 2325 return PackageManager.PERMISSION_DENIED; 2326 } 2327 2328 /** 2329 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2330 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2331 * @param message the message to log on security exception 2332 */ 2333 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2334 String message) { 2335 if (userId < 0) { 2336 throw new IllegalArgumentException("Invalid userId " + userId); 2337 } 2338 if (userId == UserHandle.getUserId(callingUid)) return; 2339 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2340 if (requireFullPermission) { 2341 mContext.enforceCallingOrSelfPermission( 2342 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2343 } else { 2344 try { 2345 mContext.enforceCallingOrSelfPermission( 2346 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2347 } catch (SecurityException se) { 2348 mContext.enforceCallingOrSelfPermission( 2349 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2350 } 2351 } 2352 } 2353 } 2354 2355 private BasePermission findPermissionTreeLP(String permName) { 2356 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2357 if (permName.startsWith(bp.name) && 2358 permName.length() > bp.name.length() && 2359 permName.charAt(bp.name.length()) == '.') { 2360 return bp; 2361 } 2362 } 2363 return null; 2364 } 2365 2366 private BasePermission checkPermissionTreeLP(String permName) { 2367 if (permName != null) { 2368 BasePermission bp = findPermissionTreeLP(permName); 2369 if (bp != null) { 2370 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2371 return bp; 2372 } 2373 throw new SecurityException("Calling uid " 2374 + Binder.getCallingUid() 2375 + " is not allowed to add to permission tree " 2376 + bp.name + " owned by uid " + bp.uid); 2377 } 2378 } 2379 throw new SecurityException("No permission tree found for " + permName); 2380 } 2381 2382 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2383 if (s1 == null) { 2384 return s2 == null; 2385 } 2386 if (s2 == null) { 2387 return false; 2388 } 2389 if (s1.getClass() != s2.getClass()) { 2390 return false; 2391 } 2392 return s1.equals(s2); 2393 } 2394 2395 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2396 if (pi1.icon != pi2.icon) return false; 2397 if (pi1.logo != pi2.logo) return false; 2398 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2399 if (!compareStrings(pi1.name, pi2.name)) return false; 2400 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2401 // We'll take care of setting this one. 2402 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2403 // These are not currently stored in settings. 2404 //if (!compareStrings(pi1.group, pi2.group)) return false; 2405 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2406 //if (pi1.labelRes != pi2.labelRes) return false; 2407 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2408 return true; 2409 } 2410 2411 int permissionInfoFootprint(PermissionInfo info) { 2412 int size = info.name.length(); 2413 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2414 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2415 return size; 2416 } 2417 2418 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2419 int size = 0; 2420 for (BasePermission perm : mSettings.mPermissions.values()) { 2421 if (perm.uid == tree.uid) { 2422 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2423 } 2424 } 2425 return size; 2426 } 2427 2428 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2429 // We calculate the max size of permissions defined by this uid and throw 2430 // if that plus the size of 'info' would exceed our stated maximum. 2431 if (tree.uid != Process.SYSTEM_UID) { 2432 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2433 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2434 throw new SecurityException("Permission tree size cap exceeded"); 2435 } 2436 } 2437 } 2438 2439 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2440 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2441 throw new SecurityException("Label must be specified in permission"); 2442 } 2443 BasePermission tree = checkPermissionTreeLP(info.name); 2444 BasePermission bp = mSettings.mPermissions.get(info.name); 2445 boolean added = bp == null; 2446 boolean changed = true; 2447 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2448 if (added) { 2449 enforcePermissionCapLocked(info, tree); 2450 bp = new BasePermission(info.name, tree.sourcePackage, 2451 BasePermission.TYPE_DYNAMIC); 2452 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2453 throw new SecurityException( 2454 "Not allowed to modify non-dynamic permission " 2455 + info.name); 2456 } else { 2457 if (bp.protectionLevel == fixedLevel 2458 && bp.perm.owner.equals(tree.perm.owner) 2459 && bp.uid == tree.uid 2460 && comparePermissionInfos(bp.perm.info, info)) { 2461 changed = false; 2462 } 2463 } 2464 bp.protectionLevel = fixedLevel; 2465 info = new PermissionInfo(info); 2466 info.protectionLevel = fixedLevel; 2467 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 2468 bp.perm.info.packageName = tree.perm.info.packageName; 2469 bp.uid = tree.uid; 2470 if (added) { 2471 mSettings.mPermissions.put(info.name, bp); 2472 } 2473 if (changed) { 2474 if (!async) { 2475 mSettings.writeLPr(); 2476 } else { 2477 scheduleWriteSettingsLocked(); 2478 } 2479 } 2480 return added; 2481 } 2482 2483 @Override 2484 public boolean addPermission(PermissionInfo info) { 2485 synchronized (mPackages) { 2486 return addPermissionLocked(info, false); 2487 } 2488 } 2489 2490 @Override 2491 public boolean addPermissionAsync(PermissionInfo info) { 2492 synchronized (mPackages) { 2493 return addPermissionLocked(info, true); 2494 } 2495 } 2496 2497 @Override 2498 public void removePermission(String name) { 2499 synchronized (mPackages) { 2500 checkPermissionTreeLP(name); 2501 BasePermission bp = mSettings.mPermissions.get(name); 2502 if (bp != null) { 2503 if (bp.type != BasePermission.TYPE_DYNAMIC) { 2504 throw new SecurityException( 2505 "Not allowed to modify non-dynamic permission " 2506 + name); 2507 } 2508 mSettings.mPermissions.remove(name); 2509 mSettings.writeLPr(); 2510 } 2511 } 2512 } 2513 2514 private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) { 2515 int index = pkg.requestedPermissions.indexOf(bp.name); 2516 if (index == -1) { 2517 throw new SecurityException("Package " + pkg.packageName 2518 + " has not requested permission " + bp.name); 2519 } 2520 boolean isNormal = 2521 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2522 == PermissionInfo.PROTECTION_NORMAL); 2523 boolean isDangerous = 2524 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2525 == PermissionInfo.PROTECTION_DANGEROUS); 2526 boolean isDevelopment = 2527 ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0); 2528 2529 if (!isNormal && !isDangerous && !isDevelopment) { 2530 throw new SecurityException("Permission " + bp.name 2531 + " is not a changeable permission type"); 2532 } 2533 2534 if (isNormal || isDangerous) { 2535 if (pkg.requestedPermissionsRequired.get(index)) { 2536 throw new SecurityException("Can't change " + bp.name 2537 + ". It is required by the application"); 2538 } 2539 } 2540 } 2541 2542 @Override 2543 public void grantPermission(String packageName, String permissionName) { 2544 mContext.enforceCallingOrSelfPermission( 2545 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2546 synchronized (mPackages) { 2547 final PackageParser.Package pkg = mPackages.get(packageName); 2548 if (pkg == null) { 2549 throw new IllegalArgumentException("Unknown package: " + packageName); 2550 } 2551 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2552 if (bp == null) { 2553 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2554 } 2555 2556 checkGrantRevokePermissions(pkg, bp); 2557 2558 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2559 if (ps == null) { 2560 return; 2561 } 2562 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2563 if (gp.grantedPermissions.add(permissionName)) { 2564 if (ps.haveGids) { 2565 gp.gids = appendInts(gp.gids, bp.gids); 2566 } 2567 mSettings.writeLPr(); 2568 } 2569 } 2570 } 2571 2572 @Override 2573 public void revokePermission(String packageName, String permissionName) { 2574 int changedAppId = -1; 2575 2576 synchronized (mPackages) { 2577 final PackageParser.Package pkg = mPackages.get(packageName); 2578 if (pkg == null) { 2579 throw new IllegalArgumentException("Unknown package: " + packageName); 2580 } 2581 if (pkg.applicationInfo.uid != Binder.getCallingUid()) { 2582 mContext.enforceCallingOrSelfPermission( 2583 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2584 } 2585 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2586 if (bp == null) { 2587 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2588 } 2589 2590 checkGrantRevokePermissions(pkg, bp); 2591 2592 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2593 if (ps == null) { 2594 return; 2595 } 2596 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2597 if (gp.grantedPermissions.remove(permissionName)) { 2598 gp.grantedPermissions.remove(permissionName); 2599 if (ps.haveGids) { 2600 gp.gids = removeInts(gp.gids, bp.gids); 2601 } 2602 mSettings.writeLPr(); 2603 changedAppId = ps.appId; 2604 } 2605 } 2606 2607 if (changedAppId >= 0) { 2608 // We changed the perm on someone, kill its processes. 2609 IActivityManager am = ActivityManagerNative.getDefault(); 2610 if (am != null) { 2611 final int callingUserId = UserHandle.getCallingUserId(); 2612 final long ident = Binder.clearCallingIdentity(); 2613 try { 2614 //XXX we should only revoke for the calling user's app permissions, 2615 // but for now we impact all users. 2616 //am.killUid(UserHandle.getUid(callingUserId, changedAppId), 2617 // "revoke " + permissionName); 2618 int[] users = sUserManager.getUserIds(); 2619 for (int user : users) { 2620 am.killUid(UserHandle.getUid(user, changedAppId), 2621 "revoke " + permissionName); 2622 } 2623 } catch (RemoteException e) { 2624 } finally { 2625 Binder.restoreCallingIdentity(ident); 2626 } 2627 } 2628 } 2629 } 2630 2631 @Override 2632 public boolean isProtectedBroadcast(String actionName) { 2633 synchronized (mPackages) { 2634 return mProtectedBroadcasts.contains(actionName); 2635 } 2636 } 2637 2638 @Override 2639 public int checkSignatures(String pkg1, String pkg2) { 2640 synchronized (mPackages) { 2641 final PackageParser.Package p1 = mPackages.get(pkg1); 2642 final PackageParser.Package p2 = mPackages.get(pkg2); 2643 if (p1 == null || p1.mExtras == null 2644 || p2 == null || p2.mExtras == null) { 2645 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2646 } 2647 return compareSignatures(p1.mSignatures, p2.mSignatures); 2648 } 2649 } 2650 2651 @Override 2652 public int checkUidSignatures(int uid1, int uid2) { 2653 // Map to base uids. 2654 uid1 = UserHandle.getAppId(uid1); 2655 uid2 = UserHandle.getAppId(uid2); 2656 // reader 2657 synchronized (mPackages) { 2658 Signature[] s1; 2659 Signature[] s2; 2660 Object obj = mSettings.getUserIdLPr(uid1); 2661 if (obj != null) { 2662 if (obj instanceof SharedUserSetting) { 2663 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 2664 } else if (obj instanceof PackageSetting) { 2665 s1 = ((PackageSetting)obj).signatures.mSignatures; 2666 } else { 2667 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2668 } 2669 } else { 2670 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2671 } 2672 obj = mSettings.getUserIdLPr(uid2); 2673 if (obj != null) { 2674 if (obj instanceof SharedUserSetting) { 2675 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 2676 } else if (obj instanceof PackageSetting) { 2677 s2 = ((PackageSetting)obj).signatures.mSignatures; 2678 } else { 2679 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2680 } 2681 } else { 2682 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2683 } 2684 return compareSignatures(s1, s2); 2685 } 2686 } 2687 2688 /** 2689 * Compares two sets of signatures. Returns: 2690 * <br /> 2691 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 2692 * <br /> 2693 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 2694 * <br /> 2695 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 2696 * <br /> 2697 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 2698 * <br /> 2699 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 2700 */ 2701 static int compareSignatures(Signature[] s1, Signature[] s2) { 2702 if (s1 == null) { 2703 return s2 == null 2704 ? PackageManager.SIGNATURE_NEITHER_SIGNED 2705 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 2706 } 2707 2708 if (s2 == null) { 2709 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 2710 } 2711 2712 if (s1.length != s2.length) { 2713 return PackageManager.SIGNATURE_NO_MATCH; 2714 } 2715 2716 // Since both signature sets are of size 1, we can compare without HashSets. 2717 if (s1.length == 1) { 2718 return s1[0].equals(s2[0]) ? 2719 PackageManager.SIGNATURE_MATCH : 2720 PackageManager.SIGNATURE_NO_MATCH; 2721 } 2722 2723 HashSet<Signature> set1 = new HashSet<Signature>(); 2724 for (Signature sig : s1) { 2725 set1.add(sig); 2726 } 2727 HashSet<Signature> set2 = new HashSet<Signature>(); 2728 for (Signature sig : s2) { 2729 set2.add(sig); 2730 } 2731 // Make sure s2 contains all signatures in s1. 2732 if (set1.equals(set2)) { 2733 return PackageManager.SIGNATURE_MATCH; 2734 } 2735 return PackageManager.SIGNATURE_NO_MATCH; 2736 } 2737 2738 /** 2739 * If the database version for this type of package (internal storage or 2740 * external storage) is less than the version where package signatures 2741 * were updated, return true. 2742 */ 2743 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2744 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 2745 DatabaseVersion.SIGNATURE_END_ENTITY)) 2746 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 2747 DatabaseVersion.SIGNATURE_END_ENTITY)); 2748 } 2749 2750 /** 2751 * Used for backward compatibility to make sure any packages with 2752 * certificate chains get upgraded to the new style. {@code existingSigs} 2753 * will be in the old format (since they were stored on disk from before the 2754 * system upgrade) and {@code scannedSigs} will be in the newer format. 2755 */ 2756 private int compareSignaturesCompat(PackageSignatures existingSigs, 2757 PackageParser.Package scannedPkg) { 2758 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 2759 return PackageManager.SIGNATURE_NO_MATCH; 2760 } 2761 2762 HashSet<Signature> existingSet = new HashSet<Signature>(); 2763 for (Signature sig : existingSigs.mSignatures) { 2764 existingSet.add(sig); 2765 } 2766 HashSet<Signature> scannedCompatSet = new HashSet<Signature>(); 2767 for (Signature sig : scannedPkg.mSignatures) { 2768 try { 2769 Signature[] chainSignatures = sig.getChainSignatures(); 2770 for (Signature chainSig : chainSignatures) { 2771 scannedCompatSet.add(chainSig); 2772 } 2773 } catch (CertificateEncodingException e) { 2774 scannedCompatSet.add(sig); 2775 } 2776 } 2777 /* 2778 * Make sure the expanded scanned set contains all signatures in the 2779 * existing one. 2780 */ 2781 if (scannedCompatSet.equals(existingSet)) { 2782 // Migrate the old signatures to the new scheme. 2783 existingSigs.assignSignatures(scannedPkg.mSignatures); 2784 // The new KeySets will be re-added later in the scanning process. 2785 synchronized (mPackages) { 2786 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 2787 } 2788 return PackageManager.SIGNATURE_MATCH; 2789 } 2790 return PackageManager.SIGNATURE_NO_MATCH; 2791 } 2792 2793 @Override 2794 public String[] getPackagesForUid(int uid) { 2795 uid = UserHandle.getAppId(uid); 2796 // reader 2797 synchronized (mPackages) { 2798 Object obj = mSettings.getUserIdLPr(uid); 2799 if (obj instanceof SharedUserSetting) { 2800 final SharedUserSetting sus = (SharedUserSetting) obj; 2801 final int N = sus.packages.size(); 2802 final String[] res = new String[N]; 2803 final Iterator<PackageSetting> it = sus.packages.iterator(); 2804 int i = 0; 2805 while (it.hasNext()) { 2806 res[i++] = it.next().name; 2807 } 2808 return res; 2809 } else if (obj instanceof PackageSetting) { 2810 final PackageSetting ps = (PackageSetting) obj; 2811 return new String[] { ps.name }; 2812 } 2813 } 2814 return null; 2815 } 2816 2817 @Override 2818 public String getNameForUid(int uid) { 2819 // reader 2820 synchronized (mPackages) { 2821 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2822 if (obj instanceof SharedUserSetting) { 2823 final SharedUserSetting sus = (SharedUserSetting) obj; 2824 return sus.name + ":" + sus.userId; 2825 } else if (obj instanceof PackageSetting) { 2826 final PackageSetting ps = (PackageSetting) obj; 2827 return ps.name; 2828 } 2829 } 2830 return null; 2831 } 2832 2833 @Override 2834 public int getUidForSharedUser(String sharedUserName) { 2835 if(sharedUserName == null) { 2836 return -1; 2837 } 2838 // reader 2839 synchronized (mPackages) { 2840 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false); 2841 if (suid == null) { 2842 return -1; 2843 } 2844 return suid.userId; 2845 } 2846 } 2847 2848 @Override 2849 public int getFlagsForUid(int uid) { 2850 synchronized (mPackages) { 2851 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2852 if (obj instanceof SharedUserSetting) { 2853 final SharedUserSetting sus = (SharedUserSetting) obj; 2854 return sus.pkgFlags; 2855 } else if (obj instanceof PackageSetting) { 2856 final PackageSetting ps = (PackageSetting) obj; 2857 return ps.pkgFlags; 2858 } 2859 } 2860 return 0; 2861 } 2862 2863 @Override 2864 public String[] getAppOpPermissionPackages(String permissionName) { 2865 synchronized (mPackages) { 2866 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 2867 if (pkgs == null) { 2868 return null; 2869 } 2870 return pkgs.toArray(new String[pkgs.size()]); 2871 } 2872 } 2873 2874 @Override 2875 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 2876 int flags, int userId) { 2877 if (!sUserManager.exists(userId)) return null; 2878 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent"); 2879 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2880 return chooseBestActivity(intent, resolvedType, flags, query, userId); 2881 } 2882 2883 @Override 2884 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 2885 IntentFilter filter, int match, ComponentName activity) { 2886 final int userId = UserHandle.getCallingUserId(); 2887 if (DEBUG_PREFERRED) { 2888 Log.v(TAG, "setLastChosenActivity intent=" + intent 2889 + " resolvedType=" + resolvedType 2890 + " flags=" + flags 2891 + " filter=" + filter 2892 + " match=" + match 2893 + " activity=" + activity); 2894 filter.dump(new PrintStreamPrinter(System.out), " "); 2895 } 2896 intent.setComponent(null); 2897 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2898 // Find any earlier preferred or last chosen entries and nuke them 2899 findPreferredActivity(intent, resolvedType, 2900 flags, query, 0, false, true, false, userId); 2901 // Add the new activity as the last chosen for this filter 2902 addPreferredActivityInternal(filter, match, null, activity, false, userId); 2903 } 2904 2905 @Override 2906 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 2907 final int userId = UserHandle.getCallingUserId(); 2908 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 2909 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2910 return findPreferredActivity(intent, resolvedType, flags, query, 0, 2911 false, false, false, userId); 2912 } 2913 2914 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 2915 int flags, List<ResolveInfo> query, int userId) { 2916 if (query != null) { 2917 final int N = query.size(); 2918 if (N == 1) { 2919 return query.get(0); 2920 } else if (N > 1) { 2921 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 2922 // If there is more than one activity with the same priority, 2923 // then let the user decide between them. 2924 ResolveInfo r0 = query.get(0); 2925 ResolveInfo r1 = query.get(1); 2926 if (DEBUG_INTENT_MATCHING || debug) { 2927 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 2928 + r1.activityInfo.name + "=" + r1.priority); 2929 } 2930 // If the first activity has a higher priority, or a different 2931 // default, then it is always desireable to pick it. 2932 if (r0.priority != r1.priority 2933 || r0.preferredOrder != r1.preferredOrder 2934 || r0.isDefault != r1.isDefault) { 2935 return query.get(0); 2936 } 2937 // If we have saved a preference for a preferred activity for 2938 // this Intent, use that. 2939 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 2940 flags, query, r0.priority, true, false, debug, userId); 2941 if (ri != null) { 2942 return ri; 2943 } 2944 if (userId != 0) { 2945 ri = new ResolveInfo(mResolveInfo); 2946 ri.activityInfo = new ActivityInfo(ri.activityInfo); 2947 ri.activityInfo.applicationInfo = new ApplicationInfo( 2948 ri.activityInfo.applicationInfo); 2949 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 2950 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 2951 return ri; 2952 } 2953 return mResolveInfo; 2954 } 2955 } 2956 return null; 2957 } 2958 2959 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 2960 int flags, List<ResolveInfo> query, boolean debug, int userId) { 2961 final int N = query.size(); 2962 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 2963 .get(userId); 2964 // Get the list of persistent preferred activities that handle the intent 2965 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 2966 List<PersistentPreferredActivity> pprefs = ppir != null 2967 ? ppir.queryIntent(intent, resolvedType, 2968 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 2969 : null; 2970 if (pprefs != null && pprefs.size() > 0) { 2971 final int M = pprefs.size(); 2972 for (int i=0; i<M; i++) { 2973 final PersistentPreferredActivity ppa = pprefs.get(i); 2974 if (DEBUG_PREFERRED || debug) { 2975 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 2976 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 2977 + "\n component=" + ppa.mComponent); 2978 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 2979 } 2980 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 2981 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 2982 if (DEBUG_PREFERRED || debug) { 2983 Slog.v(TAG, "Found persistent preferred activity:"); 2984 if (ai != null) { 2985 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 2986 } else { 2987 Slog.v(TAG, " null"); 2988 } 2989 } 2990 if (ai == null) { 2991 // This previously registered persistent preferred activity 2992 // component is no longer known. Ignore it and do NOT remove it. 2993 continue; 2994 } 2995 for (int j=0; j<N; j++) { 2996 final ResolveInfo ri = query.get(j); 2997 if (!ri.activityInfo.applicationInfo.packageName 2998 .equals(ai.applicationInfo.packageName)) { 2999 continue; 3000 } 3001 if (!ri.activityInfo.name.equals(ai.name)) { 3002 continue; 3003 } 3004 // Found a persistent preference that can handle the intent. 3005 if (DEBUG_PREFERRED || debug) { 3006 Slog.v(TAG, "Returning persistent preferred activity: " + 3007 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3008 } 3009 return ri; 3010 } 3011 } 3012 } 3013 return null; 3014 } 3015 3016 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3017 List<ResolveInfo> query, int priority, boolean always, 3018 boolean removeMatches, boolean debug, int userId) { 3019 if (!sUserManager.exists(userId)) return null; 3020 // writer 3021 synchronized (mPackages) { 3022 if (intent.getSelector() != null) { 3023 intent = intent.getSelector(); 3024 } 3025 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3026 3027 // Try to find a matching persistent preferred activity. 3028 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3029 debug, userId); 3030 3031 // If a persistent preferred activity matched, use it. 3032 if (pri != null) { 3033 return pri; 3034 } 3035 3036 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3037 // Get the list of preferred activities that handle the intent 3038 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3039 List<PreferredActivity> prefs = pir != null 3040 ? pir.queryIntent(intent, resolvedType, 3041 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3042 : null; 3043 if (prefs != null && prefs.size() > 0) { 3044 // First figure out how good the original match set is. 3045 // We will only allow preferred activities that came 3046 // from the same match quality. 3047 int match = 0; 3048 3049 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3050 3051 final int N = query.size(); 3052 for (int j=0; j<N; j++) { 3053 final ResolveInfo ri = query.get(j); 3054 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3055 + ": 0x" + Integer.toHexString(match)); 3056 if (ri.match > match) { 3057 match = ri.match; 3058 } 3059 } 3060 3061 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3062 + Integer.toHexString(match)); 3063 3064 match &= IntentFilter.MATCH_CATEGORY_MASK; 3065 final int M = prefs.size(); 3066 for (int i=0; i<M; i++) { 3067 final PreferredActivity pa = prefs.get(i); 3068 if (DEBUG_PREFERRED || debug) { 3069 Slog.v(TAG, "Checking PreferredActivity ds=" 3070 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3071 + "\n component=" + pa.mPref.mComponent); 3072 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3073 } 3074 if (pa.mPref.mMatch != match) { 3075 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3076 + Integer.toHexString(pa.mPref.mMatch)); 3077 continue; 3078 } 3079 // If it's not an "always" type preferred activity and that's what we're 3080 // looking for, skip it. 3081 if (always && !pa.mPref.mAlways) { 3082 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3083 continue; 3084 } 3085 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3086 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3087 if (DEBUG_PREFERRED || debug) { 3088 Slog.v(TAG, "Found preferred activity:"); 3089 if (ai != null) { 3090 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3091 } else { 3092 Slog.v(TAG, " null"); 3093 } 3094 } 3095 if (ai == null) { 3096 // This previously registered preferred activity 3097 // component is no longer known. Most likely an update 3098 // to the app was installed and in the new version this 3099 // component no longer exists. Clean it up by removing 3100 // it from the preferred activities list, and skip it. 3101 Slog.w(TAG, "Removing dangling preferred activity: " 3102 + pa.mPref.mComponent); 3103 pir.removeFilter(pa); 3104 continue; 3105 } 3106 for (int j=0; j<N; j++) { 3107 final ResolveInfo ri = query.get(j); 3108 if (!ri.activityInfo.applicationInfo.packageName 3109 .equals(ai.applicationInfo.packageName)) { 3110 continue; 3111 } 3112 if (!ri.activityInfo.name.equals(ai.name)) { 3113 continue; 3114 } 3115 3116 if (removeMatches) { 3117 pir.removeFilter(pa); 3118 if (DEBUG_PREFERRED) { 3119 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3120 } 3121 break; 3122 } 3123 3124 // Okay we found a previously set preferred or last chosen app. 3125 // If the result set is different from when this 3126 // was created, we need to clear it and re-ask the 3127 // user their preference, if we're looking for an "always" type entry. 3128 if (always && !pa.mPref.sameSet(query, priority)) { 3129 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3130 + intent + " type " + resolvedType); 3131 if (DEBUG_PREFERRED) { 3132 Slog.v(TAG, "Removing preferred activity since set changed " 3133 + pa.mPref.mComponent); 3134 } 3135 pir.removeFilter(pa); 3136 // Re-add the filter as a "last chosen" entry (!always) 3137 PreferredActivity lastChosen = new PreferredActivity( 3138 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3139 pir.addFilter(lastChosen); 3140 mSettings.writePackageRestrictionsLPr(userId); 3141 return null; 3142 } 3143 3144 // Yay! Either the set matched or we're looking for the last chosen 3145 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3146 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3147 mSettings.writePackageRestrictionsLPr(userId); 3148 return ri; 3149 } 3150 } 3151 } 3152 mSettings.writePackageRestrictionsLPr(userId); 3153 } 3154 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3155 return null; 3156 } 3157 3158 /* 3159 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3160 */ 3161 @Override 3162 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3163 int targetUserId) { 3164 mContext.enforceCallingOrSelfPermission( 3165 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3166 List<CrossProfileIntentFilter> matches = 3167 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3168 if (matches != null) { 3169 int size = matches.size(); 3170 for (int i = 0; i < size; i++) { 3171 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3172 } 3173 } 3174 3175 ArrayList<String> packageNames = null; 3176 SparseArray<ArrayList<String>> fromSource = 3177 mSettings.mCrossProfilePackageInfo.get(sourceUserId); 3178 if (fromSource != null) { 3179 packageNames = fromSource.get(targetUserId); 3180 } 3181 if (packageNames.contains(intent.getPackage())) { 3182 return true; 3183 } 3184 // We need the package name, so we try to resolve with the loosest flags possible 3185 List<ResolveInfo> resolveInfos = mActivities.queryIntent( 3186 intent, resolvedType, PackageManager.GET_UNINSTALLED_PACKAGES, targetUserId); 3187 int count = resolveInfos.size(); 3188 for (int i = 0; i < count; i++) { 3189 ResolveInfo resolveInfo = resolveInfos.get(i); 3190 if (packageNames.contains(resolveInfo.activityInfo.packageName)) { 3191 return true; 3192 } 3193 } 3194 return false; 3195 } 3196 3197 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3198 String resolvedType, int userId) { 3199 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3200 if (resolver != null) { 3201 return resolver.queryIntent(intent, resolvedType, false, userId); 3202 } 3203 return null; 3204 } 3205 3206 @Override 3207 public List<ResolveInfo> queryIntentActivities(Intent intent, 3208 String resolvedType, int flags, int userId) { 3209 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3210 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities"); 3211 ComponentName comp = intent.getComponent(); 3212 if (comp == null) { 3213 if (intent.getSelector() != null) { 3214 intent = intent.getSelector(); 3215 comp = intent.getComponent(); 3216 } 3217 } 3218 3219 if (comp != null) { 3220 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3221 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3222 if (ai != null) { 3223 final ResolveInfo ri = new ResolveInfo(); 3224 ri.activityInfo = ai; 3225 list.add(ri); 3226 } 3227 return list; 3228 } 3229 3230 // reader 3231 synchronized (mPackages) { 3232 final String pkgName = intent.getPackage(); 3233 boolean queryCrossProfile = (flags & PackageManager.NO_CROSS_PROFILE) == 0; 3234 if (pkgName == null) { 3235 ResolveInfo resolveInfo = null; 3236 if (queryCrossProfile) { 3237 // Check if the intent needs to be forwarded to another user for this package 3238 ArrayList<ResolveInfo> crossProfileResult = 3239 queryIntentActivitiesCrossProfilePackage( 3240 intent, resolvedType, flags, userId); 3241 if (!crossProfileResult.isEmpty()) { 3242 // Skip the current profile 3243 return crossProfileResult; 3244 } 3245 List<CrossProfileIntentFilter> matchingFilters = 3246 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3247 // Check for results that need to skip the current profile. 3248 resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3249 resolvedType, flags, userId); 3250 if (resolveInfo != null) { 3251 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3252 result.add(resolveInfo); 3253 return result; 3254 } 3255 // Check for cross profile results. 3256 resolveInfo = queryCrossProfileIntents( 3257 matchingFilters, intent, resolvedType, flags, userId); 3258 } 3259 // Check for results in the current profile. 3260 List<ResolveInfo> result = mActivities.queryIntent( 3261 intent, resolvedType, flags, userId); 3262 if (resolveInfo != null) { 3263 result.add(resolveInfo); 3264 } 3265 return result; 3266 } 3267 final PackageParser.Package pkg = mPackages.get(pkgName); 3268 if (pkg != null) { 3269 if (queryCrossProfile) { 3270 ArrayList<ResolveInfo> crossProfileResult = 3271 queryIntentActivitiesCrossProfilePackage( 3272 intent, resolvedType, flags, userId, pkg, pkgName); 3273 if (!crossProfileResult.isEmpty()) { 3274 // Skip the current profile 3275 return crossProfileResult; 3276 } 3277 } 3278 return mActivities.queryIntentForPackage(intent, resolvedType, flags, 3279 pkg.activities, userId); 3280 } 3281 return new ArrayList<ResolveInfo>(); 3282 } 3283 } 3284 3285 private ResolveInfo querySkipCurrentProfileIntents( 3286 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3287 int flags, int sourceUserId) { 3288 if (matchingFilters != null) { 3289 int size = matchingFilters.size(); 3290 for (int i = 0; i < size; i ++) { 3291 CrossProfileIntentFilter filter = matchingFilters.get(i); 3292 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 3293 // Checking if there are activities in the target user that can handle the 3294 // intent. 3295 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3296 flags, sourceUserId); 3297 if (resolveInfo != null) { 3298 return resolveInfo; 3299 } 3300 } 3301 } 3302 } 3303 return null; 3304 } 3305 3306 private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage( 3307 Intent intent, String resolvedType, int flags, int userId) { 3308 ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>(); 3309 SparseArray<ArrayList<String>> sourceForwardingInfo = 3310 mSettings.mCrossProfilePackageInfo.get(userId); 3311 if (sourceForwardingInfo != null) { 3312 int NI = sourceForwardingInfo.size(); 3313 for (int i = 0; i < NI; i++) { 3314 int targetUserId = sourceForwardingInfo.keyAt(i); 3315 ArrayList<String> packageNames = sourceForwardingInfo.valueAt(i); 3316 List<ResolveInfo> resolveInfos = mActivities.queryIntent( 3317 intent, resolvedType, flags, targetUserId); 3318 int NJ = resolveInfos.size(); 3319 for (int j = 0; j < NJ; j++) { 3320 ResolveInfo resolveInfo = resolveInfos.get(j); 3321 if (packageNames.contains(resolveInfo.activityInfo.packageName)) { 3322 matchingResolveInfos.add(createForwardingResolveInfo( 3323 resolveInfo.filter, userId, targetUserId)); 3324 } 3325 } 3326 } 3327 } 3328 return matchingResolveInfos; 3329 } 3330 3331 private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage( 3332 Intent intent, String resolvedType, int flags, int userId, PackageParser.Package pkg, 3333 String packageName) { 3334 ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>(); 3335 SparseArray<ArrayList<String>> sourceForwardingInfo = 3336 mSettings.mCrossProfilePackageInfo.get(userId); 3337 if (sourceForwardingInfo != null) { 3338 int NI = sourceForwardingInfo.size(); 3339 for (int i = 0; i < NI; i++) { 3340 int targetUserId = sourceForwardingInfo.keyAt(i); 3341 if (sourceForwardingInfo.valueAt(i).contains(packageName)) { 3342 List<ResolveInfo> resolveInfos = mActivities.queryIntentForPackage( 3343 intent, resolvedType, flags, pkg.activities, targetUserId); 3344 int NJ = resolveInfos.size(); 3345 for (int j = 0; j < NJ; j++) { 3346 ResolveInfo resolveInfo = resolveInfos.get(j); 3347 matchingResolveInfos.add(createForwardingResolveInfo( 3348 resolveInfo.filter, userId, targetUserId)); 3349 } 3350 } 3351 } 3352 } 3353 return matchingResolveInfos; 3354 } 3355 3356 // Return matching ResolveInfo if any for skip current profile intent filters. 3357 private ResolveInfo queryCrossProfileIntents( 3358 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3359 int flags, int sourceUserId) { 3360 if (matchingFilters != null) { 3361 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 3362 // match the same intent. For performance reasons, it is better not to 3363 // run queryIntent twice for the same userId 3364 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 3365 int size = matchingFilters.size(); 3366 for (int i = 0; i < size; i++) { 3367 CrossProfileIntentFilter filter = matchingFilters.get(i); 3368 int targetUserId = filter.getTargetUserId(); 3369 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 3370 && !alreadyTriedUserIds.get(targetUserId)) { 3371 // Checking if there are activities in the target user that can handle the 3372 // intent. 3373 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3374 flags, sourceUserId); 3375 if (resolveInfo != null) return resolveInfo; 3376 alreadyTriedUserIds.put(targetUserId, true); 3377 } 3378 } 3379 } 3380 return null; 3381 } 3382 3383 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 3384 String resolvedType, int flags, int sourceUserId) { 3385 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 3386 resolvedType, flags, filter.getTargetUserId()); 3387 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 3388 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 3389 } 3390 return null; 3391 } 3392 3393 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 3394 int sourceUserId, int targetUserId) { 3395 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 3396 String className; 3397 if (targetUserId == UserHandle.USER_OWNER) { 3398 className = FORWARD_INTENT_TO_USER_OWNER; 3399 } else { 3400 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 3401 } 3402 ComponentName forwardingActivityComponentName = new ComponentName( 3403 mAndroidApplication.packageName, className); 3404 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 3405 sourceUserId); 3406 if (targetUserId == UserHandle.USER_OWNER) { 3407 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 3408 forwardingResolveInfo.noResourceId = true; 3409 } 3410 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 3411 forwardingResolveInfo.priority = 0; 3412 forwardingResolveInfo.preferredOrder = 0; 3413 forwardingResolveInfo.match = 0; 3414 forwardingResolveInfo.isDefault = true; 3415 forwardingResolveInfo.filter = filter; 3416 forwardingResolveInfo.targetUserId = targetUserId; 3417 return forwardingResolveInfo; 3418 } 3419 3420 @Override 3421 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 3422 Intent[] specifics, String[] specificTypes, Intent intent, 3423 String resolvedType, int flags, int userId) { 3424 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3425 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 3426 "query intent activity options"); 3427 final String resultsAction = intent.getAction(); 3428 3429 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 3430 | PackageManager.GET_RESOLVED_FILTER, userId); 3431 3432 if (DEBUG_INTENT_MATCHING) { 3433 Log.v(TAG, "Query " + intent + ": " + results); 3434 } 3435 3436 int specificsPos = 0; 3437 int N; 3438 3439 // todo: note that the algorithm used here is O(N^2). This 3440 // isn't a problem in our current environment, but if we start running 3441 // into situations where we have more than 5 or 10 matches then this 3442 // should probably be changed to something smarter... 3443 3444 // First we go through and resolve each of the specific items 3445 // that were supplied, taking care of removing any corresponding 3446 // duplicate items in the generic resolve list. 3447 if (specifics != null) { 3448 for (int i=0; i<specifics.length; i++) { 3449 final Intent sintent = specifics[i]; 3450 if (sintent == null) { 3451 continue; 3452 } 3453 3454 if (DEBUG_INTENT_MATCHING) { 3455 Log.v(TAG, "Specific #" + i + ": " + sintent); 3456 } 3457 3458 String action = sintent.getAction(); 3459 if (resultsAction != null && resultsAction.equals(action)) { 3460 // If this action was explicitly requested, then don't 3461 // remove things that have it. 3462 action = null; 3463 } 3464 3465 ResolveInfo ri = null; 3466 ActivityInfo ai = null; 3467 3468 ComponentName comp = sintent.getComponent(); 3469 if (comp == null) { 3470 ri = resolveIntent( 3471 sintent, 3472 specificTypes != null ? specificTypes[i] : null, 3473 flags, userId); 3474 if (ri == null) { 3475 continue; 3476 } 3477 if (ri == mResolveInfo) { 3478 // ACK! Must do something better with this. 3479 } 3480 ai = ri.activityInfo; 3481 comp = new ComponentName(ai.applicationInfo.packageName, 3482 ai.name); 3483 } else { 3484 ai = getActivityInfo(comp, flags, userId); 3485 if (ai == null) { 3486 continue; 3487 } 3488 } 3489 3490 // Look for any generic query activities that are duplicates 3491 // of this specific one, and remove them from the results. 3492 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 3493 N = results.size(); 3494 int j; 3495 for (j=specificsPos; j<N; j++) { 3496 ResolveInfo sri = results.get(j); 3497 if ((sri.activityInfo.name.equals(comp.getClassName()) 3498 && sri.activityInfo.applicationInfo.packageName.equals( 3499 comp.getPackageName())) 3500 || (action != null && sri.filter.matchAction(action))) { 3501 results.remove(j); 3502 if (DEBUG_INTENT_MATCHING) Log.v( 3503 TAG, "Removing duplicate item from " + j 3504 + " due to specific " + specificsPos); 3505 if (ri == null) { 3506 ri = sri; 3507 } 3508 j--; 3509 N--; 3510 } 3511 } 3512 3513 // Add this specific item to its proper place. 3514 if (ri == null) { 3515 ri = new ResolveInfo(); 3516 ri.activityInfo = ai; 3517 } 3518 results.add(specificsPos, ri); 3519 ri.specificIndex = i; 3520 specificsPos++; 3521 } 3522 } 3523 3524 // Now we go through the remaining generic results and remove any 3525 // duplicate actions that are found here. 3526 N = results.size(); 3527 for (int i=specificsPos; i<N-1; i++) { 3528 final ResolveInfo rii = results.get(i); 3529 if (rii.filter == null) { 3530 continue; 3531 } 3532 3533 // Iterate over all of the actions of this result's intent 3534 // filter... typically this should be just one. 3535 final Iterator<String> it = rii.filter.actionsIterator(); 3536 if (it == null) { 3537 continue; 3538 } 3539 while (it.hasNext()) { 3540 final String action = it.next(); 3541 if (resultsAction != null && resultsAction.equals(action)) { 3542 // If this action was explicitly requested, then don't 3543 // remove things that have it. 3544 continue; 3545 } 3546 for (int j=i+1; j<N; j++) { 3547 final ResolveInfo rij = results.get(j); 3548 if (rij.filter != null && rij.filter.hasAction(action)) { 3549 results.remove(j); 3550 if (DEBUG_INTENT_MATCHING) Log.v( 3551 TAG, "Removing duplicate item from " + j 3552 + " due to action " + action + " at " + i); 3553 j--; 3554 N--; 3555 } 3556 } 3557 } 3558 3559 // If the caller didn't request filter information, drop it now 3560 // so we don't have to marshall/unmarshall it. 3561 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3562 rii.filter = null; 3563 } 3564 } 3565 3566 // Filter out the caller activity if so requested. 3567 if (caller != null) { 3568 N = results.size(); 3569 for (int i=0; i<N; i++) { 3570 ActivityInfo ainfo = results.get(i).activityInfo; 3571 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 3572 && caller.getClassName().equals(ainfo.name)) { 3573 results.remove(i); 3574 break; 3575 } 3576 } 3577 } 3578 3579 // If the caller didn't request filter information, 3580 // drop them now so we don't have to 3581 // marshall/unmarshall it. 3582 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3583 N = results.size(); 3584 for (int i=0; i<N; i++) { 3585 results.get(i).filter = null; 3586 } 3587 } 3588 3589 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 3590 return results; 3591 } 3592 3593 @Override 3594 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 3595 int userId) { 3596 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3597 ComponentName comp = intent.getComponent(); 3598 if (comp == null) { 3599 if (intent.getSelector() != null) { 3600 intent = intent.getSelector(); 3601 comp = intent.getComponent(); 3602 } 3603 } 3604 if (comp != null) { 3605 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3606 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 3607 if (ai != null) { 3608 ResolveInfo ri = new ResolveInfo(); 3609 ri.activityInfo = ai; 3610 list.add(ri); 3611 } 3612 return list; 3613 } 3614 3615 // reader 3616 synchronized (mPackages) { 3617 String pkgName = intent.getPackage(); 3618 if (pkgName == null) { 3619 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 3620 } 3621 final PackageParser.Package pkg = mPackages.get(pkgName); 3622 if (pkg != null) { 3623 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 3624 userId); 3625 } 3626 return null; 3627 } 3628 } 3629 3630 @Override 3631 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 3632 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 3633 if (!sUserManager.exists(userId)) return null; 3634 if (query != null) { 3635 if (query.size() >= 1) { 3636 // If there is more than one service with the same priority, 3637 // just arbitrarily pick the first one. 3638 return query.get(0); 3639 } 3640 } 3641 return null; 3642 } 3643 3644 @Override 3645 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 3646 int userId) { 3647 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3648 ComponentName comp = intent.getComponent(); 3649 if (comp == null) { 3650 if (intent.getSelector() != null) { 3651 intent = intent.getSelector(); 3652 comp = intent.getComponent(); 3653 } 3654 } 3655 if (comp != null) { 3656 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3657 final ServiceInfo si = getServiceInfo(comp, flags, userId); 3658 if (si != null) { 3659 final ResolveInfo ri = new ResolveInfo(); 3660 ri.serviceInfo = si; 3661 list.add(ri); 3662 } 3663 return list; 3664 } 3665 3666 // reader 3667 synchronized (mPackages) { 3668 String pkgName = intent.getPackage(); 3669 if (pkgName == null) { 3670 return mServices.queryIntent(intent, resolvedType, flags, userId); 3671 } 3672 final PackageParser.Package pkg = mPackages.get(pkgName); 3673 if (pkg != null) { 3674 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 3675 userId); 3676 } 3677 return null; 3678 } 3679 } 3680 3681 @Override 3682 public List<ResolveInfo> queryIntentContentProviders( 3683 Intent intent, String resolvedType, int flags, int userId) { 3684 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3685 ComponentName comp = intent.getComponent(); 3686 if (comp == null) { 3687 if (intent.getSelector() != null) { 3688 intent = intent.getSelector(); 3689 comp = intent.getComponent(); 3690 } 3691 } 3692 if (comp != null) { 3693 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3694 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 3695 if (pi != null) { 3696 final ResolveInfo ri = new ResolveInfo(); 3697 ri.providerInfo = pi; 3698 list.add(ri); 3699 } 3700 return list; 3701 } 3702 3703 // reader 3704 synchronized (mPackages) { 3705 String pkgName = intent.getPackage(); 3706 if (pkgName == null) { 3707 return mProviders.queryIntent(intent, resolvedType, flags, userId); 3708 } 3709 final PackageParser.Package pkg = mPackages.get(pkgName); 3710 if (pkg != null) { 3711 return mProviders.queryIntentForPackage( 3712 intent, resolvedType, flags, pkg.providers, userId); 3713 } 3714 return null; 3715 } 3716 } 3717 3718 @Override 3719 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 3720 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3721 3722 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages"); 3723 3724 // writer 3725 synchronized (mPackages) { 3726 ArrayList<PackageInfo> list; 3727 if (listUninstalled) { 3728 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 3729 for (PackageSetting ps : mSettings.mPackages.values()) { 3730 PackageInfo pi; 3731 if (ps.pkg != null) { 3732 pi = generatePackageInfo(ps.pkg, flags, userId); 3733 } else { 3734 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3735 } 3736 if (pi != null) { 3737 list.add(pi); 3738 } 3739 } 3740 } else { 3741 list = new ArrayList<PackageInfo>(mPackages.size()); 3742 for (PackageParser.Package p : mPackages.values()) { 3743 PackageInfo pi = generatePackageInfo(p, flags, userId); 3744 if (pi != null) { 3745 list.add(pi); 3746 } 3747 } 3748 } 3749 3750 return new ParceledListSlice<PackageInfo>(list); 3751 } 3752 } 3753 3754 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 3755 String[] permissions, boolean[] tmp, int flags, int userId) { 3756 int numMatch = 0; 3757 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 3758 for (int i=0; i<permissions.length; i++) { 3759 if (gp.grantedPermissions.contains(permissions[i])) { 3760 tmp[i] = true; 3761 numMatch++; 3762 } else { 3763 tmp[i] = false; 3764 } 3765 } 3766 if (numMatch == 0) { 3767 return; 3768 } 3769 PackageInfo pi; 3770 if (ps.pkg != null) { 3771 pi = generatePackageInfo(ps.pkg, flags, userId); 3772 } else { 3773 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3774 } 3775 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 3776 if (numMatch == permissions.length) { 3777 pi.requestedPermissions = permissions; 3778 } else { 3779 pi.requestedPermissions = new String[numMatch]; 3780 numMatch = 0; 3781 for (int i=0; i<permissions.length; i++) { 3782 if (tmp[i]) { 3783 pi.requestedPermissions[numMatch] = permissions[i]; 3784 numMatch++; 3785 } 3786 } 3787 } 3788 } 3789 list.add(pi); 3790 } 3791 3792 @Override 3793 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 3794 String[] permissions, int flags, int userId) { 3795 if (!sUserManager.exists(userId)) return null; 3796 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3797 3798 // writer 3799 synchronized (mPackages) { 3800 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 3801 boolean[] tmpBools = new boolean[permissions.length]; 3802 if (listUninstalled) { 3803 for (PackageSetting ps : mSettings.mPackages.values()) { 3804 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 3805 } 3806 } else { 3807 for (PackageParser.Package pkg : mPackages.values()) { 3808 PackageSetting ps = (PackageSetting)pkg.mExtras; 3809 if (ps != null) { 3810 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 3811 userId); 3812 } 3813 } 3814 } 3815 3816 return new ParceledListSlice<PackageInfo>(list); 3817 } 3818 } 3819 3820 @Override 3821 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 3822 if (!sUserManager.exists(userId)) return null; 3823 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3824 3825 // writer 3826 synchronized (mPackages) { 3827 ArrayList<ApplicationInfo> list; 3828 if (listUninstalled) { 3829 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 3830 for (PackageSetting ps : mSettings.mPackages.values()) { 3831 ApplicationInfo ai; 3832 if (ps.pkg != null) { 3833 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3834 ps.readUserState(userId), userId); 3835 } else { 3836 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 3837 } 3838 if (ai != null) { 3839 list.add(ai); 3840 } 3841 } 3842 } else { 3843 list = new ArrayList<ApplicationInfo>(mPackages.size()); 3844 for (PackageParser.Package p : mPackages.values()) { 3845 if (p.mExtras != null) { 3846 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3847 ((PackageSetting)p.mExtras).readUserState(userId), userId); 3848 if (ai != null) { 3849 list.add(ai); 3850 } 3851 } 3852 } 3853 } 3854 3855 return new ParceledListSlice<ApplicationInfo>(list); 3856 } 3857 } 3858 3859 public List<ApplicationInfo> getPersistentApplications(int flags) { 3860 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 3861 3862 // reader 3863 synchronized (mPackages) { 3864 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 3865 final int userId = UserHandle.getCallingUserId(); 3866 while (i.hasNext()) { 3867 final PackageParser.Package p = i.next(); 3868 if (p.applicationInfo != null 3869 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 3870 && (!mSafeMode || isSystemApp(p))) { 3871 PackageSetting ps = mSettings.mPackages.get(p.packageName); 3872 if (ps != null) { 3873 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3874 ps.readUserState(userId), userId); 3875 if (ai != null) { 3876 finalList.add(ai); 3877 } 3878 } 3879 } 3880 } 3881 } 3882 3883 return finalList; 3884 } 3885 3886 @Override 3887 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 3888 if (!sUserManager.exists(userId)) return null; 3889 // reader 3890 synchronized (mPackages) { 3891 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 3892 PackageSetting ps = provider != null 3893 ? mSettings.mPackages.get(provider.owner.packageName) 3894 : null; 3895 return ps != null 3896 && mSettings.isEnabledLPr(provider.info, flags, userId) 3897 && (!mSafeMode || (provider.info.applicationInfo.flags 3898 &ApplicationInfo.FLAG_SYSTEM) != 0) 3899 ? PackageParser.generateProviderInfo(provider, flags, 3900 ps.readUserState(userId), userId) 3901 : null; 3902 } 3903 } 3904 3905 /** 3906 * @deprecated 3907 */ 3908 @Deprecated 3909 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 3910 // reader 3911 synchronized (mPackages) { 3912 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 3913 .entrySet().iterator(); 3914 final int userId = UserHandle.getCallingUserId(); 3915 while (i.hasNext()) { 3916 Map.Entry<String, PackageParser.Provider> entry = i.next(); 3917 PackageParser.Provider p = entry.getValue(); 3918 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3919 3920 if (ps != null && p.syncable 3921 && (!mSafeMode || (p.info.applicationInfo.flags 3922 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 3923 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 3924 ps.readUserState(userId), userId); 3925 if (info != null) { 3926 outNames.add(entry.getKey()); 3927 outInfo.add(info); 3928 } 3929 } 3930 } 3931 } 3932 } 3933 3934 @Override 3935 public List<ProviderInfo> queryContentProviders(String processName, 3936 int uid, int flags) { 3937 ArrayList<ProviderInfo> finalList = null; 3938 // reader 3939 synchronized (mPackages) { 3940 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 3941 final int userId = processName != null ? 3942 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 3943 while (i.hasNext()) { 3944 final PackageParser.Provider p = i.next(); 3945 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3946 if (ps != null && p.info.authority != null 3947 && (processName == null 3948 || (p.info.processName.equals(processName) 3949 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 3950 && mSettings.isEnabledLPr(p.info, flags, userId) 3951 && (!mSafeMode 3952 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 3953 if (finalList == null) { 3954 finalList = new ArrayList<ProviderInfo>(3); 3955 } 3956 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 3957 ps.readUserState(userId), userId); 3958 if (info != null) { 3959 finalList.add(info); 3960 } 3961 } 3962 } 3963 } 3964 3965 if (finalList != null) { 3966 Collections.sort(finalList, mProviderInitOrderSorter); 3967 } 3968 3969 return finalList; 3970 } 3971 3972 @Override 3973 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 3974 int flags) { 3975 // reader 3976 synchronized (mPackages) { 3977 final PackageParser.Instrumentation i = mInstrumentation.get(name); 3978 return PackageParser.generateInstrumentationInfo(i, flags); 3979 } 3980 } 3981 3982 @Override 3983 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 3984 int flags) { 3985 ArrayList<InstrumentationInfo> finalList = 3986 new ArrayList<InstrumentationInfo>(); 3987 3988 // reader 3989 synchronized (mPackages) { 3990 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 3991 while (i.hasNext()) { 3992 final PackageParser.Instrumentation p = i.next(); 3993 if (targetPackage == null 3994 || targetPackage.equals(p.info.targetPackage)) { 3995 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 3996 flags); 3997 if (ii != null) { 3998 finalList.add(ii); 3999 } 4000 } 4001 } 4002 } 4003 4004 return finalList; 4005 } 4006 4007 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4008 HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4009 if (overlays == null) { 4010 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4011 return; 4012 } 4013 for (PackageParser.Package opkg : overlays.values()) { 4014 // Not much to do if idmap fails: we already logged the error 4015 // and we certainly don't want to abort installation of pkg simply 4016 // because an overlay didn't fit properly. For these reasons, 4017 // ignore the return value of createIdmapForPackagePairLI. 4018 createIdmapForPackagePairLI(pkg, opkg); 4019 } 4020 } 4021 4022 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4023 PackageParser.Package opkg) { 4024 if (!opkg.mTrustedOverlay) { 4025 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4026 opkg.baseCodePath + ": overlay not trusted"); 4027 return false; 4028 } 4029 HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4030 if (overlaySet == null) { 4031 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4032 opkg.baseCodePath + " but target package has no known overlays"); 4033 return false; 4034 } 4035 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4036 // TODO: generate idmap for split APKs 4037 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4038 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4039 + opkg.baseCodePath); 4040 return false; 4041 } 4042 PackageParser.Package[] overlayArray = 4043 overlaySet.values().toArray(new PackageParser.Package[0]); 4044 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4045 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4046 return p1.mOverlayPriority - p2.mOverlayPriority; 4047 } 4048 }; 4049 Arrays.sort(overlayArray, cmp); 4050 4051 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4052 int i = 0; 4053 for (PackageParser.Package p : overlayArray) { 4054 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4055 } 4056 return true; 4057 } 4058 4059 private void scanDirLI(File dir, int flags, int scanMode, long currentTime) { 4060 final File[] files = dir.listFiles(); 4061 if (ArrayUtils.isEmpty(files)) { 4062 Log.d(TAG, "No files in app dir " + dir); 4063 return; 4064 } 4065 4066 if (DEBUG_PACKAGE_SCANNING) { 4067 Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode 4068 + " flags=0x" + Integer.toHexString(flags)); 4069 } 4070 4071 for (File file : files) { 4072 final boolean isPackage = isApkFile(file) || file.isDirectory(); 4073 if (!isPackage) { 4074 // Ignore entries which are not apk's 4075 continue; 4076 } 4077 try { 4078 scanPackageLI(file, flags | PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, 4079 null, null); 4080 } catch (PackageManagerException e) { 4081 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4082 4083 // Don't mess around with apps in system partition. 4084 if ((flags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4085 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4086 // Delete the apk 4087 Slog.w(TAG, "Cleaning up failed install of " + file); 4088 file.delete(); 4089 } 4090 } 4091 } 4092 } 4093 4094 private static File getSettingsProblemFile() { 4095 File dataDir = Environment.getDataDirectory(); 4096 File systemDir = new File(dataDir, "system"); 4097 File fname = new File(systemDir, "uiderrors.txt"); 4098 return fname; 4099 } 4100 4101 static void reportSettingsProblem(int priority, String msg) { 4102 try { 4103 File fname = getSettingsProblemFile(); 4104 FileOutputStream out = new FileOutputStream(fname, true); 4105 PrintWriter pw = new FastPrintWriter(out); 4106 SimpleDateFormat formatter = new SimpleDateFormat(); 4107 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4108 pw.println(dateString + ": " + msg); 4109 pw.close(); 4110 FileUtils.setPermissions( 4111 fname.toString(), 4112 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4113 -1, -1); 4114 } catch (java.io.IOException e) { 4115 } 4116 Slog.println(priority, TAG, msg); 4117 } 4118 4119 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 4120 PackageParser.Package pkg, File srcFile, int parseFlags) 4121 throws PackageManagerException { 4122 if (ps != null 4123 && ps.codePath.equals(srcFile) 4124 && ps.timeStamp == srcFile.lastModified() 4125 && !isCompatSignatureUpdateNeeded(pkg)) { 4126 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4127 if (ps.signatures.mSignatures != null 4128 && ps.signatures.mSignatures.length != 0 4129 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4130 // Optimization: reuse the existing cached certificates 4131 // if the package appears to be unchanged. 4132 pkg.mSignatures = ps.signatures.mSignatures; 4133 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4134 synchronized (mPackages) { 4135 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 4136 } 4137 return; 4138 } 4139 4140 Slog.w(TAG, "PackageSetting for " + ps.name 4141 + " is missing signatures. Collecting certs again to recover them."); 4142 } else { 4143 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4144 } 4145 4146 try { 4147 pp.collectCertificates(pkg, parseFlags); 4148 pp.collectManifestDigest(pkg); 4149 } catch (PackageParserException e) { 4150 throw new PackageManagerException(e.error, "Failed to collect certificates for " 4151 + pkg.packageName + ": " + e.getMessage()); 4152 } 4153 } 4154 4155 /* 4156 * Scan a package and return the newly parsed package. 4157 * Returns null in case of errors and the error code is stored in mLastScanError 4158 */ 4159 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanMode, 4160 long currentTime, UserHandle user, String abiOverride) throws PackageManagerException { 4161 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4162 parseFlags |= mDefParseFlags; 4163 PackageParser pp = new PackageParser(); 4164 pp.setSeparateProcesses(mSeparateProcesses); 4165 pp.setOnlyCoreApps(mOnlyCore); 4166 pp.setDisplayMetrics(mMetrics); 4167 4168 if ((scanMode & SCAN_TRUSTED_OVERLAY) != 0) { 4169 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4170 } 4171 4172 final PackageParser.Package pkg; 4173 try { 4174 pkg = pp.parsePackage(scanFile, parseFlags); 4175 } catch (PackageParserException e) { 4176 throw new PackageManagerException(e.error, 4177 "Failed to scan " + scanFile + ": " + e.getMessage()); 4178 } 4179 4180 PackageSetting ps = null; 4181 PackageSetting updatedPkg; 4182 // reader 4183 synchronized (mPackages) { 4184 // Look to see if we already know about this package. 4185 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4186 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4187 // This package has been renamed to its original name. Let's 4188 // use that. 4189 ps = mSettings.peekPackageLPr(oldName); 4190 } 4191 // If there was no original package, see one for the real package name. 4192 if (ps == null) { 4193 ps = mSettings.peekPackageLPr(pkg.packageName); 4194 } 4195 // Check to see if this package could be hiding/updating a system 4196 // package. Must look for it either under the original or real 4197 // package name depending on our state. 4198 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4199 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4200 } 4201 boolean updatedPkgBetter = false; 4202 // First check if this is a system package that may involve an update 4203 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4204 if (ps != null && !ps.codePath.equals(scanFile)) { 4205 // The path has changed from what was last scanned... check the 4206 // version of the new path against what we have stored to determine 4207 // what to do. 4208 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4209 if (pkg.mVersionCode < ps.versionCode) { 4210 // The system package has been updated and the code path does not match 4211 // Ignore entry. Skip it. 4212 Log.i(TAG, "Package " + ps.name + " at " + scanFile 4213 + " ignored: updated version " + ps.versionCode 4214 + " better than this " + pkg.mVersionCode); 4215 if (!updatedPkg.codePath.equals(scanFile)) { 4216 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4217 + ps.name + " changing from " + updatedPkg.codePathString 4218 + " to " + scanFile); 4219 updatedPkg.codePath = scanFile; 4220 updatedPkg.codePathString = scanFile.toString(); 4221 // This is the point at which we know that the system-disk APK 4222 // for this package has moved during a reboot (e.g. due to an OTA), 4223 // so we need to reevaluate it for privilege policy. 4224 if (locationIsPrivileged(scanFile)) { 4225 updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED; 4226 } 4227 } 4228 updatedPkg.pkg = pkg; 4229 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 4230 } else { 4231 // The current app on the system partition is better than 4232 // what we have updated to on the data partition; switch 4233 // back to the system partition version. 4234 // At this point, its safely assumed that package installation for 4235 // apps in system partition will go through. If not there won't be a working 4236 // version of the app 4237 // writer 4238 synchronized (mPackages) { 4239 // Just remove the loaded entries from package lists. 4240 mPackages.remove(ps.name); 4241 } 4242 Slog.w(TAG, "Package " + ps.name + " at " + scanFile 4243 + "reverting from " + ps.codePathString 4244 + ": new version " + pkg.mVersionCode 4245 + " better than installed " + ps.versionCode); 4246 4247 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4248 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4249 getAppDexInstructionSets(ps), isMultiArch(ps)); 4250 synchronized (mInstallLock) { 4251 args.cleanUpResourcesLI(); 4252 } 4253 synchronized (mPackages) { 4254 mSettings.enableSystemPackageLPw(ps.name); 4255 } 4256 updatedPkgBetter = true; 4257 } 4258 } 4259 } 4260 4261 if (updatedPkg != null) { 4262 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4263 // initially 4264 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4265 4266 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4267 // flag set initially 4268 if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) { 4269 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4270 } 4271 } 4272 4273 // Verify certificates against what was last scanned 4274 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 4275 4276 /* 4277 * A new system app appeared, but we already had a non-system one of the 4278 * same name installed earlier. 4279 */ 4280 boolean shouldHideSystemApp = false; 4281 if (updatedPkg == null && ps != null 4282 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4283 /* 4284 * Check to make sure the signatures match first. If they don't, 4285 * wipe the installed application and its data. 4286 */ 4287 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4288 != PackageManager.SIGNATURE_MATCH) { 4289 if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!"); 4290 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4291 ps = null; 4292 } else { 4293 /* 4294 * If the newly-added system app is an older version than the 4295 * already installed version, hide it. It will be scanned later 4296 * and re-added like an update. 4297 */ 4298 if (pkg.mVersionCode < ps.versionCode) { 4299 shouldHideSystemApp = true; 4300 } else { 4301 /* 4302 * The newly found system app is a newer version that the 4303 * one previously installed. Simply remove the 4304 * already-installed application and replace it with our own 4305 * while keeping the application data. 4306 */ 4307 Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from " 4308 + ps.codePathString + ": new version " + pkg.mVersionCode 4309 + " better than installed " + ps.versionCode); 4310 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4311 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4312 getAppDexInstructionSets(ps), isMultiArch(ps)); 4313 synchronized (mInstallLock) { 4314 args.cleanUpResourcesLI(); 4315 } 4316 } 4317 } 4318 } 4319 4320 // The apk is forward locked (not public) if its code and resources 4321 // are kept in different files. (except for app in either system or 4322 // vendor path). 4323 // TODO grab this value from PackageSettings 4324 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4325 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4326 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 4327 } 4328 } 4329 4330 // TODO: extend to support forward-locked splits 4331 String resourcePath = null; 4332 String baseResourcePath = null; 4333 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 4334 if (ps != null && ps.resourcePathString != null) { 4335 resourcePath = ps.resourcePathString; 4336 baseResourcePath = ps.resourcePathString; 4337 } else { 4338 // Should not happen at all. Just log an error. 4339 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 4340 } 4341 } else { 4342 resourcePath = pkg.codePath; 4343 baseResourcePath = pkg.baseCodePath; 4344 } 4345 4346 // Set application objects path explicitly. 4347 pkg.applicationInfo.setCodePath(pkg.codePath); 4348 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 4349 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 4350 pkg.applicationInfo.setResourcePath(resourcePath); 4351 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 4352 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 4353 4354 // Note that we invoke the following method only if we are about to unpack an application 4355 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode 4356 | SCAN_UPDATE_SIGNATURE, currentTime, user, abiOverride); 4357 4358 /* 4359 * If the system app should be overridden by a previously installed 4360 * data, hide the system app now and let the /data/app scan pick it up 4361 * again. 4362 */ 4363 if (shouldHideSystemApp) { 4364 synchronized (mPackages) { 4365 /* 4366 * We have to grant systems permissions before we hide, because 4367 * grantPermissions will assume the package update is trying to 4368 * expand its permissions. 4369 */ 4370 grantPermissionsLPw(pkg, true); 4371 mSettings.disableSystemPackageLPw(pkg.packageName); 4372 } 4373 } 4374 4375 return scannedPkg; 4376 } 4377 4378 private static String fixProcessName(String defProcessName, 4379 String processName, int uid) { 4380 if (processName == null) { 4381 return defProcessName; 4382 } 4383 return processName; 4384 } 4385 4386 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 4387 throws PackageManagerException { 4388 if (pkgSetting.signatures.mSignatures != null) { 4389 // Already existing package. Make sure signatures match 4390 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 4391 == PackageManager.SIGNATURE_MATCH; 4392 if (!match) { 4393 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 4394 == PackageManager.SIGNATURE_MATCH; 4395 } 4396 if (!match) { 4397 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 4398 + pkg.packageName + " signatures do not match the " 4399 + "previously installed version; ignoring!"); 4400 } 4401 } 4402 4403 // Check for shared user signatures 4404 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 4405 // Already existing package. Make sure signatures match 4406 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4407 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 4408 if (!match) { 4409 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 4410 == PackageManager.SIGNATURE_MATCH; 4411 } 4412 if (!match) { 4413 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 4414 "Package " + pkg.packageName 4415 + " has no signatures that match those in shared user " 4416 + pkgSetting.sharedUser.name + "; ignoring!"); 4417 } 4418 } 4419 } 4420 4421 /** 4422 * Enforces that only the system UID or root's UID can call a method exposed 4423 * via Binder. 4424 * 4425 * @param message used as message if SecurityException is thrown 4426 * @throws SecurityException if the caller is not system or root 4427 */ 4428 private static final void enforceSystemOrRoot(String message) { 4429 final int uid = Binder.getCallingUid(); 4430 if (uid != Process.SYSTEM_UID && uid != 0) { 4431 throw new SecurityException(message); 4432 } 4433 } 4434 4435 @Override 4436 public void performBootDexOpt() { 4437 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4438 4439 final HashSet<PackageParser.Package> pkgs; 4440 synchronized (mPackages) { 4441 pkgs = mDeferredDexOpt; 4442 mDeferredDexOpt = null; 4443 } 4444 4445 if (pkgs != null) { 4446 // Filter out packages that aren't recently used. 4447 // 4448 // The exception is first boot of a non-eng device, which 4449 // should do a full dexopt. 4450 boolean eng = "eng".equals(SystemProperties.get("ro.build.type")); 4451 if (eng || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 4452 // TODO: add a property to control this? 4453 long dexOptLRUThresholdInMinutes; 4454 if (eng) { 4455 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 4456 } else { 4457 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 4458 } 4459 long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 4460 4461 int total = pkgs.size(); 4462 int skipped = 0; 4463 long now = System.currentTimeMillis(); 4464 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 4465 PackageParser.Package pkg = i.next(); 4466 long then = pkg.mLastPackageUsageTimeInMills; 4467 if (then + dexOptLRUThresholdInMills < now) { 4468 if (DEBUG_DEXOPT) { 4469 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 4470 ((then == 0) ? "never" : new Date(then))); 4471 } 4472 i.remove(); 4473 skipped++; 4474 } 4475 } 4476 if (DEBUG_DEXOPT) { 4477 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 4478 } 4479 } 4480 4481 int i = 0; 4482 for (PackageParser.Package pkg : pkgs) { 4483 i++; 4484 if (DEBUG_DEXOPT) { 4485 Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size() 4486 + ": " + pkg.packageName); 4487 } 4488 if (!isFirstBoot()) { 4489 try { 4490 ActivityManagerNative.getDefault().showBootMessage( 4491 mContext.getResources().getString( 4492 R.string.android_upgrading_apk, 4493 i, pkgs.size()), true); 4494 } catch (RemoteException e) { 4495 } 4496 } 4497 PackageParser.Package p = pkg; 4498 synchronized (mInstallLock) { 4499 performDexOptLI(p, null /* instruction sets */, false /* force dex */, false /* defer */, 4500 true /* include dependencies */); 4501 } 4502 } 4503 } 4504 } 4505 4506 @Override 4507 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 4508 return performDexOpt(packageName, instructionSet, true); 4509 } 4510 4511 private static String getPrimaryInstructionSet(ApplicationInfo info) { 4512 if (info.primaryCpuAbi == null) { 4513 return getPreferredInstructionSet(); 4514 } 4515 4516 return VMRuntime.getInstructionSet(info.primaryCpuAbi); 4517 } 4518 4519 public boolean performDexOpt(String packageName, String instructionSet, boolean updateUsage) { 4520 PackageParser.Package p; 4521 final String targetInstructionSet; 4522 synchronized (mPackages) { 4523 p = mPackages.get(packageName); 4524 if (p == null) { 4525 return false; 4526 } 4527 if (updateUsage) { 4528 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 4529 } 4530 mPackageUsage.write(false); 4531 4532 targetInstructionSet = instructionSet != null ? instructionSet : 4533 getPrimaryInstructionSet(p.applicationInfo); 4534 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 4535 return false; 4536 } 4537 } 4538 4539 synchronized (mInstallLock) { 4540 final String[] instructionSets = new String[] { targetInstructionSet }; 4541 return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */, 4542 true /* include dependencies */) == DEX_OPT_PERFORMED; 4543 } 4544 } 4545 4546 public HashSet<String> getPackagesThatNeedDexOpt() { 4547 HashSet<String> pkgs = null; 4548 synchronized (mPackages) { 4549 for (PackageParser.Package p : mPackages.values()) { 4550 if (DEBUG_DEXOPT) { 4551 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 4552 } 4553 if (!p.mDexOptPerformed.isEmpty()) { 4554 continue; 4555 } 4556 if (pkgs == null) { 4557 pkgs = new HashSet<String>(); 4558 } 4559 pkgs.add(p.packageName); 4560 } 4561 } 4562 return pkgs; 4563 } 4564 4565 public void shutdown() { 4566 mPackageUsage.write(true); 4567 } 4568 4569 private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets, 4570 boolean forceDex, boolean defer, HashSet<String> done) { 4571 for (int i=0; i<libs.size(); i++) { 4572 PackageParser.Package libPkg; 4573 String libName; 4574 synchronized (mPackages) { 4575 libName = libs.get(i); 4576 SharedLibraryEntry lib = mSharedLibraries.get(libName); 4577 if (lib != null && lib.apk != null) { 4578 libPkg = mPackages.get(lib.apk); 4579 } else { 4580 libPkg = null; 4581 } 4582 } 4583 if (libPkg != null && !done.contains(libName)) { 4584 performDexOptLI(libPkg, instructionSets, forceDex, defer, done); 4585 } 4586 } 4587 } 4588 4589 static final int DEX_OPT_SKIPPED = 0; 4590 static final int DEX_OPT_PERFORMED = 1; 4591 static final int DEX_OPT_DEFERRED = 2; 4592 static final int DEX_OPT_FAILED = -1; 4593 4594 private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets, 4595 boolean forceDex, boolean defer, HashSet<String> done) { 4596 final String[] instructionSets = targetInstructionSets != null ? 4597 targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo); 4598 4599 if (done != null) { 4600 done.add(pkg.packageName); 4601 if (pkg.usesLibraries != null) { 4602 performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done); 4603 } 4604 if (pkg.usesOptionalLibraries != null) { 4605 performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done); 4606 } 4607 } 4608 4609 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) { 4610 return DEX_OPT_SKIPPED; 4611 } 4612 4613 final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly(); 4614 boolean performedDexOpt = false; 4615 // There are three basic cases here: 4616 // 1.) we need to dexopt, either because we are forced or it is needed 4617 // 2.) we are defering a needed dexopt 4618 // 3.) we are skipping an unneeded dexopt 4619 for (String path : paths) { 4620 for (String instructionSet : instructionSets) { 4621 if (!forceDex && pkg.mDexOptPerformed.contains(instructionSet)) { 4622 continue; 4623 } 4624 4625 try { 4626 final boolean isDexOptNeeded = DexFile.isDexOptNeededInternal(path, 4627 pkg.packageName, instructionSet, defer); 4628 if (forceDex || (!defer && isDexOptNeeded)) { 4629 Log.i(TAG, "Running dexopt on: " + path + " pkg=" 4630 + pkg.applicationInfo.packageName + " isa=" + instructionSet); 4631 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4632 final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg), 4633 pkg.packageName, instructionSet); 4634 4635 if (ret < 0) { 4636 // Don't bother running dexopt again if we failed, it will probably 4637 // just result in an error again. Also, don't bother dexopting for other 4638 // paths & ISAs. 4639 return DEX_OPT_FAILED; 4640 } else { 4641 performedDexOpt = true; 4642 pkg.mDexOptPerformed.add(instructionSet); 4643 } 4644 } 4645 4646 // We're deciding to defer a needed dexopt. Don't bother dexopting for other 4647 // paths and instruction sets. We'll deal with them all together when we process 4648 // our list of deferred dexopts. 4649 if (defer && isDexOptNeeded) { 4650 if (mDeferredDexOpt == null) { 4651 mDeferredDexOpt = new HashSet<PackageParser.Package>(); 4652 } 4653 mDeferredDexOpt.add(pkg); 4654 return DEX_OPT_DEFERRED; 4655 } 4656 } catch (FileNotFoundException e) { 4657 Slog.w(TAG, "Apk not found for dexopt: " + path); 4658 return DEX_OPT_FAILED; 4659 } catch (IOException e) { 4660 Slog.w(TAG, "IOException reading apk: " + path, e); 4661 return DEX_OPT_FAILED; 4662 } catch (StaleDexCacheError e) { 4663 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e); 4664 return DEX_OPT_FAILED; 4665 } catch (Exception e) { 4666 Slog.w(TAG, "Exception when doing dexopt : ", e); 4667 return DEX_OPT_FAILED; 4668 } 4669 } 4670 } 4671 4672 // If we've gotten here, we're sure that no error occurred and that we haven't 4673 // deferred dex-opt. We've either dex-opted one more paths or instruction sets or 4674 // we've skipped all of them because they are up to date. In both cases this 4675 // package doesn't need dexopt any longer. 4676 return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED; 4677 } 4678 4679 private static String[] getAppDexInstructionSets(ApplicationInfo info) { 4680 if (info.primaryCpuAbi != null) { 4681 if (info.secondaryCpuAbi != null) { 4682 return new String[] { 4683 VMRuntime.getInstructionSet(info.primaryCpuAbi), 4684 VMRuntime.getInstructionSet(info.secondaryCpuAbi) }; 4685 } else { 4686 return new String[] { 4687 VMRuntime.getInstructionSet(info.primaryCpuAbi) }; 4688 } 4689 } 4690 4691 return new String[] { getPreferredInstructionSet() }; 4692 } 4693 4694 private static String[] getAppDexInstructionSets(PackageSetting ps) { 4695 if (ps.primaryCpuAbiString != null) { 4696 if (ps.secondaryCpuAbiString != null) { 4697 return new String[] { 4698 VMRuntime.getInstructionSet(ps.primaryCpuAbiString), 4699 VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) }; 4700 } else { 4701 return new String[] { 4702 VMRuntime.getInstructionSet(ps.primaryCpuAbiString) }; 4703 } 4704 } 4705 4706 return new String[] { getPreferredInstructionSet() }; 4707 } 4708 4709 private static String getPreferredInstructionSet() { 4710 if (sPreferredInstructionSet == null) { 4711 sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]); 4712 } 4713 4714 return sPreferredInstructionSet; 4715 } 4716 4717 private static List<String> getAllInstructionSets() { 4718 final String[] allAbis = Build.SUPPORTED_ABIS; 4719 final List<String> allInstructionSets = new ArrayList<String>(allAbis.length); 4720 4721 for (String abi : allAbis) { 4722 final String instructionSet = VMRuntime.getInstructionSet(abi); 4723 if (!allInstructionSets.contains(instructionSet)) { 4724 allInstructionSets.add(instructionSet); 4725 } 4726 } 4727 4728 return allInstructionSets; 4729 } 4730 4731 @Override 4732 public void forceDexOpt(String packageName) { 4733 enforceSystemOrRoot("forceDexOpt"); 4734 4735 PackageParser.Package pkg; 4736 synchronized (mPackages) { 4737 pkg = mPackages.get(packageName); 4738 if (pkg == null) { 4739 throw new IllegalArgumentException("Missing package: " + packageName); 4740 } 4741 } 4742 4743 synchronized (mInstallLock) { 4744 final String[] instructionSets = new String[] { 4745 getPrimaryInstructionSet(pkg.applicationInfo) }; 4746 final int res = performDexOptLI(pkg, instructionSets, true, false, true); 4747 if (res != DEX_OPT_PERFORMED) { 4748 throw new IllegalStateException("Failed to dexopt: " + res); 4749 } 4750 } 4751 } 4752 4753 private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets, 4754 boolean forceDex, boolean defer, boolean inclDependencies) { 4755 HashSet<String> done; 4756 if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) { 4757 done = new HashSet<String>(); 4758 done.add(pkg.packageName); 4759 } else { 4760 done = null; 4761 } 4762 return performDexOptLI(pkg, instructionSets, forceDex, defer, done); 4763 } 4764 4765 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 4766 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 4767 Slog.w(TAG, "Unable to update from " + oldPkg.name 4768 + " to " + newPkg.packageName 4769 + ": old package not in system partition"); 4770 return false; 4771 } else if (mPackages.get(oldPkg.name) != null) { 4772 Slog.w(TAG, "Unable to update from " + oldPkg.name 4773 + " to " + newPkg.packageName 4774 + ": old package still exists"); 4775 return false; 4776 } 4777 return true; 4778 } 4779 4780 File getDataPathForUser(int userId) { 4781 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId); 4782 } 4783 4784 private File getDataPathForPackage(String packageName, int userId) { 4785 /* 4786 * Until we fully support multiple users, return the directory we 4787 * previously would have. The PackageManagerTests will need to be 4788 * revised when this is changed back.. 4789 */ 4790 if (userId == 0) { 4791 return new File(mAppDataDir, packageName); 4792 } else { 4793 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 4794 + File.separator + packageName); 4795 } 4796 } 4797 4798 private int createDataDirsLI(String packageName, int uid, String seinfo) { 4799 int[] users = sUserManager.getUserIds(); 4800 int res = mInstaller.install(packageName, uid, uid, seinfo); 4801 if (res < 0) { 4802 return res; 4803 } 4804 for (int user : users) { 4805 if (user != 0) { 4806 res = mInstaller.createUserData(packageName, 4807 UserHandle.getUid(user, uid), user, seinfo); 4808 if (res < 0) { 4809 return res; 4810 } 4811 } 4812 } 4813 return res; 4814 } 4815 4816 private int removeDataDirsLI(String packageName) { 4817 int[] users = sUserManager.getUserIds(); 4818 int res = 0; 4819 for (int user : users) { 4820 int resInner = mInstaller.remove(packageName, user); 4821 if (resInner < 0) { 4822 res = resInner; 4823 } 4824 } 4825 4826 return res; 4827 } 4828 4829 private int deleteCodeCacheDirsLI(String packageName) { 4830 int[] users = sUserManager.getUserIds(); 4831 int res = 0; 4832 for (int user : users) { 4833 int resInner = mInstaller.deleteCodeCacheFiles(packageName, user); 4834 if (resInner < 0) { 4835 res = resInner; 4836 } 4837 } 4838 return res; 4839 } 4840 4841 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 4842 PackageParser.Package changingLib) { 4843 if (file.path != null) { 4844 usesLibraryFiles.add(file.path); 4845 return; 4846 } 4847 PackageParser.Package p = mPackages.get(file.apk); 4848 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 4849 // If we are doing this while in the middle of updating a library apk, 4850 // then we need to make sure to use that new apk for determining the 4851 // dependencies here. (We haven't yet finished committing the new apk 4852 // to the package manager state.) 4853 if (p == null || p.packageName.equals(changingLib.packageName)) { 4854 p = changingLib; 4855 } 4856 } 4857 if (p != null) { 4858 usesLibraryFiles.addAll(p.getAllCodePaths()); 4859 } 4860 } 4861 4862 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 4863 PackageParser.Package changingLib) throws PackageManagerException { 4864 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 4865 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 4866 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 4867 for (int i=0; i<N; i++) { 4868 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 4869 if (file == null) { 4870 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 4871 "Package " + pkg.packageName + " requires unavailable shared library " 4872 + pkg.usesLibraries.get(i) + "; failing!"); 4873 } 4874 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4875 } 4876 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 4877 for (int i=0; i<N; i++) { 4878 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 4879 if (file == null) { 4880 Slog.w(TAG, "Package " + pkg.packageName 4881 + " desires unavailable shared library " 4882 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 4883 } else { 4884 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4885 } 4886 } 4887 N = usesLibraryFiles.size(); 4888 if (N > 0) { 4889 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 4890 } else { 4891 pkg.usesLibraryFiles = null; 4892 } 4893 } 4894 } 4895 4896 private static boolean hasString(List<String> list, List<String> which) { 4897 if (list == null) { 4898 return false; 4899 } 4900 for (int i=list.size()-1; i>=0; i--) { 4901 for (int j=which.size()-1; j>=0; j--) { 4902 if (which.get(j).equals(list.get(i))) { 4903 return true; 4904 } 4905 } 4906 } 4907 return false; 4908 } 4909 4910 private void updateAllSharedLibrariesLPw() { 4911 for (PackageParser.Package pkg : mPackages.values()) { 4912 try { 4913 updateSharedLibrariesLPw(pkg, null); 4914 } catch (PackageManagerException e) { 4915 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 4916 } 4917 } 4918 } 4919 4920 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 4921 PackageParser.Package changingPkg) { 4922 ArrayList<PackageParser.Package> res = null; 4923 for (PackageParser.Package pkg : mPackages.values()) { 4924 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 4925 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 4926 if (res == null) { 4927 res = new ArrayList<PackageParser.Package>(); 4928 } 4929 res.add(pkg); 4930 try { 4931 updateSharedLibrariesLPw(pkg, changingPkg); 4932 } catch (PackageManagerException e) { 4933 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 4934 } 4935 } 4936 } 4937 return res; 4938 } 4939 4940 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 4941 int scanMode, long currentTime, UserHandle user, String abiOverride) 4942 throws PackageManagerException { 4943 final File scanFile = new File(pkg.codePath); 4944 if (pkg.applicationInfo.getCodePath() == null || 4945 pkg.applicationInfo.getResourcePath() == null) { 4946 // Bail out. The resource and code paths haven't been set. 4947 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 4948 "Code and resource paths haven't been set correctly"); 4949 } 4950 4951 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4952 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 4953 } 4954 4955 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 4956 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED; 4957 } 4958 4959 if (mCustomResolverComponentName != null && 4960 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 4961 setUpCustomResolverActivity(pkg); 4962 } 4963 4964 if (pkg.packageName.equals("android")) { 4965 synchronized (mPackages) { 4966 if (mAndroidApplication != null) { 4967 Slog.w(TAG, "*************************************************"); 4968 Slog.w(TAG, "Core android package being redefined. Skipping."); 4969 Slog.w(TAG, " file=" + scanFile); 4970 Slog.w(TAG, "*************************************************"); 4971 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 4972 "Core android package being redefined. Skipping."); 4973 } 4974 4975 // Set up information for our fall-back user intent resolution activity. 4976 mPlatformPackage = pkg; 4977 pkg.mVersionCode = mSdkVersion; 4978 mAndroidApplication = pkg.applicationInfo; 4979 4980 if (!mResolverReplaced) { 4981 mResolveActivity.applicationInfo = mAndroidApplication; 4982 mResolveActivity.name = ResolverActivity.class.getName(); 4983 mResolveActivity.packageName = mAndroidApplication.packageName; 4984 mResolveActivity.processName = "system:ui"; 4985 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 4986 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 4987 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 4988 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 4989 mResolveActivity.exported = true; 4990 mResolveActivity.enabled = true; 4991 mResolveInfo.activityInfo = mResolveActivity; 4992 mResolveInfo.priority = 0; 4993 mResolveInfo.preferredOrder = 0; 4994 mResolveInfo.match = 0; 4995 mResolveComponentName = new ComponentName( 4996 mAndroidApplication.packageName, mResolveActivity.name); 4997 } 4998 } 4999 } 5000 5001 if (DEBUG_PACKAGE_SCANNING) { 5002 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5003 Log.d(TAG, "Scanning package " + pkg.packageName); 5004 } 5005 5006 if (mPackages.containsKey(pkg.packageName) 5007 || mSharedLibraries.containsKey(pkg.packageName)) { 5008 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5009 "Application package " + pkg.packageName 5010 + " already installed. Skipping duplicate."); 5011 } 5012 5013 // Initialize package source and resource directories 5014 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5015 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5016 5017 SharedUserSetting suid = null; 5018 PackageSetting pkgSetting = null; 5019 5020 if (!isSystemApp(pkg)) { 5021 // Only system apps can use these features. 5022 pkg.mOriginalPackages = null; 5023 pkg.mRealPackage = null; 5024 pkg.mAdoptPermissions = null; 5025 } 5026 5027 // writer 5028 synchronized (mPackages) { 5029 if (pkg.mSharedUserId != null) { 5030 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true); 5031 if (suid == null) { 5032 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5033 "Creating application package " + pkg.packageName 5034 + " for shared user failed"); 5035 } 5036 if (DEBUG_PACKAGE_SCANNING) { 5037 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5038 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5039 + "): packages=" + suid.packages); 5040 } 5041 } 5042 5043 // Check if we are renaming from an original package name. 5044 PackageSetting origPackage = null; 5045 String realName = null; 5046 if (pkg.mOriginalPackages != null) { 5047 // This package may need to be renamed to a previously 5048 // installed name. Let's check on that... 5049 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5050 if (pkg.mOriginalPackages.contains(renamed)) { 5051 // This package had originally been installed as the 5052 // original name, and we have already taken care of 5053 // transitioning to the new one. Just update the new 5054 // one to continue using the old name. 5055 realName = pkg.mRealPackage; 5056 if (!pkg.packageName.equals(renamed)) { 5057 // Callers into this function may have already taken 5058 // care of renaming the package; only do it here if 5059 // it is not already done. 5060 pkg.setPackageName(renamed); 5061 } 5062 5063 } else { 5064 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5065 if ((origPackage = mSettings.peekPackageLPr( 5066 pkg.mOriginalPackages.get(i))) != null) { 5067 // We do have the package already installed under its 5068 // original name... should we use it? 5069 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5070 // New package is not compatible with original. 5071 origPackage = null; 5072 continue; 5073 } else if (origPackage.sharedUser != null) { 5074 // Make sure uid is compatible between packages. 5075 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5076 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5077 + " to " + pkg.packageName + ": old uid " 5078 + origPackage.sharedUser.name 5079 + " differs from " + pkg.mSharedUserId); 5080 origPackage = null; 5081 continue; 5082 } 5083 } else { 5084 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5085 + pkg.packageName + " to old name " + origPackage.name); 5086 } 5087 break; 5088 } 5089 } 5090 } 5091 } 5092 5093 if (mTransferedPackages.contains(pkg.packageName)) { 5094 Slog.w(TAG, "Package " + pkg.packageName 5095 + " was transferred to another, but its .apk remains"); 5096 } 5097 5098 // Just create the setting, don't add it yet. For already existing packages 5099 // the PkgSetting exists already and doesn't have to be created. 5100 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5101 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 5102 pkg.applicationInfo.primaryCpuAbi, 5103 pkg.applicationInfo.secondaryCpuAbi, 5104 pkg.applicationInfo.flags, user, false); 5105 if (pkgSetting == null) { 5106 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5107 "Creating application package " + pkg.packageName + " failed"); 5108 } 5109 5110 if (pkgSetting.origPackage != null) { 5111 // If we are first transitioning from an original package, 5112 // fix up the new package's name now. We need to do this after 5113 // looking up the package under its new name, so getPackageLP 5114 // can take care of fiddling things correctly. 5115 pkg.setPackageName(origPackage.name); 5116 5117 // File a report about this. 5118 String msg = "New package " + pkgSetting.realName 5119 + " renamed to replace old package " + pkgSetting.name; 5120 reportSettingsProblem(Log.WARN, msg); 5121 5122 // Make a note of it. 5123 mTransferedPackages.add(origPackage.name); 5124 5125 // No longer need to retain this. 5126 pkgSetting.origPackage = null; 5127 } 5128 5129 if (realName != null) { 5130 // Make a note of it. 5131 mTransferedPackages.add(pkg.packageName); 5132 } 5133 5134 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5135 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5136 } 5137 5138 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5139 // Check all shared libraries and map to their actual file path. 5140 // We only do this here for apps not on a system dir, because those 5141 // are the only ones that can fail an install due to this. We 5142 // will take care of the system apps by updating all of their 5143 // library paths after the scan is done. 5144 updateSharedLibrariesLPw(pkg, null); 5145 } 5146 5147 if (mFoundPolicyFile) { 5148 SELinuxMMAC.assignSeinfoValue(pkg); 5149 } 5150 5151 pkg.applicationInfo.uid = pkgSetting.appId; 5152 pkg.mExtras = pkgSetting; 5153 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5154 try { 5155 verifySignaturesLP(pkgSetting, pkg); 5156 } catch (PackageManagerException e) { 5157 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5158 throw e; 5159 } 5160 // The signature has changed, but this package is in the system 5161 // image... let's recover! 5162 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5163 // However... if this package is part of a shared user, but it 5164 // doesn't match the signature of the shared user, let's fail. 5165 // What this means is that you can't change the signatures 5166 // associated with an overall shared user, which doesn't seem all 5167 // that unreasonable. 5168 if (pkgSetting.sharedUser != null) { 5169 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5170 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5171 throw new PackageManagerException( 5172 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 5173 "Signature mismatch for shared user : " 5174 + pkgSetting.sharedUser); 5175 } 5176 } 5177 // File a report about this. 5178 String msg = "System package " + pkg.packageName 5179 + " signature changed; retaining data."; 5180 reportSettingsProblem(Log.WARN, msg); 5181 } 5182 } else { 5183 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 5184 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5185 + pkg.packageName + " upgrade keys do not match the " 5186 + "previously installed version"); 5187 } else { 5188 // signatures may have changed as result of upgrade 5189 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5190 } 5191 } 5192 // Verify that this new package doesn't have any content providers 5193 // that conflict with existing packages. Only do this if the 5194 // package isn't already installed, since we don't want to break 5195 // things that are installed. 5196 if ((scanMode&SCAN_NEW_INSTALL) != 0) { 5197 final int N = pkg.providers.size(); 5198 int i; 5199 for (i=0; i<N; i++) { 5200 PackageParser.Provider p = pkg.providers.get(i); 5201 if (p.info.authority != null) { 5202 String names[] = p.info.authority.split(";"); 5203 for (int j = 0; j < names.length; j++) { 5204 if (mProvidersByAuthority.containsKey(names[j])) { 5205 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5206 final String otherPackageName = 5207 ((other != null && other.getComponentName() != null) ? 5208 other.getComponentName().getPackageName() : "?"); 5209 throw new PackageManagerException( 5210 INSTALL_FAILED_CONFLICTING_PROVIDER, 5211 "Can't install because provider name " + names[j] 5212 + " (in package " + pkg.applicationInfo.packageName 5213 + ") is already used by " + otherPackageName); 5214 } 5215 } 5216 } 5217 } 5218 } 5219 5220 if (pkg.mAdoptPermissions != null) { 5221 // This package wants to adopt ownership of permissions from 5222 // another package. 5223 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 5224 final String origName = pkg.mAdoptPermissions.get(i); 5225 final PackageSetting orig = mSettings.peekPackageLPr(origName); 5226 if (orig != null) { 5227 if (verifyPackageUpdateLPr(orig, pkg)) { 5228 Slog.i(TAG, "Adopting permissions from " + origName + " to " 5229 + pkg.packageName); 5230 mSettings.transferPermissionsLPw(origName, pkg.packageName); 5231 } 5232 } 5233 } 5234 } 5235 } 5236 5237 final String pkgName = pkg.packageName; 5238 5239 final long scanFileTime = scanFile.lastModified(); 5240 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0; 5241 pkg.applicationInfo.processName = fixProcessName( 5242 pkg.applicationInfo.packageName, 5243 pkg.applicationInfo.processName, 5244 pkg.applicationInfo.uid); 5245 5246 File dataPath; 5247 if (mPlatformPackage == pkg) { 5248 // The system package is special. 5249 dataPath = new File (Environment.getDataDirectory(), "system"); 5250 pkg.applicationInfo.dataDir = dataPath.getPath(); 5251 5252 } else { 5253 // This is a normal package, need to make its data directory. 5254 dataPath = getDataPathForPackage(pkg.packageName, 0); 5255 5256 boolean uidError = false; 5257 5258 if (dataPath.exists()) { 5259 int currentUid = 0; 5260 try { 5261 StructStat stat = Os.stat(dataPath.getPath()); 5262 currentUid = stat.st_uid; 5263 } catch (ErrnoException e) { 5264 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 5265 } 5266 5267 // If we have mismatched owners for the data path, we have a problem. 5268 if (currentUid != pkg.applicationInfo.uid) { 5269 boolean recovered = false; 5270 if (currentUid == 0) { 5271 // The directory somehow became owned by root. Wow. 5272 // This is probably because the system was stopped while 5273 // installd was in the middle of messing with its libs 5274 // directory. Ask installd to fix that. 5275 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 5276 pkg.applicationInfo.uid); 5277 if (ret >= 0) { 5278 recovered = true; 5279 String msg = "Package " + pkg.packageName 5280 + " unexpectedly changed to uid 0; recovered to " + 5281 + pkg.applicationInfo.uid; 5282 reportSettingsProblem(Log.WARN, msg); 5283 } 5284 } 5285 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5286 || (scanMode&SCAN_BOOTING) != 0)) { 5287 // If this is a system app, we can at least delete its 5288 // current data so the application will still work. 5289 int ret = removeDataDirsLI(pkgName); 5290 if (ret >= 0) { 5291 // TODO: Kill the processes first 5292 // Old data gone! 5293 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5294 ? "System package " : "Third party package "; 5295 String msg = prefix + pkg.packageName 5296 + " has changed from uid: " 5297 + currentUid + " to " 5298 + pkg.applicationInfo.uid + "; old data erased"; 5299 reportSettingsProblem(Log.WARN, msg); 5300 recovered = true; 5301 5302 // And now re-install the app. 5303 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5304 pkg.applicationInfo.seinfo); 5305 if (ret == -1) { 5306 // Ack should not happen! 5307 msg = prefix + pkg.packageName 5308 + " could not have data directory re-created after delete."; 5309 reportSettingsProblem(Log.WARN, msg); 5310 throw new PackageManagerException( 5311 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 5312 } 5313 } 5314 if (!recovered) { 5315 mHasSystemUidErrors = true; 5316 } 5317 } else if (!recovered) { 5318 // If we allow this install to proceed, we will be broken. 5319 // Abort, abort! 5320 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 5321 "scanPackageLI"); 5322 } 5323 if (!recovered) { 5324 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 5325 + pkg.applicationInfo.uid + "/fs_" 5326 + currentUid; 5327 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 5328 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 5329 String msg = "Package " + pkg.packageName 5330 + " has mismatched uid: " 5331 + currentUid + " on disk, " 5332 + pkg.applicationInfo.uid + " in settings"; 5333 // writer 5334 synchronized (mPackages) { 5335 mSettings.mReadMessages.append(msg); 5336 mSettings.mReadMessages.append('\n'); 5337 uidError = true; 5338 if (!pkgSetting.uidError) { 5339 reportSettingsProblem(Log.ERROR, msg); 5340 } 5341 } 5342 } 5343 } 5344 pkg.applicationInfo.dataDir = dataPath.getPath(); 5345 if (mShouldRestoreconData) { 5346 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 5347 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 5348 pkg.applicationInfo.uid); 5349 } 5350 } else { 5351 if (DEBUG_PACKAGE_SCANNING) { 5352 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5353 Log.v(TAG, "Want this data dir: " + dataPath); 5354 } 5355 //invoke installer to do the actual installation 5356 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5357 pkg.applicationInfo.seinfo); 5358 if (ret < 0) { 5359 // Error from installer 5360 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5361 "Unable to create data dirs [errorCode=" + ret + "]"); 5362 } 5363 5364 if (dataPath.exists()) { 5365 pkg.applicationInfo.dataDir = dataPath.getPath(); 5366 } else { 5367 Slog.w(TAG, "Unable to create data directory: " + dataPath); 5368 pkg.applicationInfo.dataDir = null; 5369 } 5370 } 5371 5372 pkgSetting.uidError = uidError; 5373 } 5374 5375 final String path = scanFile.getPath(); 5376 final String codePath = pkg.applicationInfo.getCodePath(); 5377 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 5378 // For the case where we had previously uninstalled an update, get rid 5379 // of any native binaries we might have unpackaged. Note that this assumes 5380 // that system app updates were not installed via ASEC. 5381 // 5382 // TODO(multiArch): Is this cleanup really necessary ? 5383 NativeLibraryHelper.removeNativeBinariesFromDirLI( 5384 new File(codePath, LIB_DIR_NAME), false /* delete dirs */); 5385 setBundledAppAbisAndRoots(pkg, pkgSetting); 5386 5387 // If we haven't found any native libraries for the app, check if it has 5388 // renderscript code. We'll need to force the app to 32 bit if it has 5389 // renderscript bitcode. 5390 if (pkg.applicationInfo.primaryCpuAbi == null 5391 && pkg.applicationInfo.secondaryCpuAbi == null 5392 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5393 NativeLibraryHelper.Handle handle = null; 5394 try { 5395 handle = NativeLibraryHelper.Handle.create(scanFile); 5396 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5397 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 5398 } 5399 } catch (IOException ioe) { 5400 Slog.w(TAG, "Error scanning system app : " + ioe); 5401 } finally { 5402 IoUtils.closeQuietly(handle); 5403 } 5404 } 5405 5406 setNativeLibraryPaths(pkg); 5407 } else { 5408 // TODO: We can probably be smarter about this stuff. For installed apps, 5409 // we can calculate this information at install time once and for all. For 5410 // system apps, we can probably assume that this information doesn't change 5411 // after the first boot scan. As things stand, we do lots of unnecessary work. 5412 5413 // Give ourselves some initial paths; we'll come back for another 5414 // pass once we've determined ABI below. 5415 setNativeLibraryPaths(pkg); 5416 5417 final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg); 5418 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 5419 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 5420 5421 NativeLibraryHelper.Handle handle = null; 5422 try { 5423 handle = NativeLibraryHelper.Handle.create(scanFile); 5424 // TODO(multiArch): This can be null for apps that didn't go through the 5425 // usual installation process. We can calculate it again, like we 5426 // do during install time. 5427 // 5428 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 5429 // unnecessary. 5430 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 5431 5432 // Null out the abis so that they can be recalculated. 5433 pkg.applicationInfo.primaryCpuAbi = null; 5434 pkg.applicationInfo.secondaryCpuAbi = null; 5435 if (isMultiArch(pkg.applicationInfo)) { 5436 // Warn if we've set an abiOverride for multi-lib packages.. 5437 // By definition, we need to copy both 32 and 64 bit libraries for 5438 // such packages. 5439 if (abiOverride != null) { 5440 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 5441 } 5442 5443 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 5444 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 5445 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 5446 if (isAsec) { 5447 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 5448 } else { 5449 abi32 = copyNativeLibrariesForInternalApp(handle, 5450 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, useIsaSpecificSubdirs); 5451 } 5452 } 5453 5454 maybeThrowExceptionForMultiArchCopy( 5455 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 5456 5457 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5458 if (isAsec) { 5459 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 5460 } else { 5461 abi64 = copyNativeLibrariesForInternalApp(handle, 5462 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, useIsaSpecificSubdirs); 5463 } 5464 } 5465 5466 maybeThrowExceptionForMultiArchCopy( 5467 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 5468 5469 if (abi64 >= 0) { 5470 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 5471 } 5472 5473 if (abi32 >= 0) { 5474 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 5475 if (abi64 >= 0) { 5476 pkg.applicationInfo.secondaryCpuAbi = abi; 5477 } else { 5478 pkg.applicationInfo.primaryCpuAbi = abi; 5479 } 5480 } 5481 } else { 5482 String[] abiList = (abiOverride != null) ? 5483 new String[] { abiOverride } : Build.SUPPORTED_ABIS; 5484 5485 // Enable gross and lame hacks for apps that are built with old 5486 // SDK tools. We must scan their APKs for renderscript bitcode and 5487 // not launch them if it's present. Don't bother checking on devices 5488 // that don't have 64 bit support. 5489 boolean needsRenderScriptOverride = false; 5490 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && abiOverride == null && 5491 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5492 abiList = Build.SUPPORTED_32_BIT_ABIS; 5493 needsRenderScriptOverride = true; 5494 } 5495 5496 final int copyRet; 5497 if (isAsec) { 5498 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 5499 } else { 5500 copyRet = copyNativeLibrariesForInternalApp(handle, nativeLibraryRoot, abiList, 5501 useIsaSpecificSubdirs); 5502 } 5503 5504 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5505 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5506 "Error unpackaging native libs for app, errorCode=" + copyRet); 5507 } 5508 5509 if (copyRet >= 0) { 5510 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 5511 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && abiOverride != null) { 5512 pkg.applicationInfo.primaryCpuAbi = abiOverride; 5513 } else if (needsRenderScriptOverride) { 5514 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 5515 } 5516 } 5517 } catch (IOException ioe) { 5518 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 5519 } finally { 5520 IoUtils.closeQuietly(handle); 5521 } 5522 5523 // Now that we've calculated the ABIs and determined if it's an internal app, 5524 // we will go ahead and populate the nativeLibraryPath. 5525 setNativeLibraryPaths(pkg); 5526 5527 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 5528 final int[] userIds = sUserManager.getUserIds(); 5529 synchronized (mInstallLock) { 5530 // Create a native library symlink only if we have native libraries 5531 // and if the native libraries are 32 bit libraries. We do not provide 5532 // this symlink for 64 bit libraries. 5533 if (pkg.applicationInfo.primaryCpuAbi != null && 5534 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 5535 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 5536 for (int userId : userIds) { 5537 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 5538 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5539 "Failed linking native library dir (user=" + userId + ")"); 5540 } 5541 } 5542 } 5543 } 5544 } 5545 5546 // This is a special case for the "system" package, where the ABI is 5547 // dictated by the zygote configuration (and init.rc). We should keep track 5548 // of this ABI so that we can deal with "normal" applications that run under 5549 // the same UID correctly. 5550 if (mPlatformPackage == pkg) { 5551 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 5552 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 5553 } 5554 5555 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 5556 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 5557 5558 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 5559 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 5560 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 5561 5562 // Push the derived path down into PackageSettings so we know what to 5563 // clean up at uninstall time. 5564 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 5565 5566 if (DEBUG_ABI_SELECTION) { 5567 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 5568 " primary=" + pkg.applicationInfo.primaryCpuAbi + 5569 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 5570 } 5571 5572 if ((scanMode&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 5573 // We don't do this here during boot because we can do it all 5574 // at once after scanning all existing packages. 5575 // 5576 // We also do this *before* we perform dexopt on this package, so that 5577 // we can avoid redundant dexopts, and also to make sure we've got the 5578 // code and package path correct. 5579 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 5580 pkg, forceDex, (scanMode & SCAN_DEFER_DEX) != 0); 5581 } 5582 5583 if ((scanMode&SCAN_NO_DEX) == 0) { 5584 if (performDexOptLI(pkg, null /* instruction sets */, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5585 == DEX_OPT_FAILED) { 5586 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5587 removeDataDirsLI(pkg.packageName); 5588 } 5589 5590 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 5591 } 5592 } 5593 5594 if (mFactoryTest && pkg.requestedPermissions.contains( 5595 android.Manifest.permission.FACTORY_TEST)) { 5596 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 5597 } 5598 5599 ArrayList<PackageParser.Package> clientLibPkgs = null; 5600 5601 // writer 5602 synchronized (mPackages) { 5603 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5604 // Only system apps can add new shared libraries. 5605 if (pkg.libraryNames != null) { 5606 for (int i=0; i<pkg.libraryNames.size(); i++) { 5607 String name = pkg.libraryNames.get(i); 5608 boolean allowed = false; 5609 if (isUpdatedSystemApp(pkg)) { 5610 // New library entries can only be added through the 5611 // system image. This is important to get rid of a lot 5612 // of nasty edge cases: for example if we allowed a non- 5613 // system update of the app to add a library, then uninstalling 5614 // the update would make the library go away, and assumptions 5615 // we made such as through app install filtering would now 5616 // have allowed apps on the device which aren't compatible 5617 // with it. Better to just have the restriction here, be 5618 // conservative, and create many fewer cases that can negatively 5619 // impact the user experience. 5620 final PackageSetting sysPs = mSettings 5621 .getDisabledSystemPkgLPr(pkg.packageName); 5622 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 5623 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 5624 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 5625 allowed = true; 5626 allowed = true; 5627 break; 5628 } 5629 } 5630 } 5631 } else { 5632 allowed = true; 5633 } 5634 if (allowed) { 5635 if (!mSharedLibraries.containsKey(name)) { 5636 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 5637 } else if (!name.equals(pkg.packageName)) { 5638 Slog.w(TAG, "Package " + pkg.packageName + " library " 5639 + name + " already exists; skipping"); 5640 } 5641 } else { 5642 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 5643 + name + " that is not declared on system image; skipping"); 5644 } 5645 } 5646 if ((scanMode&SCAN_BOOTING) == 0) { 5647 // If we are not booting, we need to update any applications 5648 // that are clients of our shared library. If we are booting, 5649 // this will all be done once the scan is complete. 5650 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 5651 } 5652 } 5653 } 5654 } 5655 5656 // We also need to dexopt any apps that are dependent on this library. Note that 5657 // if these fail, we should abort the install since installing the library will 5658 // result in some apps being broken. 5659 if (clientLibPkgs != null) { 5660 if ((scanMode&SCAN_NO_DEX) == 0) { 5661 for (int i=0; i<clientLibPkgs.size(); i++) { 5662 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5663 if (performDexOptLI(clientPkg, null /* instruction sets */, 5664 forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5665 == DEX_OPT_FAILED) { 5666 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5667 removeDataDirsLI(pkg.packageName); 5668 } 5669 5670 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 5671 "scanPackageLI failed to dexopt clientLibPkgs"); 5672 } 5673 } 5674 } 5675 } 5676 5677 // Request the ActivityManager to kill the process(only for existing packages) 5678 // so that we do not end up in a confused state while the user is still using the older 5679 // version of the application while the new one gets installed. 5680 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 5681 // If the package lives in an asec, tell everyone that the container is going 5682 // away so they can clean up any references to its resources (which would prevent 5683 // vold from being able to unmount the asec) 5684 if (isForwardLocked(pkg) || isExternal(pkg)) { 5685 if (DEBUG_INSTALL) { 5686 Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE"); 5687 } 5688 final int[] uidArray = new int[] { pkg.applicationInfo.uid }; 5689 final ArrayList<String> pkgList = new ArrayList<String>(1); 5690 pkgList.add(pkg.applicationInfo.packageName); 5691 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 5692 } 5693 5694 // Post the request that it be killed now that the going-away broadcast is en route 5695 killApplication(pkg.applicationInfo.packageName, 5696 pkg.applicationInfo.uid, "update pkg"); 5697 } 5698 5699 // Also need to kill any apps that are dependent on the library. 5700 if (clientLibPkgs != null) { 5701 for (int i=0; i<clientLibPkgs.size(); i++) { 5702 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5703 killApplication(clientPkg.applicationInfo.packageName, 5704 clientPkg.applicationInfo.uid, "update lib"); 5705 } 5706 } 5707 5708 // writer 5709 synchronized (mPackages) { 5710 // We don't expect installation to fail beyond this point, 5711 if ((scanMode&SCAN_MONITOR) != 0) { 5712 mAppDirs.put(pkg.codePath, pkg); 5713 } 5714 // Add the new setting to mSettings 5715 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 5716 // Add the new setting to mPackages 5717 mPackages.put(pkg.applicationInfo.packageName, pkg); 5718 // Make sure we don't accidentally delete its data. 5719 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 5720 while (iter.hasNext()) { 5721 PackageCleanItem item = iter.next(); 5722 if (pkgName.equals(item.packageName)) { 5723 iter.remove(); 5724 } 5725 } 5726 5727 // Take care of first install / last update times. 5728 if (currentTime != 0) { 5729 if (pkgSetting.firstInstallTime == 0) { 5730 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 5731 } else if ((scanMode&SCAN_UPDATE_TIME) != 0) { 5732 pkgSetting.lastUpdateTime = currentTime; 5733 } 5734 } else if (pkgSetting.firstInstallTime == 0) { 5735 // We need *something*. Take time time stamp of the file. 5736 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 5737 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 5738 if (scanFileTime != pkgSetting.timeStamp) { 5739 // A package on the system image has changed; consider this 5740 // to be an update. 5741 pkgSetting.lastUpdateTime = scanFileTime; 5742 } 5743 } 5744 5745 // Add the package's KeySets to the global KeySetManagerService 5746 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5747 try { 5748 // Old KeySetData no longer valid. 5749 ksms.removeAppKeySetDataLPw(pkg.packageName); 5750 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 5751 if (pkg.mKeySetMapping != null) { 5752 for (Map.Entry<String, ArraySet<PublicKey>> entry : 5753 pkg.mKeySetMapping.entrySet()) { 5754 if (entry.getValue() != null) { 5755 ksms.addDefinedKeySetToPackageLPw(pkg.packageName, 5756 entry.getValue(), entry.getKey()); 5757 } 5758 } 5759 if (pkg.mUpgradeKeySets != null) { 5760 for (String upgradeAlias : pkg.mUpgradeKeySets) { 5761 ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias); 5762 } 5763 } 5764 } 5765 } catch (NullPointerException e) { 5766 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 5767 } catch (IllegalArgumentException e) { 5768 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 5769 } 5770 5771 int N = pkg.providers.size(); 5772 StringBuilder r = null; 5773 int i; 5774 for (i=0; i<N; i++) { 5775 PackageParser.Provider p = pkg.providers.get(i); 5776 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 5777 p.info.processName, pkg.applicationInfo.uid); 5778 mProviders.addProvider(p); 5779 p.syncable = p.info.isSyncable; 5780 if (p.info.authority != null) { 5781 String names[] = p.info.authority.split(";"); 5782 p.info.authority = null; 5783 for (int j = 0; j < names.length; j++) { 5784 if (j == 1 && p.syncable) { 5785 // We only want the first authority for a provider to possibly be 5786 // syncable, so if we already added this provider using a different 5787 // authority clear the syncable flag. We copy the provider before 5788 // changing it because the mProviders object contains a reference 5789 // to a provider that we don't want to change. 5790 // Only do this for the second authority since the resulting provider 5791 // object can be the same for all future authorities for this provider. 5792 p = new PackageParser.Provider(p); 5793 p.syncable = false; 5794 } 5795 if (!mProvidersByAuthority.containsKey(names[j])) { 5796 mProvidersByAuthority.put(names[j], p); 5797 if (p.info.authority == null) { 5798 p.info.authority = names[j]; 5799 } else { 5800 p.info.authority = p.info.authority + ";" + names[j]; 5801 } 5802 if (DEBUG_PACKAGE_SCANNING) { 5803 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5804 Log.d(TAG, "Registered content provider: " + names[j] 5805 + ", className = " + p.info.name + ", isSyncable = " 5806 + p.info.isSyncable); 5807 } 5808 } else { 5809 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5810 Slog.w(TAG, "Skipping provider name " + names[j] + 5811 " (in package " + pkg.applicationInfo.packageName + 5812 "): name already used by " 5813 + ((other != null && other.getComponentName() != null) 5814 ? other.getComponentName().getPackageName() : "?")); 5815 } 5816 } 5817 } 5818 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5819 if (r == null) { 5820 r = new StringBuilder(256); 5821 } else { 5822 r.append(' '); 5823 } 5824 r.append(p.info.name); 5825 } 5826 } 5827 if (r != null) { 5828 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 5829 } 5830 5831 N = pkg.services.size(); 5832 r = null; 5833 for (i=0; i<N; i++) { 5834 PackageParser.Service s = pkg.services.get(i); 5835 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 5836 s.info.processName, pkg.applicationInfo.uid); 5837 mServices.addService(s); 5838 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5839 if (r == null) { 5840 r = new StringBuilder(256); 5841 } else { 5842 r.append(' '); 5843 } 5844 r.append(s.info.name); 5845 } 5846 } 5847 if (r != null) { 5848 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 5849 } 5850 5851 N = pkg.receivers.size(); 5852 r = null; 5853 for (i=0; i<N; i++) { 5854 PackageParser.Activity a = pkg.receivers.get(i); 5855 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5856 a.info.processName, pkg.applicationInfo.uid); 5857 mReceivers.addActivity(a, "receiver"); 5858 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5859 if (r == null) { 5860 r = new StringBuilder(256); 5861 } else { 5862 r.append(' '); 5863 } 5864 r.append(a.info.name); 5865 } 5866 } 5867 if (r != null) { 5868 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 5869 } 5870 5871 N = pkg.activities.size(); 5872 r = null; 5873 for (i=0; i<N; i++) { 5874 PackageParser.Activity a = pkg.activities.get(i); 5875 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5876 a.info.processName, pkg.applicationInfo.uid); 5877 mActivities.addActivity(a, "activity"); 5878 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5879 if (r == null) { 5880 r = new StringBuilder(256); 5881 } else { 5882 r.append(' '); 5883 } 5884 r.append(a.info.name); 5885 } 5886 } 5887 if (r != null) { 5888 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 5889 } 5890 5891 N = pkg.permissionGroups.size(); 5892 r = null; 5893 for (i=0; i<N; i++) { 5894 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 5895 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 5896 if (cur == null) { 5897 mPermissionGroups.put(pg.info.name, pg); 5898 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5899 if (r == null) { 5900 r = new StringBuilder(256); 5901 } else { 5902 r.append(' '); 5903 } 5904 r.append(pg.info.name); 5905 } 5906 } else { 5907 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 5908 + pg.info.packageName + " ignored: original from " 5909 + cur.info.packageName); 5910 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5911 if (r == null) { 5912 r = new StringBuilder(256); 5913 } else { 5914 r.append(' '); 5915 } 5916 r.append("DUP:"); 5917 r.append(pg.info.name); 5918 } 5919 } 5920 } 5921 if (r != null) { 5922 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 5923 } 5924 5925 N = pkg.permissions.size(); 5926 r = null; 5927 for (i=0; i<N; i++) { 5928 PackageParser.Permission p = pkg.permissions.get(i); 5929 HashMap<String, BasePermission> permissionMap = 5930 p.tree ? mSettings.mPermissionTrees 5931 : mSettings.mPermissions; 5932 p.group = mPermissionGroups.get(p.info.group); 5933 if (p.info.group == null || p.group != null) { 5934 BasePermission bp = permissionMap.get(p.info.name); 5935 if (bp == null) { 5936 bp = new BasePermission(p.info.name, p.info.packageName, 5937 BasePermission.TYPE_NORMAL); 5938 permissionMap.put(p.info.name, bp); 5939 } 5940 if (bp.perm == null) { 5941 if (bp.sourcePackage != null 5942 && !bp.sourcePackage.equals(p.info.packageName)) { 5943 // If this is a permission that was formerly defined by a non-system 5944 // app, but is now defined by a system app (following an upgrade), 5945 // discard the previous declaration and consider the system's to be 5946 // canonical. 5947 if (isSystemApp(p.owner)) { 5948 String msg = "New decl " + p.owner + " of permission " 5949 + p.info.name + " is system"; 5950 reportSettingsProblem(Log.WARN, msg); 5951 bp.sourcePackage = null; 5952 } 5953 } 5954 if (bp.sourcePackage == null 5955 || bp.sourcePackage.equals(p.info.packageName)) { 5956 BasePermission tree = findPermissionTreeLP(p.info.name); 5957 if (tree == null 5958 || tree.sourcePackage.equals(p.info.packageName)) { 5959 bp.packageSetting = pkgSetting; 5960 bp.perm = p; 5961 bp.uid = pkg.applicationInfo.uid; 5962 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5963 if (r == null) { 5964 r = new StringBuilder(256); 5965 } else { 5966 r.append(' '); 5967 } 5968 r.append(p.info.name); 5969 } 5970 } else { 5971 Slog.w(TAG, "Permission " + p.info.name + " from package " 5972 + p.info.packageName + " ignored: base tree " 5973 + tree.name + " is from package " 5974 + tree.sourcePackage); 5975 } 5976 } else { 5977 Slog.w(TAG, "Permission " + p.info.name + " from package " 5978 + p.info.packageName + " ignored: original from " 5979 + bp.sourcePackage); 5980 } 5981 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5982 if (r == null) { 5983 r = new StringBuilder(256); 5984 } else { 5985 r.append(' '); 5986 } 5987 r.append("DUP:"); 5988 r.append(p.info.name); 5989 } 5990 if (bp.perm == p) { 5991 bp.protectionLevel = p.info.protectionLevel; 5992 } 5993 } else { 5994 Slog.w(TAG, "Permission " + p.info.name + " from package " 5995 + p.info.packageName + " ignored: no group " 5996 + p.group); 5997 } 5998 } 5999 if (r != null) { 6000 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6001 } 6002 6003 N = pkg.instrumentation.size(); 6004 r = null; 6005 for (i=0; i<N; i++) { 6006 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6007 a.info.packageName = pkg.applicationInfo.packageName; 6008 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6009 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6010 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6011 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6012 a.info.dataDir = pkg.applicationInfo.dataDir; 6013 6014 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6015 // need other information about the application, like the ABI and what not ? 6016 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6017 mInstrumentation.put(a.getComponentName(), a); 6018 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6019 if (r == null) { 6020 r = new StringBuilder(256); 6021 } else { 6022 r.append(' '); 6023 } 6024 r.append(a.info.name); 6025 } 6026 } 6027 if (r != null) { 6028 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6029 } 6030 6031 if (pkg.protectedBroadcasts != null) { 6032 N = pkg.protectedBroadcasts.size(); 6033 for (i=0; i<N; i++) { 6034 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6035 } 6036 } 6037 6038 pkgSetting.setTimeStamp(scanFileTime); 6039 6040 // Create idmap files for pairs of (packages, overlay packages). 6041 // Note: "android", ie framework-res.apk, is handled by native layers. 6042 if (pkg.mOverlayTarget != null) { 6043 // This is an overlay package. 6044 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6045 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6046 mOverlays.put(pkg.mOverlayTarget, 6047 new HashMap<String, PackageParser.Package>()); 6048 } 6049 HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6050 map.put(pkg.packageName, pkg); 6051 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6052 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6053 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6054 "scanPackageLI failed to createIdmap"); 6055 } 6056 } 6057 } else if (mOverlays.containsKey(pkg.packageName) && 6058 !pkg.packageName.equals("android")) { 6059 // This is a regular package, with one or more known overlay packages. 6060 createIdmapsForPackageLI(pkg); 6061 } 6062 } 6063 6064 return pkg; 6065 } 6066 6067 /** 6068 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6069 * i.e, so that all packages can be run inside a single process if required. 6070 * 6071 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6072 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6073 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6074 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6075 * updating a package that belongs to a shared user. 6076 * 6077 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6078 * adds unnecessary complexity. 6079 */ 6080 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6081 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6082 String requiredInstructionSet = null; 6083 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6084 requiredInstructionSet = VMRuntime.getInstructionSet( 6085 scannedPackage.applicationInfo.primaryCpuAbi); 6086 } 6087 6088 PackageSetting requirer = null; 6089 for (PackageSetting ps : packagesForUser) { 6090 // If packagesForUser contains scannedPackage, we skip it. This will happen 6091 // when scannedPackage is an update of an existing package. Without this check, 6092 // we will never be able to change the ABI of any package belonging to a shared 6093 // user, even if it's compatible with other packages. 6094 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6095 if (ps.primaryCpuAbiString == null) { 6096 continue; 6097 } 6098 6099 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6100 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6101 // We have a mismatch between instruction sets (say arm vs arm64) warn about 6102 // this but there's not much we can do. 6103 String errorMessage = "Instruction set mismatch, " 6104 + ((requirer == null) ? "[caller]" : requirer) 6105 + " requires " + requiredInstructionSet + " whereas " + ps 6106 + " requires " + instructionSet; 6107 Slog.w(TAG, errorMessage); 6108 } 6109 6110 if (requiredInstructionSet == null) { 6111 requiredInstructionSet = instructionSet; 6112 requirer = ps; 6113 } 6114 } 6115 } 6116 6117 if (requiredInstructionSet != null) { 6118 String adjustedAbi; 6119 if (requirer != null) { 6120 // requirer != null implies that either scannedPackage was null or that scannedPackage 6121 // did not require an ABI, in which case we have to adjust scannedPackage to match 6122 // the ABI of the set (which is the same as requirer's ABI) 6123 adjustedAbi = requirer.primaryCpuAbiString; 6124 if (scannedPackage != null) { 6125 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6126 } 6127 } else { 6128 // requirer == null implies that we're updating all ABIs in the set to 6129 // match scannedPackage. 6130 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6131 } 6132 6133 for (PackageSetting ps : packagesForUser) { 6134 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6135 if (ps.primaryCpuAbiString != null) { 6136 continue; 6137 } 6138 6139 ps.primaryCpuAbiString = adjustedAbi; 6140 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6141 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6142 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6143 6144 if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt, 6145 deferDexOpt, true) == DEX_OPT_FAILED) { 6146 ps.primaryCpuAbiString = null; 6147 ps.pkg.applicationInfo.primaryCpuAbi = null; 6148 return; 6149 } else { 6150 mInstaller.rmdex(ps.codePathString, getPreferredInstructionSet()); 6151 } 6152 } 6153 } 6154 } 6155 } 6156 } 6157 6158 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6159 synchronized (mPackages) { 6160 mResolverReplaced = true; 6161 // Set up information for custom user intent resolution activity. 6162 mResolveActivity.applicationInfo = pkg.applicationInfo; 6163 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6164 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6165 mResolveActivity.processName = null; 6166 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6167 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6168 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6169 mResolveActivity.theme = 0; 6170 mResolveActivity.exported = true; 6171 mResolveActivity.enabled = true; 6172 mResolveInfo.activityInfo = mResolveActivity; 6173 mResolveInfo.priority = 0; 6174 mResolveInfo.preferredOrder = 0; 6175 mResolveInfo.match = 0; 6176 mResolveComponentName = mCustomResolverComponentName; 6177 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6178 mResolveComponentName); 6179 } 6180 } 6181 6182 private static String calculateApkRoot(final String codePathString) { 6183 final File codePath = new File(codePathString); 6184 final File codeRoot; 6185 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6186 codeRoot = Environment.getRootDirectory(); 6187 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6188 codeRoot = Environment.getOemDirectory(); 6189 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6190 codeRoot = Environment.getVendorDirectory(); 6191 } else { 6192 // Unrecognized code path; take its top real segment as the apk root: 6193 // e.g. /something/app/blah.apk => /something 6194 try { 6195 File f = codePath.getCanonicalFile(); 6196 File parent = f.getParentFile(); // non-null because codePath is a file 6197 File tmp; 6198 while ((tmp = parent.getParentFile()) != null) { 6199 f = parent; 6200 parent = tmp; 6201 } 6202 codeRoot = f; 6203 Slog.w(TAG, "Unrecognized code path " 6204 + codePath + " - using " + codeRoot); 6205 } catch (IOException e) { 6206 // Can't canonicalize the code path -- shenanigans? 6207 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6208 return Environment.getRootDirectory().getPath(); 6209 } 6210 } 6211 return codeRoot.getPath(); 6212 } 6213 6214 /** 6215 * Derive and set the location of native libraries for the given package, 6216 * which varies depending on where and how the package was installed. 6217 */ 6218 private void setNativeLibraryPaths(PackageParser.Package pkg) { 6219 final ApplicationInfo info = pkg.applicationInfo; 6220 final String codePath = pkg.codePath; 6221 final File codeFile = new File(codePath); 6222 // If "/system/lib64/apkname" exists, assume that is the per-package 6223 // native library directory to use; otherwise use "/system/lib/apkname". 6224 final String apkRoot = calculateApkRoot(info.sourceDir); 6225 6226 final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info); 6227 final boolean asecApp = isForwardLocked(info) || isExternal(info); 6228 6229 6230 info.nativeLibraryRootDir = null; 6231 info.nativeLibraryRootRequiresIsa = false; 6232 info.nativeLibraryDir = null; 6233 info.secondaryNativeLibraryDir = null; 6234 6235 if (isApkFile(codeFile)) { 6236 // Monolithic install 6237 if (bundledApp) { 6238 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 6239 getPrimaryInstructionSet(info)); 6240 6241 // This is a bundled system app so choose the path based on the ABI. 6242 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 6243 // is just the default path. 6244 final String apkName = deriveCodePathName(codePath); 6245 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 6246 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 6247 apkName).getAbsolutePath(); 6248 6249 if (info.secondaryCpuAbi != null) { 6250 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 6251 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 6252 secondaryLibDir, apkName).getAbsolutePath(); 6253 } 6254 } else if (asecApp) { 6255 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 6256 .getAbsolutePath(); 6257 } else { 6258 final String apkName = deriveCodePathName(codePath); 6259 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 6260 .getAbsolutePath(); 6261 } 6262 6263 info.nativeLibraryRootRequiresIsa = false; 6264 info.nativeLibraryDir = info.nativeLibraryRootDir; 6265 } else { 6266 // Cluster install 6267 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 6268 info.nativeLibraryRootRequiresIsa = true; 6269 6270 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 6271 getPrimaryInstructionSet(info)).getAbsolutePath(); 6272 6273 if (info.secondaryCpuAbi != null) { 6274 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 6275 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 6276 } 6277 } 6278 } 6279 6280 /** 6281 * Calculate the abis and roots for a bundled app. These can uniquely 6282 * be determined from the contents of the system partition, i.e whether 6283 * it contains 64 or 32 bit shared libraries etc. We do not validate any 6284 * of this information, and instead assume that the system was built 6285 * sensibly. 6286 */ 6287 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 6288 PackageSetting pkgSetting) { 6289 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 6290 6291 // If "/system/lib64/apkname" exists, assume that is the per-package 6292 // native library directory to use; otherwise use "/system/lib/apkname". 6293 final String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir); 6294 setBundledAppAbi(pkg, apkRoot, apkName); 6295 // pkgSetting might be null during rescan following uninstall of updates 6296 // to a bundled app, so accommodate that possibility. The settings in 6297 // that case will be established later from the parsed package. 6298 // 6299 // If the settings aren't null, sync them up with what we've just derived. 6300 // note that apkRoot isn't stored in the package settings. 6301 if (pkgSetting != null) { 6302 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6303 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6304 } 6305 } 6306 6307 /** 6308 * Deduces the ABI of a bundled app and sets the relevant fields on the 6309 * parsed pkg object. 6310 * 6311 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 6312 * under which system libraries are installed. 6313 * @param apkName the name of the installed package. 6314 */ 6315 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 6316 final File codeFile = new File(pkg.codePath); 6317 6318 final boolean has64BitLibs; 6319 final boolean has32BitLibs; 6320 if (isApkFile(codeFile)) { 6321 // Monolithic install 6322 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 6323 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 6324 } else { 6325 // Cluster install 6326 final File rootDir = new File(codeFile, LIB_DIR_NAME); 6327 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 6328 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 6329 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 6330 has64BitLibs = (new File(rootDir, isa)).exists(); 6331 } else { 6332 has64BitLibs = false; 6333 } 6334 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 6335 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 6336 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 6337 has32BitLibs = (new File(rootDir, isa)).exists(); 6338 } else { 6339 has32BitLibs = false; 6340 } 6341 } 6342 6343 if (has64BitLibs && !has32BitLibs) { 6344 // The package has 64 bit libs, but not 32 bit libs. Its primary 6345 // ABI should be 64 bit. We can safely assume here that the bundled 6346 // native libraries correspond to the most preferred ABI in the list. 6347 6348 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6349 pkg.applicationInfo.secondaryCpuAbi = null; 6350 } else if (has32BitLibs && !has64BitLibs) { 6351 // The package has 32 bit libs but not 64 bit libs. Its primary 6352 // ABI should be 32 bit. 6353 6354 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6355 pkg.applicationInfo.secondaryCpuAbi = null; 6356 } else if (has32BitLibs && has64BitLibs) { 6357 // The application has both 64 and 32 bit bundled libraries. We check 6358 // here that the app declares multiArch support, and warn if it doesn't. 6359 // 6360 // We will be lenient here and record both ABIs. The primary will be the 6361 // ABI that's higher on the list, i.e, a device that's configured to prefer 6362 // 64 bit apps will see a 64 bit primary ABI, 6363 6364 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 6365 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 6366 } 6367 6368 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 6369 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6370 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6371 } else { 6372 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6373 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6374 } 6375 } else { 6376 pkg.applicationInfo.primaryCpuAbi = null; 6377 pkg.applicationInfo.secondaryCpuAbi = null; 6378 } 6379 } 6380 6381 private static void createNativeLibrarySubdir(File path) throws IOException { 6382 if (!path.isDirectory()) { 6383 path.delete(); 6384 6385 if (!path.mkdir()) { 6386 throw new IOException("Cannot create " + path.getPath()); 6387 } 6388 6389 try { 6390 Os.chmod(path.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); 6391 } catch (ErrnoException e) { 6392 throw new IOException("Cannot chmod native library directory " 6393 + path.getPath(), e); 6394 } 6395 } else if (!SELinux.restorecon(path)) { 6396 throw new IOException("Cannot set SELinux context for " + path.getPath()); 6397 } 6398 } 6399 6400 private static int copyNativeLibrariesForInternalApp(NativeLibraryHelper.Handle handle, 6401 final File nativeLibraryRoot, String[] abiList, boolean useIsaSubdir) throws IOException { 6402 createNativeLibrarySubdir(nativeLibraryRoot); 6403 6404 /* 6405 * If this is an internal application or our nativeLibraryPath points to 6406 * the app-lib directory, unpack the libraries if necessary. 6407 */ 6408 int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList); 6409 if (abi >= 0) { 6410 /* 6411 * If we have a matching instruction set, construct a subdir under the native 6412 * library root that corresponds to this instruction set. 6413 */ 6414 final String instructionSet = VMRuntime.getInstructionSet(abiList[abi]); 6415 final File subDir; 6416 if (useIsaSubdir) { 6417 final File isaSubdir = new File(nativeLibraryRoot, instructionSet); 6418 createNativeLibrarySubdir(isaSubdir); 6419 subDir = isaSubdir; 6420 } else { 6421 subDir = nativeLibraryRoot; 6422 } 6423 6424 int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle, subDir, abiList[abi]); 6425 if (copyRet != PackageManager.INSTALL_SUCCEEDED) { 6426 return copyRet; 6427 } 6428 } 6429 6430 return abi; 6431 } 6432 6433 private void killApplication(String pkgName, int appId, String reason) { 6434 // Request the ActivityManager to kill the process(only for existing packages) 6435 // so that we do not end up in a confused state while the user is still using the older 6436 // version of the application while the new one gets installed. 6437 IActivityManager am = ActivityManagerNative.getDefault(); 6438 if (am != null) { 6439 try { 6440 am.killApplicationWithAppId(pkgName, appId, reason); 6441 } catch (RemoteException e) { 6442 } 6443 } 6444 } 6445 6446 void removePackageLI(PackageSetting ps, boolean chatty) { 6447 if (DEBUG_INSTALL) { 6448 if (chatty) 6449 Log.d(TAG, "Removing package " + ps.name); 6450 } 6451 6452 // writer 6453 synchronized (mPackages) { 6454 mPackages.remove(ps.name); 6455 if (ps.codePathString != null) { 6456 mAppDirs.remove(ps.codePathString); 6457 } 6458 6459 final PackageParser.Package pkg = ps.pkg; 6460 if (pkg != null) { 6461 cleanPackageDataStructuresLILPw(pkg, chatty); 6462 } 6463 } 6464 } 6465 6466 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 6467 if (DEBUG_INSTALL) { 6468 if (chatty) 6469 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 6470 } 6471 6472 // writer 6473 synchronized (mPackages) { 6474 mPackages.remove(pkg.applicationInfo.packageName); 6475 if (pkg.codePath != null) { 6476 mAppDirs.remove(pkg.codePath); 6477 } 6478 cleanPackageDataStructuresLILPw(pkg, chatty); 6479 } 6480 } 6481 6482 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 6483 int N = pkg.providers.size(); 6484 StringBuilder r = null; 6485 int i; 6486 for (i=0; i<N; i++) { 6487 PackageParser.Provider p = pkg.providers.get(i); 6488 mProviders.removeProvider(p); 6489 if (p.info.authority == null) { 6490 6491 /* There was another ContentProvider with this authority when 6492 * this app was installed so this authority is null, 6493 * Ignore it as we don't have to unregister the provider. 6494 */ 6495 continue; 6496 } 6497 String names[] = p.info.authority.split(";"); 6498 for (int j = 0; j < names.length; j++) { 6499 if (mProvidersByAuthority.get(names[j]) == p) { 6500 mProvidersByAuthority.remove(names[j]); 6501 if (DEBUG_REMOVE) { 6502 if (chatty) 6503 Log.d(TAG, "Unregistered content provider: " + names[j] 6504 + ", className = " + p.info.name + ", isSyncable = " 6505 + p.info.isSyncable); 6506 } 6507 } 6508 } 6509 if (DEBUG_REMOVE && chatty) { 6510 if (r == null) { 6511 r = new StringBuilder(256); 6512 } else { 6513 r.append(' '); 6514 } 6515 r.append(p.info.name); 6516 } 6517 } 6518 if (r != null) { 6519 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 6520 } 6521 6522 N = pkg.services.size(); 6523 r = null; 6524 for (i=0; i<N; i++) { 6525 PackageParser.Service s = pkg.services.get(i); 6526 mServices.removeService(s); 6527 if (chatty) { 6528 if (r == null) { 6529 r = new StringBuilder(256); 6530 } else { 6531 r.append(' '); 6532 } 6533 r.append(s.info.name); 6534 } 6535 } 6536 if (r != null) { 6537 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 6538 } 6539 6540 N = pkg.receivers.size(); 6541 r = null; 6542 for (i=0; i<N; i++) { 6543 PackageParser.Activity a = pkg.receivers.get(i); 6544 mReceivers.removeActivity(a, "receiver"); 6545 if (DEBUG_REMOVE && chatty) { 6546 if (r == null) { 6547 r = new StringBuilder(256); 6548 } else { 6549 r.append(' '); 6550 } 6551 r.append(a.info.name); 6552 } 6553 } 6554 if (r != null) { 6555 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 6556 } 6557 6558 N = pkg.activities.size(); 6559 r = null; 6560 for (i=0; i<N; i++) { 6561 PackageParser.Activity a = pkg.activities.get(i); 6562 mActivities.removeActivity(a, "activity"); 6563 if (DEBUG_REMOVE && chatty) { 6564 if (r == null) { 6565 r = new StringBuilder(256); 6566 } else { 6567 r.append(' '); 6568 } 6569 r.append(a.info.name); 6570 } 6571 } 6572 if (r != null) { 6573 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 6574 } 6575 6576 N = pkg.permissions.size(); 6577 r = null; 6578 for (i=0; i<N; i++) { 6579 PackageParser.Permission p = pkg.permissions.get(i); 6580 BasePermission bp = mSettings.mPermissions.get(p.info.name); 6581 if (bp == null) { 6582 bp = mSettings.mPermissionTrees.get(p.info.name); 6583 } 6584 if (bp != null && bp.perm == p) { 6585 bp.perm = null; 6586 if (DEBUG_REMOVE && chatty) { 6587 if (r == null) { 6588 r = new StringBuilder(256); 6589 } else { 6590 r.append(' '); 6591 } 6592 r.append(p.info.name); 6593 } 6594 } 6595 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6596 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 6597 if (appOpPerms != null) { 6598 appOpPerms.remove(pkg.packageName); 6599 } 6600 } 6601 } 6602 if (r != null) { 6603 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6604 } 6605 6606 N = pkg.requestedPermissions.size(); 6607 r = null; 6608 for (i=0; i<N; i++) { 6609 String perm = pkg.requestedPermissions.get(i); 6610 BasePermission bp = mSettings.mPermissions.get(perm); 6611 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6612 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 6613 if (appOpPerms != null) { 6614 appOpPerms.remove(pkg.packageName); 6615 if (appOpPerms.isEmpty()) { 6616 mAppOpPermissionPackages.remove(perm); 6617 } 6618 } 6619 } 6620 } 6621 if (r != null) { 6622 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6623 } 6624 6625 N = pkg.instrumentation.size(); 6626 r = null; 6627 for (i=0; i<N; i++) { 6628 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6629 mInstrumentation.remove(a.getComponentName()); 6630 if (DEBUG_REMOVE && chatty) { 6631 if (r == null) { 6632 r = new StringBuilder(256); 6633 } else { 6634 r.append(' '); 6635 } 6636 r.append(a.info.name); 6637 } 6638 } 6639 if (r != null) { 6640 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 6641 } 6642 6643 r = null; 6644 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6645 // Only system apps can hold shared libraries. 6646 if (pkg.libraryNames != null) { 6647 for (i=0; i<pkg.libraryNames.size(); i++) { 6648 String name = pkg.libraryNames.get(i); 6649 SharedLibraryEntry cur = mSharedLibraries.get(name); 6650 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 6651 mSharedLibraries.remove(name); 6652 if (DEBUG_REMOVE && chatty) { 6653 if (r == null) { 6654 r = new StringBuilder(256); 6655 } else { 6656 r.append(' '); 6657 } 6658 r.append(name); 6659 } 6660 } 6661 } 6662 } 6663 } 6664 if (r != null) { 6665 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 6666 } 6667 } 6668 6669 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 6670 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 6671 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 6672 return true; 6673 } 6674 } 6675 return false; 6676 } 6677 6678 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 6679 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 6680 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 6681 6682 private void updatePermissionsLPw(String changingPkg, 6683 PackageParser.Package pkgInfo, int flags) { 6684 // Make sure there are no dangling permission trees. 6685 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 6686 while (it.hasNext()) { 6687 final BasePermission bp = it.next(); 6688 if (bp.packageSetting == null) { 6689 // We may not yet have parsed the package, so just see if 6690 // we still know about its settings. 6691 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6692 } 6693 if (bp.packageSetting == null) { 6694 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 6695 + " from package " + bp.sourcePackage); 6696 it.remove(); 6697 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6698 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6699 Slog.i(TAG, "Removing old permission tree: " + bp.name 6700 + " from package " + bp.sourcePackage); 6701 flags |= UPDATE_PERMISSIONS_ALL; 6702 it.remove(); 6703 } 6704 } 6705 } 6706 6707 // Make sure all dynamic permissions have been assigned to a package, 6708 // and make sure there are no dangling permissions. 6709 it = mSettings.mPermissions.values().iterator(); 6710 while (it.hasNext()) { 6711 final BasePermission bp = it.next(); 6712 if (bp.type == BasePermission.TYPE_DYNAMIC) { 6713 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 6714 + bp.name + " pkg=" + bp.sourcePackage 6715 + " info=" + bp.pendingInfo); 6716 if (bp.packageSetting == null && bp.pendingInfo != null) { 6717 final BasePermission tree = findPermissionTreeLP(bp.name); 6718 if (tree != null && tree.perm != null) { 6719 bp.packageSetting = tree.packageSetting; 6720 bp.perm = new PackageParser.Permission(tree.perm.owner, 6721 new PermissionInfo(bp.pendingInfo)); 6722 bp.perm.info.packageName = tree.perm.info.packageName; 6723 bp.perm.info.name = bp.name; 6724 bp.uid = tree.uid; 6725 } 6726 } 6727 } 6728 if (bp.packageSetting == null) { 6729 // We may not yet have parsed the package, so just see if 6730 // we still know about its settings. 6731 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6732 } 6733 if (bp.packageSetting == null) { 6734 Slog.w(TAG, "Removing dangling permission: " + bp.name 6735 + " from package " + bp.sourcePackage); 6736 it.remove(); 6737 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6738 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6739 Slog.i(TAG, "Removing old permission: " + bp.name 6740 + " from package " + bp.sourcePackage); 6741 flags |= UPDATE_PERMISSIONS_ALL; 6742 it.remove(); 6743 } 6744 } 6745 } 6746 6747 // Now update the permissions for all packages, in particular 6748 // replace the granted permissions of the system packages. 6749 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 6750 for (PackageParser.Package pkg : mPackages.values()) { 6751 if (pkg != pkgInfo) { 6752 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0); 6753 } 6754 } 6755 } 6756 6757 if (pkgInfo != null) { 6758 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0); 6759 } 6760 } 6761 6762 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) { 6763 final PackageSetting ps = (PackageSetting) pkg.mExtras; 6764 if (ps == null) { 6765 return; 6766 } 6767 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 6768 HashSet<String> origPermissions = gp.grantedPermissions; 6769 boolean changedPermission = false; 6770 6771 if (replace) { 6772 ps.permissionsFixed = false; 6773 if (gp == ps) { 6774 origPermissions = new HashSet<String>(gp.grantedPermissions); 6775 gp.grantedPermissions.clear(); 6776 gp.gids = mGlobalGids; 6777 } 6778 } 6779 6780 if (gp.gids == null) { 6781 gp.gids = mGlobalGids; 6782 } 6783 6784 final int N = pkg.requestedPermissions.size(); 6785 for (int i=0; i<N; i++) { 6786 final String name = pkg.requestedPermissions.get(i); 6787 final boolean required = pkg.requestedPermissionsRequired.get(i); 6788 final BasePermission bp = mSettings.mPermissions.get(name); 6789 if (DEBUG_INSTALL) { 6790 if (gp != ps) { 6791 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 6792 } 6793 } 6794 6795 if (bp == null || bp.packageSetting == null) { 6796 Slog.w(TAG, "Unknown permission " + name 6797 + " in package " + pkg.packageName); 6798 continue; 6799 } 6800 6801 final String perm = bp.name; 6802 boolean allowed; 6803 boolean allowedSig = false; 6804 if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6805 // Keep track of app op permissions. 6806 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 6807 if (pkgs == null) { 6808 pkgs = new ArraySet<>(); 6809 mAppOpPermissionPackages.put(bp.name, pkgs); 6810 } 6811 pkgs.add(pkg.packageName); 6812 } 6813 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 6814 if (level == PermissionInfo.PROTECTION_NORMAL 6815 || level == PermissionInfo.PROTECTION_DANGEROUS) { 6816 // We grant a normal or dangerous permission if any of the following 6817 // are true: 6818 // 1) The permission is required 6819 // 2) The permission is optional, but was granted in the past 6820 // 3) The permission is optional, but was requested by an 6821 // app in /system (not /data) 6822 // 6823 // Otherwise, reject the permission. 6824 allowed = (required || origPermissions.contains(perm) 6825 || (isSystemApp(ps) && !isUpdatedSystemApp(ps))); 6826 } else if (bp.packageSetting == null) { 6827 // This permission is invalid; skip it. 6828 allowed = false; 6829 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 6830 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions); 6831 if (allowed) { 6832 allowedSig = true; 6833 } 6834 } else { 6835 allowed = false; 6836 } 6837 if (DEBUG_INSTALL) { 6838 if (gp != ps) { 6839 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 6840 } 6841 } 6842 if (allowed) { 6843 if (!isSystemApp(ps) && ps.permissionsFixed) { 6844 // If this is an existing, non-system package, then 6845 // we can't add any new permissions to it. 6846 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 6847 // Except... if this is a permission that was added 6848 // to the platform (note: need to only do this when 6849 // updating the platform). 6850 allowed = isNewPlatformPermissionForPackage(perm, pkg); 6851 } 6852 } 6853 if (allowed) { 6854 if (!gp.grantedPermissions.contains(perm)) { 6855 changedPermission = true; 6856 gp.grantedPermissions.add(perm); 6857 gp.gids = appendInts(gp.gids, bp.gids); 6858 } else if (!ps.haveGids) { 6859 gp.gids = appendInts(gp.gids, bp.gids); 6860 } 6861 } else { 6862 Slog.w(TAG, "Not granting permission " + perm 6863 + " to package " + pkg.packageName 6864 + " because it was previously installed without"); 6865 } 6866 } else { 6867 if (gp.grantedPermissions.remove(perm)) { 6868 changedPermission = true; 6869 gp.gids = removeInts(gp.gids, bp.gids); 6870 Slog.i(TAG, "Un-granting permission " + perm 6871 + " from package " + pkg.packageName 6872 + " (protectionLevel=" + bp.protectionLevel 6873 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6874 + ")"); 6875 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 6876 // Don't print warning for app op permissions, since it is fine for them 6877 // not to be granted, there is a UI for the user to decide. 6878 Slog.w(TAG, "Not granting permission " + perm 6879 + " to package " + pkg.packageName 6880 + " (protectionLevel=" + bp.protectionLevel 6881 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6882 + ")"); 6883 } 6884 } 6885 } 6886 6887 if ((changedPermission || replace) && !ps.permissionsFixed && 6888 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 6889 // This is the first that we have heard about this package, so the 6890 // permissions we have now selected are fixed until explicitly 6891 // changed. 6892 ps.permissionsFixed = true; 6893 } 6894 ps.haveGids = true; 6895 } 6896 6897 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 6898 boolean allowed = false; 6899 final int NP = PackageParser.NEW_PERMISSIONS.length; 6900 for (int ip=0; ip<NP; ip++) { 6901 final PackageParser.NewPermissionInfo npi 6902 = PackageParser.NEW_PERMISSIONS[ip]; 6903 if (npi.name.equals(perm) 6904 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 6905 allowed = true; 6906 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 6907 + pkg.packageName); 6908 break; 6909 } 6910 } 6911 return allowed; 6912 } 6913 6914 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 6915 BasePermission bp, HashSet<String> origPermissions) { 6916 boolean allowed; 6917 allowed = (compareSignatures( 6918 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 6919 == PackageManager.SIGNATURE_MATCH) 6920 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 6921 == PackageManager.SIGNATURE_MATCH); 6922 if (!allowed && (bp.protectionLevel 6923 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 6924 if (isSystemApp(pkg)) { 6925 // For updated system applications, a system permission 6926 // is granted only if it had been defined by the original application. 6927 if (isUpdatedSystemApp(pkg)) { 6928 final PackageSetting sysPs = mSettings 6929 .getDisabledSystemPkgLPr(pkg.packageName); 6930 final GrantedPermissions origGp = sysPs.sharedUser != null 6931 ? sysPs.sharedUser : sysPs; 6932 6933 if (origGp.grantedPermissions.contains(perm)) { 6934 // If the original was granted this permission, we take 6935 // that grant decision as read and propagate it to the 6936 // update. 6937 allowed = true; 6938 } else { 6939 // The system apk may have been updated with an older 6940 // version of the one on the data partition, but which 6941 // granted a new system permission that it didn't have 6942 // before. In this case we do want to allow the app to 6943 // now get the new permission if the ancestral apk is 6944 // privileged to get it. 6945 if (sysPs.pkg != null && sysPs.isPrivileged()) { 6946 for (int j=0; 6947 j<sysPs.pkg.requestedPermissions.size(); j++) { 6948 if (perm.equals( 6949 sysPs.pkg.requestedPermissions.get(j))) { 6950 allowed = true; 6951 break; 6952 } 6953 } 6954 } 6955 } 6956 } else { 6957 allowed = isPrivilegedApp(pkg); 6958 } 6959 } 6960 } 6961 if (!allowed && (bp.protectionLevel 6962 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 6963 // For development permissions, a development permission 6964 // is granted only if it was already granted. 6965 allowed = origPermissions.contains(perm); 6966 } 6967 return allowed; 6968 } 6969 6970 final class ActivityIntentResolver 6971 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 6972 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 6973 boolean defaultOnly, int userId) { 6974 if (!sUserManager.exists(userId)) return null; 6975 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 6976 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 6977 } 6978 6979 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 6980 int userId) { 6981 if (!sUserManager.exists(userId)) return null; 6982 mFlags = flags; 6983 return super.queryIntent(intent, resolvedType, 6984 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 6985 } 6986 6987 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 6988 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 6989 if (!sUserManager.exists(userId)) return null; 6990 if (packageActivities == null) { 6991 return null; 6992 } 6993 mFlags = flags; 6994 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 6995 final int N = packageActivities.size(); 6996 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 6997 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 6998 6999 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 7000 for (int i = 0; i < N; ++i) { 7001 intentFilters = packageActivities.get(i).intents; 7002 if (intentFilters != null && intentFilters.size() > 0) { 7003 PackageParser.ActivityIntentInfo[] array = 7004 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 7005 intentFilters.toArray(array); 7006 listCut.add(array); 7007 } 7008 } 7009 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7010 } 7011 7012 public final void addActivity(PackageParser.Activity a, String type) { 7013 final boolean systemApp = isSystemApp(a.info.applicationInfo); 7014 mActivities.put(a.getComponentName(), a); 7015 if (DEBUG_SHOW_INFO) 7016 Log.v( 7017 TAG, " " + type + " " + 7018 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 7019 if (DEBUG_SHOW_INFO) 7020 Log.v(TAG, " Class=" + a.info.name); 7021 final int NI = a.intents.size(); 7022 for (int j=0; j<NI; j++) { 7023 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7024 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 7025 intent.setPriority(0); 7026 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 7027 + a.className + " with priority > 0, forcing to 0"); 7028 } 7029 if (DEBUG_SHOW_INFO) { 7030 Log.v(TAG, " IntentFilter:"); 7031 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7032 } 7033 if (!intent.debugCheck()) { 7034 Log.w(TAG, "==> For Activity " + a.info.name); 7035 } 7036 addFilter(intent); 7037 } 7038 } 7039 7040 public final void removeActivity(PackageParser.Activity a, String type) { 7041 mActivities.remove(a.getComponentName()); 7042 if (DEBUG_SHOW_INFO) { 7043 Log.v(TAG, " " + type + " " 7044 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 7045 : a.info.name) + ":"); 7046 Log.v(TAG, " Class=" + a.info.name); 7047 } 7048 final int NI = a.intents.size(); 7049 for (int j=0; j<NI; j++) { 7050 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7051 if (DEBUG_SHOW_INFO) { 7052 Log.v(TAG, " IntentFilter:"); 7053 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7054 } 7055 removeFilter(intent); 7056 } 7057 } 7058 7059 @Override 7060 protected boolean allowFilterResult( 7061 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 7062 ActivityInfo filterAi = filter.activity.info; 7063 for (int i=dest.size()-1; i>=0; i--) { 7064 ActivityInfo destAi = dest.get(i).activityInfo; 7065 if (destAi.name == filterAi.name 7066 && destAi.packageName == filterAi.packageName) { 7067 return false; 7068 } 7069 } 7070 return true; 7071 } 7072 7073 @Override 7074 protected ActivityIntentInfo[] newArray(int size) { 7075 return new ActivityIntentInfo[size]; 7076 } 7077 7078 @Override 7079 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 7080 if (!sUserManager.exists(userId)) return true; 7081 PackageParser.Package p = filter.activity.owner; 7082 if (p != null) { 7083 PackageSetting ps = (PackageSetting)p.mExtras; 7084 if (ps != null) { 7085 // System apps are never considered stopped for purposes of 7086 // filtering, because there may be no way for the user to 7087 // actually re-launch them. 7088 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 7089 && ps.getStopped(userId); 7090 } 7091 } 7092 return false; 7093 } 7094 7095 @Override 7096 protected boolean isPackageForFilter(String packageName, 7097 PackageParser.ActivityIntentInfo info) { 7098 return packageName.equals(info.activity.owner.packageName); 7099 } 7100 7101 @Override 7102 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7103 int match, int userId) { 7104 if (!sUserManager.exists(userId)) return null; 7105 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7106 return null; 7107 } 7108 final PackageParser.Activity activity = info.activity; 7109 if (mSafeMode && (activity.info.applicationInfo.flags 7110 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7111 return null; 7112 } 7113 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7114 if (ps == null) { 7115 return null; 7116 } 7117 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7118 ps.readUserState(userId), userId); 7119 if (ai == null) { 7120 return null; 7121 } 7122 final ResolveInfo res = new ResolveInfo(); 7123 res.activityInfo = ai; 7124 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7125 res.filter = info; 7126 } 7127 res.priority = info.getPriority(); 7128 res.preferredOrder = activity.owner.mPreferredOrder; 7129 //System.out.println("Result: " + res.activityInfo.className + 7130 // " = " + res.priority); 7131 res.match = match; 7132 res.isDefault = info.hasDefault; 7133 res.labelRes = info.labelRes; 7134 res.nonLocalizedLabel = info.nonLocalizedLabel; 7135 if (userNeedsBadging(userId)) { 7136 res.noResourceId = true; 7137 } else { 7138 res.icon = info.icon; 7139 } 7140 res.system = isSystemApp(res.activityInfo.applicationInfo); 7141 return res; 7142 } 7143 7144 @Override 7145 protected void sortResults(List<ResolveInfo> results) { 7146 Collections.sort(results, mResolvePrioritySorter); 7147 } 7148 7149 @Override 7150 protected void dumpFilter(PrintWriter out, String prefix, 7151 PackageParser.ActivityIntentInfo filter) { 7152 out.print(prefix); out.print( 7153 Integer.toHexString(System.identityHashCode(filter.activity))); 7154 out.print(' '); 7155 filter.activity.printComponentShortName(out); 7156 out.print(" filter "); 7157 out.println(Integer.toHexString(System.identityHashCode(filter))); 7158 } 7159 7160// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7161// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7162// final List<ResolveInfo> retList = Lists.newArrayList(); 7163// while (i.hasNext()) { 7164// final ResolveInfo resolveInfo = i.next(); 7165// if (isEnabledLP(resolveInfo.activityInfo)) { 7166// retList.add(resolveInfo); 7167// } 7168// } 7169// return retList; 7170// } 7171 7172 // Keys are String (activity class name), values are Activity. 7173 private final HashMap<ComponentName, PackageParser.Activity> mActivities 7174 = new HashMap<ComponentName, PackageParser.Activity>(); 7175 private int mFlags; 7176 } 7177 7178 private final class ServiceIntentResolver 7179 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 7180 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7181 boolean defaultOnly, int userId) { 7182 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7183 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7184 } 7185 7186 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7187 int userId) { 7188 if (!sUserManager.exists(userId)) return null; 7189 mFlags = flags; 7190 return super.queryIntent(intent, resolvedType, 7191 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7192 } 7193 7194 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7195 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 7196 if (!sUserManager.exists(userId)) return null; 7197 if (packageServices == null) { 7198 return null; 7199 } 7200 mFlags = flags; 7201 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7202 final int N = packageServices.size(); 7203 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 7204 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 7205 7206 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 7207 for (int i = 0; i < N; ++i) { 7208 intentFilters = packageServices.get(i).intents; 7209 if (intentFilters != null && intentFilters.size() > 0) { 7210 PackageParser.ServiceIntentInfo[] array = 7211 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 7212 intentFilters.toArray(array); 7213 listCut.add(array); 7214 } 7215 } 7216 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7217 } 7218 7219 public final void addService(PackageParser.Service s) { 7220 mServices.put(s.getComponentName(), s); 7221 if (DEBUG_SHOW_INFO) { 7222 Log.v(TAG, " " 7223 + (s.info.nonLocalizedLabel != null 7224 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7225 Log.v(TAG, " Class=" + s.info.name); 7226 } 7227 final int NI = s.intents.size(); 7228 int j; 7229 for (j=0; j<NI; j++) { 7230 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7231 if (DEBUG_SHOW_INFO) { 7232 Log.v(TAG, " IntentFilter:"); 7233 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7234 } 7235 if (!intent.debugCheck()) { 7236 Log.w(TAG, "==> For Service " + s.info.name); 7237 } 7238 addFilter(intent); 7239 } 7240 } 7241 7242 public final void removeService(PackageParser.Service s) { 7243 mServices.remove(s.getComponentName()); 7244 if (DEBUG_SHOW_INFO) { 7245 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 7246 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7247 Log.v(TAG, " Class=" + s.info.name); 7248 } 7249 final int NI = s.intents.size(); 7250 int j; 7251 for (j=0; j<NI; j++) { 7252 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7253 if (DEBUG_SHOW_INFO) { 7254 Log.v(TAG, " IntentFilter:"); 7255 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7256 } 7257 removeFilter(intent); 7258 } 7259 } 7260 7261 @Override 7262 protected boolean allowFilterResult( 7263 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 7264 ServiceInfo filterSi = filter.service.info; 7265 for (int i=dest.size()-1; i>=0; i--) { 7266 ServiceInfo destAi = dest.get(i).serviceInfo; 7267 if (destAi.name == filterSi.name 7268 && destAi.packageName == filterSi.packageName) { 7269 return false; 7270 } 7271 } 7272 return true; 7273 } 7274 7275 @Override 7276 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 7277 return new PackageParser.ServiceIntentInfo[size]; 7278 } 7279 7280 @Override 7281 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 7282 if (!sUserManager.exists(userId)) return true; 7283 PackageParser.Package p = filter.service.owner; 7284 if (p != null) { 7285 PackageSetting ps = (PackageSetting)p.mExtras; 7286 if (ps != null) { 7287 // System apps are never considered stopped for purposes of 7288 // filtering, because there may be no way for the user to 7289 // actually re-launch them. 7290 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7291 && ps.getStopped(userId); 7292 } 7293 } 7294 return false; 7295 } 7296 7297 @Override 7298 protected boolean isPackageForFilter(String packageName, 7299 PackageParser.ServiceIntentInfo info) { 7300 return packageName.equals(info.service.owner.packageName); 7301 } 7302 7303 @Override 7304 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 7305 int match, int userId) { 7306 if (!sUserManager.exists(userId)) return null; 7307 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 7308 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 7309 return null; 7310 } 7311 final PackageParser.Service service = info.service; 7312 if (mSafeMode && (service.info.applicationInfo.flags 7313 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7314 return null; 7315 } 7316 PackageSetting ps = (PackageSetting) service.owner.mExtras; 7317 if (ps == null) { 7318 return null; 7319 } 7320 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 7321 ps.readUserState(userId), userId); 7322 if (si == null) { 7323 return null; 7324 } 7325 final ResolveInfo res = new ResolveInfo(); 7326 res.serviceInfo = si; 7327 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7328 res.filter = filter; 7329 } 7330 res.priority = info.getPriority(); 7331 res.preferredOrder = service.owner.mPreferredOrder; 7332 //System.out.println("Result: " + res.activityInfo.className + 7333 // " = " + res.priority); 7334 res.match = match; 7335 res.isDefault = info.hasDefault; 7336 res.labelRes = info.labelRes; 7337 res.nonLocalizedLabel = info.nonLocalizedLabel; 7338 res.icon = info.icon; 7339 res.system = isSystemApp(res.serviceInfo.applicationInfo); 7340 return res; 7341 } 7342 7343 @Override 7344 protected void sortResults(List<ResolveInfo> results) { 7345 Collections.sort(results, mResolvePrioritySorter); 7346 } 7347 7348 @Override 7349 protected void dumpFilter(PrintWriter out, String prefix, 7350 PackageParser.ServiceIntentInfo filter) { 7351 out.print(prefix); out.print( 7352 Integer.toHexString(System.identityHashCode(filter.service))); 7353 out.print(' '); 7354 filter.service.printComponentShortName(out); 7355 out.print(" filter "); 7356 out.println(Integer.toHexString(System.identityHashCode(filter))); 7357 } 7358 7359// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7360// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7361// final List<ResolveInfo> retList = Lists.newArrayList(); 7362// while (i.hasNext()) { 7363// final ResolveInfo resolveInfo = (ResolveInfo) i; 7364// if (isEnabledLP(resolveInfo.serviceInfo)) { 7365// retList.add(resolveInfo); 7366// } 7367// } 7368// return retList; 7369// } 7370 7371 // Keys are String (activity class name), values are Activity. 7372 private final HashMap<ComponentName, PackageParser.Service> mServices 7373 = new HashMap<ComponentName, PackageParser.Service>(); 7374 private int mFlags; 7375 }; 7376 7377 private final class ProviderIntentResolver 7378 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 7379 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7380 boolean defaultOnly, int userId) { 7381 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7382 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7383 } 7384 7385 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7386 int userId) { 7387 if (!sUserManager.exists(userId)) 7388 return null; 7389 mFlags = flags; 7390 return super.queryIntent(intent, resolvedType, 7391 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7392 } 7393 7394 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7395 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 7396 if (!sUserManager.exists(userId)) 7397 return null; 7398 if (packageProviders == null) { 7399 return null; 7400 } 7401 mFlags = flags; 7402 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 7403 final int N = packageProviders.size(); 7404 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 7405 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 7406 7407 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 7408 for (int i = 0; i < N; ++i) { 7409 intentFilters = packageProviders.get(i).intents; 7410 if (intentFilters != null && intentFilters.size() > 0) { 7411 PackageParser.ProviderIntentInfo[] array = 7412 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 7413 intentFilters.toArray(array); 7414 listCut.add(array); 7415 } 7416 } 7417 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7418 } 7419 7420 public final void addProvider(PackageParser.Provider p) { 7421 if (mProviders.containsKey(p.getComponentName())) { 7422 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 7423 return; 7424 } 7425 7426 mProviders.put(p.getComponentName(), p); 7427 if (DEBUG_SHOW_INFO) { 7428 Log.v(TAG, " " 7429 + (p.info.nonLocalizedLabel != null 7430 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7431 Log.v(TAG, " Class=" + p.info.name); 7432 } 7433 final int NI = p.intents.size(); 7434 int j; 7435 for (j = 0; j < NI; j++) { 7436 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7437 if (DEBUG_SHOW_INFO) { 7438 Log.v(TAG, " IntentFilter:"); 7439 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7440 } 7441 if (!intent.debugCheck()) { 7442 Log.w(TAG, "==> For Provider " + p.info.name); 7443 } 7444 addFilter(intent); 7445 } 7446 } 7447 7448 public final void removeProvider(PackageParser.Provider p) { 7449 mProviders.remove(p.getComponentName()); 7450 if (DEBUG_SHOW_INFO) { 7451 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 7452 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7453 Log.v(TAG, " Class=" + p.info.name); 7454 } 7455 final int NI = p.intents.size(); 7456 int j; 7457 for (j = 0; j < NI; j++) { 7458 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7459 if (DEBUG_SHOW_INFO) { 7460 Log.v(TAG, " IntentFilter:"); 7461 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7462 } 7463 removeFilter(intent); 7464 } 7465 } 7466 7467 @Override 7468 protected boolean allowFilterResult( 7469 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 7470 ProviderInfo filterPi = filter.provider.info; 7471 for (int i = dest.size() - 1; i >= 0; i--) { 7472 ProviderInfo destPi = dest.get(i).providerInfo; 7473 if (destPi.name == filterPi.name 7474 && destPi.packageName == filterPi.packageName) { 7475 return false; 7476 } 7477 } 7478 return true; 7479 } 7480 7481 @Override 7482 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 7483 return new PackageParser.ProviderIntentInfo[size]; 7484 } 7485 7486 @Override 7487 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 7488 if (!sUserManager.exists(userId)) 7489 return true; 7490 PackageParser.Package p = filter.provider.owner; 7491 if (p != null) { 7492 PackageSetting ps = (PackageSetting) p.mExtras; 7493 if (ps != null) { 7494 // System apps are never considered stopped for purposes of 7495 // filtering, because there may be no way for the user to 7496 // actually re-launch them. 7497 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7498 && ps.getStopped(userId); 7499 } 7500 } 7501 return false; 7502 } 7503 7504 @Override 7505 protected boolean isPackageForFilter(String packageName, 7506 PackageParser.ProviderIntentInfo info) { 7507 return packageName.equals(info.provider.owner.packageName); 7508 } 7509 7510 @Override 7511 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 7512 int match, int userId) { 7513 if (!sUserManager.exists(userId)) 7514 return null; 7515 final PackageParser.ProviderIntentInfo info = filter; 7516 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 7517 return null; 7518 } 7519 final PackageParser.Provider provider = info.provider; 7520 if (mSafeMode && (provider.info.applicationInfo.flags 7521 & ApplicationInfo.FLAG_SYSTEM) == 0) { 7522 return null; 7523 } 7524 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 7525 if (ps == null) { 7526 return null; 7527 } 7528 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 7529 ps.readUserState(userId), userId); 7530 if (pi == null) { 7531 return null; 7532 } 7533 final ResolveInfo res = new ResolveInfo(); 7534 res.providerInfo = pi; 7535 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 7536 res.filter = filter; 7537 } 7538 res.priority = info.getPriority(); 7539 res.preferredOrder = provider.owner.mPreferredOrder; 7540 res.match = match; 7541 res.isDefault = info.hasDefault; 7542 res.labelRes = info.labelRes; 7543 res.nonLocalizedLabel = info.nonLocalizedLabel; 7544 res.icon = info.icon; 7545 res.system = isSystemApp(res.providerInfo.applicationInfo); 7546 return res; 7547 } 7548 7549 @Override 7550 protected void sortResults(List<ResolveInfo> results) { 7551 Collections.sort(results, mResolvePrioritySorter); 7552 } 7553 7554 @Override 7555 protected void dumpFilter(PrintWriter out, String prefix, 7556 PackageParser.ProviderIntentInfo filter) { 7557 out.print(prefix); 7558 out.print( 7559 Integer.toHexString(System.identityHashCode(filter.provider))); 7560 out.print(' '); 7561 filter.provider.printComponentShortName(out); 7562 out.print(" filter "); 7563 out.println(Integer.toHexString(System.identityHashCode(filter))); 7564 } 7565 7566 private final HashMap<ComponentName, PackageParser.Provider> mProviders 7567 = new HashMap<ComponentName, PackageParser.Provider>(); 7568 private int mFlags; 7569 }; 7570 7571 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 7572 new Comparator<ResolveInfo>() { 7573 public int compare(ResolveInfo r1, ResolveInfo r2) { 7574 int v1 = r1.priority; 7575 int v2 = r2.priority; 7576 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 7577 if (v1 != v2) { 7578 return (v1 > v2) ? -1 : 1; 7579 } 7580 v1 = r1.preferredOrder; 7581 v2 = r2.preferredOrder; 7582 if (v1 != v2) { 7583 return (v1 > v2) ? -1 : 1; 7584 } 7585 if (r1.isDefault != r2.isDefault) { 7586 return r1.isDefault ? -1 : 1; 7587 } 7588 v1 = r1.match; 7589 v2 = r2.match; 7590 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 7591 if (v1 != v2) { 7592 return (v1 > v2) ? -1 : 1; 7593 } 7594 if (r1.system != r2.system) { 7595 return r1.system ? -1 : 1; 7596 } 7597 return 0; 7598 } 7599 }; 7600 7601 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 7602 new Comparator<ProviderInfo>() { 7603 public int compare(ProviderInfo p1, ProviderInfo p2) { 7604 final int v1 = p1.initOrder; 7605 final int v2 = p2.initOrder; 7606 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 7607 } 7608 }; 7609 7610 static final void sendPackageBroadcast(String action, String pkg, 7611 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 7612 int[] userIds) { 7613 IActivityManager am = ActivityManagerNative.getDefault(); 7614 if (am != null) { 7615 try { 7616 if (userIds == null) { 7617 userIds = am.getRunningUserIds(); 7618 } 7619 for (int id : userIds) { 7620 final Intent intent = new Intent(action, 7621 pkg != null ? Uri.fromParts("package", pkg, null) : null); 7622 if (extras != null) { 7623 intent.putExtras(extras); 7624 } 7625 if (targetPkg != null) { 7626 intent.setPackage(targetPkg); 7627 } 7628 // Modify the UID when posting to other users 7629 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 7630 if (uid > 0 && UserHandle.getUserId(uid) != id) { 7631 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 7632 intent.putExtra(Intent.EXTRA_UID, uid); 7633 } 7634 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 7635 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 7636 if (DEBUG_BROADCASTS) { 7637 RuntimeException here = new RuntimeException("here"); 7638 here.fillInStackTrace(); 7639 Slog.d(TAG, "Sending to user " + id + ": " 7640 + intent.toShortString(false, true, false, false) 7641 + " " + intent.getExtras(), here); 7642 } 7643 am.broadcastIntent(null, intent, null, finishedReceiver, 7644 0, null, null, null, android.app.AppOpsManager.OP_NONE, 7645 finishedReceiver != null, false, id); 7646 } 7647 } catch (RemoteException ex) { 7648 } 7649 } 7650 } 7651 7652 /** 7653 * Check if the external storage media is available. This is true if there 7654 * is a mounted external storage medium or if the external storage is 7655 * emulated. 7656 */ 7657 private boolean isExternalMediaAvailable() { 7658 return mMediaMounted || Environment.isExternalStorageEmulated(); 7659 } 7660 7661 @Override 7662 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 7663 // writer 7664 synchronized (mPackages) { 7665 if (!isExternalMediaAvailable()) { 7666 // If the external storage is no longer mounted at this point, 7667 // the caller may not have been able to delete all of this 7668 // packages files and can not delete any more. Bail. 7669 return null; 7670 } 7671 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 7672 if (lastPackage != null) { 7673 pkgs.remove(lastPackage); 7674 } 7675 if (pkgs.size() > 0) { 7676 return pkgs.get(0); 7677 } 7678 } 7679 return null; 7680 } 7681 7682 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 7683 if (false) { 7684 RuntimeException here = new RuntimeException("here"); 7685 here.fillInStackTrace(); 7686 Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId 7687 + " andCode=" + andCode, here); 7688 } 7689 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, 7690 userId, andCode ? 1 : 0, packageName)); 7691 } 7692 7693 void startCleaningPackages() { 7694 // reader 7695 synchronized (mPackages) { 7696 if (!isExternalMediaAvailable()) { 7697 return; 7698 } 7699 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 7700 return; 7701 } 7702 } 7703 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 7704 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 7705 IActivityManager am = ActivityManagerNative.getDefault(); 7706 if (am != null) { 7707 try { 7708 am.startService(null, intent, null, UserHandle.USER_OWNER); 7709 } catch (RemoteException e) { 7710 } 7711 } 7712 } 7713 7714 @Override 7715 public void installPackage(String originPath, IPackageInstallObserver2 observer, int flags, 7716 String installerPackageName, VerificationParams verificationParams, 7717 String packageAbiOverride) { 7718 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7719 null); 7720 7721 final File originFile = new File(originPath); 7722 final int uid = Binder.getCallingUid(); 7723 if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) { 7724 try { 7725 if (observer != null) { 7726 observer.packageInstalled("", null, INSTALL_FAILED_USER_RESTRICTED, null); 7727 } 7728 } catch (RemoteException re) { 7729 } 7730 return; 7731 } 7732 7733 UserHandle user; 7734 if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) { 7735 user = UserHandle.ALL; 7736 } else { 7737 user = new UserHandle(UserHandle.getUserId(uid)); 7738 } 7739 7740 final int filteredFlags; 7741 if (uid == Process.SHELL_UID || uid == 0) { 7742 if (DEBUG_INSTALL) { 7743 Slog.v(TAG, "Install from ADB"); 7744 } 7745 filteredFlags = flags | PackageManager.INSTALL_FROM_ADB; 7746 } else { 7747 filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB; 7748 } 7749 7750 verificationParams.setInstallerUid(uid); 7751 7752 final Message msg = mHandler.obtainMessage(INIT_COPY); 7753 msg.obj = new InstallParams(originFile, false, observer, filteredFlags, 7754 installerPackageName, verificationParams, user, packageAbiOverride); 7755 mHandler.sendMessage(msg); 7756 } 7757 7758 void installStage(String packageName, File stageDir, IPackageInstallObserver2 observer, 7759 InstallSessionParams params, String installerPackageName, int installerUid, 7760 UserHandle user) { 7761 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 7762 params.referrerUri, installerUid, null); 7763 7764 final Message msg = mHandler.obtainMessage(INIT_COPY); 7765 msg.obj = new InstallParams(stageDir, true, observer, params.installFlags, 7766 installerPackageName, verifParams, user, params.abiOverride); 7767 mHandler.sendMessage(msg); 7768 } 7769 7770 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 7771 Bundle extras = new Bundle(1); 7772 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 7773 7774 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 7775 packageName, extras, null, null, new int[] {userId}); 7776 try { 7777 IActivityManager am = ActivityManagerNative.getDefault(); 7778 final boolean isSystem = 7779 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 7780 if (isSystem && am.isUserRunning(userId, false)) { 7781 // The just-installed/enabled app is bundled on the system, so presumed 7782 // to be able to run automatically without needing an explicit launch. 7783 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 7784 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 7785 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 7786 .setPackage(packageName); 7787 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 7788 android.app.AppOpsManager.OP_NONE, false, false, userId); 7789 } 7790 } catch (RemoteException e) { 7791 // shouldn't happen 7792 Slog.w(TAG, "Unable to bootstrap installed package", e); 7793 } 7794 } 7795 7796 @Override 7797 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 7798 int userId) { 7799 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7800 PackageSetting pkgSetting; 7801 final int uid = Binder.getCallingUid(); 7802 if (UserHandle.getUserId(uid) != userId) { 7803 mContext.enforceCallingOrSelfPermission( 7804 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 7805 "setApplicationHiddenSetting for user " + userId); 7806 } 7807 7808 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 7809 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 7810 return false; 7811 } 7812 7813 long callingId = Binder.clearCallingIdentity(); 7814 try { 7815 boolean sendAdded = false; 7816 boolean sendRemoved = false; 7817 // writer 7818 synchronized (mPackages) { 7819 pkgSetting = mSettings.mPackages.get(packageName); 7820 if (pkgSetting == null) { 7821 return false; 7822 } 7823 if (pkgSetting.getHidden(userId) != hidden) { 7824 pkgSetting.setHidden(hidden, userId); 7825 mSettings.writePackageRestrictionsLPr(userId); 7826 if (hidden) { 7827 sendRemoved = true; 7828 } else { 7829 sendAdded = true; 7830 } 7831 } 7832 } 7833 if (sendAdded) { 7834 sendPackageAddedForUser(packageName, pkgSetting, userId); 7835 return true; 7836 } 7837 if (sendRemoved) { 7838 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 7839 "hiding pkg"); 7840 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 7841 } 7842 } finally { 7843 Binder.restoreCallingIdentity(callingId); 7844 } 7845 return false; 7846 } 7847 7848 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 7849 int userId) { 7850 final PackageRemovedInfo info = new PackageRemovedInfo(); 7851 info.removedPackage = packageName; 7852 info.removedUsers = new int[] {userId}; 7853 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 7854 info.sendBroadcast(false, false, false); 7855 } 7856 7857 /** 7858 * Returns true if application is not found or there was an error. Otherwise it returns 7859 * the hidden state of the package for the given user. 7860 */ 7861 @Override 7862 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 7863 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7864 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 7865 "getApplicationHidden for user " + userId); 7866 PackageSetting pkgSetting; 7867 long callingId = Binder.clearCallingIdentity(); 7868 try { 7869 // writer 7870 synchronized (mPackages) { 7871 pkgSetting = mSettings.mPackages.get(packageName); 7872 if (pkgSetting == null) { 7873 return true; 7874 } 7875 return pkgSetting.getHidden(userId); 7876 } 7877 } finally { 7878 Binder.restoreCallingIdentity(callingId); 7879 } 7880 } 7881 7882 /** 7883 * @hide 7884 */ 7885 @Override 7886 public int installExistingPackageAsUser(String packageName, int userId) { 7887 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7888 null); 7889 PackageSetting pkgSetting; 7890 final int uid = Binder.getCallingUid(); 7891 enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId); 7892 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 7893 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 7894 } 7895 7896 long callingId = Binder.clearCallingIdentity(); 7897 try { 7898 boolean sendAdded = false; 7899 Bundle extras = new Bundle(1); 7900 7901 // writer 7902 synchronized (mPackages) { 7903 pkgSetting = mSettings.mPackages.get(packageName); 7904 if (pkgSetting == null) { 7905 return PackageManager.INSTALL_FAILED_INVALID_URI; 7906 } 7907 if (!pkgSetting.getInstalled(userId)) { 7908 pkgSetting.setInstalled(true, userId); 7909 pkgSetting.setHidden(false, userId); 7910 mSettings.writePackageRestrictionsLPr(userId); 7911 sendAdded = true; 7912 } 7913 } 7914 7915 if (sendAdded) { 7916 sendPackageAddedForUser(packageName, pkgSetting, userId); 7917 } 7918 } finally { 7919 Binder.restoreCallingIdentity(callingId); 7920 } 7921 7922 return PackageManager.INSTALL_SUCCEEDED; 7923 } 7924 7925 boolean isUserRestricted(int userId, String restrictionKey) { 7926 Bundle restrictions = sUserManager.getUserRestrictions(userId); 7927 if (restrictions.getBoolean(restrictionKey, false)) { 7928 Log.w(TAG, "User is restricted: " + restrictionKey); 7929 return true; 7930 } 7931 return false; 7932 } 7933 7934 @Override 7935 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 7936 mContext.enforceCallingOrSelfPermission( 7937 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7938 "Only package verification agents can verify applications"); 7939 7940 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7941 final PackageVerificationResponse response = new PackageVerificationResponse( 7942 verificationCode, Binder.getCallingUid()); 7943 msg.arg1 = id; 7944 msg.obj = response; 7945 mHandler.sendMessage(msg); 7946 } 7947 7948 @Override 7949 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 7950 long millisecondsToDelay) { 7951 mContext.enforceCallingOrSelfPermission( 7952 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7953 "Only package verification agents can extend verification timeouts"); 7954 7955 final PackageVerificationState state = mPendingVerification.get(id); 7956 final PackageVerificationResponse response = new PackageVerificationResponse( 7957 verificationCodeAtTimeout, Binder.getCallingUid()); 7958 7959 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 7960 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 7961 } 7962 if (millisecondsToDelay < 0) { 7963 millisecondsToDelay = 0; 7964 } 7965 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 7966 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 7967 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 7968 } 7969 7970 if ((state != null) && !state.timeoutExtended()) { 7971 state.extendTimeout(); 7972 7973 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7974 msg.arg1 = id; 7975 msg.obj = response; 7976 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 7977 } 7978 } 7979 7980 private void broadcastPackageVerified(int verificationId, Uri packageUri, 7981 int verificationCode, UserHandle user) { 7982 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 7983 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 7984 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 7985 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 7986 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 7987 7988 mContext.sendBroadcastAsUser(intent, user, 7989 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 7990 } 7991 7992 private ComponentName matchComponentForVerifier(String packageName, 7993 List<ResolveInfo> receivers) { 7994 ActivityInfo targetReceiver = null; 7995 7996 final int NR = receivers.size(); 7997 for (int i = 0; i < NR; i++) { 7998 final ResolveInfo info = receivers.get(i); 7999 if (info.activityInfo == null) { 8000 continue; 8001 } 8002 8003 if (packageName.equals(info.activityInfo.packageName)) { 8004 targetReceiver = info.activityInfo; 8005 break; 8006 } 8007 } 8008 8009 if (targetReceiver == null) { 8010 return null; 8011 } 8012 8013 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8014 } 8015 8016 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8017 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8018 if (pkgInfo.verifiers.length == 0) { 8019 return null; 8020 } 8021 8022 final int N = pkgInfo.verifiers.length; 8023 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8024 for (int i = 0; i < N; i++) { 8025 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8026 8027 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8028 receivers); 8029 if (comp == null) { 8030 continue; 8031 } 8032 8033 final int verifierUid = getUidForVerifier(verifierInfo); 8034 if (verifierUid == -1) { 8035 continue; 8036 } 8037 8038 if (DEBUG_VERIFY) { 8039 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8040 + " with the correct signature"); 8041 } 8042 sufficientVerifiers.add(comp); 8043 verificationState.addSufficientVerifier(verifierUid); 8044 } 8045 8046 return sufficientVerifiers; 8047 } 8048 8049 private int getUidForVerifier(VerifierInfo verifierInfo) { 8050 synchronized (mPackages) { 8051 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8052 if (pkg == null) { 8053 return -1; 8054 } else if (pkg.mSignatures.length != 1) { 8055 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8056 + " has more than one signature; ignoring"); 8057 return -1; 8058 } 8059 8060 /* 8061 * If the public key of the package's signature does not match 8062 * our expected public key, then this is a different package and 8063 * we should skip. 8064 */ 8065 8066 final byte[] expectedPublicKey; 8067 try { 8068 final Signature verifierSig = pkg.mSignatures[0]; 8069 final PublicKey publicKey = verifierSig.getPublicKey(); 8070 expectedPublicKey = publicKey.getEncoded(); 8071 } catch (CertificateException e) { 8072 return -1; 8073 } 8074 8075 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8076 8077 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8078 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8079 + " does not have the expected public key; ignoring"); 8080 return -1; 8081 } 8082 8083 return pkg.applicationInfo.uid; 8084 } 8085 } 8086 8087 @Override 8088 public void finishPackageInstall(int token) { 8089 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8090 8091 if (DEBUG_INSTALL) { 8092 Slog.v(TAG, "BM finishing package install for " + token); 8093 } 8094 8095 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8096 mHandler.sendMessage(msg); 8097 } 8098 8099 /** 8100 * Get the verification agent timeout. 8101 * 8102 * @return verification timeout in milliseconds 8103 */ 8104 private long getVerificationTimeout() { 8105 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8106 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8107 DEFAULT_VERIFICATION_TIMEOUT); 8108 } 8109 8110 /** 8111 * Get the default verification agent response code. 8112 * 8113 * @return default verification response code 8114 */ 8115 private int getDefaultVerificationResponse() { 8116 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8117 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8118 DEFAULT_VERIFICATION_RESPONSE); 8119 } 8120 8121 /** 8122 * Check whether or not package verification has been enabled. 8123 * 8124 * @return true if verification should be performed 8125 */ 8126 private boolean isVerificationEnabled(int userId, int flags) { 8127 if (!DEFAULT_VERIFY_ENABLE) { 8128 return false; 8129 } 8130 8131 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 8132 8133 // Check if installing from ADB 8134 if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) { 8135 // Do not run verification in a test harness environment 8136 if (ActivityManager.isRunningInTestHarness()) { 8137 return false; 8138 } 8139 if (ensureVerifyAppsEnabled) { 8140 return true; 8141 } 8142 // Check if the developer does not want package verification for ADB installs 8143 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8144 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8145 return false; 8146 } 8147 } 8148 8149 if (ensureVerifyAppsEnabled) { 8150 return true; 8151 } 8152 8153 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8154 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8155 } 8156 8157 /** 8158 * Get the "allow unknown sources" setting. 8159 * 8160 * @return the current "allow unknown sources" setting 8161 */ 8162 private int getUnknownSourcesSettings() { 8163 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8164 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 8165 -1); 8166 } 8167 8168 @Override 8169 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 8170 final int uid = Binder.getCallingUid(); 8171 // writer 8172 synchronized (mPackages) { 8173 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 8174 if (targetPackageSetting == null) { 8175 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 8176 } 8177 8178 PackageSetting installerPackageSetting; 8179 if (installerPackageName != null) { 8180 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 8181 if (installerPackageSetting == null) { 8182 throw new IllegalArgumentException("Unknown installer package: " 8183 + installerPackageName); 8184 } 8185 } else { 8186 installerPackageSetting = null; 8187 } 8188 8189 Signature[] callerSignature; 8190 Object obj = mSettings.getUserIdLPr(uid); 8191 if (obj != null) { 8192 if (obj instanceof SharedUserSetting) { 8193 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 8194 } else if (obj instanceof PackageSetting) { 8195 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 8196 } else { 8197 throw new SecurityException("Bad object " + obj + " for uid " + uid); 8198 } 8199 } else { 8200 throw new SecurityException("Unknown calling uid " + uid); 8201 } 8202 8203 // Verify: can't set installerPackageName to a package that is 8204 // not signed with the same cert as the caller. 8205 if (installerPackageSetting != null) { 8206 if (compareSignatures(callerSignature, 8207 installerPackageSetting.signatures.mSignatures) 8208 != PackageManager.SIGNATURE_MATCH) { 8209 throw new SecurityException( 8210 "Caller does not have same cert as new installer package " 8211 + installerPackageName); 8212 } 8213 } 8214 8215 // Verify: if target already has an installer package, it must 8216 // be signed with the same cert as the caller. 8217 if (targetPackageSetting.installerPackageName != null) { 8218 PackageSetting setting = mSettings.mPackages.get( 8219 targetPackageSetting.installerPackageName); 8220 // If the currently set package isn't valid, then it's always 8221 // okay to change it. 8222 if (setting != null) { 8223 if (compareSignatures(callerSignature, 8224 setting.signatures.mSignatures) 8225 != PackageManager.SIGNATURE_MATCH) { 8226 throw new SecurityException( 8227 "Caller does not have same cert as old installer package " 8228 + targetPackageSetting.installerPackageName); 8229 } 8230 } 8231 } 8232 8233 // Okay! 8234 targetPackageSetting.installerPackageName = installerPackageName; 8235 scheduleWriteSettingsLocked(); 8236 } 8237 } 8238 8239 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 8240 // Queue up an async operation since the package installation may take a little while. 8241 mHandler.post(new Runnable() { 8242 public void run() { 8243 mHandler.removeCallbacks(this); 8244 // Result object to be returned 8245 PackageInstalledInfo res = new PackageInstalledInfo(); 8246 res.returnCode = currentStatus; 8247 res.uid = -1; 8248 res.pkg = null; 8249 res.removedInfo = new PackageRemovedInfo(); 8250 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 8251 args.doPreInstall(res.returnCode); 8252 synchronized (mInstallLock) { 8253 installPackageLI(args, true, res); 8254 } 8255 args.doPostInstall(res.returnCode, res.uid); 8256 } 8257 8258 // A restore should be performed at this point if (a) the install 8259 // succeeded, (b) the operation is not an update, and (c) the new 8260 // package has a backupAgent defined. 8261 final boolean update = res.removedInfo.removedPackage != null; 8262 boolean doRestore = (!update 8263 && res.pkg != null 8264 && res.pkg.applicationInfo.backupAgentName != null); 8265 8266 // Set up the post-install work request bookkeeping. This will be used 8267 // and cleaned up by the post-install event handling regardless of whether 8268 // there's a restore pass performed. Token values are >= 1. 8269 int token; 8270 if (mNextInstallToken < 0) mNextInstallToken = 1; 8271 token = mNextInstallToken++; 8272 8273 PostInstallData data = new PostInstallData(args, res); 8274 mRunningInstalls.put(token, data); 8275 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 8276 8277 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 8278 // Pass responsibility to the Backup Manager. It will perform a 8279 // restore if appropriate, then pass responsibility back to the 8280 // Package Manager to run the post-install observer callbacks 8281 // and broadcasts. 8282 IBackupManager bm = IBackupManager.Stub.asInterface( 8283 ServiceManager.getService(Context.BACKUP_SERVICE)); 8284 if (bm != null) { 8285 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 8286 + " to BM for possible restore"); 8287 try { 8288 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 8289 } catch (RemoteException e) { 8290 // can't happen; the backup manager is local 8291 } catch (Exception e) { 8292 Slog.e(TAG, "Exception trying to enqueue restore", e); 8293 doRestore = false; 8294 } 8295 } else { 8296 Slog.e(TAG, "Backup Manager not found!"); 8297 doRestore = false; 8298 } 8299 } 8300 8301 if (!doRestore) { 8302 // No restore possible, or the Backup Manager was mysteriously not 8303 // available -- just fire the post-install work request directly. 8304 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 8305 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8306 mHandler.sendMessage(msg); 8307 } 8308 } 8309 }); 8310 } 8311 8312 private abstract class HandlerParams { 8313 private static final int MAX_RETRIES = 4; 8314 8315 /** 8316 * Number of times startCopy() has been attempted and had a non-fatal 8317 * error. 8318 */ 8319 private int mRetries = 0; 8320 8321 /** User handle for the user requesting the information or installation. */ 8322 private final UserHandle mUser; 8323 8324 HandlerParams(UserHandle user) { 8325 mUser = user; 8326 } 8327 8328 UserHandle getUser() { 8329 return mUser; 8330 } 8331 8332 final boolean startCopy() { 8333 boolean res; 8334 try { 8335 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 8336 8337 if (++mRetries > MAX_RETRIES) { 8338 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 8339 mHandler.sendEmptyMessage(MCS_GIVE_UP); 8340 handleServiceError(); 8341 return false; 8342 } else { 8343 handleStartCopy(); 8344 res = true; 8345 } 8346 } catch (RemoteException e) { 8347 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 8348 mHandler.sendEmptyMessage(MCS_RECONNECT); 8349 res = false; 8350 } 8351 handleReturnCode(); 8352 return res; 8353 } 8354 8355 final void serviceError() { 8356 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 8357 handleServiceError(); 8358 handleReturnCode(); 8359 } 8360 8361 abstract void handleStartCopy() throws RemoteException; 8362 abstract void handleServiceError(); 8363 abstract void handleReturnCode(); 8364 } 8365 8366 class MeasureParams extends HandlerParams { 8367 private final PackageStats mStats; 8368 private boolean mSuccess; 8369 8370 private final IPackageStatsObserver mObserver; 8371 8372 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 8373 super(new UserHandle(stats.userHandle)); 8374 mObserver = observer; 8375 mStats = stats; 8376 } 8377 8378 @Override 8379 public String toString() { 8380 return "MeasureParams{" 8381 + Integer.toHexString(System.identityHashCode(this)) 8382 + " " + mStats.packageName + "}"; 8383 } 8384 8385 @Override 8386 void handleStartCopy() throws RemoteException { 8387 synchronized (mInstallLock) { 8388 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 8389 } 8390 8391 if (mSuccess) { 8392 final boolean mounted; 8393 if (Environment.isExternalStorageEmulated()) { 8394 mounted = true; 8395 } else { 8396 final String status = Environment.getExternalStorageState(); 8397 mounted = (Environment.MEDIA_MOUNTED.equals(status) 8398 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 8399 } 8400 8401 if (mounted) { 8402 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 8403 8404 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 8405 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 8406 8407 mStats.externalDataSize = calculateDirectorySize(mContainerService, 8408 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 8409 8410 // Always subtract cache size, since it's a subdirectory 8411 mStats.externalDataSize -= mStats.externalCacheSize; 8412 8413 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 8414 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 8415 8416 mStats.externalObbSize = calculateDirectorySize(mContainerService, 8417 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 8418 } 8419 } 8420 } 8421 8422 @Override 8423 void handleReturnCode() { 8424 if (mObserver != null) { 8425 try { 8426 mObserver.onGetStatsCompleted(mStats, mSuccess); 8427 } catch (RemoteException e) { 8428 Slog.i(TAG, "Observer no longer exists."); 8429 } 8430 } 8431 } 8432 8433 @Override 8434 void handleServiceError() { 8435 Slog.e(TAG, "Could not measure application " + mStats.packageName 8436 + " external storage"); 8437 } 8438 } 8439 8440 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 8441 throws RemoteException { 8442 long result = 0; 8443 for (File path : paths) { 8444 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 8445 } 8446 return result; 8447 } 8448 8449 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 8450 for (File path : paths) { 8451 try { 8452 mcs.clearDirectory(path.getAbsolutePath()); 8453 } catch (RemoteException e) { 8454 } 8455 } 8456 } 8457 8458 class InstallParams extends HandlerParams { 8459 /** 8460 * Location where install is coming from, before it has been 8461 * copied/renamed into place. This could be a single monolithic APK 8462 * file, or a cluster directory. This location may be untrusted. 8463 */ 8464 final File originFile; 8465 8466 /** 8467 * Flag indicating that {@link #originFile} has already been staged, 8468 * meaning downstream users don't need to defensively copy the contents. 8469 */ 8470 boolean originStaged; 8471 8472 final IPackageInstallObserver2 observer; 8473 int flags; 8474 final String installerPackageName; 8475 final VerificationParams verificationParams; 8476 private InstallArgs mArgs; 8477 private int mRet; 8478 final String packageAbiOverride; 8479 boolean multiArch; 8480 8481 InstallParams(File originFile, boolean originStaged, IPackageInstallObserver2 observer, 8482 int flags, String installerPackageName, VerificationParams verificationParams, 8483 UserHandle user, String packageAbiOverride) { 8484 super(user); 8485 this.originFile = Preconditions.checkNotNull(originFile); 8486 this.originStaged = originStaged; 8487 this.observer = observer; 8488 this.flags = flags; 8489 this.installerPackageName = installerPackageName; 8490 this.verificationParams = verificationParams; 8491 this.packageAbiOverride = packageAbiOverride; 8492 } 8493 8494 @Override 8495 public String toString() { 8496 return "InstallParams{" 8497 + Integer.toHexString(System.identityHashCode(this)) 8498 + " " + originFile + "}"; 8499 } 8500 8501 public ManifestDigest getManifestDigest() { 8502 if (verificationParams == null) { 8503 return null; 8504 } 8505 return verificationParams.getManifestDigest(); 8506 } 8507 8508 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) { 8509 String packageName = pkgLite.packageName; 8510 int installLocation = pkgLite.installLocation; 8511 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8512 // reader 8513 synchronized (mPackages) { 8514 PackageParser.Package pkg = mPackages.get(packageName); 8515 if (pkg != null) { 8516 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 8517 // Check for downgrading. 8518 if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 8519 if (pkgLite.versionCode < pkg.mVersionCode) { 8520 Slog.w(TAG, "Can't install update of " + packageName 8521 + " update version " + pkgLite.versionCode 8522 + " is older than installed version " 8523 + pkg.mVersionCode); 8524 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 8525 } 8526 } 8527 // Check for updated system application. 8528 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8529 if (onSd) { 8530 Slog.w(TAG, "Cannot install update to system app on sdcard"); 8531 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 8532 } 8533 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8534 } else { 8535 if (onSd) { 8536 // Install flag overrides everything. 8537 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8538 } 8539 // If current upgrade specifies particular preference 8540 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 8541 // Application explicitly specified internal. 8542 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8543 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 8544 // App explictly prefers external. Let policy decide 8545 } else { 8546 // Prefer previous location 8547 if (isExternal(pkg)) { 8548 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8549 } 8550 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8551 } 8552 } 8553 } else { 8554 // Invalid install. Return error code 8555 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 8556 } 8557 } 8558 } 8559 // All the special cases have been taken care of. 8560 // Return result based on recommended install location. 8561 if (onSd) { 8562 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8563 } 8564 return pkgLite.recommendedInstallLocation; 8565 } 8566 8567 private long getMemoryLowThreshold() { 8568 final DeviceStorageMonitorInternal 8569 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 8570 if (dsm == null) { 8571 return 0L; 8572 } 8573 return dsm.getMemoryLowThreshold(); 8574 } 8575 8576 /* 8577 * Invoke remote method to get package information and install 8578 * location values. Override install location based on default 8579 * policy if needed and then create install arguments based 8580 * on the install location. 8581 */ 8582 public void handleStartCopy() throws RemoteException { 8583 int ret = PackageManager.INSTALL_SUCCEEDED; 8584 final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8585 final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0; 8586 PackageInfoLite pkgLite = null; 8587 8588 if (onInt && onSd) { 8589 // Check if both bits are set. 8590 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 8591 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8592 } else { 8593 final long lowThreshold = getMemoryLowThreshold(); 8594 if (lowThreshold == 0L) { 8595 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 8596 } 8597 8598 // Remote call to find out default install location 8599 final String originPath = originFile.getAbsolutePath(); 8600 pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags, lowThreshold, 8601 packageAbiOverride); 8602 // Keep track of whether this package is a multiArch package until 8603 // we perform a full scan of it. We need to do this because we might 8604 // end up extracting the package shared libraries before we perform 8605 // a full scan. 8606 multiArch = pkgLite.multiArch; 8607 8608 /* 8609 * If we have too little free space, try to free cache 8610 * before giving up. 8611 */ 8612 if (pkgLite.recommendedInstallLocation 8613 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8614 final long size = mContainerService.calculateInstalledSize( 8615 originPath, isForwardLocked(), packageAbiOverride); 8616 if (mInstaller.freeCache(size + lowThreshold) >= 0) { 8617 pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags, 8618 lowThreshold, packageAbiOverride); 8619 } 8620 /* 8621 * The cache free must have deleted the file we 8622 * downloaded to install. 8623 * 8624 * TODO: fix the "freeCache" call to not delete 8625 * the file we care about. 8626 */ 8627 if (pkgLite.recommendedInstallLocation 8628 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8629 pkgLite.recommendedInstallLocation 8630 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 8631 } 8632 } 8633 } 8634 8635 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8636 int loc = pkgLite.recommendedInstallLocation; 8637 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 8638 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8639 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 8640 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 8641 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8642 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8643 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 8644 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 8645 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8646 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 8647 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 8648 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 8649 } else { 8650 // Override with defaults if needed. 8651 loc = installLocationPolicy(pkgLite, flags); 8652 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 8653 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 8654 } else if (!onSd && !onInt) { 8655 // Override install location with flags 8656 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 8657 // Set the flag to install on external media. 8658 flags |= PackageManager.INSTALL_EXTERNAL; 8659 flags &= ~PackageManager.INSTALL_INTERNAL; 8660 } else { 8661 // Make sure the flag for installing on external 8662 // media is unset 8663 flags |= PackageManager.INSTALL_INTERNAL; 8664 flags &= ~PackageManager.INSTALL_EXTERNAL; 8665 } 8666 } 8667 } 8668 } 8669 8670 final InstallArgs args = createInstallArgs(this); 8671 mArgs = args; 8672 8673 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8674 /* 8675 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 8676 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 8677 */ 8678 int userIdentifier = getUser().getIdentifier(); 8679 if (userIdentifier == UserHandle.USER_ALL 8680 && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) { 8681 userIdentifier = UserHandle.USER_OWNER; 8682 } 8683 8684 /* 8685 * Determine if we have any installed package verifiers. If we 8686 * do, then we'll defer to them to verify the packages. 8687 */ 8688 final int requiredUid = mRequiredVerifierPackage == null ? -1 8689 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 8690 if (requiredUid != -1 && isVerificationEnabled(userIdentifier, flags)) { 8691 // TODO: send verifier the install session instead of uri 8692 final Intent verification = new Intent( 8693 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 8694 verification.setDataAndType(Uri.fromFile(originFile), PACKAGE_MIME_TYPE); 8695 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8696 8697 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 8698 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 8699 0 /* TODO: Which userId? */); 8700 8701 if (DEBUG_VERIFY) { 8702 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 8703 + verification.toString() + " with " + pkgLite.verifiers.length 8704 + " optional verifiers"); 8705 } 8706 8707 final int verificationId = mPendingVerificationToken++; 8708 8709 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8710 8711 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 8712 installerPackageName); 8713 8714 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags); 8715 8716 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 8717 pkgLite.packageName); 8718 8719 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 8720 pkgLite.versionCode); 8721 8722 if (verificationParams != null) { 8723 if (verificationParams.getVerificationURI() != null) { 8724 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 8725 verificationParams.getVerificationURI()); 8726 } 8727 if (verificationParams.getOriginatingURI() != null) { 8728 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 8729 verificationParams.getOriginatingURI()); 8730 } 8731 if (verificationParams.getReferrer() != null) { 8732 verification.putExtra(Intent.EXTRA_REFERRER, 8733 verificationParams.getReferrer()); 8734 } 8735 if (verificationParams.getOriginatingUid() >= 0) { 8736 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 8737 verificationParams.getOriginatingUid()); 8738 } 8739 if (verificationParams.getInstallerUid() >= 0) { 8740 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 8741 verificationParams.getInstallerUid()); 8742 } 8743 } 8744 8745 final PackageVerificationState verificationState = new PackageVerificationState( 8746 requiredUid, args); 8747 8748 mPendingVerification.append(verificationId, verificationState); 8749 8750 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 8751 receivers, verificationState); 8752 8753 /* 8754 * If any sufficient verifiers were listed in the package 8755 * manifest, attempt to ask them. 8756 */ 8757 if (sufficientVerifiers != null) { 8758 final int N = sufficientVerifiers.size(); 8759 if (N == 0) { 8760 Slog.i(TAG, "Additional verifiers required, but none installed."); 8761 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 8762 } else { 8763 for (int i = 0; i < N; i++) { 8764 final ComponentName verifierComponent = sufficientVerifiers.get(i); 8765 8766 final Intent sufficientIntent = new Intent(verification); 8767 sufficientIntent.setComponent(verifierComponent); 8768 8769 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 8770 } 8771 } 8772 } 8773 8774 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 8775 mRequiredVerifierPackage, receivers); 8776 if (ret == PackageManager.INSTALL_SUCCEEDED 8777 && mRequiredVerifierPackage != null) { 8778 /* 8779 * Send the intent to the required verification agent, 8780 * but only start the verification timeout after the 8781 * target BroadcastReceivers have run. 8782 */ 8783 verification.setComponent(requiredVerifierComponent); 8784 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 8785 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8786 new BroadcastReceiver() { 8787 @Override 8788 public void onReceive(Context context, Intent intent) { 8789 final Message msg = mHandler 8790 .obtainMessage(CHECK_PENDING_VERIFICATION); 8791 msg.arg1 = verificationId; 8792 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 8793 } 8794 }, null, 0, null, null); 8795 8796 /* 8797 * We don't want the copy to proceed until verification 8798 * succeeds, so null out this field. 8799 */ 8800 mArgs = null; 8801 } 8802 } else { 8803 /* 8804 * No package verification is enabled, so immediately start 8805 * the remote call to initiate copy using temporary file. 8806 */ 8807 ret = args.copyApk(mContainerService, true); 8808 } 8809 } 8810 8811 mRet = ret; 8812 } 8813 8814 @Override 8815 void handleReturnCode() { 8816 // If mArgs is null, then MCS couldn't be reached. When it 8817 // reconnects, it will try again to install. At that point, this 8818 // will succeed. 8819 if (mArgs != null) { 8820 processPendingInstall(mArgs, mRet); 8821 } 8822 } 8823 8824 @Override 8825 void handleServiceError() { 8826 mArgs = createInstallArgs(this); 8827 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8828 } 8829 8830 public boolean isForwardLocked() { 8831 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8832 } 8833 } 8834 8835 /* 8836 * Utility class used in movePackage api. 8837 * srcArgs and targetArgs are not set for invalid flags and make 8838 * sure to do null checks when invoking methods on them. 8839 * We probably want to return ErrorPrams for both failed installs 8840 * and moves. 8841 */ 8842 class MoveParams extends HandlerParams { 8843 final IPackageMoveObserver observer; 8844 final int flags; 8845 final String packageName; 8846 final InstallArgs srcArgs; 8847 final InstallArgs targetArgs; 8848 int uid; 8849 int mRet; 8850 8851 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags, 8852 String packageName, String[] instructionSets, int uid, UserHandle user, 8853 boolean isMultiArch) { 8854 super(user); 8855 this.srcArgs = srcArgs; 8856 this.observer = observer; 8857 this.flags = flags; 8858 this.packageName = packageName; 8859 this.uid = uid; 8860 if (srcArgs != null) { 8861 final String codePath = srcArgs.getCodePath(); 8862 targetArgs = createInstallArgsForMoveTarget(codePath, flags, packageName, 8863 instructionSets, isMultiArch); 8864 } else { 8865 targetArgs = null; 8866 } 8867 } 8868 8869 @Override 8870 public String toString() { 8871 return "MoveParams{" 8872 + Integer.toHexString(System.identityHashCode(this)) 8873 + " " + packageName + "}"; 8874 } 8875 8876 public void handleStartCopy() throws RemoteException { 8877 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8878 // Check for storage space on target medium 8879 if (!targetArgs.checkFreeStorage(mContainerService)) { 8880 Log.w(TAG, "Insufficient storage to install"); 8881 return; 8882 } 8883 8884 mRet = srcArgs.doPreCopy(); 8885 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8886 return; 8887 } 8888 8889 mRet = targetArgs.copyApk(mContainerService, false); 8890 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8891 srcArgs.doPostCopy(uid); 8892 return; 8893 } 8894 8895 mRet = srcArgs.doPostCopy(uid); 8896 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8897 return; 8898 } 8899 8900 mRet = targetArgs.doPreInstall(mRet); 8901 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8902 return; 8903 } 8904 8905 if (DEBUG_SD_INSTALL) { 8906 StringBuilder builder = new StringBuilder(); 8907 if (srcArgs != null) { 8908 builder.append("src: "); 8909 builder.append(srcArgs.getCodePath()); 8910 } 8911 if (targetArgs != null) { 8912 builder.append(" target : "); 8913 builder.append(targetArgs.getCodePath()); 8914 } 8915 Log.i(TAG, builder.toString()); 8916 } 8917 } 8918 8919 @Override 8920 void handleReturnCode() { 8921 targetArgs.doPostInstall(mRet, uid); 8922 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 8923 if (mRet == PackageManager.INSTALL_SUCCEEDED) { 8924 currentStatus = PackageManager.MOVE_SUCCEEDED; 8925 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){ 8926 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 8927 } 8928 processPendingMove(this, currentStatus); 8929 } 8930 8931 @Override 8932 void handleServiceError() { 8933 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8934 } 8935 } 8936 8937 /** 8938 * Used during creation of InstallArgs 8939 * 8940 * @param flags package installation flags 8941 * @return true if should be installed on external storage 8942 */ 8943 private static boolean installOnSd(int flags) { 8944 if ((flags & PackageManager.INSTALL_INTERNAL) != 0) { 8945 return false; 8946 } 8947 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) { 8948 return true; 8949 } 8950 return false; 8951 } 8952 8953 /** 8954 * Used during creation of InstallArgs 8955 * 8956 * @param flags package installation flags 8957 * @return true if should be installed as forward locked 8958 */ 8959 private static boolean installForwardLocked(int flags) { 8960 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8961 } 8962 8963 private InstallArgs createInstallArgs(InstallParams params) { 8964 // TODO: extend to support incoming zero-copy locations 8965 8966 if (installOnSd(params.flags) || params.isForwardLocked()) { 8967 return new AsecInstallArgs(params); 8968 } else { 8969 return new FileInstallArgs(params); 8970 } 8971 } 8972 8973 /** 8974 * Create args that describe an existing installed package. Typically used 8975 * when cleaning up old installs, or used as a move source. 8976 */ 8977 private InstallArgs createInstallArgsForExisting(int flags, String codePath, 8978 String resourcePath, String nativeLibraryRoot, String[] instructionSets, 8979 boolean isMultiArch) { 8980 final boolean isInAsec; 8981 if (installOnSd(flags)) { 8982 /* Apps on SD card are always in ASEC containers. */ 8983 isInAsec = true; 8984 } else if (installForwardLocked(flags) 8985 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 8986 /* 8987 * Forward-locked apps are only in ASEC containers if they're the 8988 * new style 8989 */ 8990 isInAsec = true; 8991 } else { 8992 isInAsec = false; 8993 } 8994 8995 if (isInAsec) { 8996 return new AsecInstallArgs(codePath, instructionSets, 8997 installOnSd(flags), installForwardLocked(flags), isMultiArch); 8998 } else { 8999 return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot, 9000 instructionSets, isMultiArch); 9001 } 9002 } 9003 9004 private InstallArgs createInstallArgsForMoveTarget(String codePath, int flags, String pkgName, 9005 String[] instructionSets, boolean isMultiArch) { 9006 final File codeFile = new File(codePath); 9007 if (installOnSd(flags) || installForwardLocked(flags)) { 9008 String cid = getNextCodePath(codePath, pkgName, "/" 9009 + AsecInstallArgs.RES_FILE_NAME); 9010 return new AsecInstallArgs(codeFile, cid, instructionSets, installOnSd(flags), 9011 installForwardLocked(flags), isMultiArch); 9012 } else { 9013 return new FileInstallArgs(codeFile, instructionSets, isMultiArch); 9014 } 9015 } 9016 9017 static abstract class InstallArgs { 9018 /** @see InstallParams#originFile */ 9019 final File originFile; 9020 /** @see InstallParams#originStaged */ 9021 final boolean originStaged; 9022 9023 // TODO: define inherit location 9024 9025 final IPackageInstallObserver2 observer; 9026 // Always refers to PackageManager flags only 9027 final int flags; 9028 final String installerPackageName; 9029 final ManifestDigest manifestDigest; 9030 final UserHandle user; 9031 final String abiOverride; 9032 final boolean multiArch; 9033 9034 // The list of instruction sets supported by this app. This is currently 9035 // only used during the rmdex() phase to clean up resources. We can get rid of this 9036 // if we move dex files under the common app path. 9037 /* nullable */ String[] instructionSets; 9038 9039 InstallArgs(File originFile, boolean originStaged, IPackageInstallObserver2 observer, 9040 int flags, String installerPackageName, ManifestDigest manifestDigest, 9041 UserHandle user, String[] instructionSets, 9042 String abiOverride, boolean multiArch) { 9043 this.originFile = originFile; 9044 this.originStaged = originStaged; 9045 this.flags = flags; 9046 this.observer = observer; 9047 this.installerPackageName = installerPackageName; 9048 this.manifestDigest = manifestDigest; 9049 this.user = user; 9050 this.instructionSets = instructionSets; 9051 this.abiOverride = abiOverride; 9052 this.multiArch = multiArch; 9053 } 9054 9055 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 9056 abstract int doPreInstall(int status); 9057 9058 /** 9059 * Rename package into final resting place. All paths on the given 9060 * scanned package should be updated to reflect the rename. 9061 */ 9062 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 9063 abstract int doPostInstall(int status, int uid); 9064 9065 /** @see PackageSettingBase#codePathString */ 9066 abstract String getCodePath(); 9067 /** @see PackageSettingBase#resourcePathString */ 9068 abstract String getResourcePath(); 9069 abstract String getLegacyNativeLibraryPath(); 9070 9071 // Need installer lock especially for dex file removal. 9072 abstract void cleanUpResourcesLI(); 9073 abstract boolean doPostDeleteLI(boolean delete); 9074 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9075 9076 /** 9077 * Called before the source arguments are copied. This is used mostly 9078 * for MoveParams when it needs to read the source file to put it in the 9079 * destination. 9080 */ 9081 int doPreCopy() { 9082 return PackageManager.INSTALL_SUCCEEDED; 9083 } 9084 9085 /** 9086 * Called after the source arguments are copied. This is used mostly for 9087 * MoveParams when it needs to read the source file to put it in the 9088 * destination. 9089 * 9090 * @return 9091 */ 9092 int doPostCopy(int uid) { 9093 return PackageManager.INSTALL_SUCCEEDED; 9094 } 9095 9096 protected boolean isFwdLocked() { 9097 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9098 } 9099 9100 UserHandle getUser() { 9101 return user; 9102 } 9103 } 9104 9105 /** 9106 * Logic to handle installation of non-ASEC applications, including copying 9107 * and renaming logic. 9108 */ 9109 class FileInstallArgs extends InstallArgs { 9110 private File codeFile; 9111 private File resourceFile; 9112 private File legacyNativeLibraryPath; 9113 9114 // Example topology: 9115 // /data/app/com.example/base.apk 9116 // /data/app/com.example/split_foo.apk 9117 // /data/app/com.example/lib/arm/libfoo.so 9118 // /data/app/com.example/lib/arm64/libfoo.so 9119 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 9120 9121 /** New install */ 9122 FileInstallArgs(InstallParams params) { 9123 super(params.originFile, params.originStaged, params.observer, params.flags, 9124 params.installerPackageName, params.getManifestDigest(), params.getUser(), 9125 null /* instruction sets */, params.packageAbiOverride, 9126 params.multiArch); 9127 if (isFwdLocked()) { 9128 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 9129 } 9130 } 9131 9132 /** Existing install */ 9133 FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath, 9134 String[] instructionSets, boolean isMultiArch) { 9135 super(null, false, null, 0, null, null, null, instructionSets, null, isMultiArch); 9136 this.codeFile = (codePath != null) ? new File(codePath) : null; 9137 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 9138 this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ? 9139 new File(legacyNativeLibraryPath) : null; 9140 } 9141 9142 /** New install from existing */ 9143 FileInstallArgs(File originFile, String[] instructionSets, boolean isMultiArch) { 9144 super(originFile, false, null, 0, null, null, null, instructionSets, null, 9145 isMultiArch); 9146 } 9147 9148 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9149 final long lowThreshold; 9150 9151 final DeviceStorageMonitorInternal 9152 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 9153 if (dsm == null) { 9154 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 9155 lowThreshold = 0L; 9156 } else { 9157 if (dsm.isMemoryLow()) { 9158 Log.w(TAG, "Memory is reported as being too low; aborting package install"); 9159 return false; 9160 } 9161 9162 lowThreshold = dsm.getMemoryLowThreshold(); 9163 } 9164 9165 return imcs.checkInternalFreeStorage(originFile.getAbsolutePath(), isFwdLocked(), 9166 lowThreshold); 9167 } 9168 9169 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9170 int ret = PackageManager.INSTALL_SUCCEEDED; 9171 9172 if (originStaged) { 9173 Slog.d(TAG, originFile + " already staged; skipping copy"); 9174 codeFile = originFile; 9175 resourceFile = originFile; 9176 } else { 9177 try { 9178 final File tempDir = mInstallerService.allocateSessionDir(); 9179 codeFile = tempDir; 9180 resourceFile = tempDir; 9181 } catch (IOException e) { 9182 Slog.w(TAG, "Failed to create copy file: " + e); 9183 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9184 } 9185 9186 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 9187 @Override 9188 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 9189 if (!FileUtils.isValidExtFilename(name)) { 9190 throw new IllegalArgumentException("Invalid filename: " + name); 9191 } 9192 try { 9193 final File file = new File(codeFile, name); 9194 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 9195 O_RDWR | O_CREAT, 0644); 9196 Os.chmod(file.getAbsolutePath(), 0644); 9197 return new ParcelFileDescriptor(fd); 9198 } catch (ErrnoException e) { 9199 throw new RemoteException("Failed to open: " + e.getMessage()); 9200 } 9201 } 9202 }; 9203 9204 ret = imcs.copyPackage(originFile.getAbsolutePath(), target); 9205 if (ret != PackageManager.INSTALL_SUCCEEDED) { 9206 Slog.e(TAG, "Failed to copy package"); 9207 return ret; 9208 } 9209 } 9210 9211 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 9212 NativeLibraryHelper.Handle handle = null; 9213 try { 9214 handle = NativeLibraryHelper.Handle.create(codeFile); 9215 if (multiArch) { 9216 // Warn if we've set an abiOverride for multi-lib packages.. 9217 // By definition, we need to copy both 32 and 64 bit libraries for 9218 // such packages. 9219 if (abiOverride != null) { 9220 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 9221 } 9222 9223 int copyRet = PackageManager.NO_NATIVE_LIBRARIES; 9224 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 9225 copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot, 9226 Build.SUPPORTED_32_BIT_ABIS, true /* use isa specific subdirs */); 9227 maybeThrowExceptionForMultiArchCopy("Failure copying 32 bit native libraries", copyRet); 9228 } 9229 9230 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 9231 copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot, 9232 Build.SUPPORTED_64_BIT_ABIS, true /* use isa specific subdirs */); 9233 maybeThrowExceptionForMultiArchCopy("Failure copying 64 bit native libraries", copyRet); 9234 } 9235 } else { 9236 String[] abiList = (abiOverride != null) ? 9237 new String[] { abiOverride } : Build.SUPPORTED_ABIS; 9238 9239 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && abiOverride == null && 9240 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9241 abiList = Build.SUPPORTED_32_BIT_ABIS; 9242 } 9243 9244 int copyRet = copyNativeLibrariesForInternalApp(handle, libraryRoot, abiList, 9245 true /* use isa specific subdirs */); 9246 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9247 Slog.w(TAG, "Failure copying native libraries [errorCode=" + copyRet + "]"); 9248 return copyRet; 9249 } 9250 } 9251 } catch (IOException e) { 9252 Slog.e(TAG, "Copying native libraries failed", e); 9253 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9254 } catch (PackageManagerException pme) { 9255 Slog.e(TAG, "Copying native libraries failed", pme); 9256 ret = pme.error; 9257 } finally { 9258 IoUtils.closeQuietly(handle); 9259 } 9260 9261 return ret; 9262 } 9263 9264 int doPreInstall(int status) { 9265 if (status != PackageManager.INSTALL_SUCCEEDED) { 9266 cleanUp(); 9267 } 9268 return status; 9269 } 9270 9271 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9272 if (status != PackageManager.INSTALL_SUCCEEDED) { 9273 cleanUp(); 9274 return false; 9275 } else { 9276 final File beforeCodeFile = codeFile; 9277 final File afterCodeFile = getNextCodePath(pkg.packageName); 9278 9279 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 9280 try { 9281 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 9282 } catch (ErrnoException e) { 9283 Slog.d(TAG, "Failed to rename", e); 9284 return false; 9285 } 9286 9287 if (!SELinux.restoreconRecursive(afterCodeFile)) { 9288 Slog.d(TAG, "Failed to restorecon"); 9289 return false; 9290 } 9291 9292 // Reflect the rename internally 9293 codeFile = afterCodeFile; 9294 resourceFile = afterCodeFile; 9295 9296 // Reflect the rename in scanned details 9297 pkg.codePath = afterCodeFile.getAbsolutePath(); 9298 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9299 pkg.baseCodePath); 9300 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9301 pkg.splitCodePaths); 9302 9303 // Reflect the rename in app info 9304 pkg.applicationInfo.setCodePath(pkg.codePath); 9305 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9306 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9307 pkg.applicationInfo.setResourcePath(pkg.codePath); 9308 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9309 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9310 9311 return true; 9312 } 9313 } 9314 9315 int doPostInstall(int status, int uid) { 9316 if (status != PackageManager.INSTALL_SUCCEEDED) { 9317 cleanUp(); 9318 } 9319 return status; 9320 } 9321 9322 @Override 9323 String getCodePath() { 9324 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 9325 } 9326 9327 @Override 9328 String getResourcePath() { 9329 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 9330 } 9331 9332 @Override 9333 String getLegacyNativeLibraryPath() { 9334 return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null; 9335 } 9336 9337 private boolean cleanUp() { 9338 if (codeFile == null || !codeFile.exists()) { 9339 return false; 9340 } 9341 9342 if (codeFile.isDirectory()) { 9343 FileUtils.deleteContents(codeFile); 9344 } 9345 codeFile.delete(); 9346 9347 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 9348 resourceFile.delete(); 9349 } 9350 9351 if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) { 9352 if (!FileUtils.deleteContents(legacyNativeLibraryPath)) { 9353 Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath); 9354 } 9355 legacyNativeLibraryPath.delete(); 9356 } 9357 9358 return true; 9359 } 9360 9361 void cleanUpResourcesLI() { 9362 // Try enumerating all code paths before deleting 9363 List<String> allCodePaths = Collections.EMPTY_LIST; 9364 if (codeFile != null && codeFile.exists()) { 9365 try { 9366 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9367 allCodePaths = pkg.getAllCodePaths(); 9368 } catch (PackageParserException e) { 9369 // Ignored; we tried our best 9370 } 9371 } 9372 9373 cleanUp(); 9374 9375 if (!allCodePaths.isEmpty()) { 9376 if (instructionSets == null) { 9377 throw new IllegalStateException("instructionSet == null"); 9378 } 9379 9380 for (String codePath : allCodePaths) { 9381 for (String instructionSet : instructionSets) { 9382 int retCode = mInstaller.rmdex(codePath, instructionSet); 9383 if (retCode < 0) { 9384 Slog.w(TAG, "Couldn't remove dex file for package: " 9385 + " at location " + codePath + ", retcode=" + retCode); 9386 // we don't consider this to be a failure of the core package deletion 9387 } 9388 } 9389 } 9390 } 9391 } 9392 9393 boolean doPostDeleteLI(boolean delete) { 9394 // XXX err, shouldn't we respect the delete flag? 9395 cleanUpResourcesLI(); 9396 return true; 9397 } 9398 } 9399 9400 private boolean isAsecExternal(String cid) { 9401 final String asecPath = PackageHelper.getSdFilesystem(cid); 9402 return !asecPath.startsWith(mAsecInternalPath); 9403 } 9404 9405 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 9406 PackageManagerException { 9407 if (copyRet < 0) { 9408 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 9409 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 9410 throw new PackageManagerException(copyRet, message); 9411 } 9412 } 9413 } 9414 9415 /** 9416 * Extract the MountService "container ID" from the full code path of an 9417 * .apk. 9418 */ 9419 static String cidFromCodePath(String fullCodePath) { 9420 int eidx = fullCodePath.lastIndexOf("/"); 9421 String subStr1 = fullCodePath.substring(0, eidx); 9422 int sidx = subStr1.lastIndexOf("/"); 9423 return subStr1.substring(sidx+1, eidx); 9424 } 9425 9426 /** 9427 * Logic to handle installation of ASEC applications, including copying and 9428 * renaming logic. 9429 */ 9430 class AsecInstallArgs extends InstallArgs { 9431 // TODO: teach about handling cluster directories 9432 9433 static final String RES_FILE_NAME = "pkg.apk"; 9434 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 9435 9436 String cid; 9437 String packagePath; 9438 String resourcePath; 9439 String legacyNativeLibraryDir; 9440 9441 /** New install */ 9442 AsecInstallArgs(InstallParams params) { 9443 super(params.originFile, params.originStaged, params.observer, params.flags, 9444 params.installerPackageName, params.getManifestDigest(), 9445 params.getUser(), null /* instruction sets */, 9446 params.packageAbiOverride, params.multiArch); 9447 } 9448 9449 /** Existing install */ 9450 AsecInstallArgs(String fullCodePath, String[] instructionSets, 9451 boolean isExternal, boolean isForwardLocked, boolean isMultiArch) { 9452 super(null, false, null, (isExternal ? INSTALL_EXTERNAL : 0) 9453 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9454 instructionSets, null, isMultiArch); 9455 // Extract cid from fullCodePath 9456 int eidx = fullCodePath.lastIndexOf("/"); 9457 String subStr1 = fullCodePath.substring(0, eidx); 9458 int sidx = subStr1.lastIndexOf("/"); 9459 cid = subStr1.substring(sidx+1, eidx); 9460 setCachePath(subStr1); 9461 } 9462 9463 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked, 9464 boolean isMultiArch) { 9465 super(null, false, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 9466 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9467 instructionSets, null, isMultiArch); 9468 this.cid = cid; 9469 setCachePath(PackageHelper.getSdDir(cid)); 9470 } 9471 9472 /** New install from existing */ 9473 AsecInstallArgs(File originPackageFile, String cid, String[] instructionSets, 9474 boolean isExternal, boolean isForwardLocked, boolean isMultiArch) { 9475 super(originPackageFile, false, null, (isExternal ? INSTALL_EXTERNAL : 0) 9476 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9477 instructionSets, null, isMultiArch); 9478 this.cid = cid; 9479 } 9480 9481 void createCopyFile() { 9482 cid = getTempContainerId(); 9483 } 9484 9485 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9486 return imcs.checkExternalFreeStorage(originFile.getAbsolutePath(), isFwdLocked(), 9487 abiOverride); 9488 } 9489 9490 private final boolean isExternal() { 9491 return (flags & PackageManager.INSTALL_EXTERNAL) != 0; 9492 } 9493 9494 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9495 if (temp) { 9496 createCopyFile(); 9497 } else { 9498 /* 9499 * Pre-emptively destroy the container since it's destroyed if 9500 * copying fails due to it existing anyway. 9501 */ 9502 PackageHelper.destroySdDir(cid); 9503 } 9504 9505 final String newCachePath = imcs.copyPackageToContainer( 9506 originFile.getAbsolutePath(), cid, getEncryptKey(), isExternal(), 9507 isFwdLocked(), abiOverride); 9508 9509 if (newCachePath != null) { 9510 setCachePath(newCachePath); 9511 return PackageManager.INSTALL_SUCCEEDED; 9512 } else { 9513 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9514 } 9515 } 9516 9517 @Override 9518 String getCodePath() { 9519 return packagePath; 9520 } 9521 9522 @Override 9523 String getResourcePath() { 9524 return resourcePath; 9525 } 9526 9527 @Override 9528 String getLegacyNativeLibraryPath() { 9529 return legacyNativeLibraryDir; 9530 } 9531 9532 int doPreInstall(int status) { 9533 if (status != PackageManager.INSTALL_SUCCEEDED) { 9534 // Destroy container 9535 PackageHelper.destroySdDir(cid); 9536 } else { 9537 boolean mounted = PackageHelper.isContainerMounted(cid); 9538 if (!mounted) { 9539 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), 9540 Process.SYSTEM_UID); 9541 if (newCachePath != null) { 9542 setCachePath(newCachePath); 9543 } else { 9544 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9545 } 9546 } 9547 } 9548 return status; 9549 } 9550 9551 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9552 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 9553 String newCachePath = null; 9554 if (PackageHelper.isContainerMounted(cid)) { 9555 // Unmount the container 9556 if (!PackageHelper.unMountSdDir(cid)) { 9557 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9558 return false; 9559 } 9560 } 9561 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9562 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9563 " which might be stale. Will try to clean up."); 9564 // Clean up the stale container and proceed to recreate. 9565 if (!PackageHelper.destroySdDir(newCacheId)) { 9566 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9567 return false; 9568 } 9569 // Successfully cleaned up stale container. Try to rename again. 9570 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9571 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9572 + " inspite of cleaning it up."); 9573 return false; 9574 } 9575 } 9576 if (!PackageHelper.isContainerMounted(newCacheId)) { 9577 Slog.w(TAG, "Mounting container " + newCacheId); 9578 newCachePath = PackageHelper.mountSdDir(newCacheId, 9579 getEncryptKey(), Process.SYSTEM_UID); 9580 } else { 9581 newCachePath = PackageHelper.getSdDir(newCacheId); 9582 } 9583 if (newCachePath == null) { 9584 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9585 return false; 9586 } 9587 Log.i(TAG, "Succesfully renamed " + cid + 9588 " to " + newCacheId + 9589 " at new path: " + newCachePath); 9590 cid = newCacheId; 9591 setCachePath(newCachePath); 9592 9593 // TODO: extend to support split APKs 9594 pkg.codePath = getCodePath(); 9595 pkg.baseCodePath = getCodePath(); 9596 pkg.splitCodePaths = null; 9597 9598 pkg.applicationInfo.setCodePath(getCodePath()); 9599 pkg.applicationInfo.setBaseCodePath(getCodePath()); 9600 pkg.applicationInfo.setSplitCodePaths(null); 9601 pkg.applicationInfo.setResourcePath(getResourcePath()); 9602 pkg.applicationInfo.setBaseResourcePath(getResourcePath()); 9603 pkg.applicationInfo.setSplitResourcePaths(null); 9604 9605 return true; 9606 } 9607 9608 private void setCachePath(String newCachePath) { 9609 File cachePath = new File(newCachePath); 9610 legacyNativeLibraryDir = new File(cachePath, LIB_DIR_NAME).getPath(); 9611 packagePath = new File(cachePath, RES_FILE_NAME).getPath(); 9612 9613 if (isFwdLocked()) { 9614 resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath(); 9615 } else { 9616 resourcePath = packagePath; 9617 } 9618 } 9619 9620 int doPostInstall(int status, int uid) { 9621 if (status != PackageManager.INSTALL_SUCCEEDED) { 9622 cleanUp(); 9623 } else { 9624 final int groupOwner; 9625 final String protectedFile; 9626 if (isFwdLocked()) { 9627 groupOwner = UserHandle.getSharedAppGid(uid); 9628 protectedFile = RES_FILE_NAME; 9629 } else { 9630 groupOwner = -1; 9631 protectedFile = null; 9632 } 9633 9634 if (uid < Process.FIRST_APPLICATION_UID 9635 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9636 Slog.e(TAG, "Failed to finalize " + cid); 9637 PackageHelper.destroySdDir(cid); 9638 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9639 } 9640 9641 boolean mounted = PackageHelper.isContainerMounted(cid); 9642 if (!mounted) { 9643 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9644 } 9645 } 9646 return status; 9647 } 9648 9649 private void cleanUp() { 9650 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9651 9652 // Destroy secure container 9653 PackageHelper.destroySdDir(cid); 9654 } 9655 9656 void cleanUpResourcesLI() { 9657 String sourceFile = getCodePath(); 9658 // Remove dex file 9659 if (instructionSets == null) { 9660 throw new IllegalStateException("instructionSet == null"); 9661 } 9662 for (String instructionSet : instructionSets) { 9663 int retCode = mInstaller.rmdex(sourceFile, instructionSet); 9664 if (retCode < 0) { 9665 Slog.w(TAG, "Couldn't remove dex file for package: " 9666 + " at location " 9667 + sourceFile.toString() + ", retcode=" + retCode); 9668 // we don't consider this to be a failure of the core package deletion 9669 } 9670 } 9671 cleanUp(); 9672 } 9673 9674 boolean matchContainer(String app) { 9675 if (cid.startsWith(app)) { 9676 return true; 9677 } 9678 return false; 9679 } 9680 9681 String getPackageName() { 9682 return getAsecPackageName(cid); 9683 } 9684 9685 boolean doPostDeleteLI(boolean delete) { 9686 boolean ret = false; 9687 boolean mounted = PackageHelper.isContainerMounted(cid); 9688 if (mounted) { 9689 // Unmount first 9690 ret = PackageHelper.unMountSdDir(cid); 9691 } 9692 if (ret && delete) { 9693 cleanUpResourcesLI(); 9694 } 9695 return ret; 9696 } 9697 9698 @Override 9699 int doPreCopy() { 9700 if (isFwdLocked()) { 9701 if (!PackageHelper.fixSdPermissions(cid, 9702 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 9703 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9704 } 9705 } 9706 9707 return PackageManager.INSTALL_SUCCEEDED; 9708 } 9709 9710 @Override 9711 int doPostCopy(int uid) { 9712 if (isFwdLocked()) { 9713 if (uid < Process.FIRST_APPLICATION_UID 9714 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 9715 RES_FILE_NAME)) { 9716 Slog.e(TAG, "Failed to finalize " + cid); 9717 PackageHelper.destroySdDir(cid); 9718 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9719 } 9720 } 9721 9722 return PackageManager.INSTALL_SUCCEEDED; 9723 } 9724 } 9725 9726 static String getAsecPackageName(String packageCid) { 9727 int idx = packageCid.lastIndexOf("-"); 9728 if (idx == -1) { 9729 return packageCid; 9730 } 9731 return packageCid.substring(0, idx); 9732 } 9733 9734 // Utility method used to create code paths based on package name and available index. 9735 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 9736 String idxStr = ""; 9737 int idx = 1; 9738 // Fall back to default value of idx=1 if prefix is not 9739 // part of oldCodePath 9740 if (oldCodePath != null) { 9741 String subStr = oldCodePath; 9742 // Drop the suffix right away 9743 if (suffix != null && subStr.endsWith(suffix)) { 9744 subStr = subStr.substring(0, subStr.length() - suffix.length()); 9745 } 9746 // If oldCodePath already contains prefix find out the 9747 // ending index to either increment or decrement. 9748 int sidx = subStr.lastIndexOf(prefix); 9749 if (sidx != -1) { 9750 subStr = subStr.substring(sidx + prefix.length()); 9751 if (subStr != null) { 9752 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 9753 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 9754 } 9755 try { 9756 idx = Integer.parseInt(subStr); 9757 if (idx <= 1) { 9758 idx++; 9759 } else { 9760 idx--; 9761 } 9762 } catch(NumberFormatException e) { 9763 } 9764 } 9765 } 9766 } 9767 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 9768 return prefix + idxStr; 9769 } 9770 9771 private File getNextCodePath(String packageName) { 9772 int suffix = 1; 9773 File result; 9774 do { 9775 result = new File(mAppInstallDir, packageName + "-" + suffix); 9776 suffix++; 9777 } while (result.exists()); 9778 return result; 9779 } 9780 9781 // Utility method used to ignore ADD/REMOVE events 9782 // by directory observer. 9783 private static boolean ignoreCodePath(String fullPathStr) { 9784 String apkName = deriveCodePathName(fullPathStr); 9785 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 9786 if (idx != -1 && ((idx+1) < apkName.length())) { 9787 // Make sure the package ends with a numeral 9788 String version = apkName.substring(idx+1); 9789 try { 9790 Integer.parseInt(version); 9791 return true; 9792 } catch (NumberFormatException e) {} 9793 } 9794 return false; 9795 } 9796 9797 // Utility method that returns the relative package path with respect 9798 // to the installation directory. Like say for /data/data/com.test-1.apk 9799 // string com.test-1 is returned. 9800 static String deriveCodePathName(String codePath) { 9801 if (codePath == null) { 9802 return null; 9803 } 9804 final File codeFile = new File(codePath); 9805 final String name = codeFile.getName(); 9806 if (codeFile.isDirectory()) { 9807 return name; 9808 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 9809 final int lastDot = name.lastIndexOf('.'); 9810 return name.substring(0, lastDot); 9811 } else { 9812 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 9813 return null; 9814 } 9815 } 9816 9817 class PackageInstalledInfo { 9818 String name; 9819 int uid; 9820 // The set of users that originally had this package installed. 9821 int[] origUsers; 9822 // The set of users that now have this package installed. 9823 int[] newUsers; 9824 PackageParser.Package pkg; 9825 int returnCode; 9826 String returnMsg; 9827 PackageRemovedInfo removedInfo; 9828 9829 public void setError(int code, String msg) { 9830 returnCode = code; 9831 returnMsg = msg; 9832 Slog.w(TAG, msg); 9833 } 9834 9835 public void setError(String msg, PackageParserException e) { 9836 returnCode = e.error; 9837 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9838 Slog.w(TAG, msg, e); 9839 } 9840 9841 public void setError(String msg, PackageManagerException e) { 9842 returnCode = e.error; 9843 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9844 Slog.w(TAG, msg, e); 9845 } 9846 9847 // In some error cases we want to convey more info back to the observer 9848 String origPackage; 9849 String origPermission; 9850 } 9851 9852 /* 9853 * Install a non-existing package. 9854 */ 9855 private void installNewPackageLI(PackageParser.Package pkg, 9856 int parseFlags, int scanMode, UserHandle user, 9857 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9858 // Remember this for later, in case we need to rollback this install 9859 String pkgName = pkg.packageName; 9860 9861 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 9862 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 9863 synchronized(mPackages) { 9864 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 9865 // A package with the same name is already installed, though 9866 // it has been renamed to an older name. The package we 9867 // are trying to install should be installed as an update to 9868 // the existing one, but that has not been requested, so bail. 9869 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9870 + " without first uninstalling package running as " 9871 + mSettings.mRenamedPackages.get(pkgName)); 9872 return; 9873 } 9874 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.codePath)) { 9875 // Don't allow installation over an existing package with the same name. 9876 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9877 + " without first uninstalling."); 9878 return; 9879 } 9880 } 9881 9882 try { 9883 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode, 9884 System.currentTimeMillis(), user, abiOverride); 9885 9886 updateSettingsLI(newPackage, installerPackageName, null, null, res); 9887 // delete the partially installed application. the data directory will have to be 9888 // restored if it was already existing 9889 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9890 // remove package from internal structures. Note that we want deletePackageX to 9891 // delete the package data and cache directories that it created in 9892 // scanPackageLocked, unless those directories existed before we even tried to 9893 // install. 9894 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 9895 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 9896 res.removedInfo, true); 9897 } 9898 9899 } catch (PackageManagerException e) { 9900 res.setError("Package couldn't be installed in " + pkg.codePath, e); 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 for (int i = 0; i < upgradeKeySets.length; i++) { 9910 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 9911 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 9912 return true; 9913 } 9914 } 9915 return false; 9916 } 9917 9918 private void replacePackageLI(PackageParser.Package pkg, 9919 int parseFlags, int scanMode, UserHandle user, 9920 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9921 PackageParser.Package oldPackage; 9922 String pkgName = pkg.packageName; 9923 int[] allUsers; 9924 boolean[] perUserInstalled; 9925 9926 // First find the old package info and check signatures 9927 synchronized(mPackages) { 9928 oldPackage = mPackages.get(pkgName); 9929 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 9930 PackageSetting ps = mSettings.mPackages.get(pkgName); 9931 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 9932 // default to original signature matching 9933 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 9934 != PackageManager.SIGNATURE_MATCH) { 9935 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9936 "New package has a different signature: " + pkgName); 9937 return; 9938 } 9939 } else { 9940 if(!checkUpgradeKeySetLP(ps, pkg)) { 9941 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9942 "New package not signed by keys specified by upgrade-keysets: " 9943 + pkgName); 9944 return; 9945 } 9946 } 9947 9948 // In case of rollback, remember per-user/profile install state 9949 allUsers = sUserManager.getUserIds(); 9950 perUserInstalled = new boolean[allUsers.length]; 9951 for (int i = 0; i < allUsers.length; i++) { 9952 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 9953 } 9954 } 9955 9956 boolean sysPkg = (isSystemApp(oldPackage)); 9957 if (sysPkg) { 9958 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 9959 user, allUsers, perUserInstalled, installerPackageName, res, 9960 abiOverride); 9961 } else { 9962 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 9963 user, allUsers, perUserInstalled, installerPackageName, res, 9964 abiOverride); 9965 } 9966 } 9967 9968 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 9969 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 9970 int[] allUsers, boolean[] perUserInstalled, 9971 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9972 String pkgName = deletedPackage.packageName; 9973 boolean deletedPkg = true; 9974 boolean updatedSettings = false; 9975 9976 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 9977 + deletedPackage); 9978 long origUpdateTime; 9979 if (pkg.mExtras != null) { 9980 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 9981 } else { 9982 origUpdateTime = 0; 9983 } 9984 9985 // First delete the existing package while retaining the data directory 9986 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 9987 res.removedInfo, true)) { 9988 // If the existing package wasn't successfully deleted 9989 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 9990 deletedPkg = false; 9991 } else { 9992 // Successfully deleted the old package. Now proceed with re-installation 9993 deleteCodeCacheDirsLI(pkgName); 9994 try { 9995 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 9996 scanMode | SCAN_UPDATE_TIME, System.currentTimeMillis(), user, abiOverride); 9997 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 9998 updatedSettings = true; 9999 } catch (PackageManagerException e) { 10000 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10001 } 10002 } 10003 10004 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10005 // remove package from internal structures. Note that we want deletePackageX to 10006 // delete the package data and cache directories that it created in 10007 // scanPackageLocked, unless those directories existed before we even tried to 10008 // install. 10009 if(updatedSettings) { 10010 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 10011 deletePackageLI( 10012 pkgName, null, true, allUsers, perUserInstalled, 10013 PackageManager.DELETE_KEEP_DATA, 10014 res.removedInfo, true); 10015 } 10016 // Since we failed to install the new package we need to restore the old 10017 // package that we deleted. 10018 if (deletedPkg) { 10019 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 10020 File restoreFile = new File(deletedPackage.codePath); 10021 // Parse old package 10022 boolean oldOnSd = isExternal(deletedPackage); 10023 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 10024 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) | 10025 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 10026 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE 10027 | SCAN_UPDATE_TIME; 10028 try { 10029 scanPackageLI(restoreFile, oldParseFlags, oldScanMode, origUpdateTime, null, 10030 null); 10031 } catch (PackageManagerException e) { 10032 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 10033 + e.getMessage()); 10034 return; 10035 } 10036 // Restore of old package succeeded. Update permissions. 10037 // writer 10038 synchronized (mPackages) { 10039 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 10040 UPDATE_PERMISSIONS_ALL); 10041 // can downgrade to reader 10042 mSettings.writeLPr(); 10043 } 10044 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 10045 } 10046 } 10047 } 10048 10049 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 10050 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 10051 int[] allUsers, boolean[] perUserInstalled, 10052 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 10053 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 10054 + ", old=" + deletedPackage); 10055 boolean updatedSettings = false; 10056 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING | 10057 PackageParser.PARSE_IS_SYSTEM; 10058 if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) { 10059 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10060 } 10061 String packageName = deletedPackage.packageName; 10062 if (packageName == null) { 10063 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10064 "Attempt to delete null packageName."); 10065 return; 10066 } 10067 PackageParser.Package oldPkg; 10068 PackageSetting oldPkgSetting; 10069 // reader 10070 synchronized (mPackages) { 10071 oldPkg = mPackages.get(packageName); 10072 oldPkgSetting = mSettings.mPackages.get(packageName); 10073 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 10074 (oldPkgSetting == null)) { 10075 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10076 "Couldn't find package:" + packageName + " information"); 10077 return; 10078 } 10079 } 10080 10081 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 10082 10083 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10084 res.removedInfo.removedPackage = packageName; 10085 // Remove existing system package 10086 removePackageLI(oldPkgSetting, true); 10087 // writer 10088 synchronized (mPackages) { 10089 if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) { 10090 // We didn't need to disable the .apk as a current system package, 10091 // which means we are replacing another update that is already 10092 // installed. We need to make sure to delete the older one's .apk. 10093 res.removedInfo.args = createInstallArgsForExisting(0, 10094 deletedPackage.applicationInfo.getCodePath(), 10095 deletedPackage.applicationInfo.getResourcePath(), 10096 deletedPackage.applicationInfo.nativeLibraryRootDir, 10097 getAppDexInstructionSets(deletedPackage.applicationInfo), 10098 isMultiArch(deletedPackage.applicationInfo)); 10099 } else { 10100 res.removedInfo.args = null; 10101 } 10102 } 10103 10104 // Successfully disabled the old package. Now proceed with re-installation 10105 deleteCodeCacheDirsLI(packageName); 10106 10107 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10108 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10109 10110 PackageParser.Package newPackage = null; 10111 try { 10112 newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user, abiOverride); 10113 if (newPackage.mExtras != null) { 10114 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 10115 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10116 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10117 10118 // is the update attempting to change shared user? that isn't going to work... 10119 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10120 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 10121 "Forbidding shared user change from " + oldPkgSetting.sharedUser 10122 + " to " + newPkgSetting.sharedUser); 10123 updatedSettings = true; 10124 } 10125 } 10126 10127 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10128 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10129 updatedSettings = true; 10130 } 10131 10132 } catch (PackageManagerException e) { 10133 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10134 } 10135 10136 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10137 // Re installation failed. Restore old information 10138 // Remove new pkg information 10139 if (newPackage != null) { 10140 removeInstalledPackageLI(newPackage, true); 10141 } 10142 // Add back the old system package 10143 try { 10144 scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user, 10145 null); 10146 } catch (PackageManagerException e) { 10147 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 10148 } 10149 // Restore the old system information in Settings 10150 synchronized(mPackages) { 10151 if (updatedSettings) { 10152 mSettings.enableSystemPackageLPw(packageName); 10153 mSettings.setInstallerPackageName(packageName, 10154 oldPkgSetting.installerPackageName); 10155 } 10156 mSettings.writeLPr(); 10157 } 10158 } 10159 } 10160 10161 // Utility method used to move dex files during install. 10162 private int moveDexFilesLI(String oldCodePath, PackageParser.Package newPackage) { 10163 // TODO: extend to move split APK dex files 10164 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) { 10165 final String[] instructionSets = getAppDexInstructionSets(newPackage.applicationInfo); 10166 for (String instructionSet : instructionSets) { 10167 int retCode = mInstaller.movedex(oldCodePath, newPackage.baseCodePath, 10168 instructionSet); 10169 if (retCode != 0) { 10170 /* 10171 * Programs may be lazily run through dexopt, so the 10172 * source may not exist. However, something seems to 10173 * have gone wrong, so note that dexopt needs to be 10174 * run again and remove the source file. In addition, 10175 * remove the target to make sure there isn't a stale 10176 * file from a previous version of the package. 10177 */ 10178 newPackage.mDexOptPerformed.clear(); 10179 mInstaller.rmdex(oldCodePath, instructionSet); 10180 mInstaller.rmdex(newPackage.baseCodePath, instructionSet); 10181 } 10182 } 10183 } 10184 return PackageManager.INSTALL_SUCCEEDED; 10185 } 10186 10187 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10188 int[] allUsers, boolean[] perUserInstalled, 10189 PackageInstalledInfo res) { 10190 String pkgName = newPackage.packageName; 10191 synchronized (mPackages) { 10192 //write settings. the installStatus will be incomplete at this stage. 10193 //note that the new package setting would have already been 10194 //added to mPackages. It hasn't been persisted yet. 10195 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10196 mSettings.writeLPr(); 10197 } 10198 10199 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10200 10201 synchronized (mPackages) { 10202 updatePermissionsLPw(newPackage.packageName, newPackage, 10203 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10204 ? UPDATE_PERMISSIONS_ALL : 0)); 10205 // For system-bundled packages, we assume that installing an upgraded version 10206 // of the package implies that the user actually wants to run that new code, 10207 // so we enable the package. 10208 if (isSystemApp(newPackage)) { 10209 // NB: implicit assumption that system package upgrades apply to all users 10210 if (DEBUG_INSTALL) { 10211 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10212 } 10213 PackageSetting ps = mSettings.mPackages.get(pkgName); 10214 if (ps != null) { 10215 if (res.origUsers != null) { 10216 for (int userHandle : res.origUsers) { 10217 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10218 userHandle, installerPackageName); 10219 } 10220 } 10221 // Also convey the prior install/uninstall state 10222 if (allUsers != null && perUserInstalled != null) { 10223 for (int i = 0; i < allUsers.length; i++) { 10224 if (DEBUG_INSTALL) { 10225 Slog.d(TAG, " user " + allUsers[i] 10226 + " => " + perUserInstalled[i]); 10227 } 10228 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10229 } 10230 // these install state changes will be persisted in the 10231 // upcoming call to mSettings.writeLPr(). 10232 } 10233 } 10234 } 10235 res.name = pkgName; 10236 res.uid = newPackage.applicationInfo.uid; 10237 res.pkg = newPackage; 10238 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10239 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10240 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10241 //to update install status 10242 mSettings.writeLPr(); 10243 } 10244 } 10245 10246 private void installPackageLI(InstallArgs args, boolean newInstall, PackageInstalledInfo res) { 10247 int pFlags = args.flags; 10248 String installerPackageName = args.installerPackageName; 10249 File tmpPackageFile = new File(args.getCodePath()); 10250 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10251 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0); 10252 boolean replace = false; 10253 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE 10254 | (newInstall ? SCAN_NEW_INSTALL : 0); 10255 // Result object to be returned 10256 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10257 10258 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10259 // Retrieve PackageSettings and parse package 10260 int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10261 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10262 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 10263 PackageParser pp = new PackageParser(); 10264 pp.setSeparateProcesses(mSeparateProcesses); 10265 pp.setDisplayMetrics(mMetrics); 10266 10267 final PackageParser.Package pkg; 10268 try { 10269 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 10270 } catch (PackageParserException e) { 10271 res.setError("Failed parse during installPackageLI", e); 10272 return; 10273 } 10274 10275 String pkgName = res.name = pkg.packageName; 10276 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 10277 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) { 10278 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 10279 return; 10280 } 10281 } 10282 10283 try { 10284 pp.collectCertificates(pkg, parseFlags); 10285 pp.collectManifestDigest(pkg); 10286 } catch (PackageParserException e) { 10287 res.setError("Failed collect during installPackageLI", e); 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.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest 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 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 10330 + pkg.packageName + " attempting to redeclare permission " 10331 + perm.info.name + " already owned by " + bp.sourcePackage); 10332 res.origPermission = perm.info.name; 10333 res.origPackage = bp.sourcePackage; 10334 return; 10335 } else { 10336 Slog.w(TAG, "Package " + pkg.packageName 10337 + " attempting to redeclare system permission " 10338 + perm.info.name + "; ignoring new declaration"); 10339 pkg.permissions.remove(i); 10340 } 10341 } 10342 } 10343 } 10344 10345 // Check if installing already existing package 10346 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10347 String oldName = mSettings.mRenamedPackages.get(pkgName); 10348 if (pkg.mOriginalPackages != null 10349 && pkg.mOriginalPackages.contains(oldName) 10350 && mPackages.containsKey(oldName)) { 10351 // This package is derived from an original package, 10352 // and this device has been updating from that original 10353 // name. We must continue using the original name, so 10354 // rename the new package here. 10355 pkg.setPackageName(oldName); 10356 pkgName = pkg.packageName; 10357 replace = true; 10358 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 10359 + oldName + " pkgName=" + pkgName); 10360 } else if (mPackages.containsKey(pkgName)) { 10361 // This package, under its official name, already exists 10362 // on the device; we should replace it. 10363 replace = true; 10364 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 10365 } 10366 } 10367 PackageSetting ps = mSettings.mPackages.get(pkgName); 10368 if (ps != null) { 10369 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 10370 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 10371 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 10372 systemApp = (ps.pkg.applicationInfo.flags & 10373 ApplicationInfo.FLAG_SYSTEM) != 0; 10374 } 10375 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10376 } 10377 } 10378 10379 if (systemApp && onSd) { 10380 // Disable updates to system apps on sdcard 10381 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 10382 "Cannot install updates to system apps on sdcard"); 10383 return; 10384 } 10385 10386 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 10387 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 10388 return; 10389 } 10390 10391 if (replace) { 10392 replacePackageLI(pkg, parseFlags, scanMode, args.user, 10393 installerPackageName, res, args.abiOverride); 10394 } else { 10395 installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user, 10396 installerPackageName, res, args.abiOverride); 10397 } 10398 synchronized (mPackages) { 10399 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10400 if (ps != null) { 10401 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10402 } 10403 } 10404 } 10405 10406 private static boolean isForwardLocked(PackageParser.Package pkg) { 10407 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10408 } 10409 10410 private static boolean isForwardLocked(ApplicationInfo info) { 10411 return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10412 } 10413 10414 private boolean isForwardLocked(PackageSetting ps) { 10415 return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10416 } 10417 10418 private static boolean isMultiArch(PackageSetting ps) { 10419 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10420 } 10421 10422 private static boolean isMultiArch(ApplicationInfo info) { 10423 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10424 } 10425 10426 private static boolean isExternal(PackageParser.Package pkg) { 10427 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10428 } 10429 10430 private static boolean isExternal(PackageSetting ps) { 10431 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10432 } 10433 10434 private static boolean isExternal(ApplicationInfo info) { 10435 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10436 } 10437 10438 private static boolean isSystemApp(PackageParser.Package pkg) { 10439 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10440 } 10441 10442 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 10443 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0; 10444 } 10445 10446 private static boolean isSystemApp(ApplicationInfo info) { 10447 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10448 } 10449 10450 private static boolean isSystemApp(PackageSetting ps) { 10451 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 10452 } 10453 10454 private static boolean isUpdatedSystemApp(PackageSetting ps) { 10455 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10456 } 10457 10458 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 10459 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10460 } 10461 10462 private static boolean isUpdatedSystemApp(ApplicationInfo info) { 10463 return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10464 } 10465 10466 private int packageFlagsToInstallFlags(PackageSetting ps) { 10467 int installFlags = 0; 10468 if (isExternal(ps)) { 10469 installFlags |= PackageManager.INSTALL_EXTERNAL; 10470 } 10471 if (isForwardLocked(ps)) { 10472 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 10473 } 10474 return installFlags; 10475 } 10476 10477 private void deleteTempPackageFiles() { 10478 final FilenameFilter filter = new FilenameFilter() { 10479 public boolean accept(File dir, String name) { 10480 return name.startsWith("vmdl") && name.endsWith(".tmp"); 10481 } 10482 }; 10483 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 10484 file.delete(); 10485 } 10486 } 10487 10488 @Override 10489 public void deletePackageAsUser(final String packageName, 10490 final IPackageDeleteObserver observer, 10491 final int userId, final int flags) { 10492 mContext.enforceCallingOrSelfPermission( 10493 android.Manifest.permission.DELETE_PACKAGES, null); 10494 final int uid = Binder.getCallingUid(); 10495 if (UserHandle.getUserId(uid) != userId) { 10496 mContext.enforceCallingPermission( 10497 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 10498 "deletePackage for user " + userId); 10499 } 10500 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 10501 try { 10502 observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_USER_RESTRICTED); 10503 } catch (RemoteException re) { 10504 } 10505 return; 10506 } 10507 10508 boolean uninstallBlocked = false; 10509 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 10510 int[] users = sUserManager.getUserIds(); 10511 for (int i = 0; i < users.length; ++i) { 10512 if (getBlockUninstallForUser(packageName, users[i])) { 10513 uninstallBlocked = true; 10514 break; 10515 } 10516 } 10517 } else { 10518 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 10519 } 10520 if (uninstallBlocked) { 10521 try { 10522 observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED); 10523 } catch (RemoteException re) { 10524 } 10525 return; 10526 } 10527 10528 if (DEBUG_REMOVE) { 10529 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 10530 } 10531 // Queue up an async operation since the package deletion may take a little while. 10532 mHandler.post(new Runnable() { 10533 public void run() { 10534 mHandler.removeCallbacks(this); 10535 final int returnCode = deletePackageX(packageName, userId, flags); 10536 if (observer != null) { 10537 try { 10538 observer.packageDeleted(packageName, returnCode); 10539 } catch (RemoteException e) { 10540 Log.i(TAG, "Observer no longer exists."); 10541 } //end catch 10542 } //end if 10543 } //end run 10544 }); 10545 } 10546 10547 private boolean isPackageDeviceAdmin(String packageName, int userId) { 10548 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 10549 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 10550 try { 10551 if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId) 10552 || dpm.isDeviceOwner(packageName))) { 10553 return true; 10554 } 10555 } catch (RemoteException e) { 10556 } 10557 return false; 10558 } 10559 10560 /** 10561 * This method is an internal method that could be get invoked either 10562 * to delete an installed package or to clean up a failed installation. 10563 * After deleting an installed package, a broadcast is sent to notify any 10564 * listeners that the package has been installed. For cleaning up a failed 10565 * installation, the broadcast is not necessary since the package's 10566 * installation wouldn't have sent the initial broadcast either 10567 * The key steps in deleting a package are 10568 * deleting the package information in internal structures like mPackages, 10569 * deleting the packages base directories through installd 10570 * updating mSettings to reflect current status 10571 * persisting settings for later use 10572 * sending a broadcast if necessary 10573 */ 10574 private int deletePackageX(String packageName, int userId, int flags) { 10575 final PackageRemovedInfo info = new PackageRemovedInfo(); 10576 final boolean res; 10577 10578 if (isPackageDeviceAdmin(packageName, userId)) { 10579 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 10580 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 10581 } 10582 10583 boolean removedForAllUsers = false; 10584 boolean systemUpdate = false; 10585 10586 // for the uninstall-updates case and restricted profiles, remember the per- 10587 // userhandle installed state 10588 int[] allUsers; 10589 boolean[] perUserInstalled; 10590 synchronized (mPackages) { 10591 PackageSetting ps = mSettings.mPackages.get(packageName); 10592 allUsers = sUserManager.getUserIds(); 10593 perUserInstalled = new boolean[allUsers.length]; 10594 for (int i = 0; i < allUsers.length; i++) { 10595 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10596 } 10597 } 10598 10599 synchronized (mInstallLock) { 10600 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 10601 res = deletePackageLI(packageName, 10602 (flags & PackageManager.DELETE_ALL_USERS) != 0 10603 ? UserHandle.ALL : new UserHandle(userId), 10604 true, allUsers, perUserInstalled, 10605 flags | REMOVE_CHATTY, info, true); 10606 systemUpdate = info.isRemovedPackageSystemUpdate; 10607 if (res && !systemUpdate && mPackages.get(packageName) == null) { 10608 removedForAllUsers = true; 10609 } 10610 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 10611 + " removedForAllUsers=" + removedForAllUsers); 10612 } 10613 10614 if (res) { 10615 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 10616 10617 // If the removed package was a system update, the old system package 10618 // was re-enabled; we need to broadcast this information 10619 if (systemUpdate) { 10620 Bundle extras = new Bundle(1); 10621 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 10622 ? info.removedAppId : info.uid); 10623 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10624 10625 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 10626 extras, null, null, null); 10627 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 10628 extras, null, null, null); 10629 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 10630 null, packageName, null, null); 10631 } 10632 } 10633 // Force a gc here. 10634 Runtime.getRuntime().gc(); 10635 // Delete the resources here after sending the broadcast to let 10636 // other processes clean up before deleting resources. 10637 if (info.args != null) { 10638 synchronized (mInstallLock) { 10639 info.args.doPostDeleteLI(true); 10640 } 10641 } 10642 10643 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10644 } 10645 10646 static class PackageRemovedInfo { 10647 String removedPackage; 10648 int uid = -1; 10649 int removedAppId = -1; 10650 int[] removedUsers = null; 10651 boolean isRemovedPackageSystemUpdate = false; 10652 // Clean up resources deleted packages. 10653 InstallArgs args = null; 10654 10655 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 10656 Bundle extras = new Bundle(1); 10657 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 10658 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 10659 if (replacing) { 10660 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10661 } 10662 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 10663 if (removedPackage != null) { 10664 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 10665 extras, null, null, removedUsers); 10666 if (fullRemove && !replacing) { 10667 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 10668 extras, null, null, removedUsers); 10669 } 10670 } 10671 if (removedAppId >= 0) { 10672 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 10673 removedUsers); 10674 } 10675 } 10676 } 10677 10678 /* 10679 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 10680 * flag is not set, the data directory is removed as well. 10681 * make sure this flag is set for partially installed apps. If not its meaningless to 10682 * delete a partially installed application. 10683 */ 10684 private void removePackageDataLI(PackageSetting ps, 10685 int[] allUserHandles, boolean[] perUserInstalled, 10686 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 10687 String packageName = ps.name; 10688 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 10689 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 10690 // Retrieve object to delete permissions for shared user later on 10691 final PackageSetting deletedPs; 10692 // reader 10693 synchronized (mPackages) { 10694 deletedPs = mSettings.mPackages.get(packageName); 10695 if (outInfo != null) { 10696 outInfo.removedPackage = packageName; 10697 outInfo.removedUsers = deletedPs != null 10698 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 10699 : null; 10700 } 10701 } 10702 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10703 removeDataDirsLI(packageName); 10704 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 10705 } 10706 // writer 10707 synchronized (mPackages) { 10708 if (deletedPs != null) { 10709 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10710 if (outInfo != null) { 10711 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 10712 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 10713 } 10714 if (deletedPs != null) { 10715 updatePermissionsLPw(deletedPs.name, null, 0); 10716 if (deletedPs.sharedUser != null) { 10717 // remove permissions associated with package 10718 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 10719 } 10720 } 10721 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 10722 } 10723 // make sure to preserve per-user disabled state if this removal was just 10724 // a downgrade of a system app to the factory package 10725 if (allUserHandles != null && perUserInstalled != null) { 10726 if (DEBUG_REMOVE) { 10727 Slog.d(TAG, "Propagating install state across downgrade"); 10728 } 10729 for (int i = 0; i < allUserHandles.length; i++) { 10730 if (DEBUG_REMOVE) { 10731 Slog.d(TAG, " user " + allUserHandles[i] 10732 + " => " + perUserInstalled[i]); 10733 } 10734 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10735 } 10736 } 10737 } 10738 // can downgrade to reader 10739 if (writeSettings) { 10740 // Save settings now 10741 mSettings.writeLPr(); 10742 } 10743 } 10744 if (outInfo != null) { 10745 // A user ID was deleted here. Go through all users and remove it 10746 // from KeyStore. 10747 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 10748 } 10749 } 10750 10751 static boolean locationIsPrivileged(File path) { 10752 try { 10753 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 10754 .getCanonicalPath(); 10755 return path.getCanonicalPath().startsWith(privilegedAppDir); 10756 } catch (IOException e) { 10757 Slog.e(TAG, "Unable to access code path " + path); 10758 } 10759 return false; 10760 } 10761 10762 /* 10763 * Tries to delete system package. 10764 */ 10765 private boolean deleteSystemPackageLI(PackageSetting newPs, 10766 int[] allUserHandles, boolean[] perUserInstalled, 10767 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 10768 final boolean applyUserRestrictions 10769 = (allUserHandles != null) && (perUserInstalled != null); 10770 PackageSetting disabledPs = null; 10771 // Confirm if the system package has been updated 10772 // An updated system app can be deleted. This will also have to restore 10773 // the system pkg from system partition 10774 // reader 10775 synchronized (mPackages) { 10776 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 10777 } 10778 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 10779 + " disabledPs=" + disabledPs); 10780 if (disabledPs == null) { 10781 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 10782 return false; 10783 } else if (DEBUG_REMOVE) { 10784 Slog.d(TAG, "Deleting system pkg from data partition"); 10785 } 10786 if (DEBUG_REMOVE) { 10787 if (applyUserRestrictions) { 10788 Slog.d(TAG, "Remembering install states:"); 10789 for (int i = 0; i < allUserHandles.length; i++) { 10790 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 10791 } 10792 } 10793 } 10794 // Delete the updated package 10795 outInfo.isRemovedPackageSystemUpdate = true; 10796 if (disabledPs.versionCode < newPs.versionCode) { 10797 // Delete data for downgrades 10798 flags &= ~PackageManager.DELETE_KEEP_DATA; 10799 } else { 10800 // Preserve data by setting flag 10801 flags |= PackageManager.DELETE_KEEP_DATA; 10802 } 10803 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 10804 allUserHandles, perUserInstalled, outInfo, writeSettings); 10805 if (!ret) { 10806 return false; 10807 } 10808 // writer 10809 synchronized (mPackages) { 10810 // Reinstate the old system package 10811 mSettings.enableSystemPackageLPw(newPs.name); 10812 // Remove any native libraries from the upgraded package. 10813 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 10814 } 10815 // Install the system package 10816 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 10817 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 10818 if (locationIsPrivileged(disabledPs.codePath)) { 10819 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10820 } 10821 10822 final PackageParser.Package newPkg; 10823 try { 10824 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, 10825 null, null); 10826 } catch (PackageManagerException e) { 10827 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 10828 return false; 10829 } 10830 10831 // writer 10832 synchronized (mPackages) { 10833 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 10834 updatePermissionsLPw(newPkg.packageName, newPkg, 10835 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 10836 if (applyUserRestrictions) { 10837 if (DEBUG_REMOVE) { 10838 Slog.d(TAG, "Propagating install state across reinstall"); 10839 } 10840 for (int i = 0; i < allUserHandles.length; i++) { 10841 if (DEBUG_REMOVE) { 10842 Slog.d(TAG, " user " + allUserHandles[i] 10843 + " => " + perUserInstalled[i]); 10844 } 10845 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10846 } 10847 // Regardless of writeSettings we need to ensure that this restriction 10848 // state propagation is persisted 10849 mSettings.writeAllUsersPackageRestrictionsLPr(); 10850 } 10851 // can downgrade to reader here 10852 if (writeSettings) { 10853 mSettings.writeLPr(); 10854 } 10855 } 10856 return true; 10857 } 10858 10859 private boolean deleteInstalledPackageLI(PackageSetting ps, 10860 boolean deleteCodeAndResources, int flags, 10861 int[] allUserHandles, boolean[] perUserInstalled, 10862 PackageRemovedInfo outInfo, boolean writeSettings) { 10863 if (outInfo != null) { 10864 outInfo.uid = ps.appId; 10865 } 10866 10867 // Delete package data from internal structures and also remove data if flag is set 10868 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 10869 10870 // Delete application code and resources 10871 if (deleteCodeAndResources && (outInfo != null)) { 10872 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 10873 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 10874 getAppDexInstructionSets(ps), isMultiArch(ps)); 10875 } 10876 return true; 10877 } 10878 10879 @Override 10880 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 10881 int userId) { 10882 mContext.enforceCallingOrSelfPermission( 10883 android.Manifest.permission.DELETE_PACKAGES, null); 10884 synchronized (mPackages) { 10885 PackageSetting ps = mSettings.mPackages.get(packageName); 10886 if (ps == null) { 10887 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 10888 return false; 10889 } 10890 if (!ps.getInstalled(userId)) { 10891 // Can't block uninstall for an app that is not installed or enabled. 10892 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 10893 return false; 10894 } 10895 ps.setBlockUninstall(blockUninstall, userId); 10896 mSettings.writePackageRestrictionsLPr(userId); 10897 } 10898 return true; 10899 } 10900 10901 @Override 10902 public boolean getBlockUninstallForUser(String packageName, int userId) { 10903 synchronized (mPackages) { 10904 PackageSetting ps = mSettings.mPackages.get(packageName); 10905 if (ps == null) { 10906 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 10907 return false; 10908 } 10909 return ps.getBlockUninstall(userId); 10910 } 10911 } 10912 10913 /* 10914 * This method handles package deletion in general 10915 */ 10916 private boolean deletePackageLI(String packageName, UserHandle user, 10917 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 10918 int flags, PackageRemovedInfo outInfo, 10919 boolean writeSettings) { 10920 if (packageName == null) { 10921 Slog.w(TAG, "Attempt to delete null packageName."); 10922 return false; 10923 } 10924 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 10925 PackageSetting ps; 10926 boolean dataOnly = false; 10927 int removeUser = -1; 10928 int appId = -1; 10929 synchronized (mPackages) { 10930 ps = mSettings.mPackages.get(packageName); 10931 if (ps == null) { 10932 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 10933 return false; 10934 } 10935 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 10936 && user.getIdentifier() != UserHandle.USER_ALL) { 10937 // The caller is asking that the package only be deleted for a single 10938 // user. To do this, we just mark its uninstalled state and delete 10939 // its data. If this is a system app, we only allow this to happen if 10940 // they have set the special DELETE_SYSTEM_APP which requests different 10941 // semantics than normal for uninstalling system apps. 10942 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 10943 ps.setUserState(user.getIdentifier(), 10944 COMPONENT_ENABLED_STATE_DEFAULT, 10945 false, //installed 10946 true, //stopped 10947 true, //notLaunched 10948 false, //hidden 10949 null, null, null, 10950 false // blockUninstall 10951 ); 10952 if (!isSystemApp(ps)) { 10953 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 10954 // Other user still have this package installed, so all 10955 // we need to do is clear this user's data and save that 10956 // it is uninstalled. 10957 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 10958 removeUser = user.getIdentifier(); 10959 appId = ps.appId; 10960 mSettings.writePackageRestrictionsLPr(removeUser); 10961 } else { 10962 // We need to set it back to 'installed' so the uninstall 10963 // broadcasts will be sent correctly. 10964 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 10965 ps.setInstalled(true, user.getIdentifier()); 10966 } 10967 } else { 10968 // This is a system app, so we assume that the 10969 // other users still have this package installed, so all 10970 // we need to do is clear this user's data and save that 10971 // it is uninstalled. 10972 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 10973 removeUser = user.getIdentifier(); 10974 appId = ps.appId; 10975 mSettings.writePackageRestrictionsLPr(removeUser); 10976 } 10977 } 10978 } 10979 10980 if (removeUser >= 0) { 10981 // From above, we determined that we are deleting this only 10982 // for a single user. Continue the work here. 10983 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 10984 if (outInfo != null) { 10985 outInfo.removedPackage = packageName; 10986 outInfo.removedAppId = appId; 10987 outInfo.removedUsers = new int[] {removeUser}; 10988 } 10989 mInstaller.clearUserData(packageName, removeUser); 10990 removeKeystoreDataIfNeeded(removeUser, appId); 10991 schedulePackageCleaning(packageName, removeUser, false); 10992 return true; 10993 } 10994 10995 if (dataOnly) { 10996 // Delete application data first 10997 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 10998 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 10999 return true; 11000 } 11001 11002 boolean ret = false; 11003 if (isSystemApp(ps)) { 11004 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 11005 // When an updated system application is deleted we delete the existing resources as well and 11006 // fall back to existing code in system partition 11007 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 11008 flags, outInfo, writeSettings); 11009 } else { 11010 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 11011 // Kill application pre-emptively especially for apps on sd. 11012 killApplication(packageName, ps.appId, "uninstall pkg"); 11013 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 11014 allUserHandles, perUserInstalled, 11015 outInfo, writeSettings); 11016 } 11017 11018 return ret; 11019 } 11020 11021 private final class ClearStorageConnection implements ServiceConnection { 11022 IMediaContainerService mContainerService; 11023 11024 @Override 11025 public void onServiceConnected(ComponentName name, IBinder service) { 11026 synchronized (this) { 11027 mContainerService = IMediaContainerService.Stub.asInterface(service); 11028 notifyAll(); 11029 } 11030 } 11031 11032 @Override 11033 public void onServiceDisconnected(ComponentName name) { 11034 } 11035 } 11036 11037 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 11038 final boolean mounted; 11039 if (Environment.isExternalStorageEmulated()) { 11040 mounted = true; 11041 } else { 11042 final String status = Environment.getExternalStorageState(); 11043 11044 mounted = status.equals(Environment.MEDIA_MOUNTED) 11045 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 11046 } 11047 11048 if (!mounted) { 11049 return; 11050 } 11051 11052 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 11053 int[] users; 11054 if (userId == UserHandle.USER_ALL) { 11055 users = sUserManager.getUserIds(); 11056 } else { 11057 users = new int[] { userId }; 11058 } 11059 final ClearStorageConnection conn = new ClearStorageConnection(); 11060 if (mContext.bindServiceAsUser( 11061 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 11062 try { 11063 for (int curUser : users) { 11064 long timeout = SystemClock.uptimeMillis() + 5000; 11065 synchronized (conn) { 11066 long now = SystemClock.uptimeMillis(); 11067 while (conn.mContainerService == null && now < timeout) { 11068 try { 11069 conn.wait(timeout - now); 11070 } catch (InterruptedException e) { 11071 } 11072 } 11073 } 11074 if (conn.mContainerService == null) { 11075 return; 11076 } 11077 11078 final UserEnvironment userEnv = new UserEnvironment(curUser); 11079 clearDirectory(conn.mContainerService, 11080 userEnv.buildExternalStorageAppCacheDirs(packageName)); 11081 if (allData) { 11082 clearDirectory(conn.mContainerService, 11083 userEnv.buildExternalStorageAppDataDirs(packageName)); 11084 clearDirectory(conn.mContainerService, 11085 userEnv.buildExternalStorageAppMediaDirs(packageName)); 11086 } 11087 } 11088 } finally { 11089 mContext.unbindService(conn); 11090 } 11091 } 11092 } 11093 11094 @Override 11095 public void clearApplicationUserData(final String packageName, 11096 final IPackageDataObserver observer, final int userId) { 11097 mContext.enforceCallingOrSelfPermission( 11098 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 11099 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data"); 11100 // Queue up an async operation since the package deletion may take a little while. 11101 mHandler.post(new Runnable() { 11102 public void run() { 11103 mHandler.removeCallbacks(this); 11104 final boolean succeeded; 11105 synchronized (mInstallLock) { 11106 succeeded = clearApplicationUserDataLI(packageName, userId); 11107 } 11108 clearExternalStorageDataSync(packageName, userId, true); 11109 if (succeeded) { 11110 // invoke DeviceStorageMonitor's update method to clear any notifications 11111 DeviceStorageMonitorInternal 11112 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 11113 if (dsm != null) { 11114 dsm.checkMemory(); 11115 } 11116 } 11117 if(observer != null) { 11118 try { 11119 observer.onRemoveCompleted(packageName, succeeded); 11120 } catch (RemoteException e) { 11121 Log.i(TAG, "Observer no longer exists."); 11122 } 11123 } //end if observer 11124 } //end run 11125 }); 11126 } 11127 11128 private boolean clearApplicationUserDataLI(String packageName, int userId) { 11129 if (packageName == null) { 11130 Slog.w(TAG, "Attempt to delete null packageName."); 11131 return false; 11132 } 11133 PackageParser.Package p; 11134 boolean dataOnly = false; 11135 final int appId; 11136 synchronized (mPackages) { 11137 p = mPackages.get(packageName); 11138 if (p == null) { 11139 dataOnly = true; 11140 PackageSetting ps = mSettings.mPackages.get(packageName); 11141 if ((ps == null) || (ps.pkg == null)) { 11142 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11143 return false; 11144 } 11145 p = ps.pkg; 11146 } 11147 if (!dataOnly) { 11148 // need to check this only for fully installed applications 11149 if (p == null) { 11150 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11151 return false; 11152 } 11153 final ApplicationInfo applicationInfo = p.applicationInfo; 11154 if (applicationInfo == null) { 11155 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11156 return false; 11157 } 11158 } 11159 if (p != null && p.applicationInfo != null) { 11160 appId = p.applicationInfo.uid; 11161 } else { 11162 appId = -1; 11163 } 11164 } 11165 int retCode = mInstaller.clearUserData(packageName, userId); 11166 if (retCode < 0) { 11167 Slog.w(TAG, "Couldn't remove cache files for package: " 11168 + packageName); 11169 return false; 11170 } 11171 removeKeystoreDataIfNeeded(userId, appId); 11172 return true; 11173 } 11174 11175 /** 11176 * Remove entries from the keystore daemon. Will only remove it if the 11177 * {@code appId} is valid. 11178 */ 11179 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 11180 if (appId < 0) { 11181 return; 11182 } 11183 11184 final KeyStore keyStore = KeyStore.getInstance(); 11185 if (keyStore != null) { 11186 if (userId == UserHandle.USER_ALL) { 11187 for (final int individual : sUserManager.getUserIds()) { 11188 keyStore.clearUid(UserHandle.getUid(individual, appId)); 11189 } 11190 } else { 11191 keyStore.clearUid(UserHandle.getUid(userId, appId)); 11192 } 11193 } else { 11194 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 11195 } 11196 } 11197 11198 @Override 11199 public void deleteApplicationCacheFiles(final String packageName, 11200 final IPackageDataObserver observer) { 11201 mContext.enforceCallingOrSelfPermission( 11202 android.Manifest.permission.DELETE_CACHE_FILES, null); 11203 // Queue up an async operation since the package deletion may take a little while. 11204 final int userId = UserHandle.getCallingUserId(); 11205 mHandler.post(new Runnable() { 11206 public void run() { 11207 mHandler.removeCallbacks(this); 11208 final boolean succeded; 11209 synchronized (mInstallLock) { 11210 succeded = deleteApplicationCacheFilesLI(packageName, userId); 11211 } 11212 clearExternalStorageDataSync(packageName, userId, false); 11213 if(observer != null) { 11214 try { 11215 observer.onRemoveCompleted(packageName, succeded); 11216 } catch (RemoteException e) { 11217 Log.i(TAG, "Observer no longer exists."); 11218 } 11219 } //end if observer 11220 } //end run 11221 }); 11222 } 11223 11224 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 11225 if (packageName == null) { 11226 Slog.w(TAG, "Attempt to delete null packageName."); 11227 return false; 11228 } 11229 PackageParser.Package p; 11230 synchronized (mPackages) { 11231 p = mPackages.get(packageName); 11232 } 11233 if (p == null) { 11234 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11235 return false; 11236 } 11237 final ApplicationInfo applicationInfo = p.applicationInfo; 11238 if (applicationInfo == null) { 11239 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11240 return false; 11241 } 11242 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 11243 if (retCode < 0) { 11244 Slog.w(TAG, "Couldn't remove cache files for package: " 11245 + packageName + " u" + userId); 11246 return false; 11247 } 11248 return true; 11249 } 11250 11251 @Override 11252 public void getPackageSizeInfo(final String packageName, int userHandle, 11253 final IPackageStatsObserver observer) { 11254 mContext.enforceCallingOrSelfPermission( 11255 android.Manifest.permission.GET_PACKAGE_SIZE, null); 11256 if (packageName == null) { 11257 throw new IllegalArgumentException("Attempt to get size of null packageName"); 11258 } 11259 11260 PackageStats stats = new PackageStats(packageName, userHandle); 11261 11262 /* 11263 * Queue up an async operation since the package measurement may take a 11264 * little while. 11265 */ 11266 Message msg = mHandler.obtainMessage(INIT_COPY); 11267 msg.obj = new MeasureParams(stats, observer); 11268 mHandler.sendMessage(msg); 11269 } 11270 11271 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 11272 PackageStats pStats) { 11273 if (packageName == null) { 11274 Slog.w(TAG, "Attempt to get size of null packageName."); 11275 return false; 11276 } 11277 PackageParser.Package p; 11278 boolean dataOnly = false; 11279 String libDirRoot = null; 11280 String asecPath = null; 11281 PackageSetting ps = null; 11282 synchronized (mPackages) { 11283 p = mPackages.get(packageName); 11284 ps = mSettings.mPackages.get(packageName); 11285 if(p == null) { 11286 dataOnly = true; 11287 if((ps == null) || (ps.pkg == null)) { 11288 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11289 return false; 11290 } 11291 p = ps.pkg; 11292 } 11293 if (ps != null) { 11294 libDirRoot = ps.legacyNativeLibraryPathString; 11295 } 11296 if (p != null && (isExternal(p) || isForwardLocked(p))) { 11297 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 11298 if (secureContainerId != null) { 11299 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 11300 } 11301 } 11302 } 11303 String publicSrcDir = null; 11304 if(!dataOnly) { 11305 final ApplicationInfo applicationInfo = p.applicationInfo; 11306 if (applicationInfo == null) { 11307 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11308 return false; 11309 } 11310 if (isForwardLocked(p)) { 11311 publicSrcDir = applicationInfo.getBaseResourcePath(); 11312 } 11313 } 11314 // TODO: extend to measure size of split APKs 11315 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 11316 // not just the first level. 11317 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 11318 // just the primary. 11319 int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot, 11320 publicSrcDir, asecPath, getAppDexInstructionSets(ps), 11321 pStats); 11322 if (res < 0) { 11323 return false; 11324 } 11325 11326 // Fix-up for forward-locked applications in ASEC containers. 11327 if (!isExternal(p)) { 11328 pStats.codeSize += pStats.externalCodeSize; 11329 pStats.externalCodeSize = 0L; 11330 } 11331 11332 return true; 11333 } 11334 11335 11336 @Override 11337 public void addPackageToPreferred(String packageName) { 11338 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 11339 } 11340 11341 @Override 11342 public void removePackageFromPreferred(String packageName) { 11343 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 11344 } 11345 11346 @Override 11347 public List<PackageInfo> getPreferredPackages(int flags) { 11348 return new ArrayList<PackageInfo>(); 11349 } 11350 11351 private int getUidTargetSdkVersionLockedLPr(int uid) { 11352 Object obj = mSettings.getUserIdLPr(uid); 11353 if (obj instanceof SharedUserSetting) { 11354 final SharedUserSetting sus = (SharedUserSetting) obj; 11355 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 11356 final Iterator<PackageSetting> it = sus.packages.iterator(); 11357 while (it.hasNext()) { 11358 final PackageSetting ps = it.next(); 11359 if (ps.pkg != null) { 11360 int v = ps.pkg.applicationInfo.targetSdkVersion; 11361 if (v < vers) vers = v; 11362 } 11363 } 11364 return vers; 11365 } else if (obj instanceof PackageSetting) { 11366 final PackageSetting ps = (PackageSetting) obj; 11367 if (ps.pkg != null) { 11368 return ps.pkg.applicationInfo.targetSdkVersion; 11369 } 11370 } 11371 return Build.VERSION_CODES.CUR_DEVELOPMENT; 11372 } 11373 11374 @Override 11375 public void addPreferredActivity(IntentFilter filter, int match, 11376 ComponentName[] set, ComponentName activity, int userId) { 11377 addPreferredActivityInternal(filter, match, set, activity, true, userId); 11378 } 11379 11380 private void addPreferredActivityInternal(IntentFilter filter, int match, 11381 ComponentName[] set, ComponentName activity, boolean always, int userId) { 11382 // writer 11383 int callingUid = Binder.getCallingUid(); 11384 enforceCrossUserPermission(callingUid, userId, true, "add preferred activity"); 11385 if (filter.countActions() == 0) { 11386 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11387 return; 11388 } 11389 synchronized (mPackages) { 11390 if (mContext.checkCallingOrSelfPermission( 11391 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11392 != PackageManager.PERMISSION_GRANTED) { 11393 if (getUidTargetSdkVersionLockedLPr(callingUid) 11394 < Build.VERSION_CODES.FROYO) { 11395 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 11396 + callingUid); 11397 return; 11398 } 11399 mContext.enforceCallingOrSelfPermission( 11400 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11401 } 11402 11403 Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :"); 11404 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11405 mSettings.editPreferredActivitiesLPw(userId).addFilter( 11406 new PreferredActivity(filter, match, set, activity, always)); 11407 mSettings.writePackageRestrictionsLPr(userId); 11408 } 11409 } 11410 11411 @Override 11412 public void replacePreferredActivity(IntentFilter filter, int match, 11413 ComponentName[] set, ComponentName activity) { 11414 if (filter.countActions() != 1) { 11415 throw new IllegalArgumentException( 11416 "replacePreferredActivity expects filter to have only 1 action."); 11417 } 11418 if (filter.countDataAuthorities() != 0 11419 || filter.countDataPaths() != 0 11420 || filter.countDataSchemes() > 1 11421 || filter.countDataTypes() != 0) { 11422 throw new IllegalArgumentException( 11423 "replacePreferredActivity expects filter to have no data authorities, " + 11424 "paths, or types; and at most one scheme."); 11425 } 11426 synchronized (mPackages) { 11427 if (mContext.checkCallingOrSelfPermission( 11428 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11429 != PackageManager.PERMISSION_GRANTED) { 11430 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11431 < Build.VERSION_CODES.FROYO) { 11432 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 11433 + Binder.getCallingUid()); 11434 return; 11435 } 11436 mContext.enforceCallingOrSelfPermission( 11437 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11438 } 11439 11440 final int callingUserId = UserHandle.getCallingUserId(); 11441 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId); 11442 if (pir != null) { 11443 Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0)); 11444 if (filter.countDataSchemes() == 1) { 11445 Uri.Builder builder = new Uri.Builder(); 11446 builder.scheme(filter.getDataScheme(0)); 11447 intent.setData(builder.build()); 11448 } 11449 List<PreferredActivity> matches = pir.queryIntent( 11450 intent, null, true, callingUserId); 11451 if (DEBUG_PREFERRED) { 11452 Slog.i(TAG, matches.size() + " preferred matches for " + intent); 11453 } 11454 for (int i = 0; i < matches.size(); i++) { 11455 PreferredActivity pa = matches.get(i); 11456 if (DEBUG_PREFERRED) { 11457 Slog.i(TAG, "Removing preferred activity " 11458 + pa.mPref.mComponent + ":"); 11459 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11460 } 11461 pir.removeFilter(pa); 11462 } 11463 } 11464 addPreferredActivityInternal(filter, match, set, activity, true, callingUserId); 11465 } 11466 } 11467 11468 @Override 11469 public void clearPackagePreferredActivities(String packageName) { 11470 final int uid = Binder.getCallingUid(); 11471 // writer 11472 synchronized (mPackages) { 11473 PackageParser.Package pkg = mPackages.get(packageName); 11474 if (pkg == null || pkg.applicationInfo.uid != uid) { 11475 if (mContext.checkCallingOrSelfPermission( 11476 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11477 != PackageManager.PERMISSION_GRANTED) { 11478 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11479 < Build.VERSION_CODES.FROYO) { 11480 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 11481 + Binder.getCallingUid()); 11482 return; 11483 } 11484 mContext.enforceCallingOrSelfPermission( 11485 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11486 } 11487 } 11488 11489 int user = UserHandle.getCallingUserId(); 11490 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 11491 mSettings.writePackageRestrictionsLPr(user); 11492 scheduleWriteSettingsLocked(); 11493 } 11494 } 11495 } 11496 11497 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 11498 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 11499 ArrayList<PreferredActivity> removed = null; 11500 boolean changed = false; 11501 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11502 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 11503 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11504 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 11505 continue; 11506 } 11507 Iterator<PreferredActivity> it = pir.filterIterator(); 11508 while (it.hasNext()) { 11509 PreferredActivity pa = it.next(); 11510 // Mark entry for removal only if it matches the package name 11511 // and the entry is of type "always". 11512 if (packageName == null || 11513 (pa.mPref.mComponent.getPackageName().equals(packageName) 11514 && pa.mPref.mAlways)) { 11515 if (removed == null) { 11516 removed = new ArrayList<PreferredActivity>(); 11517 } 11518 removed.add(pa); 11519 } 11520 } 11521 if (removed != null) { 11522 for (int j=0; j<removed.size(); j++) { 11523 PreferredActivity pa = removed.get(j); 11524 pir.removeFilter(pa); 11525 } 11526 changed = true; 11527 } 11528 } 11529 return changed; 11530 } 11531 11532 @Override 11533 public void resetPreferredActivities(int userId) { 11534 mContext.enforceCallingOrSelfPermission( 11535 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11536 // writer 11537 synchronized (mPackages) { 11538 int user = UserHandle.getCallingUserId(); 11539 clearPackagePreferredActivitiesLPw(null, user); 11540 mSettings.readDefaultPreferredAppsLPw(this, user); 11541 mSettings.writePackageRestrictionsLPr(user); 11542 scheduleWriteSettingsLocked(); 11543 } 11544 } 11545 11546 @Override 11547 public int getPreferredActivities(List<IntentFilter> outFilters, 11548 List<ComponentName> outActivities, String packageName) { 11549 11550 int num = 0; 11551 final int userId = UserHandle.getCallingUserId(); 11552 // reader 11553 synchronized (mPackages) { 11554 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11555 if (pir != null) { 11556 final Iterator<PreferredActivity> it = pir.filterIterator(); 11557 while (it.hasNext()) { 11558 final PreferredActivity pa = it.next(); 11559 if (packageName == null 11560 || (pa.mPref.mComponent.getPackageName().equals(packageName) 11561 && pa.mPref.mAlways)) { 11562 if (outFilters != null) { 11563 outFilters.add(new IntentFilter(pa)); 11564 } 11565 if (outActivities != null) { 11566 outActivities.add(pa.mPref.mComponent); 11567 } 11568 } 11569 } 11570 } 11571 } 11572 11573 return num; 11574 } 11575 11576 @Override 11577 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 11578 int userId) { 11579 int callingUid = Binder.getCallingUid(); 11580 if (callingUid != Process.SYSTEM_UID) { 11581 throw new SecurityException( 11582 "addPersistentPreferredActivity can only be run by the system"); 11583 } 11584 if (filter.countActions() == 0) { 11585 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11586 return; 11587 } 11588 synchronized (mPackages) { 11589 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 11590 " :"); 11591 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11592 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 11593 new PersistentPreferredActivity(filter, activity)); 11594 mSettings.writePackageRestrictionsLPr(userId); 11595 } 11596 } 11597 11598 @Override 11599 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 11600 int callingUid = Binder.getCallingUid(); 11601 if (callingUid != Process.SYSTEM_UID) { 11602 throw new SecurityException( 11603 "clearPackagePersistentPreferredActivities can only be run by the system"); 11604 } 11605 ArrayList<PersistentPreferredActivity> removed = null; 11606 boolean changed = false; 11607 synchronized (mPackages) { 11608 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 11609 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 11610 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 11611 .valueAt(i); 11612 if (userId != thisUserId) { 11613 continue; 11614 } 11615 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 11616 while (it.hasNext()) { 11617 PersistentPreferredActivity ppa = it.next(); 11618 // Mark entry for removal only if it matches the package name. 11619 if (ppa.mComponent.getPackageName().equals(packageName)) { 11620 if (removed == null) { 11621 removed = new ArrayList<PersistentPreferredActivity>(); 11622 } 11623 removed.add(ppa); 11624 } 11625 } 11626 if (removed != null) { 11627 for (int j=0; j<removed.size(); j++) { 11628 PersistentPreferredActivity ppa = removed.get(j); 11629 ppir.removeFilter(ppa); 11630 } 11631 changed = true; 11632 } 11633 } 11634 11635 if (changed) { 11636 mSettings.writePackageRestrictionsLPr(userId); 11637 } 11638 } 11639 } 11640 11641 @Override 11642 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 11643 int ownerUserId, int sourceUserId, int targetUserId, int flags) { 11644 mContext.enforceCallingOrSelfPermission( 11645 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11646 int callingUid = Binder.getCallingUid(); 11647 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11648 if (intentFilter.countActions() == 0) { 11649 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 11650 return; 11651 } 11652 synchronized (mPackages) { 11653 CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter, 11654 ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags); 11655 mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter); 11656 mSettings.writePackageRestrictionsLPr(sourceUserId); 11657 } 11658 } 11659 11660 @Override 11661 public void addCrossProfileIntentsForPackage(String packageName, 11662 int sourceUserId, int targetUserId) { 11663 mContext.enforceCallingOrSelfPermission( 11664 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11665 mSettings.addCrossProfilePackage(packageName, sourceUserId, targetUserId); 11666 mSettings.writePackageRestrictionsLPr(sourceUserId); 11667 } 11668 11669 public void removeCrossProfileIntentsForPackage(String packageName, 11670 int sourceUserId, int targetUserId) { 11671 mContext.enforceCallingOrSelfPermission( 11672 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11673 mSettings.removeCrossProfilePackage(packageName, sourceUserId, targetUserId); 11674 mSettings.writePackageRestrictionsLPr(sourceUserId); 11675 } 11676 11677 @Override 11678 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage, 11679 int ownerUserId) { 11680 mContext.enforceCallingOrSelfPermission( 11681 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11682 int callingUid = Binder.getCallingUid(); 11683 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11684 int callingUserId = UserHandle.getUserId(callingUid); 11685 synchronized (mPackages) { 11686 CrossProfileIntentResolver resolver = 11687 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11688 HashSet<CrossProfileIntentFilter> set = 11689 new HashSet<CrossProfileIntentFilter>(resolver.filterSet()); 11690 for (CrossProfileIntentFilter filter : set) { 11691 if (filter.getOwnerPackage().equals(ownerPackage) 11692 && filter.getOwnerUserId() == callingUserId) { 11693 resolver.removeFilter(filter); 11694 } 11695 } 11696 mSettings.writePackageRestrictionsLPr(sourceUserId); 11697 } 11698 } 11699 11700 // Enforcing that callingUid is owning pkg on userId 11701 private void enforceOwnerRights(String pkg, int userId, int callingUid) { 11702 // The system owns everything. 11703 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 11704 return; 11705 } 11706 int callingUserId = UserHandle.getUserId(callingUid); 11707 if (callingUserId != userId) { 11708 throw new SecurityException("calling uid " + callingUid 11709 + " pretends to own " + pkg + " on user " + userId + " but belongs to user " 11710 + callingUserId); 11711 } 11712 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 11713 if (pi == null) { 11714 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 11715 + callingUserId); 11716 } 11717 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 11718 throw new SecurityException("Calling uid " + callingUid 11719 + " does not own package " + pkg); 11720 } 11721 } 11722 11723 @Override 11724 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 11725 Intent intent = new Intent(Intent.ACTION_MAIN); 11726 intent.addCategory(Intent.CATEGORY_HOME); 11727 11728 final int callingUserId = UserHandle.getCallingUserId(); 11729 List<ResolveInfo> list = queryIntentActivities(intent, null, 11730 PackageManager.GET_META_DATA, callingUserId); 11731 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 11732 true, false, false, callingUserId); 11733 11734 allHomeCandidates.clear(); 11735 if (list != null) { 11736 for (ResolveInfo ri : list) { 11737 allHomeCandidates.add(ri); 11738 } 11739 } 11740 return (preferred == null || preferred.activityInfo == null) 11741 ? null 11742 : new ComponentName(preferred.activityInfo.packageName, 11743 preferred.activityInfo.name); 11744 } 11745 11746 /** 11747 * Check if calling UID is the current home app. This handles both the case 11748 * where the user has selected a specific home app, and where there is only 11749 * one home app. 11750 */ 11751 public boolean checkCallerIsHomeApp() { 11752 final Intent intent = new Intent(Intent.ACTION_MAIN); 11753 intent.addCategory(Intent.CATEGORY_HOME); 11754 11755 final int callingUid = Binder.getCallingUid(); 11756 final int callingUserId = UserHandle.getCallingUserId(); 11757 final List<ResolveInfo> allHomes = queryIntentActivities(intent, null, 0, callingUserId); 11758 final ResolveInfo preferredHome = findPreferredActivity(intent, null, 0, allHomes, 0, true, 11759 false, false, callingUserId); 11760 11761 if (preferredHome != null) { 11762 if (callingUid == preferredHome.activityInfo.applicationInfo.uid) { 11763 return true; 11764 } 11765 } else { 11766 for (ResolveInfo info : allHomes) { 11767 if (callingUid == info.activityInfo.applicationInfo.uid) { 11768 return true; 11769 } 11770 } 11771 } 11772 11773 return false; 11774 } 11775 11776 /** 11777 * Enforce that calling UID is the current home app. This handles both the 11778 * case where the user has selected a specific home app, and where there is 11779 * only one home app. 11780 */ 11781 public void enforceCallerIsHomeApp() { 11782 if (!checkCallerIsHomeApp()) { 11783 throw new SecurityException("Caller is not currently selected home app"); 11784 } 11785 } 11786 11787 @Override 11788 public void setApplicationEnabledSetting(String appPackageName, 11789 int newState, int flags, int userId, String callingPackage) { 11790 if (!sUserManager.exists(userId)) return; 11791 if (callingPackage == null) { 11792 callingPackage = Integer.toString(Binder.getCallingUid()); 11793 } 11794 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 11795 } 11796 11797 @Override 11798 public void setComponentEnabledSetting(ComponentName componentName, 11799 int newState, int flags, int userId) { 11800 if (!sUserManager.exists(userId)) return; 11801 setEnabledSetting(componentName.getPackageName(), 11802 componentName.getClassName(), newState, flags, userId, null); 11803 } 11804 11805 private void setEnabledSetting(final String packageName, String className, int newState, 11806 final int flags, int userId, String callingPackage) { 11807 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 11808 || newState == COMPONENT_ENABLED_STATE_ENABLED 11809 || newState == COMPONENT_ENABLED_STATE_DISABLED 11810 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 11811 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 11812 throw new IllegalArgumentException("Invalid new component state: " 11813 + newState); 11814 } 11815 PackageSetting pkgSetting; 11816 final int uid = Binder.getCallingUid(); 11817 final int permission = mContext.checkCallingOrSelfPermission( 11818 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11819 enforceCrossUserPermission(uid, userId, false, "set enabled"); 11820 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11821 boolean sendNow = false; 11822 boolean isApp = (className == null); 11823 String componentName = isApp ? packageName : className; 11824 int packageUid = -1; 11825 ArrayList<String> components; 11826 11827 // writer 11828 synchronized (mPackages) { 11829 pkgSetting = mSettings.mPackages.get(packageName); 11830 if (pkgSetting == null) { 11831 if (className == null) { 11832 throw new IllegalArgumentException( 11833 "Unknown package: " + packageName); 11834 } 11835 throw new IllegalArgumentException( 11836 "Unknown component: " + packageName 11837 + "/" + className); 11838 } 11839 // Allow root and verify that userId is not being specified by a different user 11840 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 11841 throw new SecurityException( 11842 "Permission Denial: attempt to change component state from pid=" 11843 + Binder.getCallingPid() 11844 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 11845 } 11846 if (className == null) { 11847 // We're dealing with an application/package level state change 11848 if (pkgSetting.getEnabled(userId) == newState) { 11849 // Nothing to do 11850 return; 11851 } 11852 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 11853 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 11854 // Don't care about who enables an app. 11855 callingPackage = null; 11856 } 11857 pkgSetting.setEnabled(newState, userId, callingPackage); 11858 // pkgSetting.pkg.mSetEnabled = newState; 11859 } else { 11860 // We're dealing with a component level state change 11861 // First, verify that this is a valid class name. 11862 PackageParser.Package pkg = pkgSetting.pkg; 11863 if (pkg == null || !pkg.hasComponentClassName(className)) { 11864 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 11865 throw new IllegalArgumentException("Component class " + className 11866 + " does not exist in " + packageName); 11867 } else { 11868 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 11869 + className + " does not exist in " + packageName); 11870 } 11871 } 11872 switch (newState) { 11873 case COMPONENT_ENABLED_STATE_ENABLED: 11874 if (!pkgSetting.enableComponentLPw(className, userId)) { 11875 return; 11876 } 11877 break; 11878 case COMPONENT_ENABLED_STATE_DISABLED: 11879 if (!pkgSetting.disableComponentLPw(className, userId)) { 11880 return; 11881 } 11882 break; 11883 case COMPONENT_ENABLED_STATE_DEFAULT: 11884 if (!pkgSetting.restoreComponentLPw(className, userId)) { 11885 return; 11886 } 11887 break; 11888 default: 11889 Slog.e(TAG, "Invalid new component state: " + newState); 11890 return; 11891 } 11892 } 11893 mSettings.writePackageRestrictionsLPr(userId); 11894 components = mPendingBroadcasts.get(userId, packageName); 11895 final boolean newPackage = components == null; 11896 if (newPackage) { 11897 components = new ArrayList<String>(); 11898 } 11899 if (!components.contains(componentName)) { 11900 components.add(componentName); 11901 } 11902 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 11903 sendNow = true; 11904 // Purge entry from pending broadcast list if another one exists already 11905 // since we are sending one right away. 11906 mPendingBroadcasts.remove(userId, packageName); 11907 } else { 11908 if (newPackage) { 11909 mPendingBroadcasts.put(userId, packageName, components); 11910 } 11911 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 11912 // Schedule a message 11913 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 11914 } 11915 } 11916 } 11917 11918 long callingId = Binder.clearCallingIdentity(); 11919 try { 11920 if (sendNow) { 11921 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 11922 sendPackageChangedBroadcast(packageName, 11923 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 11924 } 11925 } finally { 11926 Binder.restoreCallingIdentity(callingId); 11927 } 11928 } 11929 11930 private void sendPackageChangedBroadcast(String packageName, 11931 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 11932 if (DEBUG_INSTALL) 11933 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 11934 + componentNames); 11935 Bundle extras = new Bundle(4); 11936 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 11937 String nameList[] = new String[componentNames.size()]; 11938 componentNames.toArray(nameList); 11939 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 11940 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 11941 extras.putInt(Intent.EXTRA_UID, packageUid); 11942 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 11943 new int[] {UserHandle.getUserId(packageUid)}); 11944 } 11945 11946 @Override 11947 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 11948 if (!sUserManager.exists(userId)) return; 11949 final int uid = Binder.getCallingUid(); 11950 final int permission = mContext.checkCallingOrSelfPermission( 11951 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11952 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11953 enforceCrossUserPermission(uid, userId, true, "stop package"); 11954 // writer 11955 synchronized (mPackages) { 11956 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 11957 uid, userId)) { 11958 scheduleWritePackageRestrictionsLocked(userId); 11959 } 11960 } 11961 } 11962 11963 @Override 11964 public String getInstallerPackageName(String packageName) { 11965 // reader 11966 synchronized (mPackages) { 11967 return mSettings.getInstallerPackageNameLPr(packageName); 11968 } 11969 } 11970 11971 @Override 11972 public int getApplicationEnabledSetting(String packageName, int userId) { 11973 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11974 int uid = Binder.getCallingUid(); 11975 enforceCrossUserPermission(uid, userId, false, "get enabled"); 11976 // reader 11977 synchronized (mPackages) { 11978 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 11979 } 11980 } 11981 11982 @Override 11983 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 11984 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11985 int uid = Binder.getCallingUid(); 11986 enforceCrossUserPermission(uid, userId, false, "get component enabled"); 11987 // reader 11988 synchronized (mPackages) { 11989 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 11990 } 11991 } 11992 11993 @Override 11994 public void enterSafeMode() { 11995 enforceSystemOrRoot("Only the system can request entering safe mode"); 11996 11997 if (!mSystemReady) { 11998 mSafeMode = true; 11999 } 12000 } 12001 12002 @Override 12003 public void systemReady() { 12004 mSystemReady = true; 12005 12006 // Read the compatibilty setting when the system is ready. 12007 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 12008 mContext.getContentResolver(), 12009 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 12010 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 12011 if (DEBUG_SETTINGS) { 12012 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 12013 } 12014 12015 synchronized (mPackages) { 12016 // Verify that all of the preferred activity components actually 12017 // exist. It is possible for applications to be updated and at 12018 // that point remove a previously declared activity component that 12019 // had been set as a preferred activity. We try to clean this up 12020 // the next time we encounter that preferred activity, but it is 12021 // possible for the user flow to never be able to return to that 12022 // situation so here we do a sanity check to make sure we haven't 12023 // left any junk around. 12024 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 12025 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12026 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12027 removed.clear(); 12028 for (PreferredActivity pa : pir.filterSet()) { 12029 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 12030 removed.add(pa); 12031 } 12032 } 12033 if (removed.size() > 0) { 12034 for (int r=0; r<removed.size(); r++) { 12035 PreferredActivity pa = removed.get(r); 12036 Slog.w(TAG, "Removing dangling preferred activity: " 12037 + pa.mPref.mComponent); 12038 pir.removeFilter(pa); 12039 } 12040 mSettings.writePackageRestrictionsLPr( 12041 mSettings.mPreferredActivities.keyAt(i)); 12042 } 12043 } 12044 } 12045 sUserManager.systemReady(); 12046 } 12047 12048 @Override 12049 public boolean isSafeMode() { 12050 return mSafeMode; 12051 } 12052 12053 @Override 12054 public boolean hasSystemUidErrors() { 12055 return mHasSystemUidErrors; 12056 } 12057 12058 static String arrayToString(int[] array) { 12059 StringBuffer buf = new StringBuffer(128); 12060 buf.append('['); 12061 if (array != null) { 12062 for (int i=0; i<array.length; i++) { 12063 if (i > 0) buf.append(", "); 12064 buf.append(array[i]); 12065 } 12066 } 12067 buf.append(']'); 12068 return buf.toString(); 12069 } 12070 12071 static class DumpState { 12072 public static final int DUMP_LIBS = 1 << 0; 12073 public static final int DUMP_FEATURES = 1 << 1; 12074 public static final int DUMP_RESOLVERS = 1 << 2; 12075 public static final int DUMP_PERMISSIONS = 1 << 3; 12076 public static final int DUMP_PACKAGES = 1 << 4; 12077 public static final int DUMP_SHARED_USERS = 1 << 5; 12078 public static final int DUMP_MESSAGES = 1 << 6; 12079 public static final int DUMP_PROVIDERS = 1 << 7; 12080 public static final int DUMP_VERIFIERS = 1 << 8; 12081 public static final int DUMP_PREFERRED = 1 << 9; 12082 public static final int DUMP_PREFERRED_XML = 1 << 10; 12083 public static final int DUMP_KEYSETS = 1 << 11; 12084 public static final int DUMP_VERSION = 1 << 12; 12085 public static final int DUMP_INSTALLS = 1 << 13; 12086 12087 public static final int OPTION_SHOW_FILTERS = 1 << 0; 12088 12089 private int mTypes; 12090 12091 private int mOptions; 12092 12093 private boolean mTitlePrinted; 12094 12095 private SharedUserSetting mSharedUser; 12096 12097 public boolean isDumping(int type) { 12098 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 12099 return true; 12100 } 12101 12102 return (mTypes & type) != 0; 12103 } 12104 12105 public void setDump(int type) { 12106 mTypes |= type; 12107 } 12108 12109 public boolean isOptionEnabled(int option) { 12110 return (mOptions & option) != 0; 12111 } 12112 12113 public void setOptionEnabled(int option) { 12114 mOptions |= option; 12115 } 12116 12117 public boolean onTitlePrinted() { 12118 final boolean printed = mTitlePrinted; 12119 mTitlePrinted = true; 12120 return printed; 12121 } 12122 12123 public boolean getTitlePrinted() { 12124 return mTitlePrinted; 12125 } 12126 12127 public void setTitlePrinted(boolean enabled) { 12128 mTitlePrinted = enabled; 12129 } 12130 12131 public SharedUserSetting getSharedUser() { 12132 return mSharedUser; 12133 } 12134 12135 public void setSharedUser(SharedUserSetting user) { 12136 mSharedUser = user; 12137 } 12138 } 12139 12140 @Override 12141 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 12142 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 12143 != PackageManager.PERMISSION_GRANTED) { 12144 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 12145 + Binder.getCallingPid() 12146 + ", uid=" + Binder.getCallingUid() 12147 + " without permission " 12148 + android.Manifest.permission.DUMP); 12149 return; 12150 } 12151 12152 DumpState dumpState = new DumpState(); 12153 boolean fullPreferred = false; 12154 boolean checkin = false; 12155 12156 String packageName = null; 12157 12158 int opti = 0; 12159 while (opti < args.length) { 12160 String opt = args[opti]; 12161 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 12162 break; 12163 } 12164 opti++; 12165 if ("-a".equals(opt)) { 12166 // Right now we only know how to print all. 12167 } else if ("-h".equals(opt)) { 12168 pw.println("Package manager dump options:"); 12169 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 12170 pw.println(" --checkin: dump for a checkin"); 12171 pw.println(" -f: print details of intent filters"); 12172 pw.println(" -h: print this help"); 12173 pw.println(" cmd may be one of:"); 12174 pw.println(" l[ibraries]: list known shared libraries"); 12175 pw.println(" f[ibraries]: list device features"); 12176 pw.println(" k[eysets]: print known keysets"); 12177 pw.println(" r[esolvers]: dump intent resolvers"); 12178 pw.println(" perm[issions]: dump permissions"); 12179 pw.println(" pref[erred]: print preferred package settings"); 12180 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 12181 pw.println(" prov[iders]: dump content providers"); 12182 pw.println(" p[ackages]: dump installed packages"); 12183 pw.println(" s[hared-users]: dump shared user IDs"); 12184 pw.println(" m[essages]: print collected runtime messages"); 12185 pw.println(" v[erifiers]: print package verifier info"); 12186 pw.println(" version: print database version info"); 12187 pw.println(" write: write current settings now"); 12188 pw.println(" <package.name>: info about given package"); 12189 pw.println(" installs: details about install sessions"); 12190 return; 12191 } else if ("--checkin".equals(opt)) { 12192 checkin = true; 12193 } else if ("-f".equals(opt)) { 12194 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12195 } else { 12196 pw.println("Unknown argument: " + opt + "; use -h for help"); 12197 } 12198 } 12199 12200 // Is the caller requesting to dump a particular piece of data? 12201 if (opti < args.length) { 12202 String cmd = args[opti]; 12203 opti++; 12204 // Is this a package name? 12205 if ("android".equals(cmd) || cmd.contains(".")) { 12206 packageName = cmd; 12207 // When dumping a single package, we always dump all of its 12208 // filter information since the amount of data will be reasonable. 12209 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12210 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 12211 dumpState.setDump(DumpState.DUMP_LIBS); 12212 } else if ("f".equals(cmd) || "features".equals(cmd)) { 12213 dumpState.setDump(DumpState.DUMP_FEATURES); 12214 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 12215 dumpState.setDump(DumpState.DUMP_RESOLVERS); 12216 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 12217 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 12218 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 12219 dumpState.setDump(DumpState.DUMP_PREFERRED); 12220 } else if ("preferred-xml".equals(cmd)) { 12221 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 12222 if (opti < args.length && "--full".equals(args[opti])) { 12223 fullPreferred = true; 12224 opti++; 12225 } 12226 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 12227 dumpState.setDump(DumpState.DUMP_PACKAGES); 12228 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 12229 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 12230 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 12231 dumpState.setDump(DumpState.DUMP_PROVIDERS); 12232 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 12233 dumpState.setDump(DumpState.DUMP_MESSAGES); 12234 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 12235 dumpState.setDump(DumpState.DUMP_VERIFIERS); 12236 } else if ("version".equals(cmd)) { 12237 dumpState.setDump(DumpState.DUMP_VERSION); 12238 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 12239 dumpState.setDump(DumpState.DUMP_KEYSETS); 12240 } else if ("write".equals(cmd)) { 12241 synchronized (mPackages) { 12242 mSettings.writeLPr(); 12243 pw.println("Settings written."); 12244 return; 12245 } 12246 } else if ("installs".equals(cmd)) { 12247 dumpState.setDump(DumpState.DUMP_INSTALLS); 12248 } 12249 } 12250 12251 if (checkin) { 12252 pw.println("vers,1"); 12253 } 12254 12255 // reader 12256 synchronized (mPackages) { 12257 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 12258 if (!checkin) { 12259 if (dumpState.onTitlePrinted()) 12260 pw.println(); 12261 pw.println("Database versions:"); 12262 pw.print(" SDK Version:"); 12263 pw.print(" internal="); 12264 pw.print(mSettings.mInternalSdkPlatform); 12265 pw.print(" external="); 12266 pw.println(mSettings.mExternalSdkPlatform); 12267 pw.print(" DB Version:"); 12268 pw.print(" internal="); 12269 pw.print(mSettings.mInternalDatabaseVersion); 12270 pw.print(" external="); 12271 pw.println(mSettings.mExternalDatabaseVersion); 12272 } 12273 } 12274 12275 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 12276 if (!checkin) { 12277 if (dumpState.onTitlePrinted()) 12278 pw.println(); 12279 pw.println("Verifiers:"); 12280 pw.print(" Required: "); 12281 pw.print(mRequiredVerifierPackage); 12282 pw.print(" (uid="); 12283 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 12284 pw.println(")"); 12285 } else if (mRequiredVerifierPackage != null) { 12286 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 12287 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 12288 } 12289 } 12290 12291 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 12292 boolean printedHeader = false; 12293 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 12294 while (it.hasNext()) { 12295 String name = it.next(); 12296 SharedLibraryEntry ent = mSharedLibraries.get(name); 12297 if (!checkin) { 12298 if (!printedHeader) { 12299 if (dumpState.onTitlePrinted()) 12300 pw.println(); 12301 pw.println("Libraries:"); 12302 printedHeader = true; 12303 } 12304 pw.print(" "); 12305 } else { 12306 pw.print("lib,"); 12307 } 12308 pw.print(name); 12309 if (!checkin) { 12310 pw.print(" -> "); 12311 } 12312 if (ent.path != null) { 12313 if (!checkin) { 12314 pw.print("(jar) "); 12315 pw.print(ent.path); 12316 } else { 12317 pw.print(",jar,"); 12318 pw.print(ent.path); 12319 } 12320 } else { 12321 if (!checkin) { 12322 pw.print("(apk) "); 12323 pw.print(ent.apk); 12324 } else { 12325 pw.print(",apk,"); 12326 pw.print(ent.apk); 12327 } 12328 } 12329 pw.println(); 12330 } 12331 } 12332 12333 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 12334 if (dumpState.onTitlePrinted()) 12335 pw.println(); 12336 if (!checkin) { 12337 pw.println("Features:"); 12338 } 12339 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 12340 while (it.hasNext()) { 12341 String name = it.next(); 12342 if (!checkin) { 12343 pw.print(" "); 12344 } else { 12345 pw.print("feat,"); 12346 } 12347 pw.println(name); 12348 } 12349 } 12350 12351 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 12352 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 12353 : "Activity Resolver Table:", " ", packageName, 12354 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12355 dumpState.setTitlePrinted(true); 12356 } 12357 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 12358 : "Receiver Resolver Table:", " ", packageName, 12359 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12360 dumpState.setTitlePrinted(true); 12361 } 12362 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 12363 : "Service Resolver Table:", " ", packageName, 12364 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12365 dumpState.setTitlePrinted(true); 12366 } 12367 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 12368 : "Provider Resolver Table:", " ", packageName, 12369 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12370 dumpState.setTitlePrinted(true); 12371 } 12372 } 12373 12374 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 12375 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12376 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12377 int user = mSettings.mPreferredActivities.keyAt(i); 12378 if (pir.dump(pw, 12379 dumpState.getTitlePrinted() 12380 ? "\nPreferred Activities User " + user + ":" 12381 : "Preferred Activities User " + user + ":", " ", 12382 packageName, true)) { 12383 dumpState.setTitlePrinted(true); 12384 } 12385 } 12386 } 12387 12388 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 12389 pw.flush(); 12390 FileOutputStream fout = new FileOutputStream(fd); 12391 BufferedOutputStream str = new BufferedOutputStream(fout); 12392 XmlSerializer serializer = new FastXmlSerializer(); 12393 try { 12394 serializer.setOutput(str, "utf-8"); 12395 serializer.startDocument(null, true); 12396 serializer.setFeature( 12397 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 12398 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 12399 serializer.endDocument(); 12400 serializer.flush(); 12401 } catch (IllegalArgumentException e) { 12402 pw.println("Failed writing: " + e); 12403 } catch (IllegalStateException e) { 12404 pw.println("Failed writing: " + e); 12405 } catch (IOException e) { 12406 pw.println("Failed writing: " + e); 12407 } 12408 } 12409 12410 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 12411 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 12412 if (packageName == null) { 12413 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 12414 if (iperm == 0) { 12415 if (dumpState.onTitlePrinted()) 12416 pw.println(); 12417 pw.println("AppOp Permissions:"); 12418 } 12419 pw.print(" AppOp Permission "); 12420 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 12421 pw.println(":"); 12422 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 12423 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 12424 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 12425 } 12426 } 12427 } 12428 } 12429 12430 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 12431 boolean printedSomething = false; 12432 for (PackageParser.Provider p : mProviders.mProviders.values()) { 12433 if (packageName != null && !packageName.equals(p.info.packageName)) { 12434 continue; 12435 } 12436 if (!printedSomething) { 12437 if (dumpState.onTitlePrinted()) 12438 pw.println(); 12439 pw.println("Registered ContentProviders:"); 12440 printedSomething = true; 12441 } 12442 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 12443 pw.print(" "); pw.println(p.toString()); 12444 } 12445 printedSomething = false; 12446 for (Map.Entry<String, PackageParser.Provider> entry : 12447 mProvidersByAuthority.entrySet()) { 12448 PackageParser.Provider p = entry.getValue(); 12449 if (packageName != null && !packageName.equals(p.info.packageName)) { 12450 continue; 12451 } 12452 if (!printedSomething) { 12453 if (dumpState.onTitlePrinted()) 12454 pw.println(); 12455 pw.println("ContentProvider Authorities:"); 12456 printedSomething = true; 12457 } 12458 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 12459 pw.print(" "); pw.println(p.toString()); 12460 if (p.info != null && p.info.applicationInfo != null) { 12461 final String appInfo = p.info.applicationInfo.toString(); 12462 pw.print(" applicationInfo="); pw.println(appInfo); 12463 } 12464 } 12465 } 12466 12467 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 12468 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 12469 } 12470 12471 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 12472 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 12473 } 12474 12475 if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 12476 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState); 12477 } 12478 12479 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS)) { 12480 if (dumpState.onTitlePrinted()) pw.println(); 12481 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 12482 } 12483 12484 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 12485 if (dumpState.onTitlePrinted()) pw.println(); 12486 mSettings.dumpReadMessagesLPr(pw, dumpState); 12487 12488 pw.println(); 12489 pw.println("Package warning messages:"); 12490 final File fname = getSettingsProblemFile(); 12491 FileInputStream in = null; 12492 try { 12493 in = new FileInputStream(fname); 12494 final int avail = in.available(); 12495 final byte[] data = new byte[avail]; 12496 in.read(data); 12497 pw.print(new String(data)); 12498 } catch (FileNotFoundException e) { 12499 } catch (IOException e) { 12500 } finally { 12501 if (in != null) { 12502 try { 12503 in.close(); 12504 } catch (IOException e) { 12505 } 12506 } 12507 } 12508 } 12509 } 12510 } 12511 12512 // ------- apps on sdcard specific code ------- 12513 static final boolean DEBUG_SD_INSTALL = false; 12514 12515 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 12516 12517 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 12518 12519 private boolean mMediaMounted = false; 12520 12521 private String getEncryptKey() { 12522 try { 12523 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 12524 SD_ENCRYPTION_KEYSTORE_NAME); 12525 if (sdEncKey == null) { 12526 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 12527 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 12528 if (sdEncKey == null) { 12529 Slog.e(TAG, "Failed to create encryption keys"); 12530 return null; 12531 } 12532 } 12533 return sdEncKey; 12534 } catch (NoSuchAlgorithmException nsae) { 12535 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 12536 return null; 12537 } catch (IOException ioe) { 12538 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 12539 return null; 12540 } 12541 12542 } 12543 12544 /* package */static String getTempContainerId() { 12545 int tmpIdx = 1; 12546 String list[] = PackageHelper.getSecureContainerList(); 12547 if (list != null) { 12548 for (final String name : list) { 12549 // Ignore null and non-temporary container entries 12550 if (name == null || !name.startsWith(mTempContainerPrefix)) { 12551 continue; 12552 } 12553 12554 String subStr = name.substring(mTempContainerPrefix.length()); 12555 try { 12556 int cid = Integer.parseInt(subStr); 12557 if (cid >= tmpIdx) { 12558 tmpIdx = cid + 1; 12559 } 12560 } catch (NumberFormatException e) { 12561 } 12562 } 12563 } 12564 return mTempContainerPrefix + tmpIdx; 12565 } 12566 12567 /* 12568 * Update media status on PackageManager. 12569 */ 12570 @Override 12571 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 12572 int callingUid = Binder.getCallingUid(); 12573 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 12574 throw new SecurityException("Media status can only be updated by the system"); 12575 } 12576 // reader; this apparently protects mMediaMounted, but should probably 12577 // be a different lock in that case. 12578 synchronized (mPackages) { 12579 Log.i(TAG, "Updating external media status from " 12580 + (mMediaMounted ? "mounted" : "unmounted") + " to " 12581 + (mediaStatus ? "mounted" : "unmounted")); 12582 if (DEBUG_SD_INSTALL) 12583 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 12584 + ", mMediaMounted=" + mMediaMounted); 12585 if (mediaStatus == mMediaMounted) { 12586 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 12587 : 0, -1); 12588 mHandler.sendMessage(msg); 12589 return; 12590 } 12591 mMediaMounted = mediaStatus; 12592 } 12593 // Queue up an async operation since the package installation may take a 12594 // little while. 12595 mHandler.post(new Runnable() { 12596 public void run() { 12597 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 12598 } 12599 }); 12600 } 12601 12602 /** 12603 * Called by MountService when the initial ASECs to scan are available. 12604 * Should block until all the ASEC containers are finished being scanned. 12605 */ 12606 public void scanAvailableAsecs() { 12607 updateExternalMediaStatusInner(true, false, false); 12608 if (mShouldRestoreconData) { 12609 SELinuxMMAC.setRestoreconDone(); 12610 mShouldRestoreconData = false; 12611 } 12612 } 12613 12614 /* 12615 * Collect information of applications on external media, map them against 12616 * existing containers and update information based on current mount status. 12617 * Please note that we always have to report status if reportStatus has been 12618 * set to true especially when unloading packages. 12619 */ 12620 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 12621 boolean externalStorage) { 12622 // Collection of uids 12623 int uidArr[] = null; 12624 // Collection of stale containers 12625 HashSet<String> removeCids = new HashSet<String>(); 12626 // Collection of packages on external media with valid containers. 12627 HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>(); 12628 // Get list of secure containers. 12629 final String list[] = PackageHelper.getSecureContainerList(); 12630 if (list == null || list.length == 0) { 12631 Log.i(TAG, "No secure containers on sdcard"); 12632 } else { 12633 // Process list of secure containers and categorize them 12634 // as active or stale based on their package internal state. 12635 int uidList[] = new int[list.length]; 12636 int num = 0; 12637 // reader 12638 synchronized (mPackages) { 12639 for (String cid : list) { 12640 if (DEBUG_SD_INSTALL) 12641 Log.i(TAG, "Processing container " + cid); 12642 String pkgName = getAsecPackageName(cid); 12643 if (pkgName == null) { 12644 if (DEBUG_SD_INSTALL) 12645 Log.i(TAG, "Container : " + cid + " stale"); 12646 removeCids.add(cid); 12647 continue; 12648 } 12649 if (DEBUG_SD_INSTALL) 12650 Log.i(TAG, "Looking for pkg : " + pkgName); 12651 12652 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12653 if (ps == null) { 12654 Log.i(TAG, "Deleting container with no matching settings " + cid); 12655 removeCids.add(cid); 12656 continue; 12657 } 12658 12659 /* 12660 * Skip packages that are not external if we're unmounting 12661 * external storage. 12662 */ 12663 if (externalStorage && !isMounted && !isExternal(ps)) { 12664 continue; 12665 } 12666 12667 final AsecInstallArgs args = new AsecInstallArgs(cid, 12668 getAppDexInstructionSets(ps), isForwardLocked(ps), isMultiArch(ps)); 12669 // The package status is changed only if the code path 12670 // matches between settings and the container id. 12671 if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) { 12672 if (DEBUG_SD_INSTALL) { 12673 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 12674 + " at code path: " + ps.codePathString); 12675 } 12676 12677 // We do have a valid package installed on sdcard 12678 processCids.put(args, ps.codePathString); 12679 final int uid = ps.appId; 12680 if (uid != -1) { 12681 uidList[num++] = uid; 12682 } 12683 } else { 12684 Log.i(TAG, "Deleting stale container for " + cid); 12685 removeCids.add(cid); 12686 } 12687 } 12688 } 12689 12690 if (num > 0) { 12691 // Sort uid list 12692 Arrays.sort(uidList, 0, num); 12693 // Throw away duplicates 12694 uidArr = new int[num]; 12695 uidArr[0] = uidList[0]; 12696 int di = 0; 12697 for (int i = 1; i < num; i++) { 12698 if (uidList[i - 1] != uidList[i]) { 12699 uidArr[di++] = uidList[i]; 12700 } 12701 } 12702 } 12703 } 12704 // Process packages with valid entries. 12705 if (isMounted) { 12706 if (DEBUG_SD_INSTALL) 12707 Log.i(TAG, "Loading packages"); 12708 loadMediaPackages(processCids, uidArr, removeCids); 12709 startCleaningPackages(); 12710 } else { 12711 if (DEBUG_SD_INSTALL) 12712 Log.i(TAG, "Unloading packages"); 12713 unloadMediaPackages(processCids, uidArr, reportStatus); 12714 } 12715 } 12716 12717 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 12718 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 12719 int size = pkgList.size(); 12720 if (size > 0) { 12721 // Send broadcasts here 12722 Bundle extras = new Bundle(); 12723 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 12724 .toArray(new String[size])); 12725 if (uidArr != null) { 12726 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 12727 } 12728 if (replacing) { 12729 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 12730 } 12731 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 12732 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 12733 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 12734 } 12735 } 12736 12737 /* 12738 * Look at potentially valid container ids from processCids If package 12739 * information doesn't match the one on record or package scanning fails, 12740 * the cid is added to list of removeCids. We currently don't delete stale 12741 * containers. 12742 */ 12743 private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 12744 HashSet<String> removeCids) { 12745 ArrayList<String> pkgList = new ArrayList<String>(); 12746 Set<AsecInstallArgs> keys = processCids.keySet(); 12747 boolean doGc = false; 12748 for (AsecInstallArgs args : keys) { 12749 String codePath = processCids.get(args); 12750 if (DEBUG_SD_INSTALL) 12751 Log.i(TAG, "Loading container : " + args.cid); 12752 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12753 try { 12754 // Make sure there are no container errors first. 12755 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 12756 Slog.e(TAG, "Failed to mount cid : " + args.cid 12757 + " when installing from sdcard"); 12758 continue; 12759 } 12760 // Check code path here. 12761 if (codePath == null || !codePath.equals(args.getCodePath())) { 12762 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 12763 + " does not match one in settings " + codePath); 12764 continue; 12765 } 12766 // Parse package 12767 int parseFlags = mDefParseFlags; 12768 if (args.isExternal()) { 12769 parseFlags |= PackageParser.PARSE_ON_SDCARD; 12770 } 12771 if (args.isFwdLocked()) { 12772 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 12773 } 12774 12775 doGc = true; 12776 synchronized (mInstallLock) { 12777 PackageParser.Package pkg = null; 12778 try { 12779 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null, null); 12780 } catch (PackageManagerException e) { 12781 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 12782 } 12783 // Scan the package 12784 if (pkg != null) { 12785 /* 12786 * TODO why is the lock being held? doPostInstall is 12787 * called in other places without the lock. This needs 12788 * to be straightened out. 12789 */ 12790 // writer 12791 synchronized (mPackages) { 12792 retCode = PackageManager.INSTALL_SUCCEEDED; 12793 pkgList.add(pkg.packageName); 12794 // Post process args 12795 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 12796 pkg.applicationInfo.uid); 12797 } 12798 } else { 12799 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 12800 } 12801 } 12802 12803 } finally { 12804 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 12805 // Don't destroy container here. Wait till gc clears things 12806 // up. 12807 removeCids.add(args.cid); 12808 } 12809 } 12810 } 12811 // writer 12812 synchronized (mPackages) { 12813 // If the platform SDK has changed since the last time we booted, 12814 // we need to re-grant app permission to catch any new ones that 12815 // appear. This is really a hack, and means that apps can in some 12816 // cases get permissions that the user didn't initially explicitly 12817 // allow... it would be nice to have some better way to handle 12818 // this situation. 12819 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 12820 if (regrantPermissions) 12821 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 12822 + mSdkVersion + "; regranting permissions for external storage"); 12823 mSettings.mExternalSdkPlatform = mSdkVersion; 12824 12825 // Make sure group IDs have been assigned, and any permission 12826 // changes in other apps are accounted for 12827 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 12828 | (regrantPermissions 12829 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 12830 : 0)); 12831 12832 mSettings.updateExternalDatabaseVersion(); 12833 12834 // can downgrade to reader 12835 // Persist settings 12836 mSettings.writeLPr(); 12837 } 12838 // Send a broadcast to let everyone know we are done processing 12839 if (pkgList.size() > 0) { 12840 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12841 } 12842 // Force gc to avoid any stale parser references that we might have. 12843 if (doGc) { 12844 Runtime.getRuntime().gc(); 12845 } 12846 // List stale containers and destroy stale temporary containers. 12847 if (removeCids != null) { 12848 for (String cid : removeCids) { 12849 if (cid.startsWith(mTempContainerPrefix)) { 12850 Log.i(TAG, "Destroying stale temporary container " + cid); 12851 PackageHelper.destroySdDir(cid); 12852 } else { 12853 Log.w(TAG, "Container " + cid + " is stale"); 12854 } 12855 } 12856 } 12857 } 12858 12859 /* 12860 * Utility method to unload a list of specified containers 12861 */ 12862 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 12863 // Just unmount all valid containers. 12864 for (AsecInstallArgs arg : cidArgs) { 12865 synchronized (mInstallLock) { 12866 arg.doPostDeleteLI(false); 12867 } 12868 } 12869 } 12870 12871 /* 12872 * Unload packages mounted on external media. This involves deleting package 12873 * data from internal structures, sending broadcasts about diabled packages, 12874 * gc'ing to free up references, unmounting all secure containers 12875 * corresponding to packages on external media, and posting a 12876 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 12877 * that we always have to post this message if status has been requested no 12878 * matter what. 12879 */ 12880 private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 12881 final boolean reportStatus) { 12882 if (DEBUG_SD_INSTALL) 12883 Log.i(TAG, "unloading media packages"); 12884 ArrayList<String> pkgList = new ArrayList<String>(); 12885 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 12886 final Set<AsecInstallArgs> keys = processCids.keySet(); 12887 for (AsecInstallArgs args : keys) { 12888 String pkgName = args.getPackageName(); 12889 if (DEBUG_SD_INSTALL) 12890 Log.i(TAG, "Trying to unload pkg : " + pkgName); 12891 // Delete package internally 12892 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 12893 synchronized (mInstallLock) { 12894 boolean res = deletePackageLI(pkgName, null, false, null, null, 12895 PackageManager.DELETE_KEEP_DATA, outInfo, false); 12896 if (res) { 12897 pkgList.add(pkgName); 12898 } else { 12899 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 12900 failedList.add(args); 12901 } 12902 } 12903 } 12904 12905 // reader 12906 synchronized (mPackages) { 12907 // We didn't update the settings after removing each package; 12908 // write them now for all packages. 12909 mSettings.writeLPr(); 12910 } 12911 12912 // We have to absolutely send UPDATED_MEDIA_STATUS only 12913 // after confirming that all the receivers processed the ordered 12914 // broadcast when packages get disabled, force a gc to clean things up. 12915 // and unload all the containers. 12916 if (pkgList.size() > 0) { 12917 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 12918 new IIntentReceiver.Stub() { 12919 public void performReceive(Intent intent, int resultCode, String data, 12920 Bundle extras, boolean ordered, boolean sticky, 12921 int sendingUser) throws RemoteException { 12922 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 12923 reportStatus ? 1 : 0, 1, keys); 12924 mHandler.sendMessage(msg); 12925 } 12926 }); 12927 } else { 12928 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 12929 keys); 12930 mHandler.sendMessage(msg); 12931 } 12932 } 12933 12934 /** Binder call */ 12935 @Override 12936 public void movePackage(final String packageName, final IPackageMoveObserver observer, 12937 final int flags) { 12938 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 12939 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 12940 int returnCode = PackageManager.MOVE_SUCCEEDED; 12941 int currFlags = 0; 12942 int newFlags = 0; 12943 // reader 12944 synchronized (mPackages) { 12945 PackageParser.Package pkg = mPackages.get(packageName); 12946 if (pkg == null) { 12947 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12948 } else { 12949 // Disable moving fwd locked apps and system packages 12950 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 12951 Slog.w(TAG, "Cannot move system application"); 12952 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 12953 } else if (pkg.mOperationPending) { 12954 Slog.w(TAG, "Attempt to move package which has pending operations"); 12955 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 12956 } else { 12957 // Find install location first 12958 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 12959 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 12960 Slog.w(TAG, "Ambigous flags specified for move location."); 12961 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12962 } else { 12963 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL 12964 : PackageManager.INSTALL_INTERNAL; 12965 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL 12966 : PackageManager.INSTALL_INTERNAL; 12967 12968 if (newFlags == currFlags) { 12969 Slog.w(TAG, "No move required. Trying to move to same location"); 12970 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12971 } else { 12972 if (isForwardLocked(pkg)) { 12973 currFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12974 newFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12975 } 12976 } 12977 } 12978 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12979 pkg.mOperationPending = true; 12980 } 12981 } 12982 } 12983 12984 /* 12985 * TODO this next block probably shouldn't be inside the lock. We 12986 * can't guarantee these won't change after this is fired off 12987 * anyway. 12988 */ 12989 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 12990 processPendingMove(new MoveParams(null, observer, 0, packageName, null, -1, user, false), 12991 returnCode); 12992 } else { 12993 Message msg = mHandler.obtainMessage(INIT_COPY); 12994 final String[] instructionSets = getAppDexInstructionSets(pkg.applicationInfo); 12995 final boolean multiArch = isMultiArch(pkg.applicationInfo); 12996 InstallArgs srcArgs = createInstallArgsForExisting(currFlags, 12997 pkg.applicationInfo.getCodePath(), pkg.applicationInfo.getResourcePath(), 12998 pkg.applicationInfo.nativeLibraryRootDir, instructionSets, multiArch); 12999 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName, 13000 instructionSets, pkg.applicationInfo.uid, user, multiArch); 13001 msg.obj = mp; 13002 mHandler.sendMessage(msg); 13003 } 13004 } 13005 } 13006 13007 private void processPendingMove(final MoveParams mp, final int currentStatus) { 13008 // Queue up an async operation since the package deletion may take a 13009 // little while. 13010 mHandler.post(new Runnable() { 13011 public void run() { 13012 // TODO fix this; this does nothing. 13013 mHandler.removeCallbacks(this); 13014 int returnCode = currentStatus; 13015 if (currentStatus == PackageManager.MOVE_SUCCEEDED) { 13016 int uidArr[] = null; 13017 ArrayList<String> pkgList = null; 13018 synchronized (mPackages) { 13019 PackageParser.Package pkg = mPackages.get(mp.packageName); 13020 if (pkg == null) { 13021 Slog.w(TAG, " Package " + mp.packageName 13022 + " doesn't exist. Aborting move"); 13023 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 13024 } else if (!mp.srcArgs.getCodePath().equals( 13025 pkg.applicationInfo.getCodePath())) { 13026 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " 13027 + mp.srcArgs.getCodePath() + " to " 13028 + pkg.applicationInfo.getCodePath() 13029 + " Aborting move and returning error"); 13030 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 13031 } else { 13032 uidArr = new int[] { 13033 pkg.applicationInfo.uid 13034 }; 13035 pkgList = new ArrayList<String>(); 13036 pkgList.add(mp.packageName); 13037 } 13038 } 13039 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13040 // Send resources unavailable broadcast 13041 sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null); 13042 // Update package code and resource paths 13043 synchronized (mInstallLock) { 13044 synchronized (mPackages) { 13045 PackageParser.Package pkg = mPackages.get(mp.packageName); 13046 // Recheck for package again. 13047 if (pkg == null) { 13048 Slog.w(TAG, " Package " + mp.packageName 13049 + " doesn't exist. Aborting move"); 13050 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 13051 } else if (!mp.srcArgs.getCodePath().equals( 13052 pkg.applicationInfo.getCodePath())) { 13053 Slog.w(TAG, "Package " + mp.packageName 13054 + " code path changed from " + mp.srcArgs.getCodePath() 13055 + " to " + pkg.applicationInfo.getCodePath() 13056 + " Aborting move and returning error"); 13057 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 13058 } else { 13059 final String oldCodePath = pkg.codePath; 13060 final String newCodePath = mp.targetArgs.getCodePath(); 13061 final String newResPath = mp.targetArgs.getResourcePath(); 13062 // TODO: This assumes the new style of installation. 13063 // should we look at legacyNativeLibraryPath ? 13064 final String newNativeRoot = new File(pkg.codePath, LIB_DIR_NAME).getAbsolutePath(); 13065 final File newNativeDir = new File(newNativeRoot); 13066 13067 if (!isForwardLocked(pkg) && !isExternal(pkg)) { 13068 // TODO(multiArch): Fix this so that it looks at the existing 13069 // recorded CPU abis from the package. There's no need for a separate 13070 // round of ABI scanning here. 13071 NativeLibraryHelper.Handle handle = null; 13072 try { 13073 handle = NativeLibraryHelper.Handle.create( 13074 new File(newCodePath)); 13075 final int abi = NativeLibraryHelper.findSupportedAbi( 13076 handle, Build.SUPPORTED_ABIS); 13077 if (abi >= 0) { 13078 NativeLibraryHelper.copyNativeBinariesIfNeededLI( 13079 handle, newNativeDir, Build.SUPPORTED_ABIS[abi]); 13080 } 13081 } catch (IOException ioe) { 13082 Slog.w(TAG, "Unable to extract native libs for package :" 13083 + mp.packageName, ioe); 13084 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 13085 } finally { 13086 IoUtils.closeQuietly(handle); 13087 } 13088 } 13089 13090 final int[] users = sUserManager.getUserIds(); 13091 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13092 for (int user : users) { 13093 // TODO(multiArch): Fix this so that it links to the 13094 // correct directory. We're currently pointing to root. but we 13095 // must point to the arch specific subdirectory (if applicable). 13096 // 13097 // TODO(multiArch): Bogus reference to nativeLibraryDir. 13098 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, 13099 newNativeRoot, user) < 0) { 13100 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 13101 } 13102 } 13103 } 13104 13105 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13106 pkg.codePath = newCodePath; 13107 pkg.baseCodePath = newCodePath; 13108 // Move dex files around 13109 if (moveDexFilesLI(oldCodePath, pkg) != PackageManager.INSTALL_SUCCEEDED) { 13110 // Moving of dex files failed. Set 13111 // error code and abort move. 13112 pkg.codePath = oldCodePath; 13113 pkg.baseCodePath = oldCodePath; 13114 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 13115 } 13116 } 13117 13118 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13119 pkg.applicationInfo.setCodePath(newCodePath); 13120 pkg.applicationInfo.setBaseCodePath(newCodePath); 13121 pkg.applicationInfo.setSplitCodePaths(null); 13122 pkg.applicationInfo.setResourcePath(newResPath); 13123 pkg.applicationInfo.setBaseResourcePath(newResPath); 13124 pkg.applicationInfo.setSplitResourcePaths(null); 13125 13126 PackageSetting ps = (PackageSetting) pkg.mExtras; 13127 ps.codePath = new File(pkg.applicationInfo.getCodePath()); 13128 ps.codePathString = ps.codePath.getPath(); 13129 ps.resourcePath = new File(pkg.applicationInfo.getResourcePath()); 13130 ps.resourcePathString = ps.resourcePath.getPath(); 13131 13132 // Note that we don't have to recalculate the primary and secondary 13133 // CPU ABIs because they must already have been calculated during the 13134 // initial install of the app. 13135 ps.legacyNativeLibraryPathString = null; 13136 13137 // Set the application info flag 13138 // correctly. 13139 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) { 13140 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE; 13141 } else { 13142 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE; 13143 } 13144 ps.setFlags(pkg.applicationInfo.flags); 13145 mAppDirs.remove(oldCodePath); 13146 mAppDirs.put(newCodePath, pkg); 13147 // Persist settings 13148 mSettings.writeLPr(); 13149 } 13150 } 13151 } 13152 } 13153 // Send resources available broadcast 13154 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 13155 } 13156 } 13157 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 13158 // Clean up failed installation 13159 if (mp.targetArgs != null) { 13160 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR, 13161 -1); 13162 } 13163 } else { 13164 // Force a gc to clear things up. 13165 Runtime.getRuntime().gc(); 13166 // Delete older code 13167 synchronized (mInstallLock) { 13168 mp.srcArgs.doPostDeleteLI(true); 13169 } 13170 } 13171 13172 // Allow more operations on this file if we didn't fail because 13173 // an operation was already pending for this package. 13174 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) { 13175 synchronized (mPackages) { 13176 PackageParser.Package pkg = mPackages.get(mp.packageName); 13177 if (pkg != null) { 13178 pkg.mOperationPending = false; 13179 } 13180 } 13181 } 13182 13183 IPackageMoveObserver observer = mp.observer; 13184 if (observer != null) { 13185 try { 13186 observer.packageMoved(mp.packageName, returnCode); 13187 } catch (RemoteException e) { 13188 Log.i(TAG, "Observer no longer exists."); 13189 } 13190 } 13191 } 13192 }); 13193 } 13194 13195 @Override 13196 public boolean setInstallLocation(int loc) { 13197 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 13198 null); 13199 if (getInstallLocation() == loc) { 13200 return true; 13201 } 13202 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 13203 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 13204 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 13205 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 13206 return true; 13207 } 13208 return false; 13209 } 13210 13211 @Override 13212 public int getInstallLocation() { 13213 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13214 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 13215 PackageHelper.APP_INSTALL_AUTO); 13216 } 13217 13218 /** Called by UserManagerService */ 13219 void cleanUpUserLILPw(int userHandle) { 13220 mDirtyUsers.remove(userHandle); 13221 mSettings.removeUserLPw(userHandle); 13222 mPendingBroadcasts.remove(userHandle); 13223 if (mInstaller != null) { 13224 // Technically, we shouldn't be doing this with the package lock 13225 // held. However, this is very rare, and there is already so much 13226 // other disk I/O going on, that we'll let it slide for now. 13227 mInstaller.removeUserDataDirs(userHandle); 13228 } 13229 mUserNeedsBadging.delete(userHandle); 13230 } 13231 13232 /** Called by UserManagerService */ 13233 void createNewUserLILPw(int userHandle, File path) { 13234 if (mInstaller != null) { 13235 mInstaller.createUserConfig(userHandle); 13236 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 13237 } 13238 } 13239 13240 @Override 13241 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 13242 mContext.enforceCallingOrSelfPermission( 13243 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13244 "Only package verification agents can read the verifier device identity"); 13245 13246 synchronized (mPackages) { 13247 return mSettings.getVerifierDeviceIdentityLPw(); 13248 } 13249 } 13250 13251 @Override 13252 public void setPermissionEnforced(String permission, boolean enforced) { 13253 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 13254 if (READ_EXTERNAL_STORAGE.equals(permission)) { 13255 synchronized (mPackages) { 13256 if (mSettings.mReadExternalStorageEnforced == null 13257 || mSettings.mReadExternalStorageEnforced != enforced) { 13258 mSettings.mReadExternalStorageEnforced = enforced; 13259 mSettings.writeLPr(); 13260 } 13261 } 13262 // kill any non-foreground processes so we restart them and 13263 // grant/revoke the GID. 13264 final IActivityManager am = ActivityManagerNative.getDefault(); 13265 if (am != null) { 13266 final long token = Binder.clearCallingIdentity(); 13267 try { 13268 am.killProcessesBelowForeground("setPermissionEnforcement"); 13269 } catch (RemoteException e) { 13270 } finally { 13271 Binder.restoreCallingIdentity(token); 13272 } 13273 } 13274 } else { 13275 throw new IllegalArgumentException("No selective enforcement for " + permission); 13276 } 13277 } 13278 13279 @Override 13280 @Deprecated 13281 public boolean isPermissionEnforced(String permission) { 13282 return true; 13283 } 13284 13285 @Override 13286 public boolean isStorageLow() { 13287 final long token = Binder.clearCallingIdentity(); 13288 try { 13289 final DeviceStorageMonitorInternal 13290 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13291 if (dsm != null) { 13292 return dsm.isMemoryLow(); 13293 } else { 13294 return false; 13295 } 13296 } finally { 13297 Binder.restoreCallingIdentity(token); 13298 } 13299 } 13300 13301 @Override 13302 public IPackageInstaller getPackageInstaller() { 13303 return mInstallerService; 13304 } 13305 13306 private boolean userNeedsBadging(int userId) { 13307 int index = mUserNeedsBadging.indexOfKey(userId); 13308 if (index < 0) { 13309 final UserInfo userInfo; 13310 final long token = Binder.clearCallingIdentity(); 13311 try { 13312 userInfo = sUserManager.getUserInfo(userId); 13313 } finally { 13314 Binder.restoreCallingIdentity(token); 13315 } 13316 final boolean b; 13317 if (userInfo != null && userInfo.isManagedProfile()) { 13318 b = true; 13319 } else { 13320 b = false; 13321 } 13322 mUserNeedsBadging.put(userId, b); 13323 return b; 13324 } 13325 return mUserNeedsBadging.valueAt(index); 13326 } 13327 13328 @Override 13329 public KeySetHandle getKeySetByAlias(String packageName, String alias) { 13330 if (packageName == null || alias == null) { 13331 return null; 13332 } 13333 synchronized(mPackages) { 13334 final PackageParser.Package pkg = mPackages.get(packageName); 13335 if (pkg == null) { 13336 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13337 throw new IllegalArgumentException("Unknown package: " + packageName); 13338 } 13339 if (pkg.applicationInfo.uid != Binder.getCallingUid() 13340 && Process.SYSTEM_UID != Binder.getCallingUid()) { 13341 throw new SecurityException("May not access KeySets defined by" 13342 + " aliases in other applications."); 13343 } 13344 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13345 return ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias); 13346 } 13347 } 13348 13349 @Override 13350 public KeySetHandle getSigningKeySet(String packageName) { 13351 if (packageName == null) { 13352 return null; 13353 } 13354 synchronized(mPackages) { 13355 final PackageParser.Package pkg = mPackages.get(packageName); 13356 if (pkg == null) { 13357 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13358 throw new IllegalArgumentException("Unknown package: " + packageName); 13359 } 13360 if (pkg.applicationInfo.uid != Binder.getCallingUid() 13361 && Process.SYSTEM_UID != Binder.getCallingUid()) { 13362 throw new SecurityException("May not access signing KeySet of other apps."); 13363 } 13364 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13365 return ksms.getSigningKeySetByPackageNameLPr(packageName); 13366 } 13367 } 13368 13369 @Override 13370 public boolean isPackageSignedByKeySet(String packageName, IBinder ks) { 13371 if (packageName == null || ks == null) { 13372 return false; 13373 } 13374 synchronized(mPackages) { 13375 final PackageParser.Package pkg = mPackages.get(packageName); 13376 if (pkg == null) { 13377 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13378 throw new IllegalArgumentException("Unknown package: " + packageName); 13379 } 13380 if (ks instanceof KeySetHandle) { 13381 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13382 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ks); 13383 } 13384 return false; 13385 } 13386 } 13387 13388 @Override 13389 public boolean isPackageSignedByKeySetExactly(String packageName, IBinder ks) { 13390 if (packageName == null || ks == null) { 13391 return false; 13392 } 13393 synchronized(mPackages) { 13394 final PackageParser.Package pkg = mPackages.get(packageName); 13395 if (pkg == null) { 13396 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13397 throw new IllegalArgumentException("Unknown package: " + packageName); 13398 } 13399 if (ks instanceof KeySetHandle) { 13400 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13401 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ks); 13402 } 13403 return false; 13404 } 13405 } 13406} 13407