PackageManagerService.java revision d67a78db88d11a58691082ced6ab6bbc48976188
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS; 20import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 21import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 26import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 27import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 28import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 29import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 30import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 32import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 33import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 34import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 36import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 37import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 38import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 39import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 41import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED; 42import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 44import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 45import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 46import static android.content.pm.PackageParser.isApkFile; 47import static android.os.Process.PACKAGE_INFO_GID; 48import static android.os.Process.SYSTEM_UID; 49import static android.system.OsConstants.O_CREAT; 50import static android.system.OsConstants.O_RDWR; 51import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 52import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 53import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 54import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 55import static com.android.internal.util.ArrayUtils.appendInt; 56import static com.android.internal.util.ArrayUtils.removeInt; 57 58import android.util.ArrayMap; 59 60import com.android.internal.R; 61import com.android.internal.app.IMediaContainerService; 62import com.android.internal.app.ResolverActivity; 63import com.android.internal.content.NativeLibraryHelper; 64import com.android.internal.content.PackageHelper; 65import com.android.internal.os.IParcelFileDescriptorFactory; 66import com.android.internal.util.ArrayUtils; 67import com.android.internal.util.FastPrintWriter; 68import com.android.internal.util.FastXmlSerializer; 69import com.android.internal.util.IndentingPrintWriter; 70import com.android.server.EventLogTags; 71import com.android.server.IntentResolver; 72import com.android.server.LocalServices; 73import com.android.server.ServiceThread; 74import com.android.server.SystemConfig; 75import com.android.server.Watchdog; 76import com.android.server.pm.Settings.DatabaseVersion; 77import com.android.server.storage.DeviceStorageMonitorInternal; 78 79import org.xmlpull.v1.XmlSerializer; 80 81import android.app.ActivityManager; 82import android.app.ActivityManagerNative; 83import android.app.IActivityManager; 84import android.app.admin.IDevicePolicyManager; 85import android.app.backup.IBackupManager; 86import android.content.BroadcastReceiver; 87import android.content.ComponentName; 88import android.content.Context; 89import android.content.IIntentReceiver; 90import android.content.Intent; 91import android.content.IntentFilter; 92import android.content.IntentSender; 93import android.content.IntentSender.SendIntentException; 94import android.content.ServiceConnection; 95import android.content.pm.ActivityInfo; 96import android.content.pm.ApplicationInfo; 97import android.content.pm.FeatureInfo; 98import android.content.pm.IPackageDataObserver; 99import android.content.pm.IPackageDeleteObserver; 100import android.content.pm.IPackageDeleteObserver2; 101import android.content.pm.IPackageInstallObserver2; 102import android.content.pm.IPackageInstaller; 103import android.content.pm.IPackageManager; 104import android.content.pm.IPackageMoveObserver; 105import android.content.pm.IPackageStatsObserver; 106import android.content.pm.InstrumentationInfo; 107import android.content.pm.KeySet; 108import android.content.pm.ManifestDigest; 109import android.content.pm.PackageCleanItem; 110import android.content.pm.PackageInfo; 111import android.content.pm.PackageInfoLite; 112import android.content.pm.PackageInstaller; 113import android.content.pm.PackageManager; 114import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 115import android.content.pm.PackageParser.ActivityIntentInfo; 116import android.content.pm.PackageParser.PackageLite; 117import android.content.pm.PackageParser.PackageParserException; 118import android.content.pm.PackageParser; 119import android.content.pm.PackageStats; 120import android.content.pm.PackageUserState; 121import android.content.pm.ParceledListSlice; 122import android.content.pm.PermissionGroupInfo; 123import android.content.pm.PermissionInfo; 124import android.content.pm.ProviderInfo; 125import android.content.pm.ResolveInfo; 126import android.content.pm.ServiceInfo; 127import android.content.pm.Signature; 128import android.content.pm.UserInfo; 129import android.content.pm.VerificationParams; 130import android.content.pm.VerifierDeviceIdentity; 131import android.content.pm.VerifierInfo; 132import android.content.res.Resources; 133import android.hardware.display.DisplayManager; 134import android.net.Uri; 135import android.os.Binder; 136import android.os.Build; 137import android.os.Bundle; 138import android.os.Environment; 139import android.os.Environment.UserEnvironment; 140import android.os.storage.StorageManager; 141import android.os.FileUtils; 142import android.os.Handler; 143import android.os.IBinder; 144import android.os.Looper; 145import android.os.Message; 146import android.os.Parcel; 147import android.os.ParcelFileDescriptor; 148import android.os.Process; 149import android.os.RemoteException; 150import android.os.SELinux; 151import android.os.ServiceManager; 152import android.os.SystemClock; 153import android.os.SystemProperties; 154import android.os.UserHandle; 155import android.os.UserManager; 156import android.security.KeyStore; 157import android.security.SystemKeyStore; 158import android.system.ErrnoException; 159import android.system.Os; 160import android.system.StructStat; 161import android.text.TextUtils; 162import android.util.ArraySet; 163import android.util.AtomicFile; 164import android.util.DisplayMetrics; 165import android.util.EventLog; 166import android.util.ExceptionUtils; 167import android.util.Log; 168import android.util.LogPrinter; 169import android.util.PrintStreamPrinter; 170import android.util.Slog; 171import android.util.SparseArray; 172import android.util.SparseBooleanArray; 173import android.view.Display; 174 175import java.io.BufferedInputStream; 176import java.io.BufferedOutputStream; 177import java.io.File; 178import java.io.FileDescriptor; 179import java.io.FileInputStream; 180import java.io.FileNotFoundException; 181import java.io.FileOutputStream; 182import java.io.FilenameFilter; 183import java.io.IOException; 184import java.io.InputStream; 185import java.io.PrintWriter; 186import java.nio.charset.StandardCharsets; 187import java.security.NoSuchAlgorithmException; 188import java.security.PublicKey; 189import java.security.cert.CertificateEncodingException; 190import java.security.cert.CertificateException; 191import java.text.SimpleDateFormat; 192import java.util.ArrayList; 193import java.util.Arrays; 194import java.util.Collection; 195import java.util.Collections; 196import java.util.Comparator; 197import java.util.Date; 198import java.util.HashMap; 199import java.util.HashSet; 200import java.util.Iterator; 201import java.util.List; 202import java.util.Map; 203import java.util.Set; 204import java.util.concurrent.atomic.AtomicBoolean; 205import java.util.concurrent.atomic.AtomicLong; 206 207import dalvik.system.DexFile; 208import dalvik.system.StaleDexCacheError; 209import dalvik.system.VMRuntime; 210 211import libcore.io.IoUtils; 212import libcore.util.EmptyArray; 213 214/** 215 * Keep track of all those .apks everywhere. 216 * 217 * This is very central to the platform's security; please run the unit 218 * tests whenever making modifications here: 219 * 220mmm frameworks/base/tests/AndroidTests 221adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 222adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 223 * 224 * {@hide} 225 */ 226public class PackageManagerService extends IPackageManager.Stub { 227 static final String TAG = "PackageManager"; 228 static final boolean DEBUG_SETTINGS = false; 229 static final boolean DEBUG_PREFERRED = false; 230 static final boolean DEBUG_UPGRADE = false; 231 private static final boolean DEBUG_INSTALL = false; 232 private static final boolean DEBUG_REMOVE = false; 233 private static final boolean DEBUG_BROADCASTS = false; 234 private static final boolean DEBUG_SHOW_INFO = false; 235 private static final boolean DEBUG_PACKAGE_INFO = false; 236 private static final boolean DEBUG_INTENT_MATCHING = false; 237 private static final boolean DEBUG_PACKAGE_SCANNING = false; 238 private static final boolean DEBUG_VERIFY = false; 239 private static final boolean DEBUG_DEXOPT = false; 240 private static final boolean DEBUG_ABI_SELECTION = false; 241 242 private static final int RADIO_UID = Process.PHONE_UID; 243 private static final int LOG_UID = Process.LOG_UID; 244 private static final int NFC_UID = Process.NFC_UID; 245 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 246 private static final int SHELL_UID = Process.SHELL_UID; 247 248 // Cap the size of permission trees that 3rd party apps can define 249 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 250 251 // Suffix used during package installation when copying/moving 252 // package apks to install directory. 253 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 254 255 static final int SCAN_NO_DEX = 1<<1; 256 static final int SCAN_FORCE_DEX = 1<<2; 257 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 258 static final int SCAN_NEW_INSTALL = 1<<4; 259 static final int SCAN_NO_PATHS = 1<<5; 260 static final int SCAN_UPDATE_TIME = 1<<6; 261 static final int SCAN_DEFER_DEX = 1<<7; 262 static final int SCAN_BOOTING = 1<<8; 263 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 264 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 265 static final int SCAN_REPLACING = 1<<11; 266 267 static final int REMOVE_CHATTY = 1<<16; 268 269 /** 270 * Timeout (in milliseconds) after which the watchdog should declare that 271 * our handler thread is wedged. The usual default for such things is one 272 * minute but we sometimes do very lengthy I/O operations on this thread, 273 * such as installing multi-gigabyte applications, so ours needs to be longer. 274 */ 275 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 276 277 /** 278 * Whether verification is enabled by default. 279 */ 280 private static final boolean DEFAULT_VERIFY_ENABLE = true; 281 282 /** 283 * The default maximum time to wait for the verification agent to return in 284 * milliseconds. 285 */ 286 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 287 288 /** 289 * The default response for package verification timeout. 290 * 291 * This can be either PackageManager.VERIFICATION_ALLOW or 292 * PackageManager.VERIFICATION_REJECT. 293 */ 294 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 295 296 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 297 298 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 299 DEFAULT_CONTAINER_PACKAGE, 300 "com.android.defcontainer.DefaultContainerService"); 301 302 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 303 304 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 305 306 private static String sPreferredInstructionSet; 307 308 final ServiceThread mHandlerThread; 309 310 private static final String IDMAP_PREFIX = "/data/resource-cache/"; 311 private static final String IDMAP_SUFFIX = "@idmap"; 312 313 final PackageHandler mHandler; 314 315 final int mSdkVersion = Build.VERSION.SDK_INT; 316 317 final Context mContext; 318 final boolean mFactoryTest; 319 final boolean mOnlyCore; 320 final DisplayMetrics mMetrics; 321 final int mDefParseFlags; 322 final String[] mSeparateProcesses; 323 324 // This is where all application persistent data goes. 325 final File mAppDataDir; 326 327 // This is where all application persistent data goes for secondary users. 328 final File mUserAppDataDir; 329 330 /** The location for ASEC container files on internal storage. */ 331 final String mAsecInternalPath; 332 333 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 334 // LOCK HELD. Can be called with mInstallLock held. 335 final Installer mInstaller; 336 337 /** Directory where installed third-party apps stored */ 338 final File mAppInstallDir; 339 340 /** 341 * Directory to which applications installed internally have their 342 * 32 bit native libraries copied. 343 */ 344 private File mAppLib32InstallDir; 345 346 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 347 // apps. 348 final File mDrmAppPrivateInstallDir; 349 350 // ---------------------------------------------------------------- 351 352 // Lock for state used when installing and doing other long running 353 // operations. Methods that must be called with this lock held have 354 // the suffix "LI". 355 final Object mInstallLock = new Object(); 356 357 // ---------------------------------------------------------------- 358 359 // Keys are String (package name), values are Package. This also serves 360 // as the lock for the global state. Methods that must be called with 361 // this lock held have the prefix "LP". 362 final HashMap<String, PackageParser.Package> mPackages = 363 new HashMap<String, PackageParser.Package>(); 364 365 // Tracks available target package names -> overlay package paths. 366 final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays = 367 new HashMap<String, HashMap<String, PackageParser.Package>>(); 368 369 final Settings mSettings; 370 boolean mRestoredSettings; 371 372 // System configuration read by SystemConfig. 373 final int[] mGlobalGids; 374 final SparseArray<HashSet<String>> mSystemPermissions; 375 final HashMap<String, FeatureInfo> mAvailableFeatures; 376 377 // If mac_permissions.xml was found for seinfo labeling. 378 boolean mFoundPolicyFile; 379 380 // If a recursive restorecon of /data/data/<pkg> is needed. 381 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 382 383 public static final class SharedLibraryEntry { 384 public final String path; 385 public final String apk; 386 387 SharedLibraryEntry(String _path, String _apk) { 388 path = _path; 389 apk = _apk; 390 } 391 } 392 393 // Currently known shared libraries. 394 final HashMap<String, SharedLibraryEntry> mSharedLibraries = 395 new HashMap<String, SharedLibraryEntry>(); 396 397 // All available activities, for your resolving pleasure. 398 final ActivityIntentResolver mActivities = 399 new ActivityIntentResolver(); 400 401 // All available receivers, for your resolving pleasure. 402 final ActivityIntentResolver mReceivers = 403 new ActivityIntentResolver(); 404 405 // All available services, for your resolving pleasure. 406 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 407 408 // All available providers, for your resolving pleasure. 409 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 410 411 // Mapping from provider base names (first directory in content URI codePath) 412 // to the provider information. 413 final HashMap<String, PackageParser.Provider> mProvidersByAuthority = 414 new HashMap<String, PackageParser.Provider>(); 415 416 // Mapping from instrumentation class names to info about them. 417 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 418 new HashMap<ComponentName, PackageParser.Instrumentation>(); 419 420 // Mapping from permission names to info about them. 421 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups = 422 new HashMap<String, PackageParser.PermissionGroup>(); 423 424 // Packages whose data we have transfered into another package, thus 425 // should no longer exist. 426 final HashSet<String> mTransferedPackages = new HashSet<String>(); 427 428 // Broadcast actions that are only available to the system. 429 final HashSet<String> mProtectedBroadcasts = new HashSet<String>(); 430 431 /** List of packages waiting for verification. */ 432 final SparseArray<PackageVerificationState> mPendingVerification 433 = new SparseArray<PackageVerificationState>(); 434 435 /** Set of packages associated with each app op permission. */ 436 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 437 438 final PackageInstallerService mInstallerService; 439 440 HashSet<PackageParser.Package> mDeferredDexOpt = null; 441 442 // Cache of users who need badging. 443 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 444 445 /** Token for keys in mPendingVerification. */ 446 private int mPendingVerificationToken = 0; 447 448 boolean mSystemReady; 449 boolean mSafeMode; 450 boolean mHasSystemUidErrors; 451 452 ApplicationInfo mAndroidApplication; 453 final ActivityInfo mResolveActivity = new ActivityInfo(); 454 final ResolveInfo mResolveInfo = new ResolveInfo(); 455 ComponentName mResolveComponentName; 456 PackageParser.Package mPlatformPackage; 457 ComponentName mCustomResolverComponentName; 458 459 boolean mResolverReplaced = false; 460 461 // Set of pending broadcasts for aggregating enable/disable of components. 462 static class PendingPackageBroadcasts { 463 // for each user id, a map of <package name -> components within that package> 464 final SparseArray<HashMap<String, ArrayList<String>>> mUidMap; 465 466 public PendingPackageBroadcasts() { 467 mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2); 468 } 469 470 public ArrayList<String> get(int userId, String packageName) { 471 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 472 return packages.get(packageName); 473 } 474 475 public void put(int userId, String packageName, ArrayList<String> components) { 476 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 477 packages.put(packageName, components); 478 } 479 480 public void remove(int userId, String packageName) { 481 HashMap<String, ArrayList<String>> packages = mUidMap.get(userId); 482 if (packages != null) { 483 packages.remove(packageName); 484 } 485 } 486 487 public void remove(int userId) { 488 mUidMap.remove(userId); 489 } 490 491 public int userIdCount() { 492 return mUidMap.size(); 493 } 494 495 public int userIdAt(int n) { 496 return mUidMap.keyAt(n); 497 } 498 499 public HashMap<String, ArrayList<String>> packagesForUserId(int userId) { 500 return mUidMap.get(userId); 501 } 502 503 public int size() { 504 // total number of pending broadcast entries across all userIds 505 int num = 0; 506 for (int i = 0; i< mUidMap.size(); i++) { 507 num += mUidMap.valueAt(i).size(); 508 } 509 return num; 510 } 511 512 public void clear() { 513 mUidMap.clear(); 514 } 515 516 private HashMap<String, ArrayList<String>> getOrAllocate(int userId) { 517 HashMap<String, ArrayList<String>> map = mUidMap.get(userId); 518 if (map == null) { 519 map = new HashMap<String, ArrayList<String>>(); 520 mUidMap.put(userId, map); 521 } 522 return map; 523 } 524 } 525 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 526 527 // Service Connection to remote media container service to copy 528 // package uri's from external media onto secure containers 529 // or internal storage. 530 private IMediaContainerService mContainerService = null; 531 532 static final int SEND_PENDING_BROADCAST = 1; 533 static final int MCS_BOUND = 3; 534 static final int END_COPY = 4; 535 static final int INIT_COPY = 5; 536 static final int MCS_UNBIND = 6; 537 static final int START_CLEANING_PACKAGE = 7; 538 static final int FIND_INSTALL_LOC = 8; 539 static final int POST_INSTALL = 9; 540 static final int MCS_RECONNECT = 10; 541 static final int MCS_GIVE_UP = 11; 542 static final int UPDATED_MEDIA_STATUS = 12; 543 static final int WRITE_SETTINGS = 13; 544 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 545 static final int PACKAGE_VERIFIED = 15; 546 static final int CHECK_PENDING_VERIFICATION = 16; 547 548 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 549 550 // Delay time in millisecs 551 static final int BROADCAST_DELAY = 10 * 1000; 552 553 static UserManagerService sUserManager; 554 555 // Stores a list of users whose package restrictions file needs to be updated 556 private HashSet<Integer> mDirtyUsers = new HashSet<Integer>(); 557 558 final private DefaultContainerConnection mDefContainerConn = 559 new DefaultContainerConnection(); 560 class DefaultContainerConnection implements ServiceConnection { 561 public void onServiceConnected(ComponentName name, IBinder service) { 562 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 563 IMediaContainerService imcs = 564 IMediaContainerService.Stub.asInterface(service); 565 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 566 } 567 568 public void onServiceDisconnected(ComponentName name) { 569 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 570 } 571 }; 572 573 // Recordkeeping of restore-after-install operations that are currently in flight 574 // between the Package Manager and the Backup Manager 575 class PostInstallData { 576 public InstallArgs args; 577 public PackageInstalledInfo res; 578 579 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 580 args = _a; 581 res = _r; 582 } 583 }; 584 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 585 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 586 587 private final String mRequiredVerifierPackage; 588 589 private final PackageUsage mPackageUsage = new PackageUsage(); 590 591 private class PackageUsage { 592 private static final int WRITE_INTERVAL 593 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 594 595 private final Object mFileLock = new Object(); 596 private final AtomicLong mLastWritten = new AtomicLong(0); 597 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 598 599 private boolean mIsHistoricalPackageUsageAvailable = true; 600 601 boolean isHistoricalPackageUsageAvailable() { 602 return mIsHistoricalPackageUsageAvailable; 603 } 604 605 void write(boolean force) { 606 if (force) { 607 writeInternal(); 608 return; 609 } 610 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 611 && !DEBUG_DEXOPT) { 612 return; 613 } 614 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 615 new Thread("PackageUsage_DiskWriter") { 616 @Override 617 public void run() { 618 try { 619 writeInternal(); 620 } finally { 621 mBackgroundWriteRunning.set(false); 622 } 623 } 624 }.start(); 625 } 626 } 627 628 private void writeInternal() { 629 synchronized (mPackages) { 630 synchronized (mFileLock) { 631 AtomicFile file = getFile(); 632 FileOutputStream f = null; 633 try { 634 f = file.startWrite(); 635 BufferedOutputStream out = new BufferedOutputStream(f); 636 FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID); 637 StringBuilder sb = new StringBuilder(); 638 for (PackageParser.Package pkg : mPackages.values()) { 639 if (pkg.mLastPackageUsageTimeInMills == 0) { 640 continue; 641 } 642 sb.setLength(0); 643 sb.append(pkg.packageName); 644 sb.append(' '); 645 sb.append((long)pkg.mLastPackageUsageTimeInMills); 646 sb.append('\n'); 647 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 648 } 649 out.flush(); 650 file.finishWrite(f); 651 } catch (IOException e) { 652 if (f != null) { 653 file.failWrite(f); 654 } 655 Log.e(TAG, "Failed to write package usage times", e); 656 } 657 } 658 } 659 mLastWritten.set(SystemClock.elapsedRealtime()); 660 } 661 662 void readLP() { 663 synchronized (mFileLock) { 664 AtomicFile file = getFile(); 665 BufferedInputStream in = null; 666 try { 667 in = new BufferedInputStream(file.openRead()); 668 StringBuffer sb = new StringBuffer(); 669 while (true) { 670 String packageName = readToken(in, sb, ' '); 671 if (packageName == null) { 672 break; 673 } 674 String timeInMillisString = readToken(in, sb, '\n'); 675 if (timeInMillisString == null) { 676 throw new IOException("Failed to find last usage time for package " 677 + packageName); 678 } 679 PackageParser.Package pkg = mPackages.get(packageName); 680 if (pkg == null) { 681 continue; 682 } 683 long timeInMillis; 684 try { 685 timeInMillis = Long.parseLong(timeInMillisString.toString()); 686 } catch (NumberFormatException e) { 687 throw new IOException("Failed to parse " + timeInMillisString 688 + " as a long.", e); 689 } 690 pkg.mLastPackageUsageTimeInMills = timeInMillis; 691 } 692 } catch (FileNotFoundException expected) { 693 mIsHistoricalPackageUsageAvailable = false; 694 } catch (IOException e) { 695 Log.w(TAG, "Failed to read package usage times", e); 696 } finally { 697 IoUtils.closeQuietly(in); 698 } 699 } 700 mLastWritten.set(SystemClock.elapsedRealtime()); 701 } 702 703 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 704 throws IOException { 705 sb.setLength(0); 706 while (true) { 707 int ch = in.read(); 708 if (ch == -1) { 709 if (sb.length() == 0) { 710 return null; 711 } 712 throw new IOException("Unexpected EOF"); 713 } 714 if (ch == endOfToken) { 715 return sb.toString(); 716 } 717 sb.append((char)ch); 718 } 719 } 720 721 private AtomicFile getFile() { 722 File dataDir = Environment.getDataDirectory(); 723 File systemDir = new File(dataDir, "system"); 724 File fname = new File(systemDir, "package-usage.list"); 725 return new AtomicFile(fname); 726 } 727 } 728 729 class PackageHandler extends Handler { 730 private boolean mBound = false; 731 final ArrayList<HandlerParams> mPendingInstalls = 732 new ArrayList<HandlerParams>(); 733 734 private boolean connectToService() { 735 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 736 " DefaultContainerService"); 737 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 738 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 739 if (mContext.bindServiceAsUser(service, mDefContainerConn, 740 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 741 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 742 mBound = true; 743 return true; 744 } 745 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 746 return false; 747 } 748 749 private void disconnectService() { 750 mContainerService = null; 751 mBound = false; 752 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 753 mContext.unbindService(mDefContainerConn); 754 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 755 } 756 757 PackageHandler(Looper looper) { 758 super(looper); 759 } 760 761 public void handleMessage(Message msg) { 762 try { 763 doHandleMessage(msg); 764 } finally { 765 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 766 } 767 } 768 769 void doHandleMessage(Message msg) { 770 switch (msg.what) { 771 case INIT_COPY: { 772 HandlerParams params = (HandlerParams) msg.obj; 773 int idx = mPendingInstalls.size(); 774 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 775 // If a bind was already initiated we dont really 776 // need to do anything. The pending install 777 // will be processed later on. 778 if (!mBound) { 779 // If this is the only one pending we might 780 // have to bind to the service again. 781 if (!connectToService()) { 782 Slog.e(TAG, "Failed to bind to media container service"); 783 params.serviceError(); 784 return; 785 } else { 786 // Once we bind to the service, the first 787 // pending request will be processed. 788 mPendingInstalls.add(idx, params); 789 } 790 } else { 791 mPendingInstalls.add(idx, params); 792 // Already bound to the service. Just make 793 // sure we trigger off processing the first request. 794 if (idx == 0) { 795 mHandler.sendEmptyMessage(MCS_BOUND); 796 } 797 } 798 break; 799 } 800 case MCS_BOUND: { 801 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 802 if (msg.obj != null) { 803 mContainerService = (IMediaContainerService) msg.obj; 804 } 805 if (mContainerService == null) { 806 // Something seriously wrong. Bail out 807 Slog.e(TAG, "Cannot bind to media container service"); 808 for (HandlerParams params : mPendingInstalls) { 809 // Indicate service bind error 810 params.serviceError(); 811 } 812 mPendingInstalls.clear(); 813 } else if (mPendingInstalls.size() > 0) { 814 HandlerParams params = mPendingInstalls.get(0); 815 if (params != null) { 816 if (params.startCopy()) { 817 // We are done... look for more work or to 818 // go idle. 819 if (DEBUG_SD_INSTALL) Log.i(TAG, 820 "Checking for more work or unbind..."); 821 // Delete pending install 822 if (mPendingInstalls.size() > 0) { 823 mPendingInstalls.remove(0); 824 } 825 if (mPendingInstalls.size() == 0) { 826 if (mBound) { 827 if (DEBUG_SD_INSTALL) Log.i(TAG, 828 "Posting delayed MCS_UNBIND"); 829 removeMessages(MCS_UNBIND); 830 Message ubmsg = obtainMessage(MCS_UNBIND); 831 // Unbind after a little delay, to avoid 832 // continual thrashing. 833 sendMessageDelayed(ubmsg, 10000); 834 } 835 } else { 836 // There are more pending requests in queue. 837 // Just post MCS_BOUND message to trigger processing 838 // of next pending install. 839 if (DEBUG_SD_INSTALL) Log.i(TAG, 840 "Posting MCS_BOUND for next work"); 841 mHandler.sendEmptyMessage(MCS_BOUND); 842 } 843 } 844 } 845 } else { 846 // Should never happen ideally. 847 Slog.w(TAG, "Empty queue"); 848 } 849 break; 850 } 851 case MCS_RECONNECT: { 852 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 853 if (mPendingInstalls.size() > 0) { 854 if (mBound) { 855 disconnectService(); 856 } 857 if (!connectToService()) { 858 Slog.e(TAG, "Failed to bind to media container service"); 859 for (HandlerParams params : mPendingInstalls) { 860 // Indicate service bind error 861 params.serviceError(); 862 } 863 mPendingInstalls.clear(); 864 } 865 } 866 break; 867 } 868 case MCS_UNBIND: { 869 // If there is no actual work left, then time to unbind. 870 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 871 872 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 873 if (mBound) { 874 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 875 876 disconnectService(); 877 } 878 } else if (mPendingInstalls.size() > 0) { 879 // There are more pending requests in queue. 880 // Just post MCS_BOUND message to trigger processing 881 // of next pending install. 882 mHandler.sendEmptyMessage(MCS_BOUND); 883 } 884 885 break; 886 } 887 case MCS_GIVE_UP: { 888 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 889 mPendingInstalls.remove(0); 890 break; 891 } 892 case SEND_PENDING_BROADCAST: { 893 String packages[]; 894 ArrayList<String> components[]; 895 int size = 0; 896 int uids[]; 897 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 898 synchronized (mPackages) { 899 if (mPendingBroadcasts == null) { 900 return; 901 } 902 size = mPendingBroadcasts.size(); 903 if (size <= 0) { 904 // Nothing to be done. Just return 905 return; 906 } 907 packages = new String[size]; 908 components = new ArrayList[size]; 909 uids = new int[size]; 910 int i = 0; // filling out the above arrays 911 912 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 913 int packageUserId = mPendingBroadcasts.userIdAt(n); 914 Iterator<Map.Entry<String, ArrayList<String>>> it 915 = mPendingBroadcasts.packagesForUserId(packageUserId) 916 .entrySet().iterator(); 917 while (it.hasNext() && i < size) { 918 Map.Entry<String, ArrayList<String>> ent = it.next(); 919 packages[i] = ent.getKey(); 920 components[i] = ent.getValue(); 921 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 922 uids[i] = (ps != null) 923 ? UserHandle.getUid(packageUserId, ps.appId) 924 : -1; 925 i++; 926 } 927 } 928 size = i; 929 mPendingBroadcasts.clear(); 930 } 931 // Send broadcasts 932 for (int i = 0; i < size; i++) { 933 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 934 } 935 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 936 break; 937 } 938 case START_CLEANING_PACKAGE: { 939 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 940 final String packageName = (String)msg.obj; 941 final int userId = msg.arg1; 942 final boolean andCode = msg.arg2 != 0; 943 synchronized (mPackages) { 944 if (userId == UserHandle.USER_ALL) { 945 int[] users = sUserManager.getUserIds(); 946 for (int user : users) { 947 mSettings.addPackageToCleanLPw( 948 new PackageCleanItem(user, packageName, andCode)); 949 } 950 } else { 951 mSettings.addPackageToCleanLPw( 952 new PackageCleanItem(userId, packageName, andCode)); 953 } 954 } 955 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 956 startCleaningPackages(); 957 } break; 958 case POST_INSTALL: { 959 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 960 PostInstallData data = mRunningInstalls.get(msg.arg1); 961 mRunningInstalls.delete(msg.arg1); 962 boolean deleteOld = false; 963 964 if (data != null) { 965 InstallArgs args = data.args; 966 PackageInstalledInfo res = data.res; 967 968 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 969 res.removedInfo.sendBroadcast(false, true, false); 970 Bundle extras = new Bundle(1); 971 extras.putInt(Intent.EXTRA_UID, res.uid); 972 // Determine the set of users who are adding this 973 // package for the first time vs. those who are seeing 974 // an update. 975 int[] firstUsers; 976 int[] updateUsers = new int[0]; 977 if (res.origUsers == null || res.origUsers.length == 0) { 978 firstUsers = res.newUsers; 979 } else { 980 firstUsers = new int[0]; 981 for (int i=0; i<res.newUsers.length; i++) { 982 int user = res.newUsers[i]; 983 boolean isNew = true; 984 for (int j=0; j<res.origUsers.length; j++) { 985 if (res.origUsers[j] == user) { 986 isNew = false; 987 break; 988 } 989 } 990 if (isNew) { 991 int[] newFirst = new int[firstUsers.length+1]; 992 System.arraycopy(firstUsers, 0, newFirst, 0, 993 firstUsers.length); 994 newFirst[firstUsers.length] = user; 995 firstUsers = newFirst; 996 } else { 997 int[] newUpdate = new int[updateUsers.length+1]; 998 System.arraycopy(updateUsers, 0, newUpdate, 0, 999 updateUsers.length); 1000 newUpdate[updateUsers.length] = user; 1001 updateUsers = newUpdate; 1002 } 1003 } 1004 } 1005 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1006 res.pkg.applicationInfo.packageName, 1007 extras, null, null, firstUsers); 1008 final boolean update = res.removedInfo.removedPackage != null; 1009 if (update) { 1010 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1011 } 1012 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1013 res.pkg.applicationInfo.packageName, 1014 extras, null, null, updateUsers); 1015 if (update) { 1016 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1017 res.pkg.applicationInfo.packageName, 1018 extras, null, null, updateUsers); 1019 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1020 null, null, 1021 res.pkg.applicationInfo.packageName, null, updateUsers); 1022 1023 // treat asec-hosted packages like removable media on upgrade 1024 if (isForwardLocked(res.pkg) || isExternal(res.pkg)) { 1025 if (DEBUG_INSTALL) { 1026 Slog.i(TAG, "upgrading pkg " + res.pkg 1027 + " is ASEC-hosted -> AVAILABLE"); 1028 } 1029 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1030 ArrayList<String> pkgList = new ArrayList<String>(1); 1031 pkgList.add(res.pkg.applicationInfo.packageName); 1032 sendResourcesChangedBroadcast(true, true, 1033 pkgList,uidArray, null); 1034 } 1035 } 1036 if (res.removedInfo.args != null) { 1037 // Remove the replaced package's older resources safely now 1038 deleteOld = true; 1039 } 1040 1041 // Log current value of "unknown sources" setting 1042 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1043 getUnknownSourcesSettings()); 1044 } 1045 // Force a gc to clear up things 1046 Runtime.getRuntime().gc(); 1047 // We delete after a gc for applications on sdcard. 1048 if (deleteOld) { 1049 synchronized (mInstallLock) { 1050 res.removedInfo.args.doPostDeleteLI(true); 1051 } 1052 } 1053 if (args.observer != null) { 1054 try { 1055 Bundle extras = extrasForInstallResult(res); 1056 args.observer.onPackageInstalled(res.name, res.returnCode, 1057 res.returnMsg, extras); 1058 } catch (RemoteException e) { 1059 Slog.i(TAG, "Observer no longer exists."); 1060 } 1061 } 1062 } else { 1063 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1064 } 1065 } break; 1066 case UPDATED_MEDIA_STATUS: { 1067 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1068 boolean reportStatus = msg.arg1 == 1; 1069 boolean doGc = msg.arg2 == 1; 1070 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1071 if (doGc) { 1072 // Force a gc to clear up stale containers. 1073 Runtime.getRuntime().gc(); 1074 } 1075 if (msg.obj != null) { 1076 @SuppressWarnings("unchecked") 1077 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1078 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1079 // Unload containers 1080 unloadAllContainers(args); 1081 } 1082 if (reportStatus) { 1083 try { 1084 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1085 PackageHelper.getMountService().finishMediaUpdate(); 1086 } catch (RemoteException e) { 1087 Log.e(TAG, "MountService not running?"); 1088 } 1089 } 1090 } break; 1091 case WRITE_SETTINGS: { 1092 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1093 synchronized (mPackages) { 1094 removeMessages(WRITE_SETTINGS); 1095 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1096 mSettings.writeLPr(); 1097 mDirtyUsers.clear(); 1098 } 1099 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1100 } break; 1101 case WRITE_PACKAGE_RESTRICTIONS: { 1102 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1103 synchronized (mPackages) { 1104 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1105 for (int userId : mDirtyUsers) { 1106 mSettings.writePackageRestrictionsLPr(userId); 1107 } 1108 mDirtyUsers.clear(); 1109 } 1110 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1111 } break; 1112 case CHECK_PENDING_VERIFICATION: { 1113 final int verificationId = msg.arg1; 1114 final PackageVerificationState state = mPendingVerification.get(verificationId); 1115 1116 if ((state != null) && !state.timeoutExtended()) { 1117 final InstallArgs args = state.getInstallArgs(); 1118 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1119 1120 Slog.i(TAG, "Verification timed out for " + originUri); 1121 mPendingVerification.remove(verificationId); 1122 1123 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1124 1125 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1126 Slog.i(TAG, "Continuing with installation of " + originUri); 1127 state.setVerifierResponse(Binder.getCallingUid(), 1128 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1129 broadcastPackageVerified(verificationId, originUri, 1130 PackageManager.VERIFICATION_ALLOW, 1131 state.getInstallArgs().getUser()); 1132 try { 1133 ret = args.copyApk(mContainerService, true); 1134 } catch (RemoteException e) { 1135 Slog.e(TAG, "Could not contact the ContainerService"); 1136 } 1137 } else { 1138 broadcastPackageVerified(verificationId, originUri, 1139 PackageManager.VERIFICATION_REJECT, 1140 state.getInstallArgs().getUser()); 1141 } 1142 1143 processPendingInstall(args, ret); 1144 mHandler.sendEmptyMessage(MCS_UNBIND); 1145 } 1146 break; 1147 } 1148 case PACKAGE_VERIFIED: { 1149 final int verificationId = msg.arg1; 1150 1151 final PackageVerificationState state = mPendingVerification.get(verificationId); 1152 if (state == null) { 1153 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1154 break; 1155 } 1156 1157 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1158 1159 state.setVerifierResponse(response.callerUid, response.code); 1160 1161 if (state.isVerificationComplete()) { 1162 mPendingVerification.remove(verificationId); 1163 1164 final InstallArgs args = state.getInstallArgs(); 1165 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1166 1167 int ret; 1168 if (state.isInstallAllowed()) { 1169 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1170 broadcastPackageVerified(verificationId, originUri, 1171 response.code, state.getInstallArgs().getUser()); 1172 try { 1173 ret = args.copyApk(mContainerService, true); 1174 } catch (RemoteException e) { 1175 Slog.e(TAG, "Could not contact the ContainerService"); 1176 } 1177 } else { 1178 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1179 } 1180 1181 processPendingInstall(args, ret); 1182 1183 mHandler.sendEmptyMessage(MCS_UNBIND); 1184 } 1185 1186 break; 1187 } 1188 } 1189 } 1190 } 1191 1192 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1193 Bundle extras = null; 1194 switch (res.returnCode) { 1195 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1196 extras = new Bundle(); 1197 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1198 res.origPermission); 1199 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1200 res.origPackage); 1201 break; 1202 } 1203 } 1204 return extras; 1205 } 1206 1207 void scheduleWriteSettingsLocked() { 1208 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1209 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1210 } 1211 } 1212 1213 void scheduleWritePackageRestrictionsLocked(int userId) { 1214 if (!sUserManager.exists(userId)) return; 1215 mDirtyUsers.add(userId); 1216 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1217 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1218 } 1219 } 1220 1221 public static final PackageManagerService main(Context context, Installer installer, 1222 boolean factoryTest, boolean onlyCore) { 1223 PackageManagerService m = new PackageManagerService(context, installer, 1224 factoryTest, onlyCore); 1225 ServiceManager.addService("package", m); 1226 return m; 1227 } 1228 1229 static String[] splitString(String str, char sep) { 1230 int count = 1; 1231 int i = 0; 1232 while ((i=str.indexOf(sep, i)) >= 0) { 1233 count++; 1234 i++; 1235 } 1236 1237 String[] res = new String[count]; 1238 i=0; 1239 count = 0; 1240 int lastI=0; 1241 while ((i=str.indexOf(sep, i)) >= 0) { 1242 res[count] = str.substring(lastI, i); 1243 count++; 1244 i++; 1245 lastI = i; 1246 } 1247 res[count] = str.substring(lastI, str.length()); 1248 return res; 1249 } 1250 1251 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1252 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1253 Context.DISPLAY_SERVICE); 1254 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1255 } 1256 1257 public PackageManagerService(Context context, Installer installer, 1258 boolean factoryTest, boolean onlyCore) { 1259 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1260 SystemClock.uptimeMillis()); 1261 1262 if (mSdkVersion <= 0) { 1263 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1264 } 1265 1266 mContext = context; 1267 mFactoryTest = factoryTest; 1268 mOnlyCore = onlyCore; 1269 mMetrics = new DisplayMetrics(); 1270 mSettings = new Settings(context); 1271 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1272 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1273 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1274 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1275 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1276 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1277 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1278 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1279 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1280 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1281 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1282 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1283 1284 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1285 if (separateProcesses != null && separateProcesses.length() > 0) { 1286 if ("*".equals(separateProcesses)) { 1287 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1288 mSeparateProcesses = null; 1289 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1290 } else { 1291 mDefParseFlags = 0; 1292 mSeparateProcesses = separateProcesses.split(","); 1293 Slog.w(TAG, "Running with debug.separate_processes: " 1294 + separateProcesses); 1295 } 1296 } else { 1297 mDefParseFlags = 0; 1298 mSeparateProcesses = null; 1299 } 1300 1301 mInstaller = installer; 1302 1303 getDefaultDisplayMetrics(context, mMetrics); 1304 1305 SystemConfig systemConfig = SystemConfig.getInstance(); 1306 mGlobalGids = systemConfig.getGlobalGids(); 1307 mSystemPermissions = systemConfig.getSystemPermissions(); 1308 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1309 1310 synchronized (mInstallLock) { 1311 // writer 1312 synchronized (mPackages) { 1313 mHandlerThread = new ServiceThread(TAG, 1314 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1315 mHandlerThread.start(); 1316 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1317 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1318 1319 File dataDir = Environment.getDataDirectory(); 1320 mAppDataDir = new File(dataDir, "data"); 1321 mAppInstallDir = new File(dataDir, "app"); 1322 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1323 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1324 mUserAppDataDir = new File(dataDir, "user"); 1325 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1326 1327 sUserManager = new UserManagerService(context, this, 1328 mInstallLock, mPackages); 1329 1330 // Propagate permission configuration in to package manager. 1331 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1332 = systemConfig.getPermissions(); 1333 for (int i=0; i<permConfig.size(); i++) { 1334 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1335 BasePermission bp = mSettings.mPermissions.get(perm.name); 1336 if (bp == null) { 1337 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1338 mSettings.mPermissions.put(perm.name, bp); 1339 } 1340 if (perm.gids != null) { 1341 bp.gids = appendInts(bp.gids, perm.gids); 1342 } 1343 } 1344 1345 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1346 for (int i=0; i<libConfig.size(); i++) { 1347 mSharedLibraries.put(libConfig.keyAt(i), 1348 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1349 } 1350 1351 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1352 1353 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1354 mSdkVersion, mOnlyCore); 1355 1356 String customResolverActivity = Resources.getSystem().getString( 1357 R.string.config_customResolverActivity); 1358 if (TextUtils.isEmpty(customResolverActivity)) { 1359 customResolverActivity = null; 1360 } else { 1361 mCustomResolverComponentName = ComponentName.unflattenFromString( 1362 customResolverActivity); 1363 } 1364 1365 long startTime = SystemClock.uptimeMillis(); 1366 1367 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1368 startTime); 1369 1370 // Set flag to monitor and not change apk file paths when 1371 // scanning install directories. 1372 int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1373 1374 final HashSet<String> alreadyDexOpted = new HashSet<String>(); 1375 1376 /** 1377 * Add everything in the in the boot class path to the 1378 * list of process files because dexopt will have been run 1379 * if necessary during zygote startup. 1380 */ 1381 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1382 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1383 1384 if (bootClassPath != null) { 1385 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1386 for (String element : bootClassPathElements) { 1387 alreadyDexOpted.add(element); 1388 } 1389 } else { 1390 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1391 } 1392 1393 if (systemServerClassPath != null) { 1394 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1395 for (String element : systemServerClassPathElements) { 1396 alreadyDexOpted.add(element); 1397 } 1398 } else { 1399 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1400 } 1401 1402 boolean didDexOptLibraryOrTool = false; 1403 1404 final List<String> allInstructionSets = getAllInstructionSets(); 1405 final String[] dexCodeInstructionSets = 1406 getDexCodeInstructionSets(allInstructionSets.toArray(new String[allInstructionSets.size()])); 1407 1408 /** 1409 * Ensure all external libraries have had dexopt run on them. 1410 */ 1411 if (mSharedLibraries.size() > 0) { 1412 // NOTE: For now, we're compiling these system "shared libraries" 1413 // (and framework jars) into all available architectures. It's possible 1414 // to compile them only when we come across an app that uses them (there's 1415 // already logic for that in scanPackageLI) but that adds some complexity. 1416 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1417 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1418 final String lib = libEntry.path; 1419 if (lib == null) { 1420 continue; 1421 } 1422 1423 try { 1424 byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null, 1425 dexCodeInstructionSet, 1426 false); 1427 if (dexoptRequired != DexFile.UP_TO_DATE) { 1428 alreadyDexOpted.add(lib); 1429 1430 // The list of "shared libraries" we have at this point is 1431 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1432 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1433 } else { 1434 mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1435 } 1436 didDexOptLibraryOrTool = true; 1437 } 1438 } catch (FileNotFoundException e) { 1439 Slog.w(TAG, "Library not found: " + lib); 1440 } catch (IOException e) { 1441 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1442 + e.getMessage()); 1443 } 1444 } 1445 } 1446 } 1447 1448 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1449 1450 // Gross hack for now: we know this file doesn't contain any 1451 // code, so don't dexopt it to avoid the resulting log spew. 1452 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1453 1454 // Gross hack for now: we know this file is only part of 1455 // the boot class path for art, so don't dexopt it to 1456 // avoid the resulting log spew. 1457 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1458 1459 /** 1460 * And there are a number of commands implemented in Java, which 1461 * we currently need to do the dexopt on so that they can be 1462 * run from a non-root shell. 1463 */ 1464 String[] frameworkFiles = frameworkDir.list(); 1465 if (frameworkFiles != null) { 1466 // TODO: We could compile these only for the most preferred ABI. We should 1467 // first double check that the dex files for these commands are not referenced 1468 // by other system apps. 1469 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1470 for (int i=0; i<frameworkFiles.length; i++) { 1471 File libPath = new File(frameworkDir, frameworkFiles[i]); 1472 String path = libPath.getPath(); 1473 // Skip the file if we already did it. 1474 if (alreadyDexOpted.contains(path)) { 1475 continue; 1476 } 1477 // Skip the file if it is not a type we want to dexopt. 1478 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1479 continue; 1480 } 1481 try { 1482 byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null, 1483 dexCodeInstructionSet, 1484 false); 1485 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1486 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1487 didDexOptLibraryOrTool = true; 1488 } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) { 1489 mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1490 didDexOptLibraryOrTool = true; 1491 } 1492 } catch (FileNotFoundException e) { 1493 Slog.w(TAG, "Jar not found: " + path); 1494 } catch (IOException e) { 1495 Slog.w(TAG, "Exception reading jar: " + path, e); 1496 } 1497 } 1498 } 1499 } 1500 1501 // Collect vendor overlay packages. 1502 // (Do this before scanning any apps.) 1503 // For security and version matching reason, only consider 1504 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1505 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1506 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1507 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1508 1509 // Find base frameworks (resource packages without code). 1510 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1511 | PackageParser.PARSE_IS_SYSTEM_DIR 1512 | PackageParser.PARSE_IS_PRIVILEGED, 1513 scanFlags | SCAN_NO_DEX, 0); 1514 1515 // Collected privileged system packages. 1516 File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1517 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1518 | PackageParser.PARSE_IS_SYSTEM_DIR 1519 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1520 1521 // Collect ordinary system packages. 1522 File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1523 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1524 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1525 1526 // Collect all vendor packages. 1527 File vendorAppDir = new File("/vendor/app"); 1528 try { 1529 vendorAppDir = vendorAppDir.getCanonicalFile(); 1530 } catch (IOException e) { 1531 // failed to look up canonical path, continue with original one 1532 } 1533 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1534 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1535 1536 // Collect all OEM packages. 1537 File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1538 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1539 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1540 1541 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1542 mInstaller.moveFiles(); 1543 1544 // Prune any system packages that no longer exist. 1545 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1546 if (!mOnlyCore) { 1547 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1548 while (psit.hasNext()) { 1549 PackageSetting ps = psit.next(); 1550 1551 /* 1552 * If this is not a system app, it can't be a 1553 * disable system app. 1554 */ 1555 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1556 continue; 1557 } 1558 1559 /* 1560 * If the package is scanned, it's not erased. 1561 */ 1562 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1563 if (scannedPkg != null) { 1564 /* 1565 * If the system app is both scanned and in the 1566 * disabled packages list, then it must have been 1567 * added via OTA. Remove it from the currently 1568 * scanned package so the previously user-installed 1569 * application can be scanned. 1570 */ 1571 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1572 Slog.i(TAG, "Expecting better updatd system app for " + ps.name 1573 + "; removing system app"); 1574 removePackageLI(ps, true); 1575 } 1576 1577 continue; 1578 } 1579 1580 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1581 psit.remove(); 1582 String msg = "System package " + ps.name 1583 + " no longer exists; wiping its data"; 1584 reportSettingsProblem(Log.WARN, msg); 1585 removeDataDirsLI(ps.name); 1586 } else { 1587 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1588 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1589 possiblyDeletedUpdatedSystemApps.add(ps.name); 1590 } 1591 } 1592 } 1593 } 1594 1595 //look for any incomplete package installations 1596 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1597 //clean up list 1598 for(int i = 0; i < deletePkgsList.size(); i++) { 1599 //clean up here 1600 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1601 } 1602 //delete tmp files 1603 deleteTempPackageFiles(); 1604 1605 // Remove any shared userIDs that have no associated packages 1606 mSettings.pruneSharedUsersLPw(); 1607 1608 if (!mOnlyCore) { 1609 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 1610 SystemClock.uptimeMillis()); 1611 scanDirLI(mAppInstallDir, 0, scanFlags, 0); 1612 1613 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 1614 scanFlags, 0); 1615 1616 /** 1617 * Remove disable package settings for any updated system 1618 * apps that were removed via an OTA. If they're not a 1619 * previously-updated app, remove them completely. 1620 * Otherwise, just revoke their system-level permissions. 1621 */ 1622 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 1623 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 1624 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 1625 1626 String msg; 1627 if (deletedPkg == null) { 1628 msg = "Updated system package " + deletedAppName 1629 + " no longer exists; wiping its data"; 1630 removeDataDirsLI(deletedAppName); 1631 } else { 1632 msg = "Updated system app + " + deletedAppName 1633 + " no longer present; removing system privileges for " 1634 + deletedAppName; 1635 1636 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 1637 1638 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 1639 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 1640 } 1641 reportSettingsProblem(Log.WARN, msg); 1642 } 1643 } 1644 1645 // Now that we know all of the shared libraries, update all clients to have 1646 // the correct library paths. 1647 updateAllSharedLibrariesLPw(); 1648 1649 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 1650 // NOTE: We ignore potential failures here during a system scan (like 1651 // the rest of the commands above) because there's precious little we 1652 // can do about it. A settings error is reported, though. 1653 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 1654 false /* force dexopt */, false /* defer dexopt */); 1655 } 1656 1657 // Now that we know all the packages we are keeping, 1658 // read and update their last usage times. 1659 mPackageUsage.readLP(); 1660 1661 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 1662 SystemClock.uptimeMillis()); 1663 Slog.i(TAG, "Time to scan packages: " 1664 + ((SystemClock.uptimeMillis()-startTime)/1000f) 1665 + " seconds"); 1666 1667 // If the platform SDK has changed since the last time we booted, 1668 // we need to re-grant app permission to catch any new ones that 1669 // appear. This is really a hack, and means that apps can in some 1670 // cases get permissions that the user didn't initially explicitly 1671 // allow... it would be nice to have some better way to handle 1672 // this situation. 1673 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 1674 != mSdkVersion; 1675 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 1676 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 1677 + "; regranting permissions for internal storage"); 1678 mSettings.mInternalSdkPlatform = mSdkVersion; 1679 1680 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 1681 | (regrantPermissions 1682 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 1683 : 0)); 1684 1685 // If this is the first boot, and it is a normal boot, then 1686 // we need to initialize the default preferred apps. 1687 if (!mRestoredSettings && !onlyCore) { 1688 mSettings.readDefaultPreferredAppsLPw(this, 0); 1689 } 1690 1691 // If this is first boot after an OTA, and a normal boot, then 1692 // we need to clear code cache directories. 1693 if (!Build.FINGERPRINT.equals(mSettings.mFingerprint) && !onlyCore) { 1694 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 1695 for (String pkgName : mSettings.mPackages.keySet()) { 1696 deleteCodeCacheDirsLI(pkgName); 1697 } 1698 mSettings.mFingerprint = Build.FINGERPRINT; 1699 } 1700 1701 // All the changes are done during package scanning. 1702 mSettings.updateInternalDatabaseVersion(); 1703 1704 // can downgrade to reader 1705 mSettings.writeLPr(); 1706 1707 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 1708 SystemClock.uptimeMillis()); 1709 1710 1711 mRequiredVerifierPackage = getRequiredVerifierLPr(); 1712 } // synchronized (mPackages) 1713 } // synchronized (mInstallLock) 1714 1715 mInstallerService = new PackageInstallerService(context, this, mAppInstallDir); 1716 1717 // Now after opening every single application zip, make sure they 1718 // are all flushed. Not really needed, but keeps things nice and 1719 // tidy. 1720 Runtime.getRuntime().gc(); 1721 } 1722 1723 @Override 1724 public boolean isFirstBoot() { 1725 return !mRestoredSettings; 1726 } 1727 1728 @Override 1729 public boolean isOnlyCoreApps() { 1730 return mOnlyCore; 1731 } 1732 1733 private String getRequiredVerifierLPr() { 1734 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 1735 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 1736 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 1737 1738 String requiredVerifier = null; 1739 1740 final int N = receivers.size(); 1741 for (int i = 0; i < N; i++) { 1742 final ResolveInfo info = receivers.get(i); 1743 1744 if (info.activityInfo == null) { 1745 continue; 1746 } 1747 1748 final String packageName = info.activityInfo.packageName; 1749 1750 final PackageSetting ps = mSettings.mPackages.get(packageName); 1751 if (ps == null) { 1752 continue; 1753 } 1754 1755 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1756 if (!gp.grantedPermissions 1757 .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) { 1758 continue; 1759 } 1760 1761 if (requiredVerifier != null) { 1762 throw new RuntimeException("There can be only one required verifier"); 1763 } 1764 1765 requiredVerifier = packageName; 1766 } 1767 1768 return requiredVerifier; 1769 } 1770 1771 @Override 1772 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 1773 throws RemoteException { 1774 try { 1775 return super.onTransact(code, data, reply, flags); 1776 } catch (RuntimeException e) { 1777 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 1778 Slog.wtf(TAG, "Package Manager Crash", e); 1779 } 1780 throw e; 1781 } 1782 } 1783 1784 void cleanupInstallFailedPackage(PackageSetting ps) { 1785 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name); 1786 removeDataDirsLI(ps.name); 1787 1788 // TODO: try cleaning up codePath directory contents first, since it 1789 // might be a cluster 1790 1791 if (ps.codePath != null) { 1792 if (!ps.codePath.delete()) { 1793 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath); 1794 } 1795 } 1796 if (ps.resourcePath != null) { 1797 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) { 1798 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath); 1799 } 1800 } 1801 mSettings.removePackageLPw(ps.name); 1802 } 1803 1804 static int[] appendInts(int[] cur, int[] add) { 1805 if (add == null) return cur; 1806 if (cur == null) return add; 1807 final int N = add.length; 1808 for (int i=0; i<N; i++) { 1809 cur = appendInt(cur, add[i]); 1810 } 1811 return cur; 1812 } 1813 1814 static int[] removeInts(int[] cur, int[] rem) { 1815 if (rem == null) return cur; 1816 if (cur == null) return cur; 1817 final int N = rem.length; 1818 for (int i=0; i<N; i++) { 1819 cur = removeInt(cur, rem[i]); 1820 } 1821 return cur; 1822 } 1823 1824 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 1825 if (!sUserManager.exists(userId)) return null; 1826 final PackageSetting ps = (PackageSetting) p.mExtras; 1827 if (ps == null) { 1828 return null; 1829 } 1830 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1831 final PackageUserState state = ps.readUserState(userId); 1832 return PackageParser.generatePackageInfo(p, gp.gids, flags, 1833 ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions, 1834 state, userId); 1835 } 1836 1837 @Override 1838 public boolean isPackageAvailable(String packageName, int userId) { 1839 if (!sUserManager.exists(userId)) return false; 1840 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available"); 1841 synchronized (mPackages) { 1842 PackageParser.Package p = mPackages.get(packageName); 1843 if (p != null) { 1844 final PackageSetting ps = (PackageSetting) p.mExtras; 1845 if (ps != null) { 1846 final PackageUserState state = ps.readUserState(userId); 1847 if (state != null) { 1848 return PackageParser.isAvailable(state); 1849 } 1850 } 1851 } 1852 } 1853 return false; 1854 } 1855 1856 @Override 1857 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 1858 if (!sUserManager.exists(userId)) return null; 1859 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info"); 1860 // reader 1861 synchronized (mPackages) { 1862 PackageParser.Package p = mPackages.get(packageName); 1863 if (DEBUG_PACKAGE_INFO) 1864 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 1865 if (p != null) { 1866 return generatePackageInfo(p, flags, userId); 1867 } 1868 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 1869 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 1870 } 1871 } 1872 return null; 1873 } 1874 1875 @Override 1876 public String[] currentToCanonicalPackageNames(String[] names) { 1877 String[] out = new String[names.length]; 1878 // reader 1879 synchronized (mPackages) { 1880 for (int i=names.length-1; i>=0; i--) { 1881 PackageSetting ps = mSettings.mPackages.get(names[i]); 1882 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 1883 } 1884 } 1885 return out; 1886 } 1887 1888 @Override 1889 public String[] canonicalToCurrentPackageNames(String[] names) { 1890 String[] out = new String[names.length]; 1891 // reader 1892 synchronized (mPackages) { 1893 for (int i=names.length-1; i>=0; i--) { 1894 String cur = mSettings.mRenamedPackages.get(names[i]); 1895 out[i] = cur != null ? cur : names[i]; 1896 } 1897 } 1898 return out; 1899 } 1900 1901 @Override 1902 public int getPackageUid(String packageName, int userId) { 1903 if (!sUserManager.exists(userId)) return -1; 1904 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid"); 1905 // reader 1906 synchronized (mPackages) { 1907 PackageParser.Package p = mPackages.get(packageName); 1908 if(p != null) { 1909 return UserHandle.getUid(userId, p.applicationInfo.uid); 1910 } 1911 PackageSetting ps = mSettings.mPackages.get(packageName); 1912 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 1913 return -1; 1914 } 1915 p = ps.pkg; 1916 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 1917 } 1918 } 1919 1920 @Override 1921 public int[] getPackageGids(String packageName) { 1922 // reader 1923 synchronized (mPackages) { 1924 PackageParser.Package p = mPackages.get(packageName); 1925 if (DEBUG_PACKAGE_INFO) 1926 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 1927 if (p != null) { 1928 final PackageSetting ps = (PackageSetting)p.mExtras; 1929 return ps.getGids(); 1930 } 1931 } 1932 // stupid thing to indicate an error. 1933 return new int[0]; 1934 } 1935 1936 static final PermissionInfo generatePermissionInfo( 1937 BasePermission bp, int flags) { 1938 if (bp.perm != null) { 1939 return PackageParser.generatePermissionInfo(bp.perm, flags); 1940 } 1941 PermissionInfo pi = new PermissionInfo(); 1942 pi.name = bp.name; 1943 pi.packageName = bp.sourcePackage; 1944 pi.nonLocalizedLabel = bp.name; 1945 pi.protectionLevel = bp.protectionLevel; 1946 return pi; 1947 } 1948 1949 @Override 1950 public PermissionInfo getPermissionInfo(String name, int flags) { 1951 // reader 1952 synchronized (mPackages) { 1953 final BasePermission p = mSettings.mPermissions.get(name); 1954 if (p != null) { 1955 return generatePermissionInfo(p, flags); 1956 } 1957 return null; 1958 } 1959 } 1960 1961 @Override 1962 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 1963 // reader 1964 synchronized (mPackages) { 1965 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 1966 for (BasePermission p : mSettings.mPermissions.values()) { 1967 if (group == null) { 1968 if (p.perm == null || p.perm.info.group == null) { 1969 out.add(generatePermissionInfo(p, flags)); 1970 } 1971 } else { 1972 if (p.perm != null && group.equals(p.perm.info.group)) { 1973 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 1974 } 1975 } 1976 } 1977 1978 if (out.size() > 0) { 1979 return out; 1980 } 1981 return mPermissionGroups.containsKey(group) ? out : null; 1982 } 1983 } 1984 1985 @Override 1986 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 1987 // reader 1988 synchronized (mPackages) { 1989 return PackageParser.generatePermissionGroupInfo( 1990 mPermissionGroups.get(name), flags); 1991 } 1992 } 1993 1994 @Override 1995 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 1996 // reader 1997 synchronized (mPackages) { 1998 final int N = mPermissionGroups.size(); 1999 ArrayList<PermissionGroupInfo> out 2000 = new ArrayList<PermissionGroupInfo>(N); 2001 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2002 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2003 } 2004 return out; 2005 } 2006 } 2007 2008 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2009 int userId) { 2010 if (!sUserManager.exists(userId)) return null; 2011 PackageSetting ps = mSettings.mPackages.get(packageName); 2012 if (ps != null) { 2013 if (ps.pkg == null) { 2014 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2015 flags, userId); 2016 if (pInfo != null) { 2017 return pInfo.applicationInfo; 2018 } 2019 return null; 2020 } 2021 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2022 ps.readUserState(userId), userId); 2023 } 2024 return null; 2025 } 2026 2027 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2028 int userId) { 2029 if (!sUserManager.exists(userId)) return null; 2030 PackageSetting ps = mSettings.mPackages.get(packageName); 2031 if (ps != null) { 2032 PackageParser.Package pkg = ps.pkg; 2033 if (pkg == null) { 2034 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2035 return null; 2036 } 2037 // Only data remains, so we aren't worried about code paths 2038 pkg = new PackageParser.Package(packageName); 2039 pkg.applicationInfo.packageName = packageName; 2040 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2041 pkg.applicationInfo.dataDir = 2042 getDataPathForPackage(packageName, 0).getPath(); 2043 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2044 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2045 } 2046 return generatePackageInfo(pkg, flags, userId); 2047 } 2048 return null; 2049 } 2050 2051 @Override 2052 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2053 if (!sUserManager.exists(userId)) return null; 2054 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info"); 2055 // writer 2056 synchronized (mPackages) { 2057 PackageParser.Package p = mPackages.get(packageName); 2058 if (DEBUG_PACKAGE_INFO) Log.v( 2059 TAG, "getApplicationInfo " + packageName 2060 + ": " + p); 2061 if (p != null) { 2062 PackageSetting ps = mSettings.mPackages.get(packageName); 2063 if (ps == null) return null; 2064 // Note: isEnabledLP() does not apply here - always return info 2065 return PackageParser.generateApplicationInfo( 2066 p, flags, ps.readUserState(userId), userId); 2067 } 2068 if ("android".equals(packageName)||"system".equals(packageName)) { 2069 return mAndroidApplication; 2070 } 2071 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2072 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2073 } 2074 } 2075 return null; 2076 } 2077 2078 2079 @Override 2080 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2081 mContext.enforceCallingOrSelfPermission( 2082 android.Manifest.permission.CLEAR_APP_CACHE, null); 2083 // Queue up an async operation since clearing cache may take a little while. 2084 mHandler.post(new Runnable() { 2085 public void run() { 2086 mHandler.removeCallbacks(this); 2087 int retCode = -1; 2088 synchronized (mInstallLock) { 2089 retCode = mInstaller.freeCache(freeStorageSize); 2090 if (retCode < 0) { 2091 Slog.w(TAG, "Couldn't clear application caches"); 2092 } 2093 } 2094 if (observer != null) { 2095 try { 2096 observer.onRemoveCompleted(null, (retCode >= 0)); 2097 } catch (RemoteException e) { 2098 Slog.w(TAG, "RemoveException when invoking call back"); 2099 } 2100 } 2101 } 2102 }); 2103 } 2104 2105 @Override 2106 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2107 mContext.enforceCallingOrSelfPermission( 2108 android.Manifest.permission.CLEAR_APP_CACHE, null); 2109 // Queue up an async operation since clearing cache may take a little while. 2110 mHandler.post(new Runnable() { 2111 public void run() { 2112 mHandler.removeCallbacks(this); 2113 int retCode = -1; 2114 synchronized (mInstallLock) { 2115 retCode = mInstaller.freeCache(freeStorageSize); 2116 if (retCode < 0) { 2117 Slog.w(TAG, "Couldn't clear application caches"); 2118 } 2119 } 2120 if(pi != null) { 2121 try { 2122 // Callback via pending intent 2123 int code = (retCode >= 0) ? 1 : 0; 2124 pi.sendIntent(null, code, null, 2125 null, null); 2126 } catch (SendIntentException e1) { 2127 Slog.i(TAG, "Failed to send pending intent"); 2128 } 2129 } 2130 } 2131 }); 2132 } 2133 2134 void freeStorage(long freeStorageSize) throws IOException { 2135 synchronized (mInstallLock) { 2136 if (mInstaller.freeCache(freeStorageSize) < 0) { 2137 throw new IOException("Failed to free enough space"); 2138 } 2139 } 2140 } 2141 2142 @Override 2143 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2144 if (!sUserManager.exists(userId)) return null; 2145 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info"); 2146 synchronized (mPackages) { 2147 PackageParser.Activity a = mActivities.mActivities.get(component); 2148 2149 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2150 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2151 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2152 if (ps == null) return null; 2153 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2154 userId); 2155 } 2156 if (mResolveComponentName.equals(component)) { 2157 return mResolveActivity; 2158 } 2159 } 2160 return null; 2161 } 2162 2163 @Override 2164 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2165 String resolvedType) { 2166 synchronized (mPackages) { 2167 PackageParser.Activity a = mActivities.mActivities.get(component); 2168 if (a == null) { 2169 return false; 2170 } 2171 for (int i=0; i<a.intents.size(); i++) { 2172 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2173 intent.getData(), intent.getCategories(), TAG) >= 0) { 2174 return true; 2175 } 2176 } 2177 return false; 2178 } 2179 } 2180 2181 @Override 2182 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2183 if (!sUserManager.exists(userId)) return null; 2184 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info"); 2185 synchronized (mPackages) { 2186 PackageParser.Activity a = mReceivers.mActivities.get(component); 2187 if (DEBUG_PACKAGE_INFO) Log.v( 2188 TAG, "getReceiverInfo " + component + ": " + a); 2189 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2190 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2191 if (ps == null) return null; 2192 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2193 userId); 2194 } 2195 } 2196 return null; 2197 } 2198 2199 @Override 2200 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2201 if (!sUserManager.exists(userId)) return null; 2202 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info"); 2203 synchronized (mPackages) { 2204 PackageParser.Service s = mServices.mServices.get(component); 2205 if (DEBUG_PACKAGE_INFO) Log.v( 2206 TAG, "getServiceInfo " + component + ": " + s); 2207 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2208 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2209 if (ps == null) return null; 2210 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2211 userId); 2212 } 2213 } 2214 return null; 2215 } 2216 2217 @Override 2218 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2219 if (!sUserManager.exists(userId)) return null; 2220 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info"); 2221 synchronized (mPackages) { 2222 PackageParser.Provider p = mProviders.mProviders.get(component); 2223 if (DEBUG_PACKAGE_INFO) Log.v( 2224 TAG, "getProviderInfo " + component + ": " + p); 2225 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2226 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2227 if (ps == null) return null; 2228 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2229 userId); 2230 } 2231 } 2232 return null; 2233 } 2234 2235 @Override 2236 public String[] getSystemSharedLibraryNames() { 2237 Set<String> libSet; 2238 synchronized (mPackages) { 2239 libSet = mSharedLibraries.keySet(); 2240 int size = libSet.size(); 2241 if (size > 0) { 2242 String[] libs = new String[size]; 2243 libSet.toArray(libs); 2244 return libs; 2245 } 2246 } 2247 return null; 2248 } 2249 2250 @Override 2251 public FeatureInfo[] getSystemAvailableFeatures() { 2252 Collection<FeatureInfo> featSet; 2253 synchronized (mPackages) { 2254 featSet = mAvailableFeatures.values(); 2255 int size = featSet.size(); 2256 if (size > 0) { 2257 FeatureInfo[] features = new FeatureInfo[size+1]; 2258 featSet.toArray(features); 2259 FeatureInfo fi = new FeatureInfo(); 2260 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2261 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2262 features[size] = fi; 2263 return features; 2264 } 2265 } 2266 return null; 2267 } 2268 2269 @Override 2270 public boolean hasSystemFeature(String name) { 2271 synchronized (mPackages) { 2272 return mAvailableFeatures.containsKey(name); 2273 } 2274 } 2275 2276 private void checkValidCaller(int uid, int userId) { 2277 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2278 return; 2279 2280 throw new SecurityException("Caller uid=" + uid 2281 + " is not privileged to communicate with user=" + userId); 2282 } 2283 2284 @Override 2285 public int checkPermission(String permName, String pkgName) { 2286 synchronized (mPackages) { 2287 PackageParser.Package p = mPackages.get(pkgName); 2288 if (p != null && p.mExtras != null) { 2289 PackageSetting ps = (PackageSetting)p.mExtras; 2290 if (ps.sharedUser != null) { 2291 if (ps.sharedUser.grantedPermissions.contains(permName)) { 2292 return PackageManager.PERMISSION_GRANTED; 2293 } 2294 } else if (ps.grantedPermissions.contains(permName)) { 2295 return PackageManager.PERMISSION_GRANTED; 2296 } 2297 } 2298 } 2299 return PackageManager.PERMISSION_DENIED; 2300 } 2301 2302 @Override 2303 public int checkUidPermission(String permName, int uid) { 2304 synchronized (mPackages) { 2305 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2306 if (obj != null) { 2307 GrantedPermissions gp = (GrantedPermissions)obj; 2308 if (gp.grantedPermissions.contains(permName)) { 2309 return PackageManager.PERMISSION_GRANTED; 2310 } 2311 } else { 2312 HashSet<String> perms = mSystemPermissions.get(uid); 2313 if (perms != null && perms.contains(permName)) { 2314 return PackageManager.PERMISSION_GRANTED; 2315 } 2316 } 2317 } 2318 return PackageManager.PERMISSION_DENIED; 2319 } 2320 2321 /** 2322 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2323 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2324 * @param message the message to log on security exception 2325 */ 2326 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2327 String message) { 2328 if (userId < 0) { 2329 throw new IllegalArgumentException("Invalid userId " + userId); 2330 } 2331 if (userId == UserHandle.getUserId(callingUid)) return; 2332 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2333 if (requireFullPermission) { 2334 mContext.enforceCallingOrSelfPermission( 2335 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2336 } else { 2337 try { 2338 mContext.enforceCallingOrSelfPermission( 2339 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2340 } catch (SecurityException se) { 2341 mContext.enforceCallingOrSelfPermission( 2342 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2343 } 2344 } 2345 } 2346 } 2347 2348 private BasePermission findPermissionTreeLP(String permName) { 2349 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2350 if (permName.startsWith(bp.name) && 2351 permName.length() > bp.name.length() && 2352 permName.charAt(bp.name.length()) == '.') { 2353 return bp; 2354 } 2355 } 2356 return null; 2357 } 2358 2359 private BasePermission checkPermissionTreeLP(String permName) { 2360 if (permName != null) { 2361 BasePermission bp = findPermissionTreeLP(permName); 2362 if (bp != null) { 2363 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2364 return bp; 2365 } 2366 throw new SecurityException("Calling uid " 2367 + Binder.getCallingUid() 2368 + " is not allowed to add to permission tree " 2369 + bp.name + " owned by uid " + bp.uid); 2370 } 2371 } 2372 throw new SecurityException("No permission tree found for " + permName); 2373 } 2374 2375 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2376 if (s1 == null) { 2377 return s2 == null; 2378 } 2379 if (s2 == null) { 2380 return false; 2381 } 2382 if (s1.getClass() != s2.getClass()) { 2383 return false; 2384 } 2385 return s1.equals(s2); 2386 } 2387 2388 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2389 if (pi1.icon != pi2.icon) return false; 2390 if (pi1.logo != pi2.logo) return false; 2391 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2392 if (!compareStrings(pi1.name, pi2.name)) return false; 2393 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2394 // We'll take care of setting this one. 2395 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2396 // These are not currently stored in settings. 2397 //if (!compareStrings(pi1.group, pi2.group)) return false; 2398 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2399 //if (pi1.labelRes != pi2.labelRes) return false; 2400 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2401 return true; 2402 } 2403 2404 int permissionInfoFootprint(PermissionInfo info) { 2405 int size = info.name.length(); 2406 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2407 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2408 return size; 2409 } 2410 2411 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2412 int size = 0; 2413 for (BasePermission perm : mSettings.mPermissions.values()) { 2414 if (perm.uid == tree.uid) { 2415 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2416 } 2417 } 2418 return size; 2419 } 2420 2421 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2422 // We calculate the max size of permissions defined by this uid and throw 2423 // if that plus the size of 'info' would exceed our stated maximum. 2424 if (tree.uid != Process.SYSTEM_UID) { 2425 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2426 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2427 throw new SecurityException("Permission tree size cap exceeded"); 2428 } 2429 } 2430 } 2431 2432 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2433 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2434 throw new SecurityException("Label must be specified in permission"); 2435 } 2436 BasePermission tree = checkPermissionTreeLP(info.name); 2437 BasePermission bp = mSettings.mPermissions.get(info.name); 2438 boolean added = bp == null; 2439 boolean changed = true; 2440 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2441 if (added) { 2442 enforcePermissionCapLocked(info, tree); 2443 bp = new BasePermission(info.name, tree.sourcePackage, 2444 BasePermission.TYPE_DYNAMIC); 2445 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2446 throw new SecurityException( 2447 "Not allowed to modify non-dynamic permission " 2448 + info.name); 2449 } else { 2450 if (bp.protectionLevel == fixedLevel 2451 && bp.perm.owner.equals(tree.perm.owner) 2452 && bp.uid == tree.uid 2453 && comparePermissionInfos(bp.perm.info, info)) { 2454 changed = false; 2455 } 2456 } 2457 bp.protectionLevel = fixedLevel; 2458 info = new PermissionInfo(info); 2459 info.protectionLevel = fixedLevel; 2460 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 2461 bp.perm.info.packageName = tree.perm.info.packageName; 2462 bp.uid = tree.uid; 2463 if (added) { 2464 mSettings.mPermissions.put(info.name, bp); 2465 } 2466 if (changed) { 2467 if (!async) { 2468 mSettings.writeLPr(); 2469 } else { 2470 scheduleWriteSettingsLocked(); 2471 } 2472 } 2473 return added; 2474 } 2475 2476 @Override 2477 public boolean addPermission(PermissionInfo info) { 2478 synchronized (mPackages) { 2479 return addPermissionLocked(info, false); 2480 } 2481 } 2482 2483 @Override 2484 public boolean addPermissionAsync(PermissionInfo info) { 2485 synchronized (mPackages) { 2486 return addPermissionLocked(info, true); 2487 } 2488 } 2489 2490 @Override 2491 public void removePermission(String name) { 2492 synchronized (mPackages) { 2493 checkPermissionTreeLP(name); 2494 BasePermission bp = mSettings.mPermissions.get(name); 2495 if (bp != null) { 2496 if (bp.type != BasePermission.TYPE_DYNAMIC) { 2497 throw new SecurityException( 2498 "Not allowed to modify non-dynamic permission " 2499 + name); 2500 } 2501 mSettings.mPermissions.remove(name); 2502 mSettings.writeLPr(); 2503 } 2504 } 2505 } 2506 2507 private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) { 2508 int index = pkg.requestedPermissions.indexOf(bp.name); 2509 if (index == -1) { 2510 throw new SecurityException("Package " + pkg.packageName 2511 + " has not requested permission " + bp.name); 2512 } 2513 boolean isNormal = 2514 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2515 == PermissionInfo.PROTECTION_NORMAL); 2516 boolean isDangerous = 2517 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2518 == PermissionInfo.PROTECTION_DANGEROUS); 2519 boolean isDevelopment = 2520 ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0); 2521 2522 if (!isNormal && !isDangerous && !isDevelopment) { 2523 throw new SecurityException("Permission " + bp.name 2524 + " is not a changeable permission type"); 2525 } 2526 2527 if (isNormal || isDangerous) { 2528 if (pkg.requestedPermissionsRequired.get(index)) { 2529 throw new SecurityException("Can't change " + bp.name 2530 + ". It is required by the application"); 2531 } 2532 } 2533 } 2534 2535 @Override 2536 public void grantPermission(String packageName, String permissionName) { 2537 mContext.enforceCallingOrSelfPermission( 2538 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2539 synchronized (mPackages) { 2540 final PackageParser.Package pkg = mPackages.get(packageName); 2541 if (pkg == null) { 2542 throw new IllegalArgumentException("Unknown package: " + packageName); 2543 } 2544 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2545 if (bp == null) { 2546 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2547 } 2548 2549 checkGrantRevokePermissions(pkg, bp); 2550 2551 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2552 if (ps == null) { 2553 return; 2554 } 2555 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2556 if (gp.grantedPermissions.add(permissionName)) { 2557 if (ps.haveGids) { 2558 gp.gids = appendInts(gp.gids, bp.gids); 2559 } 2560 mSettings.writeLPr(); 2561 } 2562 } 2563 } 2564 2565 @Override 2566 public void revokePermission(String packageName, String permissionName) { 2567 int changedAppId = -1; 2568 2569 synchronized (mPackages) { 2570 final PackageParser.Package pkg = mPackages.get(packageName); 2571 if (pkg == null) { 2572 throw new IllegalArgumentException("Unknown package: " + packageName); 2573 } 2574 if (pkg.applicationInfo.uid != Binder.getCallingUid()) { 2575 mContext.enforceCallingOrSelfPermission( 2576 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2577 } 2578 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2579 if (bp == null) { 2580 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2581 } 2582 2583 checkGrantRevokePermissions(pkg, bp); 2584 2585 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2586 if (ps == null) { 2587 return; 2588 } 2589 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2590 if (gp.grantedPermissions.remove(permissionName)) { 2591 gp.grantedPermissions.remove(permissionName); 2592 if (ps.haveGids) { 2593 gp.gids = removeInts(gp.gids, bp.gids); 2594 } 2595 mSettings.writeLPr(); 2596 changedAppId = ps.appId; 2597 } 2598 } 2599 2600 if (changedAppId >= 0) { 2601 // We changed the perm on someone, kill its processes. 2602 IActivityManager am = ActivityManagerNative.getDefault(); 2603 if (am != null) { 2604 final int callingUserId = UserHandle.getCallingUserId(); 2605 final long ident = Binder.clearCallingIdentity(); 2606 try { 2607 //XXX we should only revoke for the calling user's app permissions, 2608 // but for now we impact all users. 2609 //am.killUid(UserHandle.getUid(callingUserId, changedAppId), 2610 // "revoke " + permissionName); 2611 int[] users = sUserManager.getUserIds(); 2612 for (int user : users) { 2613 am.killUid(UserHandle.getUid(user, changedAppId), 2614 "revoke " + permissionName); 2615 } 2616 } catch (RemoteException e) { 2617 } finally { 2618 Binder.restoreCallingIdentity(ident); 2619 } 2620 } 2621 } 2622 } 2623 2624 @Override 2625 public boolean isProtectedBroadcast(String actionName) { 2626 synchronized (mPackages) { 2627 return mProtectedBroadcasts.contains(actionName); 2628 } 2629 } 2630 2631 @Override 2632 public int checkSignatures(String pkg1, String pkg2) { 2633 synchronized (mPackages) { 2634 final PackageParser.Package p1 = mPackages.get(pkg1); 2635 final PackageParser.Package p2 = mPackages.get(pkg2); 2636 if (p1 == null || p1.mExtras == null 2637 || p2 == null || p2.mExtras == null) { 2638 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2639 } 2640 return compareSignatures(p1.mSignatures, p2.mSignatures); 2641 } 2642 } 2643 2644 @Override 2645 public int checkUidSignatures(int uid1, int uid2) { 2646 // Map to base uids. 2647 uid1 = UserHandle.getAppId(uid1); 2648 uid2 = UserHandle.getAppId(uid2); 2649 // reader 2650 synchronized (mPackages) { 2651 Signature[] s1; 2652 Signature[] s2; 2653 Object obj = mSettings.getUserIdLPr(uid1); 2654 if (obj != null) { 2655 if (obj instanceof SharedUserSetting) { 2656 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 2657 } else if (obj instanceof PackageSetting) { 2658 s1 = ((PackageSetting)obj).signatures.mSignatures; 2659 } else { 2660 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2661 } 2662 } else { 2663 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2664 } 2665 obj = mSettings.getUserIdLPr(uid2); 2666 if (obj != null) { 2667 if (obj instanceof SharedUserSetting) { 2668 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 2669 } else if (obj instanceof PackageSetting) { 2670 s2 = ((PackageSetting)obj).signatures.mSignatures; 2671 } else { 2672 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2673 } 2674 } else { 2675 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2676 } 2677 return compareSignatures(s1, s2); 2678 } 2679 } 2680 2681 /** 2682 * Compares two sets of signatures. Returns: 2683 * <br /> 2684 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 2685 * <br /> 2686 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 2687 * <br /> 2688 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 2689 * <br /> 2690 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 2691 * <br /> 2692 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 2693 */ 2694 static int compareSignatures(Signature[] s1, Signature[] s2) { 2695 if (s1 == null) { 2696 return s2 == null 2697 ? PackageManager.SIGNATURE_NEITHER_SIGNED 2698 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 2699 } 2700 2701 if (s2 == null) { 2702 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 2703 } 2704 2705 if (s1.length != s2.length) { 2706 return PackageManager.SIGNATURE_NO_MATCH; 2707 } 2708 2709 // Since both signature sets are of size 1, we can compare without HashSets. 2710 if (s1.length == 1) { 2711 return s1[0].equals(s2[0]) ? 2712 PackageManager.SIGNATURE_MATCH : 2713 PackageManager.SIGNATURE_NO_MATCH; 2714 } 2715 2716 HashSet<Signature> set1 = new HashSet<Signature>(); 2717 for (Signature sig : s1) { 2718 set1.add(sig); 2719 } 2720 HashSet<Signature> set2 = new HashSet<Signature>(); 2721 for (Signature sig : s2) { 2722 set2.add(sig); 2723 } 2724 // Make sure s2 contains all signatures in s1. 2725 if (set1.equals(set2)) { 2726 return PackageManager.SIGNATURE_MATCH; 2727 } 2728 return PackageManager.SIGNATURE_NO_MATCH; 2729 } 2730 2731 /** 2732 * If the database version for this type of package (internal storage or 2733 * external storage) is less than the version where package signatures 2734 * were updated, return true. 2735 */ 2736 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2737 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 2738 DatabaseVersion.SIGNATURE_END_ENTITY)) 2739 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 2740 DatabaseVersion.SIGNATURE_END_ENTITY)); 2741 } 2742 2743 /** 2744 * Used for backward compatibility to make sure any packages with 2745 * certificate chains get upgraded to the new style. {@code existingSigs} 2746 * will be in the old format (since they were stored on disk from before the 2747 * system upgrade) and {@code scannedSigs} will be in the newer format. 2748 */ 2749 private int compareSignaturesCompat(PackageSignatures existingSigs, 2750 PackageParser.Package scannedPkg) { 2751 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 2752 return PackageManager.SIGNATURE_NO_MATCH; 2753 } 2754 2755 HashSet<Signature> existingSet = new HashSet<Signature>(); 2756 for (Signature sig : existingSigs.mSignatures) { 2757 existingSet.add(sig); 2758 } 2759 HashSet<Signature> scannedCompatSet = new HashSet<Signature>(); 2760 for (Signature sig : scannedPkg.mSignatures) { 2761 try { 2762 Signature[] chainSignatures = sig.getChainSignatures(); 2763 for (Signature chainSig : chainSignatures) { 2764 scannedCompatSet.add(chainSig); 2765 } 2766 } catch (CertificateEncodingException e) { 2767 scannedCompatSet.add(sig); 2768 } 2769 } 2770 /* 2771 * Make sure the expanded scanned set contains all signatures in the 2772 * existing one. 2773 */ 2774 if (scannedCompatSet.equals(existingSet)) { 2775 // Migrate the old signatures to the new scheme. 2776 existingSigs.assignSignatures(scannedPkg.mSignatures); 2777 // The new KeySets will be re-added later in the scanning process. 2778 synchronized (mPackages) { 2779 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 2780 } 2781 return PackageManager.SIGNATURE_MATCH; 2782 } 2783 return PackageManager.SIGNATURE_NO_MATCH; 2784 } 2785 2786 @Override 2787 public String[] getPackagesForUid(int uid) { 2788 uid = UserHandle.getAppId(uid); 2789 // reader 2790 synchronized (mPackages) { 2791 Object obj = mSettings.getUserIdLPr(uid); 2792 if (obj instanceof SharedUserSetting) { 2793 final SharedUserSetting sus = (SharedUserSetting) obj; 2794 final int N = sus.packages.size(); 2795 final String[] res = new String[N]; 2796 final Iterator<PackageSetting> it = sus.packages.iterator(); 2797 int i = 0; 2798 while (it.hasNext()) { 2799 res[i++] = it.next().name; 2800 } 2801 return res; 2802 } else if (obj instanceof PackageSetting) { 2803 final PackageSetting ps = (PackageSetting) obj; 2804 return new String[] { ps.name }; 2805 } 2806 } 2807 return null; 2808 } 2809 2810 @Override 2811 public String getNameForUid(int uid) { 2812 // reader 2813 synchronized (mPackages) { 2814 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2815 if (obj instanceof SharedUserSetting) { 2816 final SharedUserSetting sus = (SharedUserSetting) obj; 2817 return sus.name + ":" + sus.userId; 2818 } else if (obj instanceof PackageSetting) { 2819 final PackageSetting ps = (PackageSetting) obj; 2820 return ps.name; 2821 } 2822 } 2823 return null; 2824 } 2825 2826 @Override 2827 public int getUidForSharedUser(String sharedUserName) { 2828 if(sharedUserName == null) { 2829 return -1; 2830 } 2831 // reader 2832 synchronized (mPackages) { 2833 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false); 2834 if (suid == null) { 2835 return -1; 2836 } 2837 return suid.userId; 2838 } 2839 } 2840 2841 @Override 2842 public int getFlagsForUid(int uid) { 2843 synchronized (mPackages) { 2844 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2845 if (obj instanceof SharedUserSetting) { 2846 final SharedUserSetting sus = (SharedUserSetting) obj; 2847 return sus.pkgFlags; 2848 } else if (obj instanceof PackageSetting) { 2849 final PackageSetting ps = (PackageSetting) obj; 2850 return ps.pkgFlags; 2851 } 2852 } 2853 return 0; 2854 } 2855 2856 @Override 2857 public String[] getAppOpPermissionPackages(String permissionName) { 2858 synchronized (mPackages) { 2859 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 2860 if (pkgs == null) { 2861 return null; 2862 } 2863 return pkgs.toArray(new String[pkgs.size()]); 2864 } 2865 } 2866 2867 @Override 2868 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 2869 int flags, int userId) { 2870 if (!sUserManager.exists(userId)) return null; 2871 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent"); 2872 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2873 return chooseBestActivity(intent, resolvedType, flags, query, userId); 2874 } 2875 2876 @Override 2877 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 2878 IntentFilter filter, int match, ComponentName activity) { 2879 final int userId = UserHandle.getCallingUserId(); 2880 if (DEBUG_PREFERRED) { 2881 Log.v(TAG, "setLastChosenActivity intent=" + intent 2882 + " resolvedType=" + resolvedType 2883 + " flags=" + flags 2884 + " filter=" + filter 2885 + " match=" + match 2886 + " activity=" + activity); 2887 filter.dump(new PrintStreamPrinter(System.out), " "); 2888 } 2889 intent.setComponent(null); 2890 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2891 // Find any earlier preferred or last chosen entries and nuke them 2892 findPreferredActivity(intent, resolvedType, 2893 flags, query, 0, false, true, false, userId); 2894 // Add the new activity as the last chosen for this filter 2895 addPreferredActivityInternal(filter, match, null, activity, false, userId, 2896 "Setting last chosen"); 2897 } 2898 2899 @Override 2900 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 2901 final int userId = UserHandle.getCallingUserId(); 2902 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 2903 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2904 return findPreferredActivity(intent, resolvedType, flags, query, 0, 2905 false, false, false, userId); 2906 } 2907 2908 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 2909 int flags, List<ResolveInfo> query, int userId) { 2910 if (query != null) { 2911 final int N = query.size(); 2912 if (N == 1) { 2913 return query.get(0); 2914 } else if (N > 1) { 2915 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 2916 // If there is more than one activity with the same priority, 2917 // then let the user decide between them. 2918 ResolveInfo r0 = query.get(0); 2919 ResolveInfo r1 = query.get(1); 2920 if (DEBUG_INTENT_MATCHING || debug) { 2921 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 2922 + r1.activityInfo.name + "=" + r1.priority); 2923 } 2924 // If the first activity has a higher priority, or a different 2925 // default, then it is always desireable to pick it. 2926 if (r0.priority != r1.priority 2927 || r0.preferredOrder != r1.preferredOrder 2928 || r0.isDefault != r1.isDefault) { 2929 return query.get(0); 2930 } 2931 // If we have saved a preference for a preferred activity for 2932 // this Intent, use that. 2933 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 2934 flags, query, r0.priority, true, false, debug, userId); 2935 if (ri != null) { 2936 return ri; 2937 } 2938 if (userId != 0) { 2939 ri = new ResolveInfo(mResolveInfo); 2940 ri.activityInfo = new ActivityInfo(ri.activityInfo); 2941 ri.activityInfo.applicationInfo = new ApplicationInfo( 2942 ri.activityInfo.applicationInfo); 2943 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 2944 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 2945 return ri; 2946 } 2947 return mResolveInfo; 2948 } 2949 } 2950 return null; 2951 } 2952 2953 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 2954 int flags, List<ResolveInfo> query, boolean debug, int userId) { 2955 final int N = query.size(); 2956 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 2957 .get(userId); 2958 // Get the list of persistent preferred activities that handle the intent 2959 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 2960 List<PersistentPreferredActivity> pprefs = ppir != null 2961 ? ppir.queryIntent(intent, resolvedType, 2962 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 2963 : null; 2964 if (pprefs != null && pprefs.size() > 0) { 2965 final int M = pprefs.size(); 2966 for (int i=0; i<M; i++) { 2967 final PersistentPreferredActivity ppa = pprefs.get(i); 2968 if (DEBUG_PREFERRED || debug) { 2969 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 2970 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 2971 + "\n component=" + ppa.mComponent); 2972 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 2973 } 2974 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 2975 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 2976 if (DEBUG_PREFERRED || debug) { 2977 Slog.v(TAG, "Found persistent preferred activity:"); 2978 if (ai != null) { 2979 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 2980 } else { 2981 Slog.v(TAG, " null"); 2982 } 2983 } 2984 if (ai == null) { 2985 // This previously registered persistent preferred activity 2986 // component is no longer known. Ignore it and do NOT remove it. 2987 continue; 2988 } 2989 for (int j=0; j<N; j++) { 2990 final ResolveInfo ri = query.get(j); 2991 if (!ri.activityInfo.applicationInfo.packageName 2992 .equals(ai.applicationInfo.packageName)) { 2993 continue; 2994 } 2995 if (!ri.activityInfo.name.equals(ai.name)) { 2996 continue; 2997 } 2998 // Found a persistent preference that can handle the intent. 2999 if (DEBUG_PREFERRED || debug) { 3000 Slog.v(TAG, "Returning persistent preferred activity: " + 3001 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3002 } 3003 return ri; 3004 } 3005 } 3006 } 3007 return null; 3008 } 3009 3010 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3011 List<ResolveInfo> query, int priority, boolean always, 3012 boolean removeMatches, boolean debug, int userId) { 3013 if (!sUserManager.exists(userId)) return null; 3014 // writer 3015 synchronized (mPackages) { 3016 if (intent.getSelector() != null) { 3017 intent = intent.getSelector(); 3018 } 3019 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3020 3021 // Try to find a matching persistent preferred activity. 3022 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3023 debug, userId); 3024 3025 // If a persistent preferred activity matched, use it. 3026 if (pri != null) { 3027 return pri; 3028 } 3029 3030 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3031 // Get the list of preferred activities that handle the intent 3032 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3033 List<PreferredActivity> prefs = pir != null 3034 ? pir.queryIntent(intent, resolvedType, 3035 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3036 : null; 3037 if (prefs != null && prefs.size() > 0) { 3038 boolean changed = false; 3039 try { 3040 // First figure out how good the original match set is. 3041 // We will only allow preferred activities that came 3042 // from the same match quality. 3043 int match = 0; 3044 3045 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3046 3047 final int N = query.size(); 3048 for (int j=0; j<N; j++) { 3049 final ResolveInfo ri = query.get(j); 3050 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3051 + ": 0x" + Integer.toHexString(match)); 3052 if (ri.match > match) { 3053 match = ri.match; 3054 } 3055 } 3056 3057 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3058 + Integer.toHexString(match)); 3059 3060 match &= IntentFilter.MATCH_CATEGORY_MASK; 3061 final int M = prefs.size(); 3062 for (int i=0; i<M; i++) { 3063 final PreferredActivity pa = prefs.get(i); 3064 if (DEBUG_PREFERRED || debug) { 3065 Slog.v(TAG, "Checking PreferredActivity ds=" 3066 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3067 + "\n component=" + pa.mPref.mComponent); 3068 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3069 } 3070 if (pa.mPref.mMatch != match) { 3071 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3072 + Integer.toHexString(pa.mPref.mMatch)); 3073 continue; 3074 } 3075 // If it's not an "always" type preferred activity and that's what we're 3076 // looking for, skip it. 3077 if (always && !pa.mPref.mAlways) { 3078 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3079 continue; 3080 } 3081 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3082 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3083 if (DEBUG_PREFERRED || debug) { 3084 Slog.v(TAG, "Found preferred activity:"); 3085 if (ai != null) { 3086 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3087 } else { 3088 Slog.v(TAG, " null"); 3089 } 3090 } 3091 if (ai == null) { 3092 // This previously registered preferred activity 3093 // component is no longer known. Most likely an update 3094 // to the app was installed and in the new version this 3095 // component no longer exists. Clean it up by removing 3096 // it from the preferred activities list, and skip it. 3097 Slog.w(TAG, "Removing dangling preferred activity: " 3098 + pa.mPref.mComponent); 3099 pir.removeFilter(pa); 3100 changed = true; 3101 continue; 3102 } 3103 for (int j=0; j<N; j++) { 3104 final ResolveInfo ri = query.get(j); 3105 if (!ri.activityInfo.applicationInfo.packageName 3106 .equals(ai.applicationInfo.packageName)) { 3107 continue; 3108 } 3109 if (!ri.activityInfo.name.equals(ai.name)) { 3110 continue; 3111 } 3112 3113 if (removeMatches) { 3114 pir.removeFilter(pa); 3115 changed = true; 3116 if (DEBUG_PREFERRED) { 3117 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3118 } 3119 break; 3120 } 3121 3122 // Okay we found a previously set preferred or last chosen app. 3123 // If the result set is different from when this 3124 // was created, we need to clear it and re-ask the 3125 // user their preference, if we're looking for an "always" type entry. 3126 if (always && !pa.mPref.sameSet(query, priority)) { 3127 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3128 + intent + " type " + resolvedType); 3129 if (DEBUG_PREFERRED) { 3130 Slog.v(TAG, "Removing preferred activity since set changed " 3131 + pa.mPref.mComponent); 3132 } 3133 pir.removeFilter(pa); 3134 // Re-add the filter as a "last chosen" entry (!always) 3135 PreferredActivity lastChosen = new PreferredActivity( 3136 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3137 pir.addFilter(lastChosen); 3138 changed = true; 3139 return null; 3140 } 3141 3142 // Yay! Either the set matched or we're looking for the last chosen 3143 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3144 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3145 return ri; 3146 } 3147 } 3148 } finally { 3149 if (changed) { 3150 if (DEBUG_PREFERRED) { 3151 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 3152 } 3153 mSettings.writePackageRestrictionsLPr(userId); 3154 } 3155 } 3156 } 3157 } 3158 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3159 return null; 3160 } 3161 3162 /* 3163 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3164 */ 3165 @Override 3166 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3167 int targetUserId) { 3168 mContext.enforceCallingOrSelfPermission( 3169 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3170 List<CrossProfileIntentFilter> matches = 3171 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3172 if (matches != null) { 3173 int size = matches.size(); 3174 for (int i = 0; i < size; i++) { 3175 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3176 } 3177 } 3178 ArrayList<String> packageNames = null; 3179 SparseArray<ArrayList<String>> fromSource = 3180 mSettings.mCrossProfilePackageInfo.get(sourceUserId); 3181 if (fromSource != null) { 3182 packageNames = fromSource.get(targetUserId); 3183 if (packageNames != null) { 3184 // We need the package name, so we try to resolve with the loosest flags possible 3185 List<ResolveInfo> resolveInfos = mActivities.queryIntent(intent, resolvedType, 3186 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 } 3195 } 3196 return false; 3197 } 3198 3199 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3200 String resolvedType, int userId) { 3201 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3202 if (resolver != null) { 3203 return resolver.queryIntent(intent, resolvedType, false, userId); 3204 } 3205 return null; 3206 } 3207 3208 @Override 3209 public List<ResolveInfo> queryIntentActivities(Intent intent, 3210 String resolvedType, int flags, int userId) { 3211 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3212 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities"); 3213 ComponentName comp = intent.getComponent(); 3214 if (comp == null) { 3215 if (intent.getSelector() != null) { 3216 intent = intent.getSelector(); 3217 comp = intent.getComponent(); 3218 } 3219 } 3220 3221 if (comp != null) { 3222 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3223 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3224 if (ai != null) { 3225 final ResolveInfo ri = new ResolveInfo(); 3226 ri.activityInfo = ai; 3227 list.add(ri); 3228 } 3229 return list; 3230 } 3231 3232 // reader 3233 synchronized (mPackages) { 3234 final String pkgName = intent.getPackage(); 3235 boolean queryCrossProfile = (flags & PackageManager.NO_CROSS_PROFILE) == 0; 3236 if (pkgName == null) { 3237 ResolveInfo resolveInfo = null; 3238 if (queryCrossProfile) { 3239 // Check if the intent needs to be forwarded to another user for this package 3240 ArrayList<ResolveInfo> crossProfileResult = 3241 queryIntentActivitiesCrossProfilePackage( 3242 intent, resolvedType, flags, userId); 3243 if (!crossProfileResult.isEmpty()) { 3244 // Skip the current profile 3245 return crossProfileResult; 3246 } 3247 List<CrossProfileIntentFilter> matchingFilters = 3248 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3249 // Check for results that need to skip the current profile. 3250 resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3251 resolvedType, flags, userId); 3252 if (resolveInfo != null) { 3253 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3254 result.add(resolveInfo); 3255 return result; 3256 } 3257 // Check for cross profile results. 3258 resolveInfo = queryCrossProfileIntents( 3259 matchingFilters, intent, resolvedType, flags, userId); 3260 } 3261 // Check for results in the current profile. 3262 List<ResolveInfo> result = mActivities.queryIntent( 3263 intent, resolvedType, flags, userId); 3264 if (resolveInfo != null) { 3265 result.add(resolveInfo); 3266 Collections.sort(result, mResolvePrioritySorter); 3267 } 3268 return result; 3269 } 3270 final PackageParser.Package pkg = mPackages.get(pkgName); 3271 if (pkg != null) { 3272 if (queryCrossProfile) { 3273 ArrayList<ResolveInfo> crossProfileResult = 3274 queryIntentActivitiesCrossProfilePackage( 3275 intent, resolvedType, flags, userId, pkg, pkgName); 3276 if (!crossProfileResult.isEmpty()) { 3277 // Skip the current profile 3278 return crossProfileResult; 3279 } 3280 } 3281 return mActivities.queryIntentForPackage(intent, resolvedType, flags, 3282 pkg.activities, userId); 3283 } 3284 return new ArrayList<ResolveInfo>(); 3285 } 3286 } 3287 3288 private ResolveInfo querySkipCurrentProfileIntents( 3289 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3290 int flags, int sourceUserId) { 3291 if (matchingFilters != null) { 3292 int size = matchingFilters.size(); 3293 for (int i = 0; i < size; i ++) { 3294 CrossProfileIntentFilter filter = matchingFilters.get(i); 3295 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 3296 // Checking if there are activities in the target user that can handle the 3297 // intent. 3298 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3299 flags, sourceUserId); 3300 if (resolveInfo != null) { 3301 return resolveInfo; 3302 } 3303 } 3304 } 3305 } 3306 return null; 3307 } 3308 3309 private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage( 3310 Intent intent, String resolvedType, int flags, int userId) { 3311 ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>(); 3312 SparseArray<ArrayList<String>> sourceForwardingInfo = 3313 mSettings.mCrossProfilePackageInfo.get(userId); 3314 if (sourceForwardingInfo != null) { 3315 int NI = sourceForwardingInfo.size(); 3316 for (int i = 0; i < NI; i++) { 3317 int targetUserId = sourceForwardingInfo.keyAt(i); 3318 ArrayList<String> packageNames = sourceForwardingInfo.valueAt(i); 3319 List<ResolveInfo> resolveInfos = mActivities.queryIntent( 3320 intent, resolvedType, flags, targetUserId); 3321 int NJ = resolveInfos.size(); 3322 for (int j = 0; j < NJ; j++) { 3323 ResolveInfo resolveInfo = resolveInfos.get(j); 3324 if (packageNames.contains(resolveInfo.activityInfo.packageName)) { 3325 matchingResolveInfos.add(createForwardingResolveInfo( 3326 resolveInfo.filter, userId, targetUserId)); 3327 } 3328 } 3329 } 3330 } 3331 return matchingResolveInfos; 3332 } 3333 3334 private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage( 3335 Intent intent, String resolvedType, int flags, int userId, PackageParser.Package pkg, 3336 String packageName) { 3337 ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>(); 3338 SparseArray<ArrayList<String>> sourceForwardingInfo = 3339 mSettings.mCrossProfilePackageInfo.get(userId); 3340 if (sourceForwardingInfo != null) { 3341 int NI = sourceForwardingInfo.size(); 3342 for (int i = 0; i < NI; i++) { 3343 int targetUserId = sourceForwardingInfo.keyAt(i); 3344 if (sourceForwardingInfo.valueAt(i).contains(packageName)) { 3345 List<ResolveInfo> resolveInfos = mActivities.queryIntentForPackage( 3346 intent, resolvedType, flags, pkg.activities, targetUserId); 3347 int NJ = resolveInfos.size(); 3348 for (int j = 0; j < NJ; j++) { 3349 ResolveInfo resolveInfo = resolveInfos.get(j); 3350 matchingResolveInfos.add(createForwardingResolveInfo( 3351 resolveInfo.filter, userId, targetUserId)); 3352 } 3353 } 3354 } 3355 } 3356 return matchingResolveInfos; 3357 } 3358 3359 // Return matching ResolveInfo if any for skip current profile intent filters. 3360 private ResolveInfo queryCrossProfileIntents( 3361 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3362 int flags, int sourceUserId) { 3363 if (matchingFilters != null) { 3364 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 3365 // match the same intent. For performance reasons, it is better not to 3366 // run queryIntent twice for the same userId 3367 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 3368 int size = matchingFilters.size(); 3369 for (int i = 0; i < size; i++) { 3370 CrossProfileIntentFilter filter = matchingFilters.get(i); 3371 int targetUserId = filter.getTargetUserId(); 3372 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 3373 && !alreadyTriedUserIds.get(targetUserId)) { 3374 // Checking if there are activities in the target user that can handle the 3375 // intent. 3376 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3377 flags, sourceUserId); 3378 if (resolveInfo != null) return resolveInfo; 3379 alreadyTriedUserIds.put(targetUserId, true); 3380 } 3381 } 3382 } 3383 return null; 3384 } 3385 3386 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 3387 String resolvedType, int flags, int sourceUserId) { 3388 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 3389 resolvedType, flags, filter.getTargetUserId()); 3390 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 3391 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 3392 } 3393 return null; 3394 } 3395 3396 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 3397 int sourceUserId, int targetUserId) { 3398 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 3399 String className; 3400 if (targetUserId == UserHandle.USER_OWNER) { 3401 className = FORWARD_INTENT_TO_USER_OWNER; 3402 } else { 3403 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 3404 } 3405 ComponentName forwardingActivityComponentName = new ComponentName( 3406 mAndroidApplication.packageName, className); 3407 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 3408 sourceUserId); 3409 if (targetUserId == UserHandle.USER_OWNER) { 3410 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 3411 forwardingResolveInfo.noResourceId = true; 3412 } 3413 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 3414 forwardingResolveInfo.priority = 0; 3415 forwardingResolveInfo.preferredOrder = 0; 3416 forwardingResolveInfo.match = 0; 3417 forwardingResolveInfo.isDefault = true; 3418 forwardingResolveInfo.filter = filter; 3419 forwardingResolveInfo.targetUserId = targetUserId; 3420 return forwardingResolveInfo; 3421 } 3422 3423 @Override 3424 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 3425 Intent[] specifics, String[] specificTypes, Intent intent, 3426 String resolvedType, int flags, int userId) { 3427 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3428 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 3429 "query intent activity options"); 3430 final String resultsAction = intent.getAction(); 3431 3432 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 3433 | PackageManager.GET_RESOLVED_FILTER, userId); 3434 3435 if (DEBUG_INTENT_MATCHING) { 3436 Log.v(TAG, "Query " + intent + ": " + results); 3437 } 3438 3439 int specificsPos = 0; 3440 int N; 3441 3442 // todo: note that the algorithm used here is O(N^2). This 3443 // isn't a problem in our current environment, but if we start running 3444 // into situations where we have more than 5 or 10 matches then this 3445 // should probably be changed to something smarter... 3446 3447 // First we go through and resolve each of the specific items 3448 // that were supplied, taking care of removing any corresponding 3449 // duplicate items in the generic resolve list. 3450 if (specifics != null) { 3451 for (int i=0; i<specifics.length; i++) { 3452 final Intent sintent = specifics[i]; 3453 if (sintent == null) { 3454 continue; 3455 } 3456 3457 if (DEBUG_INTENT_MATCHING) { 3458 Log.v(TAG, "Specific #" + i + ": " + sintent); 3459 } 3460 3461 String action = sintent.getAction(); 3462 if (resultsAction != null && resultsAction.equals(action)) { 3463 // If this action was explicitly requested, then don't 3464 // remove things that have it. 3465 action = null; 3466 } 3467 3468 ResolveInfo ri = null; 3469 ActivityInfo ai = null; 3470 3471 ComponentName comp = sintent.getComponent(); 3472 if (comp == null) { 3473 ri = resolveIntent( 3474 sintent, 3475 specificTypes != null ? specificTypes[i] : null, 3476 flags, userId); 3477 if (ri == null) { 3478 continue; 3479 } 3480 if (ri == mResolveInfo) { 3481 // ACK! Must do something better with this. 3482 } 3483 ai = ri.activityInfo; 3484 comp = new ComponentName(ai.applicationInfo.packageName, 3485 ai.name); 3486 } else { 3487 ai = getActivityInfo(comp, flags, userId); 3488 if (ai == null) { 3489 continue; 3490 } 3491 } 3492 3493 // Look for any generic query activities that are duplicates 3494 // of this specific one, and remove them from the results. 3495 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 3496 N = results.size(); 3497 int j; 3498 for (j=specificsPos; j<N; j++) { 3499 ResolveInfo sri = results.get(j); 3500 if ((sri.activityInfo.name.equals(comp.getClassName()) 3501 && sri.activityInfo.applicationInfo.packageName.equals( 3502 comp.getPackageName())) 3503 || (action != null && sri.filter.matchAction(action))) { 3504 results.remove(j); 3505 if (DEBUG_INTENT_MATCHING) Log.v( 3506 TAG, "Removing duplicate item from " + j 3507 + " due to specific " + specificsPos); 3508 if (ri == null) { 3509 ri = sri; 3510 } 3511 j--; 3512 N--; 3513 } 3514 } 3515 3516 // Add this specific item to its proper place. 3517 if (ri == null) { 3518 ri = new ResolveInfo(); 3519 ri.activityInfo = ai; 3520 } 3521 results.add(specificsPos, ri); 3522 ri.specificIndex = i; 3523 specificsPos++; 3524 } 3525 } 3526 3527 // Now we go through the remaining generic results and remove any 3528 // duplicate actions that are found here. 3529 N = results.size(); 3530 for (int i=specificsPos; i<N-1; i++) { 3531 final ResolveInfo rii = results.get(i); 3532 if (rii.filter == null) { 3533 continue; 3534 } 3535 3536 // Iterate over all of the actions of this result's intent 3537 // filter... typically this should be just one. 3538 final Iterator<String> it = rii.filter.actionsIterator(); 3539 if (it == null) { 3540 continue; 3541 } 3542 while (it.hasNext()) { 3543 final String action = it.next(); 3544 if (resultsAction != null && resultsAction.equals(action)) { 3545 // If this action was explicitly requested, then don't 3546 // remove things that have it. 3547 continue; 3548 } 3549 for (int j=i+1; j<N; j++) { 3550 final ResolveInfo rij = results.get(j); 3551 if (rij.filter != null && rij.filter.hasAction(action)) { 3552 results.remove(j); 3553 if (DEBUG_INTENT_MATCHING) Log.v( 3554 TAG, "Removing duplicate item from " + j 3555 + " due to action " + action + " at " + i); 3556 j--; 3557 N--; 3558 } 3559 } 3560 } 3561 3562 // If the caller didn't request filter information, drop it now 3563 // so we don't have to marshall/unmarshall it. 3564 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3565 rii.filter = null; 3566 } 3567 } 3568 3569 // Filter out the caller activity if so requested. 3570 if (caller != null) { 3571 N = results.size(); 3572 for (int i=0; i<N; i++) { 3573 ActivityInfo ainfo = results.get(i).activityInfo; 3574 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 3575 && caller.getClassName().equals(ainfo.name)) { 3576 results.remove(i); 3577 break; 3578 } 3579 } 3580 } 3581 3582 // If the caller didn't request filter information, 3583 // drop them now so we don't have to 3584 // marshall/unmarshall it. 3585 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3586 N = results.size(); 3587 for (int i=0; i<N; i++) { 3588 results.get(i).filter = null; 3589 } 3590 } 3591 3592 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 3593 return results; 3594 } 3595 3596 @Override 3597 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 3598 int userId) { 3599 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3600 ComponentName comp = intent.getComponent(); 3601 if (comp == null) { 3602 if (intent.getSelector() != null) { 3603 intent = intent.getSelector(); 3604 comp = intent.getComponent(); 3605 } 3606 } 3607 if (comp != null) { 3608 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3609 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 3610 if (ai != null) { 3611 ResolveInfo ri = new ResolveInfo(); 3612 ri.activityInfo = ai; 3613 list.add(ri); 3614 } 3615 return list; 3616 } 3617 3618 // reader 3619 synchronized (mPackages) { 3620 String pkgName = intent.getPackage(); 3621 if (pkgName == null) { 3622 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 3623 } 3624 final PackageParser.Package pkg = mPackages.get(pkgName); 3625 if (pkg != null) { 3626 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 3627 userId); 3628 } 3629 return null; 3630 } 3631 } 3632 3633 @Override 3634 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 3635 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 3636 if (!sUserManager.exists(userId)) return null; 3637 if (query != null) { 3638 if (query.size() >= 1) { 3639 // If there is more than one service with the same priority, 3640 // just arbitrarily pick the first one. 3641 return query.get(0); 3642 } 3643 } 3644 return null; 3645 } 3646 3647 @Override 3648 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 3649 int userId) { 3650 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3651 ComponentName comp = intent.getComponent(); 3652 if (comp == null) { 3653 if (intent.getSelector() != null) { 3654 intent = intent.getSelector(); 3655 comp = intent.getComponent(); 3656 } 3657 } 3658 if (comp != null) { 3659 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3660 final ServiceInfo si = getServiceInfo(comp, flags, userId); 3661 if (si != null) { 3662 final ResolveInfo ri = new ResolveInfo(); 3663 ri.serviceInfo = si; 3664 list.add(ri); 3665 } 3666 return list; 3667 } 3668 3669 // reader 3670 synchronized (mPackages) { 3671 String pkgName = intent.getPackage(); 3672 if (pkgName == null) { 3673 return mServices.queryIntent(intent, resolvedType, flags, userId); 3674 } 3675 final PackageParser.Package pkg = mPackages.get(pkgName); 3676 if (pkg != null) { 3677 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 3678 userId); 3679 } 3680 return null; 3681 } 3682 } 3683 3684 @Override 3685 public List<ResolveInfo> queryIntentContentProviders( 3686 Intent intent, String resolvedType, int flags, int userId) { 3687 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3688 ComponentName comp = intent.getComponent(); 3689 if (comp == null) { 3690 if (intent.getSelector() != null) { 3691 intent = intent.getSelector(); 3692 comp = intent.getComponent(); 3693 } 3694 } 3695 if (comp != null) { 3696 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3697 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 3698 if (pi != null) { 3699 final ResolveInfo ri = new ResolveInfo(); 3700 ri.providerInfo = pi; 3701 list.add(ri); 3702 } 3703 return list; 3704 } 3705 3706 // reader 3707 synchronized (mPackages) { 3708 String pkgName = intent.getPackage(); 3709 if (pkgName == null) { 3710 return mProviders.queryIntent(intent, resolvedType, flags, userId); 3711 } 3712 final PackageParser.Package pkg = mPackages.get(pkgName); 3713 if (pkg != null) { 3714 return mProviders.queryIntentForPackage( 3715 intent, resolvedType, flags, pkg.providers, userId); 3716 } 3717 return null; 3718 } 3719 } 3720 3721 @Override 3722 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 3723 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3724 3725 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages"); 3726 3727 // writer 3728 synchronized (mPackages) { 3729 ArrayList<PackageInfo> list; 3730 if (listUninstalled) { 3731 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 3732 for (PackageSetting ps : mSettings.mPackages.values()) { 3733 PackageInfo pi; 3734 if (ps.pkg != null) { 3735 pi = generatePackageInfo(ps.pkg, flags, userId); 3736 } else { 3737 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3738 } 3739 if (pi != null) { 3740 list.add(pi); 3741 } 3742 } 3743 } else { 3744 list = new ArrayList<PackageInfo>(mPackages.size()); 3745 for (PackageParser.Package p : mPackages.values()) { 3746 PackageInfo pi = generatePackageInfo(p, flags, userId); 3747 if (pi != null) { 3748 list.add(pi); 3749 } 3750 } 3751 } 3752 3753 return new ParceledListSlice<PackageInfo>(list); 3754 } 3755 } 3756 3757 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 3758 String[] permissions, boolean[] tmp, int flags, int userId) { 3759 int numMatch = 0; 3760 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 3761 for (int i=0; i<permissions.length; i++) { 3762 if (gp.grantedPermissions.contains(permissions[i])) { 3763 tmp[i] = true; 3764 numMatch++; 3765 } else { 3766 tmp[i] = false; 3767 } 3768 } 3769 if (numMatch == 0) { 3770 return; 3771 } 3772 PackageInfo pi; 3773 if (ps.pkg != null) { 3774 pi = generatePackageInfo(ps.pkg, flags, userId); 3775 } else { 3776 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3777 } 3778 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 3779 if (numMatch == permissions.length) { 3780 pi.requestedPermissions = permissions; 3781 } else { 3782 pi.requestedPermissions = new String[numMatch]; 3783 numMatch = 0; 3784 for (int i=0; i<permissions.length; i++) { 3785 if (tmp[i]) { 3786 pi.requestedPermissions[numMatch] = permissions[i]; 3787 numMatch++; 3788 } 3789 } 3790 } 3791 } 3792 list.add(pi); 3793 } 3794 3795 @Override 3796 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 3797 String[] permissions, int flags, int userId) { 3798 if (!sUserManager.exists(userId)) return null; 3799 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3800 3801 // writer 3802 synchronized (mPackages) { 3803 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 3804 boolean[] tmpBools = new boolean[permissions.length]; 3805 if (listUninstalled) { 3806 for (PackageSetting ps : mSettings.mPackages.values()) { 3807 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 3808 } 3809 } else { 3810 for (PackageParser.Package pkg : mPackages.values()) { 3811 PackageSetting ps = (PackageSetting)pkg.mExtras; 3812 if (ps != null) { 3813 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 3814 userId); 3815 } 3816 } 3817 } 3818 3819 return new ParceledListSlice<PackageInfo>(list); 3820 } 3821 } 3822 3823 @Override 3824 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 3825 if (!sUserManager.exists(userId)) return null; 3826 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3827 3828 // writer 3829 synchronized (mPackages) { 3830 ArrayList<ApplicationInfo> list; 3831 if (listUninstalled) { 3832 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 3833 for (PackageSetting ps : mSettings.mPackages.values()) { 3834 ApplicationInfo ai; 3835 if (ps.pkg != null) { 3836 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3837 ps.readUserState(userId), userId); 3838 } else { 3839 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 3840 } 3841 if (ai != null) { 3842 list.add(ai); 3843 } 3844 } 3845 } else { 3846 list = new ArrayList<ApplicationInfo>(mPackages.size()); 3847 for (PackageParser.Package p : mPackages.values()) { 3848 if (p.mExtras != null) { 3849 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3850 ((PackageSetting)p.mExtras).readUserState(userId), userId); 3851 if (ai != null) { 3852 list.add(ai); 3853 } 3854 } 3855 } 3856 } 3857 3858 return new ParceledListSlice<ApplicationInfo>(list); 3859 } 3860 } 3861 3862 public List<ApplicationInfo> getPersistentApplications(int flags) { 3863 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 3864 3865 // reader 3866 synchronized (mPackages) { 3867 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 3868 final int userId = UserHandle.getCallingUserId(); 3869 while (i.hasNext()) { 3870 final PackageParser.Package p = i.next(); 3871 if (p.applicationInfo != null 3872 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 3873 && (!mSafeMode || isSystemApp(p))) { 3874 PackageSetting ps = mSettings.mPackages.get(p.packageName); 3875 if (ps != null) { 3876 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3877 ps.readUserState(userId), userId); 3878 if (ai != null) { 3879 finalList.add(ai); 3880 } 3881 } 3882 } 3883 } 3884 } 3885 3886 return finalList; 3887 } 3888 3889 @Override 3890 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 3891 if (!sUserManager.exists(userId)) return null; 3892 // reader 3893 synchronized (mPackages) { 3894 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 3895 PackageSetting ps = provider != null 3896 ? mSettings.mPackages.get(provider.owner.packageName) 3897 : null; 3898 return ps != null 3899 && mSettings.isEnabledLPr(provider.info, flags, userId) 3900 && (!mSafeMode || (provider.info.applicationInfo.flags 3901 &ApplicationInfo.FLAG_SYSTEM) != 0) 3902 ? PackageParser.generateProviderInfo(provider, flags, 3903 ps.readUserState(userId), userId) 3904 : null; 3905 } 3906 } 3907 3908 /** 3909 * @deprecated 3910 */ 3911 @Deprecated 3912 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 3913 // reader 3914 synchronized (mPackages) { 3915 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 3916 .entrySet().iterator(); 3917 final int userId = UserHandle.getCallingUserId(); 3918 while (i.hasNext()) { 3919 Map.Entry<String, PackageParser.Provider> entry = i.next(); 3920 PackageParser.Provider p = entry.getValue(); 3921 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3922 3923 if (ps != null && p.syncable 3924 && (!mSafeMode || (p.info.applicationInfo.flags 3925 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 3926 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 3927 ps.readUserState(userId), userId); 3928 if (info != null) { 3929 outNames.add(entry.getKey()); 3930 outInfo.add(info); 3931 } 3932 } 3933 } 3934 } 3935 } 3936 3937 @Override 3938 public List<ProviderInfo> queryContentProviders(String processName, 3939 int uid, int flags) { 3940 ArrayList<ProviderInfo> finalList = null; 3941 // reader 3942 synchronized (mPackages) { 3943 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 3944 final int userId = processName != null ? 3945 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 3946 while (i.hasNext()) { 3947 final PackageParser.Provider p = i.next(); 3948 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3949 if (ps != null && p.info.authority != null 3950 && (processName == null 3951 || (p.info.processName.equals(processName) 3952 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 3953 && mSettings.isEnabledLPr(p.info, flags, userId) 3954 && (!mSafeMode 3955 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 3956 if (finalList == null) { 3957 finalList = new ArrayList<ProviderInfo>(3); 3958 } 3959 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 3960 ps.readUserState(userId), userId); 3961 if (info != null) { 3962 finalList.add(info); 3963 } 3964 } 3965 } 3966 } 3967 3968 if (finalList != null) { 3969 Collections.sort(finalList, mProviderInitOrderSorter); 3970 } 3971 3972 return finalList; 3973 } 3974 3975 @Override 3976 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 3977 int flags) { 3978 // reader 3979 synchronized (mPackages) { 3980 final PackageParser.Instrumentation i = mInstrumentation.get(name); 3981 return PackageParser.generateInstrumentationInfo(i, flags); 3982 } 3983 } 3984 3985 @Override 3986 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 3987 int flags) { 3988 ArrayList<InstrumentationInfo> finalList = 3989 new ArrayList<InstrumentationInfo>(); 3990 3991 // reader 3992 synchronized (mPackages) { 3993 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 3994 while (i.hasNext()) { 3995 final PackageParser.Instrumentation p = i.next(); 3996 if (targetPackage == null 3997 || targetPackage.equals(p.info.targetPackage)) { 3998 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 3999 flags); 4000 if (ii != null) { 4001 finalList.add(ii); 4002 } 4003 } 4004 } 4005 } 4006 4007 return finalList; 4008 } 4009 4010 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4011 HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4012 if (overlays == null) { 4013 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4014 return; 4015 } 4016 for (PackageParser.Package opkg : overlays.values()) { 4017 // Not much to do if idmap fails: we already logged the error 4018 // and we certainly don't want to abort installation of pkg simply 4019 // because an overlay didn't fit properly. For these reasons, 4020 // ignore the return value of createIdmapForPackagePairLI. 4021 createIdmapForPackagePairLI(pkg, opkg); 4022 } 4023 } 4024 4025 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4026 PackageParser.Package opkg) { 4027 if (!opkg.mTrustedOverlay) { 4028 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4029 opkg.baseCodePath + ": overlay not trusted"); 4030 return false; 4031 } 4032 HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4033 if (overlaySet == null) { 4034 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4035 opkg.baseCodePath + " but target package has no known overlays"); 4036 return false; 4037 } 4038 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4039 // TODO: generate idmap for split APKs 4040 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4041 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4042 + opkg.baseCodePath); 4043 return false; 4044 } 4045 PackageParser.Package[] overlayArray = 4046 overlaySet.values().toArray(new PackageParser.Package[0]); 4047 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4048 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4049 return p1.mOverlayPriority - p2.mOverlayPriority; 4050 } 4051 }; 4052 Arrays.sort(overlayArray, cmp); 4053 4054 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4055 int i = 0; 4056 for (PackageParser.Package p : overlayArray) { 4057 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4058 } 4059 return true; 4060 } 4061 4062 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 4063 final File[] files = dir.listFiles(); 4064 if (ArrayUtils.isEmpty(files)) { 4065 Log.d(TAG, "No files in app dir " + dir); 4066 return; 4067 } 4068 4069 if (DEBUG_PACKAGE_SCANNING) { 4070 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 4071 + " flags=0x" + Integer.toHexString(parseFlags)); 4072 } 4073 4074 for (File file : files) { 4075 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 4076 && !PackageInstallerService.isStageName(file.getName()); 4077 if (!isPackage) { 4078 // Ignore entries which are not packages 4079 continue; 4080 } 4081 try { 4082 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 4083 scanFlags, currentTime, null); 4084 } catch (PackageManagerException e) { 4085 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4086 4087 // Delete invalid userdata apps 4088 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4089 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4090 Slog.w(TAG, "Deleting invalid package at " + file); 4091 if (file.isDirectory()) { 4092 FileUtils.deleteContents(file); 4093 } 4094 file.delete(); 4095 } 4096 } 4097 } 4098 } 4099 4100 private static File getSettingsProblemFile() { 4101 File dataDir = Environment.getDataDirectory(); 4102 File systemDir = new File(dataDir, "system"); 4103 File fname = new File(systemDir, "uiderrors.txt"); 4104 return fname; 4105 } 4106 4107 static void reportSettingsProblem(int priority, String msg) { 4108 try { 4109 File fname = getSettingsProblemFile(); 4110 FileOutputStream out = new FileOutputStream(fname, true); 4111 PrintWriter pw = new FastPrintWriter(out); 4112 SimpleDateFormat formatter = new SimpleDateFormat(); 4113 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4114 pw.println(dateString + ": " + msg); 4115 pw.close(); 4116 FileUtils.setPermissions( 4117 fname.toString(), 4118 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4119 -1, -1); 4120 } catch (java.io.IOException e) { 4121 } 4122 Slog.println(priority, TAG, msg); 4123 } 4124 4125 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 4126 PackageParser.Package pkg, File srcFile, int parseFlags) 4127 throws PackageManagerException { 4128 if (ps != null 4129 && ps.codePath.equals(srcFile) 4130 && ps.timeStamp == srcFile.lastModified() 4131 && !isCompatSignatureUpdateNeeded(pkg)) { 4132 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4133 if (ps.signatures.mSignatures != null 4134 && ps.signatures.mSignatures.length != 0 4135 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4136 // Optimization: reuse the existing cached certificates 4137 // if the package appears to be unchanged. 4138 pkg.mSignatures = ps.signatures.mSignatures; 4139 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4140 synchronized (mPackages) { 4141 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 4142 } 4143 return; 4144 } 4145 4146 Slog.w(TAG, "PackageSetting for " + ps.name 4147 + " is missing signatures. Collecting certs again to recover them."); 4148 } else { 4149 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4150 } 4151 4152 try { 4153 pp.collectCertificates(pkg, parseFlags); 4154 pp.collectManifestDigest(pkg); 4155 } catch (PackageParserException e) { 4156 throw new PackageManagerException(e.error, "Failed to collect certificates for " 4157 + pkg.packageName + ": " + e.getMessage()); 4158 } 4159 } 4160 4161 /* 4162 * Scan a package and return the newly parsed package. 4163 * Returns null in case of errors and the error code is stored in mLastScanError 4164 */ 4165 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 4166 long currentTime, UserHandle user) throws PackageManagerException { 4167 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4168 parseFlags |= mDefParseFlags; 4169 PackageParser pp = new PackageParser(); 4170 pp.setSeparateProcesses(mSeparateProcesses); 4171 pp.setOnlyCoreApps(mOnlyCore); 4172 pp.setDisplayMetrics(mMetrics); 4173 4174 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 4175 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4176 } 4177 4178 final PackageParser.Package pkg; 4179 try { 4180 pkg = pp.parsePackage(scanFile, parseFlags); 4181 } catch (PackageParserException e) { 4182 throw new PackageManagerException(e.error, 4183 "Failed to scan " + scanFile + ": " + e.getMessage()); 4184 } 4185 4186 PackageSetting ps = null; 4187 PackageSetting updatedPkg; 4188 // reader 4189 synchronized (mPackages) { 4190 // Look to see if we already know about this package. 4191 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4192 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4193 // This package has been renamed to its original name. Let's 4194 // use that. 4195 ps = mSettings.peekPackageLPr(oldName); 4196 } 4197 // If there was no original package, see one for the real package name. 4198 if (ps == null) { 4199 ps = mSettings.peekPackageLPr(pkg.packageName); 4200 } 4201 // Check to see if this package could be hiding/updating a system 4202 // package. Must look for it either under the original or real 4203 // package name depending on our state. 4204 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4205 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4206 } 4207 boolean updatedPkgBetter = false; 4208 // First check if this is a system package that may involve an update 4209 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4210 if (ps != null && !ps.codePath.equals(scanFile)) { 4211 // The path has changed from what was last scanned... check the 4212 // version of the new path against what we have stored to determine 4213 // what to do. 4214 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4215 if (pkg.mVersionCode < ps.versionCode) { 4216 // The system package has been updated and the code path does not match 4217 // Ignore entry. Skip it. 4218 Log.i(TAG, "Package " + ps.name + " at " + scanFile 4219 + " ignored: updated version " + ps.versionCode 4220 + " better than this " + pkg.mVersionCode); 4221 if (!updatedPkg.codePath.equals(scanFile)) { 4222 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4223 + ps.name + " changing from " + updatedPkg.codePathString 4224 + " to " + scanFile); 4225 updatedPkg.codePath = scanFile; 4226 updatedPkg.codePathString = scanFile.toString(); 4227 // This is the point at which we know that the system-disk APK 4228 // for this package has moved during a reboot (e.g. due to an OTA), 4229 // so we need to reevaluate it for privilege policy. 4230 if (locationIsPrivileged(scanFile)) { 4231 updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED; 4232 } 4233 } 4234 updatedPkg.pkg = pkg; 4235 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 4236 } else { 4237 // The current app on the system partition is better than 4238 // what we have updated to on the data partition; switch 4239 // back to the system partition version. 4240 // At this point, its safely assumed that package installation for 4241 // apps in system partition will go through. If not there won't be a working 4242 // version of the app 4243 // writer 4244 synchronized (mPackages) { 4245 // Just remove the loaded entries from package lists. 4246 mPackages.remove(ps.name); 4247 } 4248 Slog.w(TAG, "Package " + ps.name + " at " + scanFile 4249 + "reverting from " + ps.codePathString 4250 + ": new version " + pkg.mVersionCode 4251 + " better than installed " + ps.versionCode); 4252 4253 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4254 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4255 getAppDexInstructionSets(ps)); 4256 synchronized (mInstallLock) { 4257 args.cleanUpResourcesLI(); 4258 } 4259 synchronized (mPackages) { 4260 mSettings.enableSystemPackageLPw(ps.name); 4261 } 4262 updatedPkgBetter = true; 4263 } 4264 } 4265 } 4266 4267 if (updatedPkg != null) { 4268 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4269 // initially 4270 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4271 4272 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4273 // flag set initially 4274 if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) { 4275 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4276 } 4277 } 4278 4279 // Verify certificates against what was last scanned 4280 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 4281 4282 /* 4283 * A new system app appeared, but we already had a non-system one of the 4284 * same name installed earlier. 4285 */ 4286 boolean shouldHideSystemApp = false; 4287 if (updatedPkg == null && ps != null 4288 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4289 /* 4290 * Check to make sure the signatures match first. If they don't, 4291 * wipe the installed application and its data. 4292 */ 4293 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4294 != PackageManager.SIGNATURE_MATCH) { 4295 if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!"); 4296 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4297 ps = null; 4298 } else { 4299 /* 4300 * If the newly-added system app is an older version than the 4301 * already installed version, hide it. It will be scanned later 4302 * and re-added like an update. 4303 */ 4304 if (pkg.mVersionCode < ps.versionCode) { 4305 shouldHideSystemApp = true; 4306 } else { 4307 /* 4308 * The newly found system app is a newer version that the 4309 * one previously installed. Simply remove the 4310 * already-installed application and replace it with our own 4311 * while keeping the application data. 4312 */ 4313 Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from " 4314 + ps.codePathString + ": new version " + pkg.mVersionCode 4315 + " better than installed " + ps.versionCode); 4316 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4317 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4318 getAppDexInstructionSets(ps)); 4319 synchronized (mInstallLock) { 4320 args.cleanUpResourcesLI(); 4321 } 4322 } 4323 } 4324 } 4325 4326 // The apk is forward locked (not public) if its code and resources 4327 // are kept in different files. (except for app in either system or 4328 // vendor path). 4329 // TODO grab this value from PackageSettings 4330 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4331 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4332 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 4333 } 4334 } 4335 4336 // TODO: extend to support forward-locked splits 4337 String resourcePath = null; 4338 String baseResourcePath = null; 4339 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 4340 if (ps != null && ps.resourcePathString != null) { 4341 resourcePath = ps.resourcePathString; 4342 baseResourcePath = ps.resourcePathString; 4343 } else { 4344 // Should not happen at all. Just log an error. 4345 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 4346 } 4347 } else { 4348 resourcePath = pkg.codePath; 4349 baseResourcePath = pkg.baseCodePath; 4350 } 4351 4352 // Set application objects path explicitly. 4353 pkg.applicationInfo.setCodePath(pkg.codePath); 4354 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 4355 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 4356 pkg.applicationInfo.setResourcePath(resourcePath); 4357 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 4358 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 4359 4360 // Note that we invoke the following method only if we are about to unpack an application 4361 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 4362 | SCAN_UPDATE_SIGNATURE, currentTime, user); 4363 4364 /* 4365 * If the system app should be overridden by a previously installed 4366 * data, hide the system app now and let the /data/app scan pick it up 4367 * again. 4368 */ 4369 if (shouldHideSystemApp) { 4370 synchronized (mPackages) { 4371 /* 4372 * We have to grant systems permissions before we hide, because 4373 * grantPermissions will assume the package update is trying to 4374 * expand its permissions. 4375 */ 4376 grantPermissionsLPw(pkg, true); 4377 mSettings.disableSystemPackageLPw(pkg.packageName); 4378 } 4379 } 4380 4381 return scannedPkg; 4382 } 4383 4384 private static String fixProcessName(String defProcessName, 4385 String processName, int uid) { 4386 if (processName == null) { 4387 return defProcessName; 4388 } 4389 return processName; 4390 } 4391 4392 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 4393 throws PackageManagerException { 4394 if (pkgSetting.signatures.mSignatures != null) { 4395 // Already existing package. Make sure signatures match 4396 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 4397 == PackageManager.SIGNATURE_MATCH; 4398 if (!match) { 4399 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 4400 == PackageManager.SIGNATURE_MATCH; 4401 } 4402 if (!match) { 4403 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 4404 + pkg.packageName + " signatures do not match the " 4405 + "previously installed version; ignoring!"); 4406 } 4407 } 4408 4409 // Check for shared user signatures 4410 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 4411 // Already existing package. Make sure signatures match 4412 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4413 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 4414 if (!match) { 4415 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 4416 == PackageManager.SIGNATURE_MATCH; 4417 } 4418 if (!match) { 4419 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 4420 "Package " + pkg.packageName 4421 + " has no signatures that match those in shared user " 4422 + pkgSetting.sharedUser.name + "; ignoring!"); 4423 } 4424 } 4425 } 4426 4427 /** 4428 * Enforces that only the system UID or root's UID can call a method exposed 4429 * via Binder. 4430 * 4431 * @param message used as message if SecurityException is thrown 4432 * @throws SecurityException if the caller is not system or root 4433 */ 4434 private static final void enforceSystemOrRoot(String message) { 4435 final int uid = Binder.getCallingUid(); 4436 if (uid != Process.SYSTEM_UID && uid != 0) { 4437 throw new SecurityException(message); 4438 } 4439 } 4440 4441 @Override 4442 public void performBootDexOpt() { 4443 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4444 4445 final HashSet<PackageParser.Package> pkgs; 4446 synchronized (mPackages) { 4447 pkgs = mDeferredDexOpt; 4448 mDeferredDexOpt = null; 4449 } 4450 4451 if (pkgs != null) { 4452 // Filter out packages that aren't recently used. 4453 // 4454 // The exception is first boot of a non-eng device, which 4455 // should do a full dexopt. 4456 boolean eng = "eng".equals(SystemProperties.get("ro.build.type")); 4457 if (eng || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 4458 // TODO: add a property to control this? 4459 long dexOptLRUThresholdInMinutes; 4460 if (eng) { 4461 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 4462 } else { 4463 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 4464 } 4465 long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 4466 4467 int total = pkgs.size(); 4468 int skipped = 0; 4469 long now = System.currentTimeMillis(); 4470 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 4471 PackageParser.Package pkg = i.next(); 4472 long then = pkg.mLastPackageUsageTimeInMills; 4473 if (then + dexOptLRUThresholdInMills < now) { 4474 if (DEBUG_DEXOPT) { 4475 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 4476 ((then == 0) ? "never" : new Date(then))); 4477 } 4478 i.remove(); 4479 skipped++; 4480 } 4481 } 4482 if (DEBUG_DEXOPT) { 4483 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 4484 } 4485 } 4486 4487 int i = 0; 4488 for (PackageParser.Package pkg : pkgs) { 4489 i++; 4490 if (DEBUG_DEXOPT) { 4491 Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size() 4492 + ": " + pkg.packageName); 4493 } 4494 if (!isFirstBoot()) { 4495 try { 4496 ActivityManagerNative.getDefault().showBootMessage( 4497 mContext.getResources().getString( 4498 R.string.android_upgrading_apk, 4499 i, pkgs.size()), true); 4500 } catch (RemoteException e) { 4501 } 4502 } 4503 PackageParser.Package p = pkg; 4504 synchronized (mInstallLock) { 4505 performDexOptLI(p, null /* instruction sets */, false /* force dex */, false /* defer */, 4506 true /* include dependencies */); 4507 } 4508 } 4509 } 4510 } 4511 4512 @Override 4513 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 4514 return performDexOpt(packageName, instructionSet, true); 4515 } 4516 4517 private static String getPrimaryInstructionSet(ApplicationInfo info) { 4518 if (info.primaryCpuAbi == null) { 4519 return getPreferredInstructionSet(); 4520 } 4521 4522 return VMRuntime.getInstructionSet(info.primaryCpuAbi); 4523 } 4524 4525 public boolean performDexOpt(String packageName, String instructionSet, boolean updateUsage) { 4526 PackageParser.Package p; 4527 final String targetInstructionSet; 4528 synchronized (mPackages) { 4529 p = mPackages.get(packageName); 4530 if (p == null) { 4531 return false; 4532 } 4533 if (updateUsage) { 4534 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 4535 } 4536 mPackageUsage.write(false); 4537 4538 targetInstructionSet = instructionSet != null ? instructionSet : 4539 getPrimaryInstructionSet(p.applicationInfo); 4540 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 4541 return false; 4542 } 4543 } 4544 4545 synchronized (mInstallLock) { 4546 final String[] instructionSets = new String[] { targetInstructionSet }; 4547 return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */, 4548 true /* include dependencies */) == DEX_OPT_PERFORMED; 4549 } 4550 } 4551 4552 public HashSet<String> getPackagesThatNeedDexOpt() { 4553 HashSet<String> pkgs = null; 4554 synchronized (mPackages) { 4555 for (PackageParser.Package p : mPackages.values()) { 4556 if (DEBUG_DEXOPT) { 4557 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 4558 } 4559 if (!p.mDexOptPerformed.isEmpty()) { 4560 continue; 4561 } 4562 if (pkgs == null) { 4563 pkgs = new HashSet<String>(); 4564 } 4565 pkgs.add(p.packageName); 4566 } 4567 } 4568 return pkgs; 4569 } 4570 4571 public void shutdown() { 4572 mPackageUsage.write(true); 4573 } 4574 4575 private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets, 4576 boolean forceDex, boolean defer, HashSet<String> done) { 4577 for (int i=0; i<libs.size(); i++) { 4578 PackageParser.Package libPkg; 4579 String libName; 4580 synchronized (mPackages) { 4581 libName = libs.get(i); 4582 SharedLibraryEntry lib = mSharedLibraries.get(libName); 4583 if (lib != null && lib.apk != null) { 4584 libPkg = mPackages.get(lib.apk); 4585 } else { 4586 libPkg = null; 4587 } 4588 } 4589 if (libPkg != null && !done.contains(libName)) { 4590 performDexOptLI(libPkg, instructionSets, forceDex, defer, done); 4591 } 4592 } 4593 } 4594 4595 static final int DEX_OPT_SKIPPED = 0; 4596 static final int DEX_OPT_PERFORMED = 1; 4597 static final int DEX_OPT_DEFERRED = 2; 4598 static final int DEX_OPT_FAILED = -1; 4599 4600 private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets, 4601 boolean forceDex, boolean defer, HashSet<String> done) { 4602 final String[] instructionSets = targetInstructionSets != null ? 4603 targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo); 4604 4605 if (done != null) { 4606 done.add(pkg.packageName); 4607 if (pkg.usesLibraries != null) { 4608 performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done); 4609 } 4610 if (pkg.usesOptionalLibraries != null) { 4611 performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done); 4612 } 4613 } 4614 4615 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) { 4616 return DEX_OPT_SKIPPED; 4617 } 4618 4619 final boolean vmSafeMode = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0; 4620 4621 final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly(); 4622 boolean performedDexOpt = false; 4623 // There are three basic cases here: 4624 // 1.) we need to dexopt, either because we are forced or it is needed 4625 // 2.) we are defering a needed dexopt 4626 // 3.) we are skipping an unneeded dexopt 4627 final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 4628 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 4629 if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) { 4630 continue; 4631 } 4632 4633 for (String path : paths) { 4634 try { 4635 // This will return DEXOPT_NEEDED if we either cannot find any odex file for this 4636 // patckage or the one we find does not match the image checksum (i.e. it was 4637 // compiled against an old image). It will return PATCHOAT_NEEDED if we can find a 4638 // odex file and it matches the checksum of the image but not its base address, 4639 // meaning we need to move it. 4640 final byte isDexOptNeeded = DexFile.isDexOptNeededInternal(path, 4641 pkg.packageName, dexCodeInstructionSet, defer); 4642 if (forceDex || (!defer && isDexOptNeeded == DexFile.DEXOPT_NEEDED)) { 4643 Log.i(TAG, "Running dexopt on: " + path + " pkg=" 4644 + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet 4645 + " vmSafeMode=" + vmSafeMode); 4646 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4647 final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg), 4648 pkg.packageName, dexCodeInstructionSet, vmSafeMode); 4649 4650 if (ret < 0) { 4651 // Don't bother running dexopt again if we failed, it will probably 4652 // just result in an error again. Also, don't bother dexopting for other 4653 // paths & ISAs. 4654 return DEX_OPT_FAILED; 4655 } 4656 4657 performedDexOpt = true; 4658 } else if (!defer && isDexOptNeeded == DexFile.PATCHOAT_NEEDED) { 4659 Log.i(TAG, "Running patchoat on: " + pkg.applicationInfo.packageName); 4660 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4661 final int ret = mInstaller.patchoat(path, sharedGid, !isForwardLocked(pkg), 4662 pkg.packageName, dexCodeInstructionSet); 4663 4664 if (ret < 0) { 4665 // Don't bother running patchoat again if we failed, it will probably 4666 // just result in an error again. Also, don't bother dexopting for other 4667 // paths & ISAs. 4668 return DEX_OPT_FAILED; 4669 } 4670 4671 performedDexOpt = true; 4672 } 4673 4674 // We're deciding to defer a needed dexopt. Don't bother dexopting for other 4675 // paths and instruction sets. We'll deal with them all together when we process 4676 // our list of deferred dexopts. 4677 if (defer && isDexOptNeeded != DexFile.UP_TO_DATE) { 4678 if (mDeferredDexOpt == null) { 4679 mDeferredDexOpt = new HashSet<PackageParser.Package>(); 4680 } 4681 mDeferredDexOpt.add(pkg); 4682 return DEX_OPT_DEFERRED; 4683 } 4684 } catch (FileNotFoundException e) { 4685 Slog.w(TAG, "Apk not found for dexopt: " + path); 4686 return DEX_OPT_FAILED; 4687 } catch (IOException e) { 4688 Slog.w(TAG, "IOException reading apk: " + path, e); 4689 return DEX_OPT_FAILED; 4690 } catch (StaleDexCacheError e) { 4691 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e); 4692 return DEX_OPT_FAILED; 4693 } catch (Exception e) { 4694 Slog.w(TAG, "Exception when doing dexopt : ", e); 4695 return DEX_OPT_FAILED; 4696 } 4697 } 4698 4699 // At this point we haven't failed dexopt and we haven't deferred dexopt. We must 4700 // either have either succeeded dexopt, or have had isDexOptNeededInternal tell us 4701 // it isn't required. We therefore mark that this package doesn't need dexopt unless 4702 // it's forced. performedDexOpt will tell us whether we performed dex-opt or skipped 4703 // it. 4704 pkg.mDexOptPerformed.add(dexCodeInstructionSet); 4705 } 4706 4707 // If we've gotten here, we're sure that no error occurred and that we haven't 4708 // deferred dex-opt. We've either dex-opted one more paths or instruction sets or 4709 // we've skipped all of them because they are up to date. In both cases this 4710 // package doesn't need dexopt any longer. 4711 return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED; 4712 } 4713 4714 private static String[] getAppDexInstructionSets(ApplicationInfo info) { 4715 if (info.primaryCpuAbi != null) { 4716 if (info.secondaryCpuAbi != null) { 4717 return new String[] { 4718 VMRuntime.getInstructionSet(info.primaryCpuAbi), 4719 VMRuntime.getInstructionSet(info.secondaryCpuAbi) }; 4720 } else { 4721 return new String[] { 4722 VMRuntime.getInstructionSet(info.primaryCpuAbi) }; 4723 } 4724 } 4725 4726 return new String[] { getPreferredInstructionSet() }; 4727 } 4728 4729 private static String[] getAppDexInstructionSets(PackageSetting ps) { 4730 if (ps.primaryCpuAbiString != null) { 4731 if (ps.secondaryCpuAbiString != null) { 4732 return new String[] { 4733 VMRuntime.getInstructionSet(ps.primaryCpuAbiString), 4734 VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) }; 4735 } else { 4736 return new String[] { 4737 VMRuntime.getInstructionSet(ps.primaryCpuAbiString) }; 4738 } 4739 } 4740 4741 return new String[] { getPreferredInstructionSet() }; 4742 } 4743 4744 private static String getPreferredInstructionSet() { 4745 if (sPreferredInstructionSet == null) { 4746 sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]); 4747 } 4748 4749 return sPreferredInstructionSet; 4750 } 4751 4752 private static List<String> getAllInstructionSets() { 4753 final String[] allAbis = Build.SUPPORTED_ABIS; 4754 final List<String> allInstructionSets = new ArrayList<String>(allAbis.length); 4755 4756 for (String abi : allAbis) { 4757 final String instructionSet = VMRuntime.getInstructionSet(abi); 4758 if (!allInstructionSets.contains(instructionSet)) { 4759 allInstructionSets.add(instructionSet); 4760 } 4761 } 4762 4763 return allInstructionSets; 4764 } 4765 4766 /** 4767 * Returns the instruction set that should be used to compile dex code. In the presence of 4768 * a native bridge this might be different than the one shared libraries use. 4769 */ 4770 private static String getDexCodeInstructionSet(String sharedLibraryIsa) { 4771 String dexCodeIsa = SystemProperties.get("ro.dalvik.vm.isa." + sharedLibraryIsa); 4772 return (dexCodeIsa.isEmpty() ? sharedLibraryIsa : dexCodeIsa); 4773 } 4774 4775 private static String[] getDexCodeInstructionSets(String[] instructionSets) { 4776 HashSet<String> dexCodeInstructionSets = new HashSet<String>(instructionSets.length); 4777 for (String instructionSet : instructionSets) { 4778 dexCodeInstructionSets.add(getDexCodeInstructionSet(instructionSet)); 4779 } 4780 return dexCodeInstructionSets.toArray(new String[dexCodeInstructionSets.size()]); 4781 } 4782 4783 @Override 4784 public void forceDexOpt(String packageName) { 4785 enforceSystemOrRoot("forceDexOpt"); 4786 4787 PackageParser.Package pkg; 4788 synchronized (mPackages) { 4789 pkg = mPackages.get(packageName); 4790 if (pkg == null) { 4791 throw new IllegalArgumentException("Missing package: " + packageName); 4792 } 4793 } 4794 4795 synchronized (mInstallLock) { 4796 final String[] instructionSets = new String[] { 4797 getPrimaryInstructionSet(pkg.applicationInfo) }; 4798 final int res = performDexOptLI(pkg, instructionSets, true, false, true); 4799 if (res != DEX_OPT_PERFORMED) { 4800 throw new IllegalStateException("Failed to dexopt: " + res); 4801 } 4802 } 4803 } 4804 4805 private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets, 4806 boolean forceDex, boolean defer, boolean inclDependencies) { 4807 HashSet<String> done; 4808 if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) { 4809 done = new HashSet<String>(); 4810 done.add(pkg.packageName); 4811 } else { 4812 done = null; 4813 } 4814 return performDexOptLI(pkg, instructionSets, forceDex, defer, done); 4815 } 4816 4817 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 4818 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 4819 Slog.w(TAG, "Unable to update from " + oldPkg.name 4820 + " to " + newPkg.packageName 4821 + ": old package not in system partition"); 4822 return false; 4823 } else if (mPackages.get(oldPkg.name) != null) { 4824 Slog.w(TAG, "Unable to update from " + oldPkg.name 4825 + " to " + newPkg.packageName 4826 + ": old package still exists"); 4827 return false; 4828 } 4829 return true; 4830 } 4831 4832 File getDataPathForUser(int userId) { 4833 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId); 4834 } 4835 4836 private File getDataPathForPackage(String packageName, int userId) { 4837 /* 4838 * Until we fully support multiple users, return the directory we 4839 * previously would have. The PackageManagerTests will need to be 4840 * revised when this is changed back.. 4841 */ 4842 if (userId == 0) { 4843 return new File(mAppDataDir, packageName); 4844 } else { 4845 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 4846 + File.separator + packageName); 4847 } 4848 } 4849 4850 private int createDataDirsLI(String packageName, int uid, String seinfo) { 4851 int[] users = sUserManager.getUserIds(); 4852 int res = mInstaller.install(packageName, uid, uid, seinfo); 4853 if (res < 0) { 4854 return res; 4855 } 4856 for (int user : users) { 4857 if (user != 0) { 4858 res = mInstaller.createUserData(packageName, 4859 UserHandle.getUid(user, uid), user, seinfo); 4860 if (res < 0) { 4861 return res; 4862 } 4863 } 4864 } 4865 return res; 4866 } 4867 4868 private int removeDataDirsLI(String packageName) { 4869 int[] users = sUserManager.getUserIds(); 4870 int res = 0; 4871 for (int user : users) { 4872 int resInner = mInstaller.remove(packageName, user); 4873 if (resInner < 0) { 4874 res = resInner; 4875 } 4876 } 4877 4878 return res; 4879 } 4880 4881 private int deleteCodeCacheDirsLI(String packageName) { 4882 int[] users = sUserManager.getUserIds(); 4883 int res = 0; 4884 for (int user : users) { 4885 int resInner = mInstaller.deleteCodeCacheFiles(packageName, user); 4886 if (resInner < 0) { 4887 res = resInner; 4888 } 4889 } 4890 return res; 4891 } 4892 4893 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 4894 PackageParser.Package changingLib) { 4895 if (file.path != null) { 4896 usesLibraryFiles.add(file.path); 4897 return; 4898 } 4899 PackageParser.Package p = mPackages.get(file.apk); 4900 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 4901 // If we are doing this while in the middle of updating a library apk, 4902 // then we need to make sure to use that new apk for determining the 4903 // dependencies here. (We haven't yet finished committing the new apk 4904 // to the package manager state.) 4905 if (p == null || p.packageName.equals(changingLib.packageName)) { 4906 p = changingLib; 4907 } 4908 } 4909 if (p != null) { 4910 usesLibraryFiles.addAll(p.getAllCodePaths()); 4911 } 4912 } 4913 4914 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 4915 PackageParser.Package changingLib) throws PackageManagerException { 4916 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 4917 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 4918 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 4919 for (int i=0; i<N; i++) { 4920 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 4921 if (file == null) { 4922 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 4923 "Package " + pkg.packageName + " requires unavailable shared library " 4924 + pkg.usesLibraries.get(i) + "; failing!"); 4925 } 4926 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4927 } 4928 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 4929 for (int i=0; i<N; i++) { 4930 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 4931 if (file == null) { 4932 Slog.w(TAG, "Package " + pkg.packageName 4933 + " desires unavailable shared library " 4934 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 4935 } else { 4936 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4937 } 4938 } 4939 N = usesLibraryFiles.size(); 4940 if (N > 0) { 4941 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 4942 } else { 4943 pkg.usesLibraryFiles = null; 4944 } 4945 } 4946 } 4947 4948 private static boolean hasString(List<String> list, List<String> which) { 4949 if (list == null) { 4950 return false; 4951 } 4952 for (int i=list.size()-1; i>=0; i--) { 4953 for (int j=which.size()-1; j>=0; j--) { 4954 if (which.get(j).equals(list.get(i))) { 4955 return true; 4956 } 4957 } 4958 } 4959 return false; 4960 } 4961 4962 private void updateAllSharedLibrariesLPw() { 4963 for (PackageParser.Package pkg : mPackages.values()) { 4964 try { 4965 updateSharedLibrariesLPw(pkg, null); 4966 } catch (PackageManagerException e) { 4967 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 4968 } 4969 } 4970 } 4971 4972 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 4973 PackageParser.Package changingPkg) { 4974 ArrayList<PackageParser.Package> res = null; 4975 for (PackageParser.Package pkg : mPackages.values()) { 4976 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 4977 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 4978 if (res == null) { 4979 res = new ArrayList<PackageParser.Package>(); 4980 } 4981 res.add(pkg); 4982 try { 4983 updateSharedLibrariesLPw(pkg, changingPkg); 4984 } catch (PackageManagerException e) { 4985 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 4986 } 4987 } 4988 } 4989 return res; 4990 } 4991 4992 /** 4993 * Derive the value of the {@code cpuAbiOverride} based on the provided 4994 * value and an optional stored value from the package settings. 4995 */ 4996 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 4997 String cpuAbiOverride = null; 4998 4999 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5000 cpuAbiOverride = null; 5001 } else if (abiOverride != null) { 5002 cpuAbiOverride = abiOverride; 5003 } else if (settings != null) { 5004 cpuAbiOverride = settings.cpuAbiOverrideString; 5005 } 5006 5007 return cpuAbiOverride; 5008 } 5009 5010 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5011 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5012 final File scanFile = new File(pkg.codePath); 5013 if (pkg.applicationInfo.getCodePath() == null || 5014 pkg.applicationInfo.getResourcePath() == null) { 5015 // Bail out. The resource and code paths haven't been set. 5016 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5017 "Code and resource paths haven't been set correctly"); 5018 } 5019 5020 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5021 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5022 } 5023 5024 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5025 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED; 5026 } 5027 5028 if (mCustomResolverComponentName != null && 5029 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5030 setUpCustomResolverActivity(pkg); 5031 } 5032 5033 if (pkg.packageName.equals("android")) { 5034 synchronized (mPackages) { 5035 if (mAndroidApplication != null) { 5036 Slog.w(TAG, "*************************************************"); 5037 Slog.w(TAG, "Core android package being redefined. Skipping."); 5038 Slog.w(TAG, " file=" + scanFile); 5039 Slog.w(TAG, "*************************************************"); 5040 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5041 "Core android package being redefined. Skipping."); 5042 } 5043 5044 // Set up information for our fall-back user intent resolution activity. 5045 mPlatformPackage = pkg; 5046 pkg.mVersionCode = mSdkVersion; 5047 mAndroidApplication = pkg.applicationInfo; 5048 5049 if (!mResolverReplaced) { 5050 mResolveActivity.applicationInfo = mAndroidApplication; 5051 mResolveActivity.name = ResolverActivity.class.getName(); 5052 mResolveActivity.packageName = mAndroidApplication.packageName; 5053 mResolveActivity.processName = "system:ui"; 5054 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5055 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5056 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5057 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5058 mResolveActivity.exported = true; 5059 mResolveActivity.enabled = true; 5060 mResolveInfo.activityInfo = mResolveActivity; 5061 mResolveInfo.priority = 0; 5062 mResolveInfo.preferredOrder = 0; 5063 mResolveInfo.match = 0; 5064 mResolveComponentName = new ComponentName( 5065 mAndroidApplication.packageName, mResolveActivity.name); 5066 } 5067 } 5068 } 5069 5070 if (DEBUG_PACKAGE_SCANNING) { 5071 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5072 Log.d(TAG, "Scanning package " + pkg.packageName); 5073 } 5074 5075 if (mPackages.containsKey(pkg.packageName) 5076 || mSharedLibraries.containsKey(pkg.packageName)) { 5077 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5078 "Application package " + pkg.packageName 5079 + " already installed. Skipping duplicate."); 5080 } 5081 5082 // Initialize package source and resource directories 5083 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5084 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5085 5086 SharedUserSetting suid = null; 5087 PackageSetting pkgSetting = null; 5088 5089 if (!isSystemApp(pkg)) { 5090 // Only system apps can use these features. 5091 pkg.mOriginalPackages = null; 5092 pkg.mRealPackage = null; 5093 pkg.mAdoptPermissions = null; 5094 } 5095 5096 // writer 5097 synchronized (mPackages) { 5098 if (pkg.mSharedUserId != null) { 5099 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true); 5100 if (suid == null) { 5101 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5102 "Creating application package " + pkg.packageName 5103 + " for shared user failed"); 5104 } 5105 if (DEBUG_PACKAGE_SCANNING) { 5106 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5107 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5108 + "): packages=" + suid.packages); 5109 } 5110 } 5111 5112 // Check if we are renaming from an original package name. 5113 PackageSetting origPackage = null; 5114 String realName = null; 5115 if (pkg.mOriginalPackages != null) { 5116 // This package may need to be renamed to a previously 5117 // installed name. Let's check on that... 5118 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5119 if (pkg.mOriginalPackages.contains(renamed)) { 5120 // This package had originally been installed as the 5121 // original name, and we have already taken care of 5122 // transitioning to the new one. Just update the new 5123 // one to continue using the old name. 5124 realName = pkg.mRealPackage; 5125 if (!pkg.packageName.equals(renamed)) { 5126 // Callers into this function may have already taken 5127 // care of renaming the package; only do it here if 5128 // it is not already done. 5129 pkg.setPackageName(renamed); 5130 } 5131 5132 } else { 5133 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5134 if ((origPackage = mSettings.peekPackageLPr( 5135 pkg.mOriginalPackages.get(i))) != null) { 5136 // We do have the package already installed under its 5137 // original name... should we use it? 5138 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5139 // New package is not compatible with original. 5140 origPackage = null; 5141 continue; 5142 } else if (origPackage.sharedUser != null) { 5143 // Make sure uid is compatible between packages. 5144 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5145 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5146 + " to " + pkg.packageName + ": old uid " 5147 + origPackage.sharedUser.name 5148 + " differs from " + pkg.mSharedUserId); 5149 origPackage = null; 5150 continue; 5151 } 5152 } else { 5153 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5154 + pkg.packageName + " to old name " + origPackage.name); 5155 } 5156 break; 5157 } 5158 } 5159 } 5160 } 5161 5162 if (mTransferedPackages.contains(pkg.packageName)) { 5163 Slog.w(TAG, "Package " + pkg.packageName 5164 + " was transferred to another, but its .apk remains"); 5165 } 5166 5167 // Just create the setting, don't add it yet. For already existing packages 5168 // the PkgSetting exists already and doesn't have to be created. 5169 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5170 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 5171 pkg.applicationInfo.primaryCpuAbi, 5172 pkg.applicationInfo.secondaryCpuAbi, 5173 pkg.applicationInfo.flags, user, false); 5174 if (pkgSetting == null) { 5175 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5176 "Creating application package " + pkg.packageName + " failed"); 5177 } 5178 5179 if (pkgSetting.origPackage != null) { 5180 // If we are first transitioning from an original package, 5181 // fix up the new package's name now. We need to do this after 5182 // looking up the package under its new name, so getPackageLP 5183 // can take care of fiddling things correctly. 5184 pkg.setPackageName(origPackage.name); 5185 5186 // File a report about this. 5187 String msg = "New package " + pkgSetting.realName 5188 + " renamed to replace old package " + pkgSetting.name; 5189 reportSettingsProblem(Log.WARN, msg); 5190 5191 // Make a note of it. 5192 mTransferedPackages.add(origPackage.name); 5193 5194 // No longer need to retain this. 5195 pkgSetting.origPackage = null; 5196 } 5197 5198 if (realName != null) { 5199 // Make a note of it. 5200 mTransferedPackages.add(pkg.packageName); 5201 } 5202 5203 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5204 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5205 } 5206 5207 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5208 // Check all shared libraries and map to their actual file path. 5209 // We only do this here for apps not on a system dir, because those 5210 // are the only ones that can fail an install due to this. We 5211 // will take care of the system apps by updating all of their 5212 // library paths after the scan is done. 5213 updateSharedLibrariesLPw(pkg, null); 5214 } 5215 5216 if (mFoundPolicyFile) { 5217 SELinuxMMAC.assignSeinfoValue(pkg); 5218 } 5219 5220 pkg.applicationInfo.uid = pkgSetting.appId; 5221 pkg.mExtras = pkgSetting; 5222 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5223 try { 5224 verifySignaturesLP(pkgSetting, pkg); 5225 } catch (PackageManagerException e) { 5226 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5227 throw e; 5228 } 5229 // The signature has changed, but this package is in the system 5230 // image... let's recover! 5231 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5232 // However... if this package is part of a shared user, but it 5233 // doesn't match the signature of the shared user, let's fail. 5234 // What this means is that you can't change the signatures 5235 // associated with an overall shared user, which doesn't seem all 5236 // that unreasonable. 5237 if (pkgSetting.sharedUser != null) { 5238 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5239 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5240 throw new PackageManagerException( 5241 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 5242 "Signature mismatch for shared user : " 5243 + pkgSetting.sharedUser); 5244 } 5245 } 5246 // File a report about this. 5247 String msg = "System package " + pkg.packageName 5248 + " signature changed; retaining data."; 5249 reportSettingsProblem(Log.WARN, msg); 5250 } 5251 } else { 5252 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 5253 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5254 + pkg.packageName + " upgrade keys do not match the " 5255 + "previously installed version"); 5256 } else { 5257 // signatures may have changed as result of upgrade 5258 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5259 } 5260 } 5261 // Verify that this new package doesn't have any content providers 5262 // that conflict with existing packages. Only do this if the 5263 // package isn't already installed, since we don't want to break 5264 // things that are installed. 5265 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 5266 final int N = pkg.providers.size(); 5267 int i; 5268 for (i=0; i<N; i++) { 5269 PackageParser.Provider p = pkg.providers.get(i); 5270 if (p.info.authority != null) { 5271 String names[] = p.info.authority.split(";"); 5272 for (int j = 0; j < names.length; j++) { 5273 if (mProvidersByAuthority.containsKey(names[j])) { 5274 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5275 final String otherPackageName = 5276 ((other != null && other.getComponentName() != null) ? 5277 other.getComponentName().getPackageName() : "?"); 5278 throw new PackageManagerException( 5279 INSTALL_FAILED_CONFLICTING_PROVIDER, 5280 "Can't install because provider name " + names[j] 5281 + " (in package " + pkg.applicationInfo.packageName 5282 + ") is already used by " + otherPackageName); 5283 } 5284 } 5285 } 5286 } 5287 } 5288 5289 if (pkg.mAdoptPermissions != null) { 5290 // This package wants to adopt ownership of permissions from 5291 // another package. 5292 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 5293 final String origName = pkg.mAdoptPermissions.get(i); 5294 final PackageSetting orig = mSettings.peekPackageLPr(origName); 5295 if (orig != null) { 5296 if (verifyPackageUpdateLPr(orig, pkg)) { 5297 Slog.i(TAG, "Adopting permissions from " + origName + " to " 5298 + pkg.packageName); 5299 mSettings.transferPermissionsLPw(origName, pkg.packageName); 5300 } 5301 } 5302 } 5303 } 5304 } 5305 5306 final String pkgName = pkg.packageName; 5307 5308 final long scanFileTime = scanFile.lastModified(); 5309 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 5310 pkg.applicationInfo.processName = fixProcessName( 5311 pkg.applicationInfo.packageName, 5312 pkg.applicationInfo.processName, 5313 pkg.applicationInfo.uid); 5314 5315 File dataPath; 5316 if (mPlatformPackage == pkg) { 5317 // The system package is special. 5318 dataPath = new File (Environment.getDataDirectory(), "system"); 5319 pkg.applicationInfo.dataDir = dataPath.getPath(); 5320 5321 } else { 5322 // This is a normal package, need to make its data directory. 5323 dataPath = getDataPathForPackage(pkg.packageName, 0); 5324 5325 boolean uidError = false; 5326 5327 if (dataPath.exists()) { 5328 int currentUid = 0; 5329 try { 5330 StructStat stat = Os.stat(dataPath.getPath()); 5331 currentUid = stat.st_uid; 5332 } catch (ErrnoException e) { 5333 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 5334 } 5335 5336 // If we have mismatched owners for the data path, we have a problem. 5337 if (currentUid != pkg.applicationInfo.uid) { 5338 boolean recovered = false; 5339 if (currentUid == 0) { 5340 // The directory somehow became owned by root. Wow. 5341 // This is probably because the system was stopped while 5342 // installd was in the middle of messing with its libs 5343 // directory. Ask installd to fix that. 5344 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 5345 pkg.applicationInfo.uid); 5346 if (ret >= 0) { 5347 recovered = true; 5348 String msg = "Package " + pkg.packageName 5349 + " unexpectedly changed to uid 0; recovered to " + 5350 + pkg.applicationInfo.uid; 5351 reportSettingsProblem(Log.WARN, msg); 5352 } 5353 } 5354 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5355 || (scanFlags&SCAN_BOOTING) != 0)) { 5356 // If this is a system app, we can at least delete its 5357 // current data so the application will still work. 5358 int ret = removeDataDirsLI(pkgName); 5359 if (ret >= 0) { 5360 // TODO: Kill the processes first 5361 // Old data gone! 5362 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5363 ? "System package " : "Third party package "; 5364 String msg = prefix + pkg.packageName 5365 + " has changed from uid: " 5366 + currentUid + " to " 5367 + pkg.applicationInfo.uid + "; old data erased"; 5368 reportSettingsProblem(Log.WARN, msg); 5369 recovered = true; 5370 5371 // And now re-install the app. 5372 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5373 pkg.applicationInfo.seinfo); 5374 if (ret == -1) { 5375 // Ack should not happen! 5376 msg = prefix + pkg.packageName 5377 + " could not have data directory re-created after delete."; 5378 reportSettingsProblem(Log.WARN, msg); 5379 throw new PackageManagerException( 5380 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 5381 } 5382 } 5383 if (!recovered) { 5384 mHasSystemUidErrors = true; 5385 } 5386 } else if (!recovered) { 5387 // If we allow this install to proceed, we will be broken. 5388 // Abort, abort! 5389 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 5390 "scanPackageLI"); 5391 } 5392 if (!recovered) { 5393 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 5394 + pkg.applicationInfo.uid + "/fs_" 5395 + currentUid; 5396 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 5397 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 5398 String msg = "Package " + pkg.packageName 5399 + " has mismatched uid: " 5400 + currentUid + " on disk, " 5401 + pkg.applicationInfo.uid + " in settings"; 5402 // writer 5403 synchronized (mPackages) { 5404 mSettings.mReadMessages.append(msg); 5405 mSettings.mReadMessages.append('\n'); 5406 uidError = true; 5407 if (!pkgSetting.uidError) { 5408 reportSettingsProblem(Log.ERROR, msg); 5409 } 5410 } 5411 } 5412 } 5413 pkg.applicationInfo.dataDir = dataPath.getPath(); 5414 if (mShouldRestoreconData) { 5415 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 5416 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 5417 pkg.applicationInfo.uid); 5418 } 5419 } else { 5420 if (DEBUG_PACKAGE_SCANNING) { 5421 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5422 Log.v(TAG, "Want this data dir: " + dataPath); 5423 } 5424 //invoke installer to do the actual installation 5425 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5426 pkg.applicationInfo.seinfo); 5427 if (ret < 0) { 5428 // Error from installer 5429 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5430 "Unable to create data dirs [errorCode=" + ret + "]"); 5431 } 5432 5433 if (dataPath.exists()) { 5434 pkg.applicationInfo.dataDir = dataPath.getPath(); 5435 } else { 5436 Slog.w(TAG, "Unable to create data directory: " + dataPath); 5437 pkg.applicationInfo.dataDir = null; 5438 } 5439 } 5440 5441 pkgSetting.uidError = uidError; 5442 } 5443 5444 final String path = scanFile.getPath(); 5445 final String codePath = pkg.applicationInfo.getCodePath(); 5446 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 5447 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 5448 setBundledAppAbisAndRoots(pkg, pkgSetting); 5449 5450 // If we haven't found any native libraries for the app, check if it has 5451 // renderscript code. We'll need to force the app to 32 bit if it has 5452 // renderscript bitcode. 5453 if (pkg.applicationInfo.primaryCpuAbi == null 5454 && pkg.applicationInfo.secondaryCpuAbi == null 5455 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5456 NativeLibraryHelper.Handle handle = null; 5457 try { 5458 handle = NativeLibraryHelper.Handle.create(scanFile); 5459 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5460 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 5461 } 5462 } catch (IOException ioe) { 5463 Slog.w(TAG, "Error scanning system app : " + ioe); 5464 } finally { 5465 IoUtils.closeQuietly(handle); 5466 } 5467 } 5468 5469 setNativeLibraryPaths(pkg); 5470 } else { 5471 // TODO: We can probably be smarter about this stuff. For installed apps, 5472 // we can calculate this information at install time once and for all. For 5473 // system apps, we can probably assume that this information doesn't change 5474 // after the first boot scan. As things stand, we do lots of unnecessary work. 5475 5476 // Give ourselves some initial paths; we'll come back for another 5477 // pass once we've determined ABI below. 5478 setNativeLibraryPaths(pkg); 5479 5480 final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg); 5481 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 5482 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 5483 5484 NativeLibraryHelper.Handle handle = null; 5485 try { 5486 handle = NativeLibraryHelper.Handle.create(scanFile); 5487 // TODO(multiArch): This can be null for apps that didn't go through the 5488 // usual installation process. We can calculate it again, like we 5489 // do during install time. 5490 // 5491 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 5492 // unnecessary. 5493 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 5494 5495 // Null out the abis so that they can be recalculated. 5496 pkg.applicationInfo.primaryCpuAbi = null; 5497 pkg.applicationInfo.secondaryCpuAbi = null; 5498 if (isMultiArch(pkg.applicationInfo)) { 5499 // Warn if we've set an abiOverride for multi-lib packages.. 5500 // By definition, we need to copy both 32 and 64 bit libraries for 5501 // such packages. 5502 if (pkg.cpuAbiOverride != null 5503 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 5504 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 5505 } 5506 5507 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 5508 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 5509 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 5510 if (isAsec) { 5511 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 5512 } else { 5513 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5514 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 5515 useIsaSpecificSubdirs); 5516 } 5517 } 5518 5519 maybeThrowExceptionForMultiArchCopy( 5520 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 5521 5522 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5523 if (isAsec) { 5524 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 5525 } else { 5526 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5527 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 5528 useIsaSpecificSubdirs); 5529 } 5530 } 5531 5532 maybeThrowExceptionForMultiArchCopy( 5533 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 5534 5535 if (abi64 >= 0) { 5536 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 5537 } 5538 5539 if (abi32 >= 0) { 5540 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 5541 if (abi64 >= 0) { 5542 pkg.applicationInfo.secondaryCpuAbi = abi; 5543 } else { 5544 pkg.applicationInfo.primaryCpuAbi = abi; 5545 } 5546 } 5547 } else { 5548 String[] abiList = (cpuAbiOverride != null) ? 5549 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 5550 5551 // Enable gross and lame hacks for apps that are built with old 5552 // SDK tools. We must scan their APKs for renderscript bitcode and 5553 // not launch them if it's present. Don't bother checking on devices 5554 // that don't have 64 bit support. 5555 boolean needsRenderScriptOverride = false; 5556 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 5557 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5558 abiList = Build.SUPPORTED_32_BIT_ABIS; 5559 needsRenderScriptOverride = true; 5560 } 5561 5562 final int copyRet; 5563 if (isAsec) { 5564 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 5565 } else { 5566 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5567 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 5568 } 5569 5570 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5571 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5572 "Error unpackaging native libs for app, errorCode=" + copyRet); 5573 } 5574 5575 if (copyRet >= 0) { 5576 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 5577 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 5578 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 5579 } else if (needsRenderScriptOverride) { 5580 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 5581 } 5582 } 5583 } catch (IOException ioe) { 5584 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 5585 } finally { 5586 IoUtils.closeQuietly(handle); 5587 } 5588 5589 // Now that we've calculated the ABIs and determined if it's an internal app, 5590 // we will go ahead and populate the nativeLibraryPath. 5591 setNativeLibraryPaths(pkg); 5592 5593 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 5594 final int[] userIds = sUserManager.getUserIds(); 5595 synchronized (mInstallLock) { 5596 // Create a native library symlink only if we have native libraries 5597 // and if the native libraries are 32 bit libraries. We do not provide 5598 // this symlink for 64 bit libraries. 5599 if (pkg.applicationInfo.primaryCpuAbi != null && 5600 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 5601 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 5602 for (int userId : userIds) { 5603 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 5604 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5605 "Failed linking native library dir (user=" + userId + ")"); 5606 } 5607 } 5608 } 5609 } 5610 } 5611 5612 // This is a special case for the "system" package, where the ABI is 5613 // dictated by the zygote configuration (and init.rc). We should keep track 5614 // of this ABI so that we can deal with "normal" applications that run under 5615 // the same UID correctly. 5616 if (mPlatformPackage == pkg) { 5617 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 5618 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 5619 } 5620 5621 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 5622 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 5623 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 5624 // Copy the derived override back to the parsed package, so that we can 5625 // update the package settings accordingly. 5626 pkg.cpuAbiOverride = cpuAbiOverride; 5627 5628 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 5629 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 5630 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 5631 5632 // Push the derived path down into PackageSettings so we know what to 5633 // clean up at uninstall time. 5634 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 5635 5636 if (DEBUG_ABI_SELECTION) { 5637 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 5638 " primary=" + pkg.applicationInfo.primaryCpuAbi + 5639 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 5640 } 5641 5642 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 5643 // We don't do this here during boot because we can do it all 5644 // at once after scanning all existing packages. 5645 // 5646 // We also do this *before* we perform dexopt on this package, so that 5647 // we can avoid redundant dexopts, and also to make sure we've got the 5648 // code and package path correct. 5649 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 5650 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 5651 } 5652 5653 if ((scanFlags&SCAN_NO_DEX) == 0) { 5654 if (performDexOptLI(pkg, null /* instruction sets */, forceDex, (scanFlags&SCAN_DEFER_DEX) != 0, false) 5655 == DEX_OPT_FAILED) { 5656 if ((scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5657 removeDataDirsLI(pkg.packageName); 5658 } 5659 5660 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 5661 } 5662 } 5663 5664 if (mFactoryTest && pkg.requestedPermissions.contains( 5665 android.Manifest.permission.FACTORY_TEST)) { 5666 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 5667 } 5668 5669 ArrayList<PackageParser.Package> clientLibPkgs = null; 5670 5671 // writer 5672 synchronized (mPackages) { 5673 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5674 // Only system apps can add new shared libraries. 5675 if (pkg.libraryNames != null) { 5676 for (int i=0; i<pkg.libraryNames.size(); i++) { 5677 String name = pkg.libraryNames.get(i); 5678 boolean allowed = false; 5679 if (isUpdatedSystemApp(pkg)) { 5680 // New library entries can only be added through the 5681 // system image. This is important to get rid of a lot 5682 // of nasty edge cases: for example if we allowed a non- 5683 // system update of the app to add a library, then uninstalling 5684 // the update would make the library go away, and assumptions 5685 // we made such as through app install filtering would now 5686 // have allowed apps on the device which aren't compatible 5687 // with it. Better to just have the restriction here, be 5688 // conservative, and create many fewer cases that can negatively 5689 // impact the user experience. 5690 final PackageSetting sysPs = mSettings 5691 .getDisabledSystemPkgLPr(pkg.packageName); 5692 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 5693 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 5694 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 5695 allowed = true; 5696 allowed = true; 5697 break; 5698 } 5699 } 5700 } 5701 } else { 5702 allowed = true; 5703 } 5704 if (allowed) { 5705 if (!mSharedLibraries.containsKey(name)) { 5706 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 5707 } else if (!name.equals(pkg.packageName)) { 5708 Slog.w(TAG, "Package " + pkg.packageName + " library " 5709 + name + " already exists; skipping"); 5710 } 5711 } else { 5712 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 5713 + name + " that is not declared on system image; skipping"); 5714 } 5715 } 5716 if ((scanFlags&SCAN_BOOTING) == 0) { 5717 // If we are not booting, we need to update any applications 5718 // that are clients of our shared library. If we are booting, 5719 // this will all be done once the scan is complete. 5720 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 5721 } 5722 } 5723 } 5724 } 5725 5726 // We also need to dexopt any apps that are dependent on this library. Note that 5727 // if these fail, we should abort the install since installing the library will 5728 // result in some apps being broken. 5729 if (clientLibPkgs != null) { 5730 if ((scanFlags&SCAN_NO_DEX) == 0) { 5731 for (int i=0; i<clientLibPkgs.size(); i++) { 5732 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5733 if (performDexOptLI(clientPkg, null /* instruction sets */, 5734 forceDex, (scanFlags&SCAN_DEFER_DEX) != 0, false) 5735 == DEX_OPT_FAILED) { 5736 if ((scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5737 removeDataDirsLI(pkg.packageName); 5738 } 5739 5740 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 5741 "scanPackageLI failed to dexopt clientLibPkgs"); 5742 } 5743 } 5744 } 5745 } 5746 5747 // Request the ActivityManager to kill the process(only for existing packages) 5748 // so that we do not end up in a confused state while the user is still using the older 5749 // version of the application while the new one gets installed. 5750 if ((scanFlags & SCAN_REPLACING) != 0) { 5751 killApplication(pkg.applicationInfo.packageName, 5752 pkg.applicationInfo.uid, "update pkg"); 5753 } 5754 5755 // Also need to kill any apps that are dependent on the library. 5756 if (clientLibPkgs != null) { 5757 for (int i=0; i<clientLibPkgs.size(); i++) { 5758 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5759 killApplication(clientPkg.applicationInfo.packageName, 5760 clientPkg.applicationInfo.uid, "update lib"); 5761 } 5762 } 5763 5764 // writer 5765 synchronized (mPackages) { 5766 // We don't expect installation to fail beyond this point 5767 5768 // Add the new setting to mSettings 5769 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 5770 // Add the new setting to mPackages 5771 mPackages.put(pkg.applicationInfo.packageName, pkg); 5772 // Make sure we don't accidentally delete its data. 5773 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 5774 while (iter.hasNext()) { 5775 PackageCleanItem item = iter.next(); 5776 if (pkgName.equals(item.packageName)) { 5777 iter.remove(); 5778 } 5779 } 5780 5781 // Take care of first install / last update times. 5782 if (currentTime != 0) { 5783 if (pkgSetting.firstInstallTime == 0) { 5784 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 5785 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 5786 pkgSetting.lastUpdateTime = currentTime; 5787 } 5788 } else if (pkgSetting.firstInstallTime == 0) { 5789 // We need *something*. Take time time stamp of the file. 5790 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 5791 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 5792 if (scanFileTime != pkgSetting.timeStamp) { 5793 // A package on the system image has changed; consider this 5794 // to be an update. 5795 pkgSetting.lastUpdateTime = scanFileTime; 5796 } 5797 } 5798 5799 // Add the package's KeySets to the global KeySetManagerService 5800 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5801 try { 5802 // Old KeySetData no longer valid. 5803 ksms.removeAppKeySetDataLPw(pkg.packageName); 5804 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 5805 if (pkg.mKeySetMapping != null) { 5806 for (Map.Entry<String, ArraySet<PublicKey>> entry : 5807 pkg.mKeySetMapping.entrySet()) { 5808 if (entry.getValue() != null) { 5809 ksms.addDefinedKeySetToPackageLPw(pkg.packageName, 5810 entry.getValue(), entry.getKey()); 5811 } 5812 } 5813 if (pkg.mUpgradeKeySets != null) { 5814 for (String upgradeAlias : pkg.mUpgradeKeySets) { 5815 ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias); 5816 } 5817 } 5818 } 5819 } catch (NullPointerException e) { 5820 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 5821 } catch (IllegalArgumentException e) { 5822 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 5823 } 5824 5825 int N = pkg.providers.size(); 5826 StringBuilder r = null; 5827 int i; 5828 for (i=0; i<N; i++) { 5829 PackageParser.Provider p = pkg.providers.get(i); 5830 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 5831 p.info.processName, pkg.applicationInfo.uid); 5832 mProviders.addProvider(p); 5833 p.syncable = p.info.isSyncable; 5834 if (p.info.authority != null) { 5835 String names[] = p.info.authority.split(";"); 5836 p.info.authority = null; 5837 for (int j = 0; j < names.length; j++) { 5838 if (j == 1 && p.syncable) { 5839 // We only want the first authority for a provider to possibly be 5840 // syncable, so if we already added this provider using a different 5841 // authority clear the syncable flag. We copy the provider before 5842 // changing it because the mProviders object contains a reference 5843 // to a provider that we don't want to change. 5844 // Only do this for the second authority since the resulting provider 5845 // object can be the same for all future authorities for this provider. 5846 p = new PackageParser.Provider(p); 5847 p.syncable = false; 5848 } 5849 if (!mProvidersByAuthority.containsKey(names[j])) { 5850 mProvidersByAuthority.put(names[j], p); 5851 if (p.info.authority == null) { 5852 p.info.authority = names[j]; 5853 } else { 5854 p.info.authority = p.info.authority + ";" + names[j]; 5855 } 5856 if (DEBUG_PACKAGE_SCANNING) { 5857 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5858 Log.d(TAG, "Registered content provider: " + names[j] 5859 + ", className = " + p.info.name + ", isSyncable = " 5860 + p.info.isSyncable); 5861 } 5862 } else { 5863 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5864 Slog.w(TAG, "Skipping provider name " + names[j] + 5865 " (in package " + pkg.applicationInfo.packageName + 5866 "): name already used by " 5867 + ((other != null && other.getComponentName() != null) 5868 ? other.getComponentName().getPackageName() : "?")); 5869 } 5870 } 5871 } 5872 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5873 if (r == null) { 5874 r = new StringBuilder(256); 5875 } else { 5876 r.append(' '); 5877 } 5878 r.append(p.info.name); 5879 } 5880 } 5881 if (r != null) { 5882 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 5883 } 5884 5885 N = pkg.services.size(); 5886 r = null; 5887 for (i=0; i<N; i++) { 5888 PackageParser.Service s = pkg.services.get(i); 5889 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 5890 s.info.processName, pkg.applicationInfo.uid); 5891 mServices.addService(s); 5892 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5893 if (r == null) { 5894 r = new StringBuilder(256); 5895 } else { 5896 r.append(' '); 5897 } 5898 r.append(s.info.name); 5899 } 5900 } 5901 if (r != null) { 5902 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 5903 } 5904 5905 N = pkg.receivers.size(); 5906 r = null; 5907 for (i=0; i<N; i++) { 5908 PackageParser.Activity a = pkg.receivers.get(i); 5909 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5910 a.info.processName, pkg.applicationInfo.uid); 5911 mReceivers.addActivity(a, "receiver"); 5912 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5913 if (r == null) { 5914 r = new StringBuilder(256); 5915 } else { 5916 r.append(' '); 5917 } 5918 r.append(a.info.name); 5919 } 5920 } 5921 if (r != null) { 5922 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 5923 } 5924 5925 N = pkg.activities.size(); 5926 r = null; 5927 for (i=0; i<N; i++) { 5928 PackageParser.Activity a = pkg.activities.get(i); 5929 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5930 a.info.processName, pkg.applicationInfo.uid); 5931 mActivities.addActivity(a, "activity"); 5932 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5933 if (r == null) { 5934 r = new StringBuilder(256); 5935 } else { 5936 r.append(' '); 5937 } 5938 r.append(a.info.name); 5939 } 5940 } 5941 if (r != null) { 5942 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 5943 } 5944 5945 N = pkg.permissionGroups.size(); 5946 r = null; 5947 for (i=0; i<N; i++) { 5948 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 5949 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 5950 if (cur == null) { 5951 mPermissionGroups.put(pg.info.name, pg); 5952 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5953 if (r == null) { 5954 r = new StringBuilder(256); 5955 } else { 5956 r.append(' '); 5957 } 5958 r.append(pg.info.name); 5959 } 5960 } else { 5961 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 5962 + pg.info.packageName + " ignored: original from " 5963 + cur.info.packageName); 5964 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5965 if (r == null) { 5966 r = new StringBuilder(256); 5967 } else { 5968 r.append(' '); 5969 } 5970 r.append("DUP:"); 5971 r.append(pg.info.name); 5972 } 5973 } 5974 } 5975 if (r != null) { 5976 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 5977 } 5978 5979 N = pkg.permissions.size(); 5980 r = null; 5981 for (i=0; i<N; i++) { 5982 PackageParser.Permission p = pkg.permissions.get(i); 5983 HashMap<String, BasePermission> permissionMap = 5984 p.tree ? mSettings.mPermissionTrees 5985 : mSettings.mPermissions; 5986 p.group = mPermissionGroups.get(p.info.group); 5987 if (p.info.group == null || p.group != null) { 5988 BasePermission bp = permissionMap.get(p.info.name); 5989 if (bp == null) { 5990 bp = new BasePermission(p.info.name, p.info.packageName, 5991 BasePermission.TYPE_NORMAL); 5992 permissionMap.put(p.info.name, bp); 5993 } 5994 if (bp.perm == null) { 5995 if (bp.sourcePackage != null 5996 && !bp.sourcePackage.equals(p.info.packageName)) { 5997 // If this is a permission that was formerly defined by a non-system 5998 // app, but is now defined by a system app (following an upgrade), 5999 // discard the previous declaration and consider the system's to be 6000 // canonical. 6001 if (isSystemApp(p.owner)) { 6002 String msg = "New decl " + p.owner + " of permission " 6003 + p.info.name + " is system"; 6004 reportSettingsProblem(Log.WARN, msg); 6005 bp.sourcePackage = null; 6006 } 6007 } 6008 if (bp.sourcePackage == null 6009 || bp.sourcePackage.equals(p.info.packageName)) { 6010 BasePermission tree = findPermissionTreeLP(p.info.name); 6011 if (tree == null 6012 || tree.sourcePackage.equals(p.info.packageName)) { 6013 bp.packageSetting = pkgSetting; 6014 bp.perm = p; 6015 bp.uid = pkg.applicationInfo.uid; 6016 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6017 if (r == null) { 6018 r = new StringBuilder(256); 6019 } else { 6020 r.append(' '); 6021 } 6022 r.append(p.info.name); 6023 } 6024 } else { 6025 Slog.w(TAG, "Permission " + p.info.name + " from package " 6026 + p.info.packageName + " ignored: base tree " 6027 + tree.name + " is from package " 6028 + tree.sourcePackage); 6029 } 6030 } else { 6031 Slog.w(TAG, "Permission " + p.info.name + " from package " 6032 + p.info.packageName + " ignored: original from " 6033 + bp.sourcePackage); 6034 } 6035 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6036 if (r == null) { 6037 r = new StringBuilder(256); 6038 } else { 6039 r.append(' '); 6040 } 6041 r.append("DUP:"); 6042 r.append(p.info.name); 6043 } 6044 if (bp.perm == p) { 6045 bp.protectionLevel = p.info.protectionLevel; 6046 } 6047 } else { 6048 Slog.w(TAG, "Permission " + p.info.name + " from package " 6049 + p.info.packageName + " ignored: no group " 6050 + p.group); 6051 } 6052 } 6053 if (r != null) { 6054 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6055 } 6056 6057 N = pkg.instrumentation.size(); 6058 r = null; 6059 for (i=0; i<N; i++) { 6060 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6061 a.info.packageName = pkg.applicationInfo.packageName; 6062 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6063 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6064 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6065 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6066 a.info.dataDir = pkg.applicationInfo.dataDir; 6067 6068 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6069 // need other information about the application, like the ABI and what not ? 6070 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6071 mInstrumentation.put(a.getComponentName(), a); 6072 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6073 if (r == null) { 6074 r = new StringBuilder(256); 6075 } else { 6076 r.append(' '); 6077 } 6078 r.append(a.info.name); 6079 } 6080 } 6081 if (r != null) { 6082 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6083 } 6084 6085 if (pkg.protectedBroadcasts != null) { 6086 N = pkg.protectedBroadcasts.size(); 6087 for (i=0; i<N; i++) { 6088 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6089 } 6090 } 6091 6092 pkgSetting.setTimeStamp(scanFileTime); 6093 6094 // Create idmap files for pairs of (packages, overlay packages). 6095 // Note: "android", ie framework-res.apk, is handled by native layers. 6096 if (pkg.mOverlayTarget != null) { 6097 // This is an overlay package. 6098 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6099 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6100 mOverlays.put(pkg.mOverlayTarget, 6101 new HashMap<String, PackageParser.Package>()); 6102 } 6103 HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6104 map.put(pkg.packageName, pkg); 6105 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6106 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6107 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6108 "scanPackageLI failed to createIdmap"); 6109 } 6110 } 6111 } else if (mOverlays.containsKey(pkg.packageName) && 6112 !pkg.packageName.equals("android")) { 6113 // This is a regular package, with one or more known overlay packages. 6114 createIdmapsForPackageLI(pkg); 6115 } 6116 } 6117 6118 return pkg; 6119 } 6120 6121 /** 6122 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6123 * i.e, so that all packages can be run inside a single process if required. 6124 * 6125 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6126 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6127 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6128 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6129 * updating a package that belongs to a shared user. 6130 * 6131 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6132 * adds unnecessary complexity. 6133 */ 6134 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6135 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6136 String requiredInstructionSet = null; 6137 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6138 requiredInstructionSet = VMRuntime.getInstructionSet( 6139 scannedPackage.applicationInfo.primaryCpuAbi); 6140 } 6141 6142 PackageSetting requirer = null; 6143 for (PackageSetting ps : packagesForUser) { 6144 // If packagesForUser contains scannedPackage, we skip it. This will happen 6145 // when scannedPackage is an update of an existing package. Without this check, 6146 // we will never be able to change the ABI of any package belonging to a shared 6147 // user, even if it's compatible with other packages. 6148 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6149 if (ps.primaryCpuAbiString == null) { 6150 continue; 6151 } 6152 6153 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6154 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6155 // We have a mismatch between instruction sets (say arm vs arm64) warn about 6156 // this but there's not much we can do. 6157 String errorMessage = "Instruction set mismatch, " 6158 + ((requirer == null) ? "[caller]" : requirer) 6159 + " requires " + requiredInstructionSet + " whereas " + ps 6160 + " requires " + instructionSet; 6161 Slog.w(TAG, errorMessage); 6162 } 6163 6164 if (requiredInstructionSet == null) { 6165 requiredInstructionSet = instructionSet; 6166 requirer = ps; 6167 } 6168 } 6169 } 6170 6171 if (requiredInstructionSet != null) { 6172 String adjustedAbi; 6173 if (requirer != null) { 6174 // requirer != null implies that either scannedPackage was null or that scannedPackage 6175 // did not require an ABI, in which case we have to adjust scannedPackage to match 6176 // the ABI of the set (which is the same as requirer's ABI) 6177 adjustedAbi = requirer.primaryCpuAbiString; 6178 if (scannedPackage != null) { 6179 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6180 } 6181 } else { 6182 // requirer == null implies that we're updating all ABIs in the set to 6183 // match scannedPackage. 6184 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6185 } 6186 6187 for (PackageSetting ps : packagesForUser) { 6188 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6189 if (ps.primaryCpuAbiString != null) { 6190 continue; 6191 } 6192 6193 ps.primaryCpuAbiString = adjustedAbi; 6194 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6195 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6196 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6197 6198 if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt, 6199 deferDexOpt, true) == DEX_OPT_FAILED) { 6200 ps.primaryCpuAbiString = null; 6201 ps.pkg.applicationInfo.primaryCpuAbi = null; 6202 return; 6203 } else { 6204 mInstaller.rmdex(ps.codePathString, 6205 getDexCodeInstructionSet(getPreferredInstructionSet())); 6206 } 6207 } 6208 } 6209 } 6210 } 6211 } 6212 6213 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6214 synchronized (mPackages) { 6215 mResolverReplaced = true; 6216 // Set up information for custom user intent resolution activity. 6217 mResolveActivity.applicationInfo = pkg.applicationInfo; 6218 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6219 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6220 mResolveActivity.processName = null; 6221 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6222 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6223 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6224 mResolveActivity.theme = 0; 6225 mResolveActivity.exported = true; 6226 mResolveActivity.enabled = true; 6227 mResolveInfo.activityInfo = mResolveActivity; 6228 mResolveInfo.priority = 0; 6229 mResolveInfo.preferredOrder = 0; 6230 mResolveInfo.match = 0; 6231 mResolveComponentName = mCustomResolverComponentName; 6232 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6233 mResolveComponentName); 6234 } 6235 } 6236 6237 private static String calculateBundledApkRoot(final String codePathString) { 6238 final File codePath = new File(codePathString); 6239 final File codeRoot; 6240 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6241 codeRoot = Environment.getRootDirectory(); 6242 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6243 codeRoot = Environment.getOemDirectory(); 6244 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6245 codeRoot = Environment.getVendorDirectory(); 6246 } else { 6247 // Unrecognized code path; take its top real segment as the apk root: 6248 // e.g. /something/app/blah.apk => /something 6249 try { 6250 File f = codePath.getCanonicalFile(); 6251 File parent = f.getParentFile(); // non-null because codePath is a file 6252 File tmp; 6253 while ((tmp = parent.getParentFile()) != null) { 6254 f = parent; 6255 parent = tmp; 6256 } 6257 codeRoot = f; 6258 Slog.w(TAG, "Unrecognized code path " 6259 + codePath + " - using " + codeRoot); 6260 } catch (IOException e) { 6261 // Can't canonicalize the code path -- shenanigans? 6262 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6263 return Environment.getRootDirectory().getPath(); 6264 } 6265 } 6266 return codeRoot.getPath(); 6267 } 6268 6269 /** 6270 * Derive and set the location of native libraries for the given package, 6271 * which varies depending on where and how the package was installed. 6272 */ 6273 private void setNativeLibraryPaths(PackageParser.Package pkg) { 6274 final ApplicationInfo info = pkg.applicationInfo; 6275 final String codePath = pkg.codePath; 6276 final File codeFile = new File(codePath); 6277 final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info); 6278 final boolean asecApp = isForwardLocked(info) || isExternal(info); 6279 6280 info.nativeLibraryRootDir = null; 6281 info.nativeLibraryRootRequiresIsa = false; 6282 info.nativeLibraryDir = null; 6283 info.secondaryNativeLibraryDir = null; 6284 6285 if (isApkFile(codeFile)) { 6286 // Monolithic install 6287 if (bundledApp) { 6288 // If "/system/lib64/apkname" exists, assume that is the per-package 6289 // native library directory to use; otherwise use "/system/lib/apkname". 6290 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 6291 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 6292 getPrimaryInstructionSet(info)); 6293 6294 // This is a bundled system app so choose the path based on the ABI. 6295 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 6296 // is just the default path. 6297 final String apkName = deriveCodePathName(codePath); 6298 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 6299 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 6300 apkName).getAbsolutePath(); 6301 6302 if (info.secondaryCpuAbi != null) { 6303 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 6304 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 6305 secondaryLibDir, apkName).getAbsolutePath(); 6306 } 6307 } else if (asecApp) { 6308 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 6309 .getAbsolutePath(); 6310 } else { 6311 final String apkName = deriveCodePathName(codePath); 6312 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 6313 .getAbsolutePath(); 6314 } 6315 6316 info.nativeLibraryRootRequiresIsa = false; 6317 info.nativeLibraryDir = info.nativeLibraryRootDir; 6318 } else { 6319 // Cluster install 6320 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 6321 info.nativeLibraryRootRequiresIsa = true; 6322 6323 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 6324 getPrimaryInstructionSet(info)).getAbsolutePath(); 6325 6326 if (info.secondaryCpuAbi != null) { 6327 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 6328 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 6329 } 6330 } 6331 } 6332 6333 /** 6334 * Calculate the abis and roots for a bundled app. These can uniquely 6335 * be determined from the contents of the system partition, i.e whether 6336 * it contains 64 or 32 bit shared libraries etc. We do not validate any 6337 * of this information, and instead assume that the system was built 6338 * sensibly. 6339 */ 6340 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 6341 PackageSetting pkgSetting) { 6342 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 6343 6344 // If "/system/lib64/apkname" exists, assume that is the per-package 6345 // native library directory to use; otherwise use "/system/lib/apkname". 6346 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 6347 setBundledAppAbi(pkg, apkRoot, apkName); 6348 // pkgSetting might be null during rescan following uninstall of updates 6349 // to a bundled app, so accommodate that possibility. The settings in 6350 // that case will be established later from the parsed package. 6351 // 6352 // If the settings aren't null, sync them up with what we've just derived. 6353 // note that apkRoot isn't stored in the package settings. 6354 if (pkgSetting != null) { 6355 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6356 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6357 } 6358 } 6359 6360 /** 6361 * Deduces the ABI of a bundled app and sets the relevant fields on the 6362 * parsed pkg object. 6363 * 6364 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 6365 * under which system libraries are installed. 6366 * @param apkName the name of the installed package. 6367 */ 6368 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 6369 final File codeFile = new File(pkg.codePath); 6370 6371 final boolean has64BitLibs; 6372 final boolean has32BitLibs; 6373 if (isApkFile(codeFile)) { 6374 // Monolithic install 6375 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 6376 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 6377 } else { 6378 // Cluster install 6379 final File rootDir = new File(codeFile, LIB_DIR_NAME); 6380 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 6381 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 6382 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 6383 has64BitLibs = (new File(rootDir, isa)).exists(); 6384 } else { 6385 has64BitLibs = false; 6386 } 6387 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 6388 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 6389 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 6390 has32BitLibs = (new File(rootDir, isa)).exists(); 6391 } else { 6392 has32BitLibs = false; 6393 } 6394 } 6395 6396 if (has64BitLibs && !has32BitLibs) { 6397 // The package has 64 bit libs, but not 32 bit libs. Its primary 6398 // ABI should be 64 bit. We can safely assume here that the bundled 6399 // native libraries correspond to the most preferred ABI in the list. 6400 6401 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6402 pkg.applicationInfo.secondaryCpuAbi = null; 6403 } else if (has32BitLibs && !has64BitLibs) { 6404 // The package has 32 bit libs but not 64 bit libs. Its primary 6405 // ABI should be 32 bit. 6406 6407 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6408 pkg.applicationInfo.secondaryCpuAbi = null; 6409 } else if (has32BitLibs && has64BitLibs) { 6410 // The application has both 64 and 32 bit bundled libraries. We check 6411 // here that the app declares multiArch support, and warn if it doesn't. 6412 // 6413 // We will be lenient here and record both ABIs. The primary will be the 6414 // ABI that's higher on the list, i.e, a device that's configured to prefer 6415 // 64 bit apps will see a 64 bit primary ABI, 6416 6417 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 6418 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 6419 } 6420 6421 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 6422 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6423 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6424 } else { 6425 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6426 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6427 } 6428 } else { 6429 pkg.applicationInfo.primaryCpuAbi = null; 6430 pkg.applicationInfo.secondaryCpuAbi = null; 6431 } 6432 } 6433 6434 private void killApplication(String pkgName, int appId, String reason) { 6435 // Request the ActivityManager to kill the process(only for existing packages) 6436 // so that we do not end up in a confused state while the user is still using the older 6437 // version of the application while the new one gets installed. 6438 IActivityManager am = ActivityManagerNative.getDefault(); 6439 if (am != null) { 6440 try { 6441 am.killApplicationWithAppId(pkgName, appId, reason); 6442 } catch (RemoteException e) { 6443 } 6444 } 6445 } 6446 6447 void removePackageLI(PackageSetting ps, boolean chatty) { 6448 if (DEBUG_INSTALL) { 6449 if (chatty) 6450 Log.d(TAG, "Removing package " + ps.name); 6451 } 6452 6453 // writer 6454 synchronized (mPackages) { 6455 mPackages.remove(ps.name); 6456 final PackageParser.Package pkg = ps.pkg; 6457 if (pkg != null) { 6458 cleanPackageDataStructuresLILPw(pkg, chatty); 6459 } 6460 } 6461 } 6462 6463 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 6464 if (DEBUG_INSTALL) { 6465 if (chatty) 6466 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 6467 } 6468 6469 // writer 6470 synchronized (mPackages) { 6471 mPackages.remove(pkg.applicationInfo.packageName); 6472 cleanPackageDataStructuresLILPw(pkg, chatty); 6473 } 6474 } 6475 6476 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 6477 int N = pkg.providers.size(); 6478 StringBuilder r = null; 6479 int i; 6480 for (i=0; i<N; i++) { 6481 PackageParser.Provider p = pkg.providers.get(i); 6482 mProviders.removeProvider(p); 6483 if (p.info.authority == null) { 6484 6485 /* There was another ContentProvider with this authority when 6486 * this app was installed so this authority is null, 6487 * Ignore it as we don't have to unregister the provider. 6488 */ 6489 continue; 6490 } 6491 String names[] = p.info.authority.split(";"); 6492 for (int j = 0; j < names.length; j++) { 6493 if (mProvidersByAuthority.get(names[j]) == p) { 6494 mProvidersByAuthority.remove(names[j]); 6495 if (DEBUG_REMOVE) { 6496 if (chatty) 6497 Log.d(TAG, "Unregistered content provider: " + names[j] 6498 + ", className = " + p.info.name + ", isSyncable = " 6499 + p.info.isSyncable); 6500 } 6501 } 6502 } 6503 if (DEBUG_REMOVE && chatty) { 6504 if (r == null) { 6505 r = new StringBuilder(256); 6506 } else { 6507 r.append(' '); 6508 } 6509 r.append(p.info.name); 6510 } 6511 } 6512 if (r != null) { 6513 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 6514 } 6515 6516 N = pkg.services.size(); 6517 r = null; 6518 for (i=0; i<N; i++) { 6519 PackageParser.Service s = pkg.services.get(i); 6520 mServices.removeService(s); 6521 if (chatty) { 6522 if (r == null) { 6523 r = new StringBuilder(256); 6524 } else { 6525 r.append(' '); 6526 } 6527 r.append(s.info.name); 6528 } 6529 } 6530 if (r != null) { 6531 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 6532 } 6533 6534 N = pkg.receivers.size(); 6535 r = null; 6536 for (i=0; i<N; i++) { 6537 PackageParser.Activity a = pkg.receivers.get(i); 6538 mReceivers.removeActivity(a, "receiver"); 6539 if (DEBUG_REMOVE && chatty) { 6540 if (r == null) { 6541 r = new StringBuilder(256); 6542 } else { 6543 r.append(' '); 6544 } 6545 r.append(a.info.name); 6546 } 6547 } 6548 if (r != null) { 6549 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 6550 } 6551 6552 N = pkg.activities.size(); 6553 r = null; 6554 for (i=0; i<N; i++) { 6555 PackageParser.Activity a = pkg.activities.get(i); 6556 mActivities.removeActivity(a, "activity"); 6557 if (DEBUG_REMOVE && chatty) { 6558 if (r == null) { 6559 r = new StringBuilder(256); 6560 } else { 6561 r.append(' '); 6562 } 6563 r.append(a.info.name); 6564 } 6565 } 6566 if (r != null) { 6567 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 6568 } 6569 6570 N = pkg.permissions.size(); 6571 r = null; 6572 for (i=0; i<N; i++) { 6573 PackageParser.Permission p = pkg.permissions.get(i); 6574 BasePermission bp = mSettings.mPermissions.get(p.info.name); 6575 if (bp == null) { 6576 bp = mSettings.mPermissionTrees.get(p.info.name); 6577 } 6578 if (bp != null && bp.perm == p) { 6579 bp.perm = null; 6580 if (DEBUG_REMOVE && chatty) { 6581 if (r == null) { 6582 r = new StringBuilder(256); 6583 } else { 6584 r.append(' '); 6585 } 6586 r.append(p.info.name); 6587 } 6588 } 6589 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6590 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 6591 if (appOpPerms != null) { 6592 appOpPerms.remove(pkg.packageName); 6593 } 6594 } 6595 } 6596 if (r != null) { 6597 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6598 } 6599 6600 N = pkg.requestedPermissions.size(); 6601 r = null; 6602 for (i=0; i<N; i++) { 6603 String perm = pkg.requestedPermissions.get(i); 6604 BasePermission bp = mSettings.mPermissions.get(perm); 6605 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6606 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 6607 if (appOpPerms != null) { 6608 appOpPerms.remove(pkg.packageName); 6609 if (appOpPerms.isEmpty()) { 6610 mAppOpPermissionPackages.remove(perm); 6611 } 6612 } 6613 } 6614 } 6615 if (r != null) { 6616 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6617 } 6618 6619 N = pkg.instrumentation.size(); 6620 r = null; 6621 for (i=0; i<N; i++) { 6622 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6623 mInstrumentation.remove(a.getComponentName()); 6624 if (DEBUG_REMOVE && chatty) { 6625 if (r == null) { 6626 r = new StringBuilder(256); 6627 } else { 6628 r.append(' '); 6629 } 6630 r.append(a.info.name); 6631 } 6632 } 6633 if (r != null) { 6634 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 6635 } 6636 6637 r = null; 6638 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6639 // Only system apps can hold shared libraries. 6640 if (pkg.libraryNames != null) { 6641 for (i=0; i<pkg.libraryNames.size(); i++) { 6642 String name = pkg.libraryNames.get(i); 6643 SharedLibraryEntry cur = mSharedLibraries.get(name); 6644 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 6645 mSharedLibraries.remove(name); 6646 if (DEBUG_REMOVE && chatty) { 6647 if (r == null) { 6648 r = new StringBuilder(256); 6649 } else { 6650 r.append(' '); 6651 } 6652 r.append(name); 6653 } 6654 } 6655 } 6656 } 6657 } 6658 if (r != null) { 6659 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 6660 } 6661 } 6662 6663 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 6664 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 6665 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 6666 return true; 6667 } 6668 } 6669 return false; 6670 } 6671 6672 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 6673 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 6674 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 6675 6676 private void updatePermissionsLPw(String changingPkg, 6677 PackageParser.Package pkgInfo, int flags) { 6678 // Make sure there are no dangling permission trees. 6679 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 6680 while (it.hasNext()) { 6681 final BasePermission bp = it.next(); 6682 if (bp.packageSetting == null) { 6683 // We may not yet have parsed the package, so just see if 6684 // we still know about its settings. 6685 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6686 } 6687 if (bp.packageSetting == null) { 6688 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 6689 + " from package " + bp.sourcePackage); 6690 it.remove(); 6691 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6692 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6693 Slog.i(TAG, "Removing old permission tree: " + bp.name 6694 + " from package " + bp.sourcePackage); 6695 flags |= UPDATE_PERMISSIONS_ALL; 6696 it.remove(); 6697 } 6698 } 6699 } 6700 6701 // Make sure all dynamic permissions have been assigned to a package, 6702 // and make sure there are no dangling permissions. 6703 it = mSettings.mPermissions.values().iterator(); 6704 while (it.hasNext()) { 6705 final BasePermission bp = it.next(); 6706 if (bp.type == BasePermission.TYPE_DYNAMIC) { 6707 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 6708 + bp.name + " pkg=" + bp.sourcePackage 6709 + " info=" + bp.pendingInfo); 6710 if (bp.packageSetting == null && bp.pendingInfo != null) { 6711 final BasePermission tree = findPermissionTreeLP(bp.name); 6712 if (tree != null && tree.perm != null) { 6713 bp.packageSetting = tree.packageSetting; 6714 bp.perm = new PackageParser.Permission(tree.perm.owner, 6715 new PermissionInfo(bp.pendingInfo)); 6716 bp.perm.info.packageName = tree.perm.info.packageName; 6717 bp.perm.info.name = bp.name; 6718 bp.uid = tree.uid; 6719 } 6720 } 6721 } 6722 if (bp.packageSetting == null) { 6723 // We may not yet have parsed the package, so just see if 6724 // we still know about its settings. 6725 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6726 } 6727 if (bp.packageSetting == null) { 6728 Slog.w(TAG, "Removing dangling permission: " + bp.name 6729 + " from package " + bp.sourcePackage); 6730 it.remove(); 6731 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6732 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6733 Slog.i(TAG, "Removing old permission: " + bp.name 6734 + " from package " + bp.sourcePackage); 6735 flags |= UPDATE_PERMISSIONS_ALL; 6736 it.remove(); 6737 } 6738 } 6739 } 6740 6741 // Now update the permissions for all packages, in particular 6742 // replace the granted permissions of the system packages. 6743 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 6744 for (PackageParser.Package pkg : mPackages.values()) { 6745 if (pkg != pkgInfo) { 6746 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0); 6747 } 6748 } 6749 } 6750 6751 if (pkgInfo != null) { 6752 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0); 6753 } 6754 } 6755 6756 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) { 6757 final PackageSetting ps = (PackageSetting) pkg.mExtras; 6758 if (ps == null) { 6759 return; 6760 } 6761 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 6762 HashSet<String> origPermissions = gp.grantedPermissions; 6763 boolean changedPermission = false; 6764 6765 if (replace) { 6766 ps.permissionsFixed = false; 6767 if (gp == ps) { 6768 origPermissions = new HashSet<String>(gp.grantedPermissions); 6769 gp.grantedPermissions.clear(); 6770 gp.gids = mGlobalGids; 6771 } 6772 } 6773 6774 if (gp.gids == null) { 6775 gp.gids = mGlobalGids; 6776 } 6777 6778 final int N = pkg.requestedPermissions.size(); 6779 for (int i=0; i<N; i++) { 6780 final String name = pkg.requestedPermissions.get(i); 6781 final boolean required = pkg.requestedPermissionsRequired.get(i); 6782 final BasePermission bp = mSettings.mPermissions.get(name); 6783 if (DEBUG_INSTALL) { 6784 if (gp != ps) { 6785 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 6786 } 6787 } 6788 6789 if (bp == null || bp.packageSetting == null) { 6790 Slog.w(TAG, "Unknown permission " + name 6791 + " in package " + pkg.packageName); 6792 continue; 6793 } 6794 6795 final String perm = bp.name; 6796 boolean allowed; 6797 boolean allowedSig = false; 6798 if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6799 // Keep track of app op permissions. 6800 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 6801 if (pkgs == null) { 6802 pkgs = new ArraySet<>(); 6803 mAppOpPermissionPackages.put(bp.name, pkgs); 6804 } 6805 pkgs.add(pkg.packageName); 6806 } 6807 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 6808 if (level == PermissionInfo.PROTECTION_NORMAL 6809 || level == PermissionInfo.PROTECTION_DANGEROUS) { 6810 // We grant a normal or dangerous permission if any of the following 6811 // are true: 6812 // 1) The permission is required 6813 // 2) The permission is optional, but was granted in the past 6814 // 3) The permission is optional, but was requested by an 6815 // app in /system (not /data) 6816 // 6817 // Otherwise, reject the permission. 6818 allowed = (required || origPermissions.contains(perm) 6819 || (isSystemApp(ps) && !isUpdatedSystemApp(ps))); 6820 } else if (bp.packageSetting == null) { 6821 // This permission is invalid; skip it. 6822 allowed = false; 6823 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 6824 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions); 6825 if (allowed) { 6826 allowedSig = true; 6827 } 6828 } else { 6829 allowed = false; 6830 } 6831 if (DEBUG_INSTALL) { 6832 if (gp != ps) { 6833 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 6834 } 6835 } 6836 if (allowed) { 6837 if (!isSystemApp(ps) && ps.permissionsFixed) { 6838 // If this is an existing, non-system package, then 6839 // we can't add any new permissions to it. 6840 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 6841 // Except... if this is a permission that was added 6842 // to the platform (note: need to only do this when 6843 // updating the platform). 6844 allowed = isNewPlatformPermissionForPackage(perm, pkg); 6845 } 6846 } 6847 if (allowed) { 6848 if (!gp.grantedPermissions.contains(perm)) { 6849 changedPermission = true; 6850 gp.grantedPermissions.add(perm); 6851 gp.gids = appendInts(gp.gids, bp.gids); 6852 } else if (!ps.haveGids) { 6853 gp.gids = appendInts(gp.gids, bp.gids); 6854 } 6855 } else { 6856 Slog.w(TAG, "Not granting permission " + perm 6857 + " to package " + pkg.packageName 6858 + " because it was previously installed without"); 6859 } 6860 } else { 6861 if (gp.grantedPermissions.remove(perm)) { 6862 changedPermission = true; 6863 gp.gids = removeInts(gp.gids, bp.gids); 6864 Slog.i(TAG, "Un-granting permission " + perm 6865 + " from package " + pkg.packageName 6866 + " (protectionLevel=" + bp.protectionLevel 6867 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6868 + ")"); 6869 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 6870 // Don't print warning for app op permissions, since it is fine for them 6871 // not to be granted, there is a UI for the user to decide. 6872 Slog.w(TAG, "Not granting permission " + perm 6873 + " to package " + pkg.packageName 6874 + " (protectionLevel=" + bp.protectionLevel 6875 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6876 + ")"); 6877 } 6878 } 6879 } 6880 6881 if ((changedPermission || replace) && !ps.permissionsFixed && 6882 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 6883 // This is the first that we have heard about this package, so the 6884 // permissions we have now selected are fixed until explicitly 6885 // changed. 6886 ps.permissionsFixed = true; 6887 } 6888 ps.haveGids = true; 6889 } 6890 6891 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 6892 boolean allowed = false; 6893 final int NP = PackageParser.NEW_PERMISSIONS.length; 6894 for (int ip=0; ip<NP; ip++) { 6895 final PackageParser.NewPermissionInfo npi 6896 = PackageParser.NEW_PERMISSIONS[ip]; 6897 if (npi.name.equals(perm) 6898 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 6899 allowed = true; 6900 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 6901 + pkg.packageName); 6902 break; 6903 } 6904 } 6905 return allowed; 6906 } 6907 6908 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 6909 BasePermission bp, HashSet<String> origPermissions) { 6910 boolean allowed; 6911 allowed = (compareSignatures( 6912 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 6913 == PackageManager.SIGNATURE_MATCH) 6914 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 6915 == PackageManager.SIGNATURE_MATCH); 6916 if (!allowed && (bp.protectionLevel 6917 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 6918 if (isSystemApp(pkg)) { 6919 // For updated system applications, a system permission 6920 // is granted only if it had been defined by the original application. 6921 if (isUpdatedSystemApp(pkg)) { 6922 final PackageSetting sysPs = mSettings 6923 .getDisabledSystemPkgLPr(pkg.packageName); 6924 final GrantedPermissions origGp = sysPs.sharedUser != null 6925 ? sysPs.sharedUser : sysPs; 6926 6927 if (origGp.grantedPermissions.contains(perm)) { 6928 // If the original was granted this permission, we take 6929 // that grant decision as read and propagate it to the 6930 // update. 6931 allowed = true; 6932 } else { 6933 // The system apk may have been updated with an older 6934 // version of the one on the data partition, but which 6935 // granted a new system permission that it didn't have 6936 // before. In this case we do want to allow the app to 6937 // now get the new permission if the ancestral apk is 6938 // privileged to get it. 6939 if (sysPs.pkg != null && sysPs.isPrivileged()) { 6940 for (int j=0; 6941 j<sysPs.pkg.requestedPermissions.size(); j++) { 6942 if (perm.equals( 6943 sysPs.pkg.requestedPermissions.get(j))) { 6944 allowed = true; 6945 break; 6946 } 6947 } 6948 } 6949 } 6950 } else { 6951 allowed = isPrivilegedApp(pkg); 6952 } 6953 } 6954 } 6955 if (!allowed && (bp.protectionLevel 6956 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 6957 // For development permissions, a development permission 6958 // is granted only if it was already granted. 6959 allowed = origPermissions.contains(perm); 6960 } 6961 return allowed; 6962 } 6963 6964 final class ActivityIntentResolver 6965 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 6966 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 6967 boolean defaultOnly, int userId) { 6968 if (!sUserManager.exists(userId)) return null; 6969 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 6970 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 6971 } 6972 6973 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 6974 int userId) { 6975 if (!sUserManager.exists(userId)) return null; 6976 mFlags = flags; 6977 return super.queryIntent(intent, resolvedType, 6978 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 6979 } 6980 6981 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 6982 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 6983 if (!sUserManager.exists(userId)) return null; 6984 if (packageActivities == null) { 6985 return null; 6986 } 6987 mFlags = flags; 6988 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 6989 final int N = packageActivities.size(); 6990 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 6991 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 6992 6993 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 6994 for (int i = 0; i < N; ++i) { 6995 intentFilters = packageActivities.get(i).intents; 6996 if (intentFilters != null && intentFilters.size() > 0) { 6997 PackageParser.ActivityIntentInfo[] array = 6998 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 6999 intentFilters.toArray(array); 7000 listCut.add(array); 7001 } 7002 } 7003 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7004 } 7005 7006 public final void addActivity(PackageParser.Activity a, String type) { 7007 final boolean systemApp = isSystemApp(a.info.applicationInfo); 7008 mActivities.put(a.getComponentName(), a); 7009 if (DEBUG_SHOW_INFO) 7010 Log.v( 7011 TAG, " " + type + " " + 7012 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 7013 if (DEBUG_SHOW_INFO) 7014 Log.v(TAG, " Class=" + a.info.name); 7015 final int NI = a.intents.size(); 7016 for (int j=0; j<NI; j++) { 7017 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7018 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 7019 intent.setPriority(0); 7020 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 7021 + a.className + " with priority > 0, forcing to 0"); 7022 } 7023 if (DEBUG_SHOW_INFO) { 7024 Log.v(TAG, " IntentFilter:"); 7025 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7026 } 7027 if (!intent.debugCheck()) { 7028 Log.w(TAG, "==> For Activity " + a.info.name); 7029 } 7030 addFilter(intent); 7031 } 7032 } 7033 7034 public final void removeActivity(PackageParser.Activity a, String type) { 7035 mActivities.remove(a.getComponentName()); 7036 if (DEBUG_SHOW_INFO) { 7037 Log.v(TAG, " " + type + " " 7038 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 7039 : a.info.name) + ":"); 7040 Log.v(TAG, " Class=" + a.info.name); 7041 } 7042 final int NI = a.intents.size(); 7043 for (int j=0; j<NI; j++) { 7044 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7045 if (DEBUG_SHOW_INFO) { 7046 Log.v(TAG, " IntentFilter:"); 7047 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7048 } 7049 removeFilter(intent); 7050 } 7051 } 7052 7053 @Override 7054 protected boolean allowFilterResult( 7055 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 7056 ActivityInfo filterAi = filter.activity.info; 7057 for (int i=dest.size()-1; i>=0; i--) { 7058 ActivityInfo destAi = dest.get(i).activityInfo; 7059 if (destAi.name == filterAi.name 7060 && destAi.packageName == filterAi.packageName) { 7061 return false; 7062 } 7063 } 7064 return true; 7065 } 7066 7067 @Override 7068 protected ActivityIntentInfo[] newArray(int size) { 7069 return new ActivityIntentInfo[size]; 7070 } 7071 7072 @Override 7073 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 7074 if (!sUserManager.exists(userId)) return true; 7075 PackageParser.Package p = filter.activity.owner; 7076 if (p != null) { 7077 PackageSetting ps = (PackageSetting)p.mExtras; 7078 if (ps != null) { 7079 // System apps are never considered stopped for purposes of 7080 // filtering, because there may be no way for the user to 7081 // actually re-launch them. 7082 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 7083 && ps.getStopped(userId); 7084 } 7085 } 7086 return false; 7087 } 7088 7089 @Override 7090 protected boolean isPackageForFilter(String packageName, 7091 PackageParser.ActivityIntentInfo info) { 7092 return packageName.equals(info.activity.owner.packageName); 7093 } 7094 7095 @Override 7096 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7097 int match, int userId) { 7098 if (!sUserManager.exists(userId)) return null; 7099 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7100 return null; 7101 } 7102 final PackageParser.Activity activity = info.activity; 7103 if (mSafeMode && (activity.info.applicationInfo.flags 7104 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7105 return null; 7106 } 7107 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7108 if (ps == null) { 7109 return null; 7110 } 7111 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7112 ps.readUserState(userId), userId); 7113 if (ai == null) { 7114 return null; 7115 } 7116 final ResolveInfo res = new ResolveInfo(); 7117 res.activityInfo = ai; 7118 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7119 res.filter = info; 7120 } 7121 res.priority = info.getPriority(); 7122 res.preferredOrder = activity.owner.mPreferredOrder; 7123 //System.out.println("Result: " + res.activityInfo.className + 7124 // " = " + res.priority); 7125 res.match = match; 7126 res.isDefault = info.hasDefault; 7127 res.labelRes = info.labelRes; 7128 res.nonLocalizedLabel = info.nonLocalizedLabel; 7129 if (userNeedsBadging(userId)) { 7130 res.noResourceId = true; 7131 } else { 7132 res.icon = info.icon; 7133 } 7134 res.system = isSystemApp(res.activityInfo.applicationInfo); 7135 return res; 7136 } 7137 7138 @Override 7139 protected void sortResults(List<ResolveInfo> results) { 7140 Collections.sort(results, mResolvePrioritySorter); 7141 } 7142 7143 @Override 7144 protected void dumpFilter(PrintWriter out, String prefix, 7145 PackageParser.ActivityIntentInfo filter) { 7146 out.print(prefix); out.print( 7147 Integer.toHexString(System.identityHashCode(filter.activity))); 7148 out.print(' '); 7149 filter.activity.printComponentShortName(out); 7150 out.print(" filter "); 7151 out.println(Integer.toHexString(System.identityHashCode(filter))); 7152 } 7153 7154// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7155// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7156// final List<ResolveInfo> retList = Lists.newArrayList(); 7157// while (i.hasNext()) { 7158// final ResolveInfo resolveInfo = i.next(); 7159// if (isEnabledLP(resolveInfo.activityInfo)) { 7160// retList.add(resolveInfo); 7161// } 7162// } 7163// return retList; 7164// } 7165 7166 // Keys are String (activity class name), values are Activity. 7167 private final HashMap<ComponentName, PackageParser.Activity> mActivities 7168 = new HashMap<ComponentName, PackageParser.Activity>(); 7169 private int mFlags; 7170 } 7171 7172 private final class ServiceIntentResolver 7173 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 7174 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7175 boolean defaultOnly, int userId) { 7176 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7177 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7178 } 7179 7180 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7181 int userId) { 7182 if (!sUserManager.exists(userId)) return null; 7183 mFlags = flags; 7184 return super.queryIntent(intent, resolvedType, 7185 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7186 } 7187 7188 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7189 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 7190 if (!sUserManager.exists(userId)) return null; 7191 if (packageServices == null) { 7192 return null; 7193 } 7194 mFlags = flags; 7195 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7196 final int N = packageServices.size(); 7197 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 7198 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 7199 7200 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 7201 for (int i = 0; i < N; ++i) { 7202 intentFilters = packageServices.get(i).intents; 7203 if (intentFilters != null && intentFilters.size() > 0) { 7204 PackageParser.ServiceIntentInfo[] array = 7205 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 7206 intentFilters.toArray(array); 7207 listCut.add(array); 7208 } 7209 } 7210 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7211 } 7212 7213 public final void addService(PackageParser.Service s) { 7214 mServices.put(s.getComponentName(), s); 7215 if (DEBUG_SHOW_INFO) { 7216 Log.v(TAG, " " 7217 + (s.info.nonLocalizedLabel != null 7218 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7219 Log.v(TAG, " Class=" + s.info.name); 7220 } 7221 final int NI = s.intents.size(); 7222 int j; 7223 for (j=0; j<NI; j++) { 7224 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7225 if (DEBUG_SHOW_INFO) { 7226 Log.v(TAG, " IntentFilter:"); 7227 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7228 } 7229 if (!intent.debugCheck()) { 7230 Log.w(TAG, "==> For Service " + s.info.name); 7231 } 7232 addFilter(intent); 7233 } 7234 } 7235 7236 public final void removeService(PackageParser.Service s) { 7237 mServices.remove(s.getComponentName()); 7238 if (DEBUG_SHOW_INFO) { 7239 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 7240 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7241 Log.v(TAG, " Class=" + s.info.name); 7242 } 7243 final int NI = s.intents.size(); 7244 int j; 7245 for (j=0; j<NI; j++) { 7246 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7247 if (DEBUG_SHOW_INFO) { 7248 Log.v(TAG, " IntentFilter:"); 7249 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7250 } 7251 removeFilter(intent); 7252 } 7253 } 7254 7255 @Override 7256 protected boolean allowFilterResult( 7257 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 7258 ServiceInfo filterSi = filter.service.info; 7259 for (int i=dest.size()-1; i>=0; i--) { 7260 ServiceInfo destAi = dest.get(i).serviceInfo; 7261 if (destAi.name == filterSi.name 7262 && destAi.packageName == filterSi.packageName) { 7263 return false; 7264 } 7265 } 7266 return true; 7267 } 7268 7269 @Override 7270 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 7271 return new PackageParser.ServiceIntentInfo[size]; 7272 } 7273 7274 @Override 7275 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 7276 if (!sUserManager.exists(userId)) return true; 7277 PackageParser.Package p = filter.service.owner; 7278 if (p != null) { 7279 PackageSetting ps = (PackageSetting)p.mExtras; 7280 if (ps != null) { 7281 // System apps are never considered stopped for purposes of 7282 // filtering, because there may be no way for the user to 7283 // actually re-launch them. 7284 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7285 && ps.getStopped(userId); 7286 } 7287 } 7288 return false; 7289 } 7290 7291 @Override 7292 protected boolean isPackageForFilter(String packageName, 7293 PackageParser.ServiceIntentInfo info) { 7294 return packageName.equals(info.service.owner.packageName); 7295 } 7296 7297 @Override 7298 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 7299 int match, int userId) { 7300 if (!sUserManager.exists(userId)) return null; 7301 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 7302 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 7303 return null; 7304 } 7305 final PackageParser.Service service = info.service; 7306 if (mSafeMode && (service.info.applicationInfo.flags 7307 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7308 return null; 7309 } 7310 PackageSetting ps = (PackageSetting) service.owner.mExtras; 7311 if (ps == null) { 7312 return null; 7313 } 7314 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 7315 ps.readUserState(userId), userId); 7316 if (si == null) { 7317 return null; 7318 } 7319 final ResolveInfo res = new ResolveInfo(); 7320 res.serviceInfo = si; 7321 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7322 res.filter = filter; 7323 } 7324 res.priority = info.getPriority(); 7325 res.preferredOrder = service.owner.mPreferredOrder; 7326 //System.out.println("Result: " + res.activityInfo.className + 7327 // " = " + res.priority); 7328 res.match = match; 7329 res.isDefault = info.hasDefault; 7330 res.labelRes = info.labelRes; 7331 res.nonLocalizedLabel = info.nonLocalizedLabel; 7332 res.icon = info.icon; 7333 res.system = isSystemApp(res.serviceInfo.applicationInfo); 7334 return res; 7335 } 7336 7337 @Override 7338 protected void sortResults(List<ResolveInfo> results) { 7339 Collections.sort(results, mResolvePrioritySorter); 7340 } 7341 7342 @Override 7343 protected void dumpFilter(PrintWriter out, String prefix, 7344 PackageParser.ServiceIntentInfo filter) { 7345 out.print(prefix); out.print( 7346 Integer.toHexString(System.identityHashCode(filter.service))); 7347 out.print(' '); 7348 filter.service.printComponentShortName(out); 7349 out.print(" filter "); 7350 out.println(Integer.toHexString(System.identityHashCode(filter))); 7351 } 7352 7353// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7354// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7355// final List<ResolveInfo> retList = Lists.newArrayList(); 7356// while (i.hasNext()) { 7357// final ResolveInfo resolveInfo = (ResolveInfo) i; 7358// if (isEnabledLP(resolveInfo.serviceInfo)) { 7359// retList.add(resolveInfo); 7360// } 7361// } 7362// return retList; 7363// } 7364 7365 // Keys are String (activity class name), values are Activity. 7366 private final HashMap<ComponentName, PackageParser.Service> mServices 7367 = new HashMap<ComponentName, PackageParser.Service>(); 7368 private int mFlags; 7369 }; 7370 7371 private final class ProviderIntentResolver 7372 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 7373 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7374 boolean defaultOnly, int userId) { 7375 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7376 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7377 } 7378 7379 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7380 int userId) { 7381 if (!sUserManager.exists(userId)) 7382 return null; 7383 mFlags = flags; 7384 return super.queryIntent(intent, resolvedType, 7385 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7386 } 7387 7388 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7389 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 7390 if (!sUserManager.exists(userId)) 7391 return null; 7392 if (packageProviders == null) { 7393 return null; 7394 } 7395 mFlags = flags; 7396 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 7397 final int N = packageProviders.size(); 7398 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 7399 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 7400 7401 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 7402 for (int i = 0; i < N; ++i) { 7403 intentFilters = packageProviders.get(i).intents; 7404 if (intentFilters != null && intentFilters.size() > 0) { 7405 PackageParser.ProviderIntentInfo[] array = 7406 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 7407 intentFilters.toArray(array); 7408 listCut.add(array); 7409 } 7410 } 7411 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7412 } 7413 7414 public final void addProvider(PackageParser.Provider p) { 7415 if (mProviders.containsKey(p.getComponentName())) { 7416 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 7417 return; 7418 } 7419 7420 mProviders.put(p.getComponentName(), p); 7421 if (DEBUG_SHOW_INFO) { 7422 Log.v(TAG, " " 7423 + (p.info.nonLocalizedLabel != null 7424 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7425 Log.v(TAG, " Class=" + p.info.name); 7426 } 7427 final int NI = p.intents.size(); 7428 int j; 7429 for (j = 0; j < NI; j++) { 7430 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7431 if (DEBUG_SHOW_INFO) { 7432 Log.v(TAG, " IntentFilter:"); 7433 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7434 } 7435 if (!intent.debugCheck()) { 7436 Log.w(TAG, "==> For Provider " + p.info.name); 7437 } 7438 addFilter(intent); 7439 } 7440 } 7441 7442 public final void removeProvider(PackageParser.Provider p) { 7443 mProviders.remove(p.getComponentName()); 7444 if (DEBUG_SHOW_INFO) { 7445 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 7446 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7447 Log.v(TAG, " Class=" + p.info.name); 7448 } 7449 final int NI = p.intents.size(); 7450 int j; 7451 for (j = 0; j < NI; j++) { 7452 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7453 if (DEBUG_SHOW_INFO) { 7454 Log.v(TAG, " IntentFilter:"); 7455 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7456 } 7457 removeFilter(intent); 7458 } 7459 } 7460 7461 @Override 7462 protected boolean allowFilterResult( 7463 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 7464 ProviderInfo filterPi = filter.provider.info; 7465 for (int i = dest.size() - 1; i >= 0; i--) { 7466 ProviderInfo destPi = dest.get(i).providerInfo; 7467 if (destPi.name == filterPi.name 7468 && destPi.packageName == filterPi.packageName) { 7469 return false; 7470 } 7471 } 7472 return true; 7473 } 7474 7475 @Override 7476 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 7477 return new PackageParser.ProviderIntentInfo[size]; 7478 } 7479 7480 @Override 7481 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 7482 if (!sUserManager.exists(userId)) 7483 return true; 7484 PackageParser.Package p = filter.provider.owner; 7485 if (p != null) { 7486 PackageSetting ps = (PackageSetting) p.mExtras; 7487 if (ps != null) { 7488 // System apps are never considered stopped for purposes of 7489 // filtering, because there may be no way for the user to 7490 // actually re-launch them. 7491 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7492 && ps.getStopped(userId); 7493 } 7494 } 7495 return false; 7496 } 7497 7498 @Override 7499 protected boolean isPackageForFilter(String packageName, 7500 PackageParser.ProviderIntentInfo info) { 7501 return packageName.equals(info.provider.owner.packageName); 7502 } 7503 7504 @Override 7505 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 7506 int match, int userId) { 7507 if (!sUserManager.exists(userId)) 7508 return null; 7509 final PackageParser.ProviderIntentInfo info = filter; 7510 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 7511 return null; 7512 } 7513 final PackageParser.Provider provider = info.provider; 7514 if (mSafeMode && (provider.info.applicationInfo.flags 7515 & ApplicationInfo.FLAG_SYSTEM) == 0) { 7516 return null; 7517 } 7518 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 7519 if (ps == null) { 7520 return null; 7521 } 7522 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 7523 ps.readUserState(userId), userId); 7524 if (pi == null) { 7525 return null; 7526 } 7527 final ResolveInfo res = new ResolveInfo(); 7528 res.providerInfo = pi; 7529 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 7530 res.filter = filter; 7531 } 7532 res.priority = info.getPriority(); 7533 res.preferredOrder = provider.owner.mPreferredOrder; 7534 res.match = match; 7535 res.isDefault = info.hasDefault; 7536 res.labelRes = info.labelRes; 7537 res.nonLocalizedLabel = info.nonLocalizedLabel; 7538 res.icon = info.icon; 7539 res.system = isSystemApp(res.providerInfo.applicationInfo); 7540 return res; 7541 } 7542 7543 @Override 7544 protected void sortResults(List<ResolveInfo> results) { 7545 Collections.sort(results, mResolvePrioritySorter); 7546 } 7547 7548 @Override 7549 protected void dumpFilter(PrintWriter out, String prefix, 7550 PackageParser.ProviderIntentInfo filter) { 7551 out.print(prefix); 7552 out.print( 7553 Integer.toHexString(System.identityHashCode(filter.provider))); 7554 out.print(' '); 7555 filter.provider.printComponentShortName(out); 7556 out.print(" filter "); 7557 out.println(Integer.toHexString(System.identityHashCode(filter))); 7558 } 7559 7560 private final HashMap<ComponentName, PackageParser.Provider> mProviders 7561 = new HashMap<ComponentName, PackageParser.Provider>(); 7562 private int mFlags; 7563 }; 7564 7565 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 7566 new Comparator<ResolveInfo>() { 7567 public int compare(ResolveInfo r1, ResolveInfo r2) { 7568 int v1 = r1.priority; 7569 int v2 = r2.priority; 7570 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 7571 if (v1 != v2) { 7572 return (v1 > v2) ? -1 : 1; 7573 } 7574 v1 = r1.preferredOrder; 7575 v2 = r2.preferredOrder; 7576 if (v1 != v2) { 7577 return (v1 > v2) ? -1 : 1; 7578 } 7579 if (r1.isDefault != r2.isDefault) { 7580 return r1.isDefault ? -1 : 1; 7581 } 7582 v1 = r1.match; 7583 v2 = r2.match; 7584 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 7585 if (v1 != v2) { 7586 return (v1 > v2) ? -1 : 1; 7587 } 7588 if (r1.system != r2.system) { 7589 return r1.system ? -1 : 1; 7590 } 7591 return 0; 7592 } 7593 }; 7594 7595 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 7596 new Comparator<ProviderInfo>() { 7597 public int compare(ProviderInfo p1, ProviderInfo p2) { 7598 final int v1 = p1.initOrder; 7599 final int v2 = p2.initOrder; 7600 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 7601 } 7602 }; 7603 7604 static final void sendPackageBroadcast(String action, String pkg, 7605 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 7606 int[] userIds) { 7607 IActivityManager am = ActivityManagerNative.getDefault(); 7608 if (am != null) { 7609 try { 7610 if (userIds == null) { 7611 userIds = am.getRunningUserIds(); 7612 } 7613 for (int id : userIds) { 7614 final Intent intent = new Intent(action, 7615 pkg != null ? Uri.fromParts("package", pkg, null) : null); 7616 if (extras != null) { 7617 intent.putExtras(extras); 7618 } 7619 if (targetPkg != null) { 7620 intent.setPackage(targetPkg); 7621 } 7622 // Modify the UID when posting to other users 7623 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 7624 if (uid > 0 && UserHandle.getUserId(uid) != id) { 7625 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 7626 intent.putExtra(Intent.EXTRA_UID, uid); 7627 } 7628 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 7629 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 7630 if (DEBUG_BROADCASTS) { 7631 RuntimeException here = new RuntimeException("here"); 7632 here.fillInStackTrace(); 7633 Slog.d(TAG, "Sending to user " + id + ": " 7634 + intent.toShortString(false, true, false, false) 7635 + " " + intent.getExtras(), here); 7636 } 7637 am.broadcastIntent(null, intent, null, finishedReceiver, 7638 0, null, null, null, android.app.AppOpsManager.OP_NONE, 7639 finishedReceiver != null, false, id); 7640 } 7641 } catch (RemoteException ex) { 7642 } 7643 } 7644 } 7645 7646 /** 7647 * Check if the external storage media is available. This is true if there 7648 * is a mounted external storage medium or if the external storage is 7649 * emulated. 7650 */ 7651 private boolean isExternalMediaAvailable() { 7652 return mMediaMounted || Environment.isExternalStorageEmulated(); 7653 } 7654 7655 @Override 7656 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 7657 // writer 7658 synchronized (mPackages) { 7659 if (!isExternalMediaAvailable()) { 7660 // If the external storage is no longer mounted at this point, 7661 // the caller may not have been able to delete all of this 7662 // packages files and can not delete any more. Bail. 7663 return null; 7664 } 7665 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 7666 if (lastPackage != null) { 7667 pkgs.remove(lastPackage); 7668 } 7669 if (pkgs.size() > 0) { 7670 return pkgs.get(0); 7671 } 7672 } 7673 return null; 7674 } 7675 7676 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 7677 if (false) { 7678 RuntimeException here = new RuntimeException("here"); 7679 here.fillInStackTrace(); 7680 Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId 7681 + " andCode=" + andCode, here); 7682 } 7683 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, 7684 userId, andCode ? 1 : 0, packageName)); 7685 } 7686 7687 void startCleaningPackages() { 7688 // reader 7689 synchronized (mPackages) { 7690 if (!isExternalMediaAvailable()) { 7691 return; 7692 } 7693 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 7694 return; 7695 } 7696 } 7697 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 7698 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 7699 IActivityManager am = ActivityManagerNative.getDefault(); 7700 if (am != null) { 7701 try { 7702 am.startService(null, intent, null, UserHandle.USER_OWNER); 7703 } catch (RemoteException e) { 7704 } 7705 } 7706 } 7707 7708 @Override 7709 public void installPackage(String originPath, IPackageInstallObserver2 observer, 7710 int installFlags, String installerPackageName, VerificationParams verificationParams, 7711 String packageAbiOverride) { 7712 installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams, 7713 packageAbiOverride, UserHandle.getCallingUserId()); 7714 } 7715 7716 @Override 7717 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 7718 int installFlags, String installerPackageName, VerificationParams verificationParams, 7719 String packageAbiOverride, int userId) { 7720 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7721 null); 7722 if (UserHandle.getCallingUserId() != userId) { 7723 mContext.enforceCallingOrSelfPermission( 7724 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 7725 "installPackage " + userId); 7726 } 7727 7728 final File originFile = new File(originPath); 7729 final int uid = Binder.getCallingUid(); 7730 if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) { 7731 try { 7732 if (observer != null) { 7733 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 7734 } 7735 } catch (RemoteException re) { 7736 } 7737 return; 7738 } 7739 7740 UserHandle user; 7741 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 7742 user = UserHandle.ALL; 7743 } else { 7744 user = new UserHandle(userId); 7745 } 7746 7747 final int filteredInstallFlags; 7748 if (uid == Process.SHELL_UID || uid == 0) { 7749 if (DEBUG_INSTALL) { 7750 Slog.v(TAG, "Install from ADB"); 7751 } 7752 filteredInstallFlags = installFlags | PackageManager.INSTALL_FROM_ADB; 7753 } else { 7754 filteredInstallFlags = installFlags & ~PackageManager.INSTALL_FROM_ADB; 7755 } 7756 7757 verificationParams.setInstallerUid(uid); 7758 7759 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 7760 7761 final Message msg = mHandler.obtainMessage(INIT_COPY); 7762 msg.obj = new InstallParams(origin, observer, filteredInstallFlags, 7763 installerPackageName, verificationParams, user, packageAbiOverride); 7764 mHandler.sendMessage(msg); 7765 } 7766 7767 void installStage(String packageName, File stagedDir, String stagedCid, 7768 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 7769 String installerPackageName, int installerUid, UserHandle user) { 7770 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 7771 params.referrerUri, installerUid, null); 7772 7773 final OriginInfo origin; 7774 if (stagedDir != null) { 7775 origin = OriginInfo.fromStagedFile(stagedDir); 7776 } else { 7777 origin = OriginInfo.fromStagedContainer(stagedCid); 7778 } 7779 7780 final Message msg = mHandler.obtainMessage(INIT_COPY); 7781 msg.obj = new InstallParams(origin, observer, params.installFlags, 7782 installerPackageName, verifParams, user, params.abiOverride); 7783 mHandler.sendMessage(msg); 7784 } 7785 7786 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 7787 Bundle extras = new Bundle(1); 7788 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 7789 7790 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 7791 packageName, extras, null, null, new int[] {userId}); 7792 try { 7793 IActivityManager am = ActivityManagerNative.getDefault(); 7794 final boolean isSystem = 7795 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 7796 if (isSystem && am.isUserRunning(userId, false)) { 7797 // The just-installed/enabled app is bundled on the system, so presumed 7798 // to be able to run automatically without needing an explicit launch. 7799 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 7800 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 7801 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 7802 .setPackage(packageName); 7803 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 7804 android.app.AppOpsManager.OP_NONE, false, false, userId); 7805 } 7806 } catch (RemoteException e) { 7807 // shouldn't happen 7808 Slog.w(TAG, "Unable to bootstrap installed package", e); 7809 } 7810 } 7811 7812 @Override 7813 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 7814 int userId) { 7815 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7816 PackageSetting pkgSetting; 7817 final int uid = Binder.getCallingUid(); 7818 if (UserHandle.getUserId(uid) != userId) { 7819 mContext.enforceCallingOrSelfPermission( 7820 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 7821 "setApplicationHiddenSetting for user " + userId); 7822 } 7823 7824 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 7825 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 7826 return false; 7827 } 7828 7829 long callingId = Binder.clearCallingIdentity(); 7830 try { 7831 boolean sendAdded = false; 7832 boolean sendRemoved = false; 7833 // writer 7834 synchronized (mPackages) { 7835 pkgSetting = mSettings.mPackages.get(packageName); 7836 if (pkgSetting == null) { 7837 return false; 7838 } 7839 if (pkgSetting.getHidden(userId) != hidden) { 7840 pkgSetting.setHidden(hidden, userId); 7841 mSettings.writePackageRestrictionsLPr(userId); 7842 if (hidden) { 7843 sendRemoved = true; 7844 } else { 7845 sendAdded = true; 7846 } 7847 } 7848 } 7849 if (sendAdded) { 7850 sendPackageAddedForUser(packageName, pkgSetting, userId); 7851 return true; 7852 } 7853 if (sendRemoved) { 7854 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 7855 "hiding pkg"); 7856 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 7857 } 7858 } finally { 7859 Binder.restoreCallingIdentity(callingId); 7860 } 7861 return false; 7862 } 7863 7864 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 7865 int userId) { 7866 final PackageRemovedInfo info = new PackageRemovedInfo(); 7867 info.removedPackage = packageName; 7868 info.removedUsers = new int[] {userId}; 7869 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 7870 info.sendBroadcast(false, false, false); 7871 } 7872 7873 /** 7874 * Returns true if application is not found or there was an error. Otherwise it returns 7875 * the hidden state of the package for the given user. 7876 */ 7877 @Override 7878 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 7879 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7880 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 7881 "getApplicationHidden for user " + userId); 7882 PackageSetting pkgSetting; 7883 long callingId = Binder.clearCallingIdentity(); 7884 try { 7885 // writer 7886 synchronized (mPackages) { 7887 pkgSetting = mSettings.mPackages.get(packageName); 7888 if (pkgSetting == null) { 7889 return true; 7890 } 7891 return pkgSetting.getHidden(userId); 7892 } 7893 } finally { 7894 Binder.restoreCallingIdentity(callingId); 7895 } 7896 } 7897 7898 /** 7899 * @hide 7900 */ 7901 @Override 7902 public int installExistingPackageAsUser(String packageName, int userId) { 7903 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7904 null); 7905 PackageSetting pkgSetting; 7906 final int uid = Binder.getCallingUid(); 7907 enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId); 7908 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 7909 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 7910 } 7911 7912 long callingId = Binder.clearCallingIdentity(); 7913 try { 7914 boolean sendAdded = false; 7915 Bundle extras = new Bundle(1); 7916 7917 // writer 7918 synchronized (mPackages) { 7919 pkgSetting = mSettings.mPackages.get(packageName); 7920 if (pkgSetting == null) { 7921 return PackageManager.INSTALL_FAILED_INVALID_URI; 7922 } 7923 if (!pkgSetting.getInstalled(userId)) { 7924 pkgSetting.setInstalled(true, userId); 7925 pkgSetting.setHidden(false, userId); 7926 mSettings.writePackageRestrictionsLPr(userId); 7927 sendAdded = true; 7928 } 7929 } 7930 7931 if (sendAdded) { 7932 sendPackageAddedForUser(packageName, pkgSetting, userId); 7933 } 7934 } finally { 7935 Binder.restoreCallingIdentity(callingId); 7936 } 7937 7938 return PackageManager.INSTALL_SUCCEEDED; 7939 } 7940 7941 boolean isUserRestricted(int userId, String restrictionKey) { 7942 Bundle restrictions = sUserManager.getUserRestrictions(userId); 7943 if (restrictions.getBoolean(restrictionKey, false)) { 7944 Log.w(TAG, "User is restricted: " + restrictionKey); 7945 return true; 7946 } 7947 return false; 7948 } 7949 7950 @Override 7951 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 7952 mContext.enforceCallingOrSelfPermission( 7953 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7954 "Only package verification agents can verify applications"); 7955 7956 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7957 final PackageVerificationResponse response = new PackageVerificationResponse( 7958 verificationCode, Binder.getCallingUid()); 7959 msg.arg1 = id; 7960 msg.obj = response; 7961 mHandler.sendMessage(msg); 7962 } 7963 7964 @Override 7965 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 7966 long millisecondsToDelay) { 7967 mContext.enforceCallingOrSelfPermission( 7968 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7969 "Only package verification agents can extend verification timeouts"); 7970 7971 final PackageVerificationState state = mPendingVerification.get(id); 7972 final PackageVerificationResponse response = new PackageVerificationResponse( 7973 verificationCodeAtTimeout, Binder.getCallingUid()); 7974 7975 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 7976 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 7977 } 7978 if (millisecondsToDelay < 0) { 7979 millisecondsToDelay = 0; 7980 } 7981 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 7982 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 7983 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 7984 } 7985 7986 if ((state != null) && !state.timeoutExtended()) { 7987 state.extendTimeout(); 7988 7989 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7990 msg.arg1 = id; 7991 msg.obj = response; 7992 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 7993 } 7994 } 7995 7996 private void broadcastPackageVerified(int verificationId, Uri packageUri, 7997 int verificationCode, UserHandle user) { 7998 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 7999 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 8000 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8001 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8002 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 8003 8004 mContext.sendBroadcastAsUser(intent, user, 8005 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 8006 } 8007 8008 private ComponentName matchComponentForVerifier(String packageName, 8009 List<ResolveInfo> receivers) { 8010 ActivityInfo targetReceiver = null; 8011 8012 final int NR = receivers.size(); 8013 for (int i = 0; i < NR; i++) { 8014 final ResolveInfo info = receivers.get(i); 8015 if (info.activityInfo == null) { 8016 continue; 8017 } 8018 8019 if (packageName.equals(info.activityInfo.packageName)) { 8020 targetReceiver = info.activityInfo; 8021 break; 8022 } 8023 } 8024 8025 if (targetReceiver == null) { 8026 return null; 8027 } 8028 8029 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8030 } 8031 8032 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8033 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8034 if (pkgInfo.verifiers.length == 0) { 8035 return null; 8036 } 8037 8038 final int N = pkgInfo.verifiers.length; 8039 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8040 for (int i = 0; i < N; i++) { 8041 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8042 8043 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8044 receivers); 8045 if (comp == null) { 8046 continue; 8047 } 8048 8049 final int verifierUid = getUidForVerifier(verifierInfo); 8050 if (verifierUid == -1) { 8051 continue; 8052 } 8053 8054 if (DEBUG_VERIFY) { 8055 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8056 + " with the correct signature"); 8057 } 8058 sufficientVerifiers.add(comp); 8059 verificationState.addSufficientVerifier(verifierUid); 8060 } 8061 8062 return sufficientVerifiers; 8063 } 8064 8065 private int getUidForVerifier(VerifierInfo verifierInfo) { 8066 synchronized (mPackages) { 8067 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8068 if (pkg == null) { 8069 return -1; 8070 } else if (pkg.mSignatures.length != 1) { 8071 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8072 + " has more than one signature; ignoring"); 8073 return -1; 8074 } 8075 8076 /* 8077 * If the public key of the package's signature does not match 8078 * our expected public key, then this is a different package and 8079 * we should skip. 8080 */ 8081 8082 final byte[] expectedPublicKey; 8083 try { 8084 final Signature verifierSig = pkg.mSignatures[0]; 8085 final PublicKey publicKey = verifierSig.getPublicKey(); 8086 expectedPublicKey = publicKey.getEncoded(); 8087 } catch (CertificateException e) { 8088 return -1; 8089 } 8090 8091 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8092 8093 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8094 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8095 + " does not have the expected public key; ignoring"); 8096 return -1; 8097 } 8098 8099 return pkg.applicationInfo.uid; 8100 } 8101 } 8102 8103 @Override 8104 public void finishPackageInstall(int token) { 8105 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8106 8107 if (DEBUG_INSTALL) { 8108 Slog.v(TAG, "BM finishing package install for " + token); 8109 } 8110 8111 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8112 mHandler.sendMessage(msg); 8113 } 8114 8115 /** 8116 * Get the verification agent timeout. 8117 * 8118 * @return verification timeout in milliseconds 8119 */ 8120 private long getVerificationTimeout() { 8121 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8122 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8123 DEFAULT_VERIFICATION_TIMEOUT); 8124 } 8125 8126 /** 8127 * Get the default verification agent response code. 8128 * 8129 * @return default verification response code 8130 */ 8131 private int getDefaultVerificationResponse() { 8132 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8133 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8134 DEFAULT_VERIFICATION_RESPONSE); 8135 } 8136 8137 /** 8138 * Check whether or not package verification has been enabled. 8139 * 8140 * @return true if verification should be performed 8141 */ 8142 private boolean isVerificationEnabled(int userId, int installFlags) { 8143 if (!DEFAULT_VERIFY_ENABLE) { 8144 return false; 8145 } 8146 8147 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 8148 8149 // Check if installing from ADB 8150 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 8151 // Do not run verification in a test harness environment 8152 if (ActivityManager.isRunningInTestHarness()) { 8153 return false; 8154 } 8155 if (ensureVerifyAppsEnabled) { 8156 return true; 8157 } 8158 // Check if the developer does not want package verification for ADB installs 8159 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8160 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8161 return false; 8162 } 8163 } 8164 8165 if (ensureVerifyAppsEnabled) { 8166 return true; 8167 } 8168 8169 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8170 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8171 } 8172 8173 /** 8174 * Get the "allow unknown sources" setting. 8175 * 8176 * @return the current "allow unknown sources" setting 8177 */ 8178 private int getUnknownSourcesSettings() { 8179 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8180 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 8181 -1); 8182 } 8183 8184 @Override 8185 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 8186 final int uid = Binder.getCallingUid(); 8187 // writer 8188 synchronized (mPackages) { 8189 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 8190 if (targetPackageSetting == null) { 8191 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 8192 } 8193 8194 PackageSetting installerPackageSetting; 8195 if (installerPackageName != null) { 8196 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 8197 if (installerPackageSetting == null) { 8198 throw new IllegalArgumentException("Unknown installer package: " 8199 + installerPackageName); 8200 } 8201 } else { 8202 installerPackageSetting = null; 8203 } 8204 8205 Signature[] callerSignature; 8206 Object obj = mSettings.getUserIdLPr(uid); 8207 if (obj != null) { 8208 if (obj instanceof SharedUserSetting) { 8209 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 8210 } else if (obj instanceof PackageSetting) { 8211 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 8212 } else { 8213 throw new SecurityException("Bad object " + obj + " for uid " + uid); 8214 } 8215 } else { 8216 throw new SecurityException("Unknown calling uid " + uid); 8217 } 8218 8219 // Verify: can't set installerPackageName to a package that is 8220 // not signed with the same cert as the caller. 8221 if (installerPackageSetting != null) { 8222 if (compareSignatures(callerSignature, 8223 installerPackageSetting.signatures.mSignatures) 8224 != PackageManager.SIGNATURE_MATCH) { 8225 throw new SecurityException( 8226 "Caller does not have same cert as new installer package " 8227 + installerPackageName); 8228 } 8229 } 8230 8231 // Verify: if target already has an installer package, it must 8232 // be signed with the same cert as the caller. 8233 if (targetPackageSetting.installerPackageName != null) { 8234 PackageSetting setting = mSettings.mPackages.get( 8235 targetPackageSetting.installerPackageName); 8236 // If the currently set package isn't valid, then it's always 8237 // okay to change it. 8238 if (setting != null) { 8239 if (compareSignatures(callerSignature, 8240 setting.signatures.mSignatures) 8241 != PackageManager.SIGNATURE_MATCH) { 8242 throw new SecurityException( 8243 "Caller does not have same cert as old installer package " 8244 + targetPackageSetting.installerPackageName); 8245 } 8246 } 8247 } 8248 8249 // Okay! 8250 targetPackageSetting.installerPackageName = installerPackageName; 8251 scheduleWriteSettingsLocked(); 8252 } 8253 } 8254 8255 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 8256 // Queue up an async operation since the package installation may take a little while. 8257 mHandler.post(new Runnable() { 8258 public void run() { 8259 mHandler.removeCallbacks(this); 8260 // Result object to be returned 8261 PackageInstalledInfo res = new PackageInstalledInfo(); 8262 res.returnCode = currentStatus; 8263 res.uid = -1; 8264 res.pkg = null; 8265 res.removedInfo = new PackageRemovedInfo(); 8266 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 8267 args.doPreInstall(res.returnCode); 8268 synchronized (mInstallLock) { 8269 installPackageLI(args, res); 8270 } 8271 args.doPostInstall(res.returnCode, res.uid); 8272 } 8273 8274 // A restore should be performed at this point if (a) the install 8275 // succeeded, (b) the operation is not an update, and (c) the new 8276 // package has not opted out of backup participation. 8277 final boolean update = res.removedInfo.removedPackage != null; 8278 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 8279 boolean doRestore = !update 8280 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 8281 8282 // Set up the post-install work request bookkeeping. This will be used 8283 // and cleaned up by the post-install event handling regardless of whether 8284 // there's a restore pass performed. Token values are >= 1. 8285 int token; 8286 if (mNextInstallToken < 0) mNextInstallToken = 1; 8287 token = mNextInstallToken++; 8288 8289 PostInstallData data = new PostInstallData(args, res); 8290 mRunningInstalls.put(token, data); 8291 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 8292 8293 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 8294 // Pass responsibility to the Backup Manager. It will perform a 8295 // restore if appropriate, then pass responsibility back to the 8296 // Package Manager to run the post-install observer callbacks 8297 // and broadcasts. 8298 IBackupManager bm = IBackupManager.Stub.asInterface( 8299 ServiceManager.getService(Context.BACKUP_SERVICE)); 8300 if (bm != null) { 8301 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 8302 + " to BM for possible restore"); 8303 try { 8304 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 8305 } catch (RemoteException e) { 8306 // can't happen; the backup manager is local 8307 } catch (Exception e) { 8308 Slog.e(TAG, "Exception trying to enqueue restore", e); 8309 doRestore = false; 8310 } 8311 } else { 8312 Slog.e(TAG, "Backup Manager not found!"); 8313 doRestore = false; 8314 } 8315 } 8316 8317 if (!doRestore) { 8318 // No restore possible, or the Backup Manager was mysteriously not 8319 // available -- just fire the post-install work request directly. 8320 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 8321 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8322 mHandler.sendMessage(msg); 8323 } 8324 } 8325 }); 8326 } 8327 8328 private abstract class HandlerParams { 8329 private static final int MAX_RETRIES = 4; 8330 8331 /** 8332 * Number of times startCopy() has been attempted and had a non-fatal 8333 * error. 8334 */ 8335 private int mRetries = 0; 8336 8337 /** User handle for the user requesting the information or installation. */ 8338 private final UserHandle mUser; 8339 8340 HandlerParams(UserHandle user) { 8341 mUser = user; 8342 } 8343 8344 UserHandle getUser() { 8345 return mUser; 8346 } 8347 8348 final boolean startCopy() { 8349 boolean res; 8350 try { 8351 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 8352 8353 if (++mRetries > MAX_RETRIES) { 8354 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 8355 mHandler.sendEmptyMessage(MCS_GIVE_UP); 8356 handleServiceError(); 8357 return false; 8358 } else { 8359 handleStartCopy(); 8360 res = true; 8361 } 8362 } catch (RemoteException e) { 8363 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 8364 mHandler.sendEmptyMessage(MCS_RECONNECT); 8365 res = false; 8366 } 8367 handleReturnCode(); 8368 return res; 8369 } 8370 8371 final void serviceError() { 8372 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 8373 handleServiceError(); 8374 handleReturnCode(); 8375 } 8376 8377 abstract void handleStartCopy() throws RemoteException; 8378 abstract void handleServiceError(); 8379 abstract void handleReturnCode(); 8380 } 8381 8382 class MeasureParams extends HandlerParams { 8383 private final PackageStats mStats; 8384 private boolean mSuccess; 8385 8386 private final IPackageStatsObserver mObserver; 8387 8388 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 8389 super(new UserHandle(stats.userHandle)); 8390 mObserver = observer; 8391 mStats = stats; 8392 } 8393 8394 @Override 8395 public String toString() { 8396 return "MeasureParams{" 8397 + Integer.toHexString(System.identityHashCode(this)) 8398 + " " + mStats.packageName + "}"; 8399 } 8400 8401 @Override 8402 void handleStartCopy() throws RemoteException { 8403 synchronized (mInstallLock) { 8404 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 8405 } 8406 8407 if (mSuccess) { 8408 final boolean mounted; 8409 if (Environment.isExternalStorageEmulated()) { 8410 mounted = true; 8411 } else { 8412 final String status = Environment.getExternalStorageState(); 8413 mounted = (Environment.MEDIA_MOUNTED.equals(status) 8414 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 8415 } 8416 8417 if (mounted) { 8418 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 8419 8420 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 8421 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 8422 8423 mStats.externalDataSize = calculateDirectorySize(mContainerService, 8424 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 8425 8426 // Always subtract cache size, since it's a subdirectory 8427 mStats.externalDataSize -= mStats.externalCacheSize; 8428 8429 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 8430 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 8431 8432 mStats.externalObbSize = calculateDirectorySize(mContainerService, 8433 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 8434 } 8435 } 8436 } 8437 8438 @Override 8439 void handleReturnCode() { 8440 if (mObserver != null) { 8441 try { 8442 mObserver.onGetStatsCompleted(mStats, mSuccess); 8443 } catch (RemoteException e) { 8444 Slog.i(TAG, "Observer no longer exists."); 8445 } 8446 } 8447 } 8448 8449 @Override 8450 void handleServiceError() { 8451 Slog.e(TAG, "Could not measure application " + mStats.packageName 8452 + " external storage"); 8453 } 8454 } 8455 8456 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 8457 throws RemoteException { 8458 long result = 0; 8459 for (File path : paths) { 8460 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 8461 } 8462 return result; 8463 } 8464 8465 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 8466 for (File path : paths) { 8467 try { 8468 mcs.clearDirectory(path.getAbsolutePath()); 8469 } catch (RemoteException e) { 8470 } 8471 } 8472 } 8473 8474 static class OriginInfo { 8475 /** 8476 * Location where install is coming from, before it has been 8477 * copied/renamed into place. This could be a single monolithic APK 8478 * file, or a cluster directory. This location may be untrusted. 8479 */ 8480 final File file; 8481 final String cid; 8482 8483 /** 8484 * Flag indicating that {@link #file} or {@link #cid} has already been 8485 * staged, meaning downstream users don't need to defensively copy the 8486 * contents. 8487 */ 8488 final boolean staged; 8489 8490 /** 8491 * Flag indicating that {@link #file} or {@link #cid} is an already 8492 * installed app that is being moved. 8493 */ 8494 final boolean existing; 8495 8496 final String resolvedPath; 8497 final File resolvedFile; 8498 8499 static OriginInfo fromNothing() { 8500 return new OriginInfo(null, null, false, false); 8501 } 8502 8503 static OriginInfo fromUntrustedFile(File file) { 8504 return new OriginInfo(file, null, false, false); 8505 } 8506 8507 static OriginInfo fromExistingFile(File file) { 8508 return new OriginInfo(file, null, false, true); 8509 } 8510 8511 static OriginInfo fromStagedFile(File file) { 8512 return new OriginInfo(file, null, true, false); 8513 } 8514 8515 static OriginInfo fromStagedContainer(String cid) { 8516 return new OriginInfo(null, cid, true, false); 8517 } 8518 8519 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 8520 this.file = file; 8521 this.cid = cid; 8522 this.staged = staged; 8523 this.existing = existing; 8524 8525 if (cid != null) { 8526 resolvedPath = PackageHelper.getSdDir(cid); 8527 resolvedFile = new File(resolvedPath); 8528 } else if (file != null) { 8529 resolvedPath = file.getAbsolutePath(); 8530 resolvedFile = file; 8531 } else { 8532 resolvedPath = null; 8533 resolvedFile = null; 8534 } 8535 } 8536 } 8537 8538 class InstallParams extends HandlerParams { 8539 final OriginInfo origin; 8540 final IPackageInstallObserver2 observer; 8541 int installFlags; 8542 final String installerPackageName; 8543 final VerificationParams verificationParams; 8544 private InstallArgs mArgs; 8545 private int mRet; 8546 final String packageAbiOverride; 8547 8548 InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 8549 String installerPackageName, VerificationParams verificationParams, UserHandle user, 8550 String packageAbiOverride) { 8551 super(user); 8552 this.origin = origin; 8553 this.observer = observer; 8554 this.installFlags = installFlags; 8555 this.installerPackageName = installerPackageName; 8556 this.verificationParams = verificationParams; 8557 this.packageAbiOverride = packageAbiOverride; 8558 } 8559 8560 @Override 8561 public String toString() { 8562 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 8563 + " file=" + origin.file + " cid=" + origin.cid + "}"; 8564 } 8565 8566 public ManifestDigest getManifestDigest() { 8567 if (verificationParams == null) { 8568 return null; 8569 } 8570 return verificationParams.getManifestDigest(); 8571 } 8572 8573 private int installLocationPolicy(PackageInfoLite pkgLite) { 8574 String packageName = pkgLite.packageName; 8575 int installLocation = pkgLite.installLocation; 8576 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 8577 // reader 8578 synchronized (mPackages) { 8579 PackageParser.Package pkg = mPackages.get(packageName); 8580 if (pkg != null) { 8581 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 8582 // Check for downgrading. 8583 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 8584 if (pkgLite.versionCode < pkg.mVersionCode) { 8585 Slog.w(TAG, "Can't install update of " + packageName 8586 + " update version " + pkgLite.versionCode 8587 + " is older than installed version " 8588 + pkg.mVersionCode); 8589 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 8590 } 8591 } 8592 // Check for updated system application. 8593 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8594 if (onSd) { 8595 Slog.w(TAG, "Cannot install update to system app on sdcard"); 8596 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 8597 } 8598 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8599 } else { 8600 if (onSd) { 8601 // Install flag overrides everything. 8602 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8603 } 8604 // If current upgrade specifies particular preference 8605 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 8606 // Application explicitly specified internal. 8607 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8608 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 8609 // App explictly prefers external. Let policy decide 8610 } else { 8611 // Prefer previous location 8612 if (isExternal(pkg)) { 8613 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8614 } 8615 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8616 } 8617 } 8618 } else { 8619 // Invalid install. Return error code 8620 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 8621 } 8622 } 8623 } 8624 // All the special cases have been taken care of. 8625 // Return result based on recommended install location. 8626 if (onSd) { 8627 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8628 } 8629 return pkgLite.recommendedInstallLocation; 8630 } 8631 8632 /* 8633 * Invoke remote method to get package information and install 8634 * location values. Override install location based on default 8635 * policy if needed and then create install arguments based 8636 * on the install location. 8637 */ 8638 public void handleStartCopy() throws RemoteException { 8639 int ret = PackageManager.INSTALL_SUCCEEDED; 8640 8641 // If we're already staged, we've firmly committed to an install location 8642 if (origin.staged) { 8643 if (origin.file != null) { 8644 installFlags |= PackageManager.INSTALL_INTERNAL; 8645 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 8646 } else if (origin.cid != null) { 8647 installFlags |= PackageManager.INSTALL_EXTERNAL; 8648 installFlags &= ~PackageManager.INSTALL_INTERNAL; 8649 } else { 8650 throw new IllegalStateException("Invalid stage location"); 8651 } 8652 } 8653 8654 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 8655 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 8656 8657 PackageInfoLite pkgLite = null; 8658 8659 if (onInt && onSd) { 8660 // Check if both bits are set. 8661 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 8662 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8663 } else { 8664 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 8665 packageAbiOverride); 8666 8667 /* 8668 * If we have too little free space, try to free cache 8669 * before giving up. 8670 */ 8671 if (!origin.staged && pkgLite.recommendedInstallLocation 8672 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8673 // TODO: focus freeing disk space on the target device 8674 final StorageManager storage = StorageManager.from(mContext); 8675 final long lowThreshold = storage.getStorageLowBytes( 8676 Environment.getDataDirectory()); 8677 8678 final long sizeBytes = mContainerService.calculateInstalledSize( 8679 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 8680 8681 if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) { 8682 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 8683 installFlags, packageAbiOverride); 8684 } 8685 8686 /* 8687 * The cache free must have deleted the file we 8688 * downloaded to install. 8689 * 8690 * TODO: fix the "freeCache" call to not delete 8691 * the file we care about. 8692 */ 8693 if (pkgLite.recommendedInstallLocation 8694 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8695 pkgLite.recommendedInstallLocation 8696 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 8697 } 8698 } 8699 } 8700 8701 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8702 int loc = pkgLite.recommendedInstallLocation; 8703 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 8704 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8705 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 8706 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 8707 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8708 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8709 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 8710 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 8711 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8712 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 8713 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 8714 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 8715 } else { 8716 // Override with defaults if needed. 8717 loc = installLocationPolicy(pkgLite); 8718 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 8719 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 8720 } else if (!onSd && !onInt) { 8721 // Override install location with flags 8722 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 8723 // Set the flag to install on external media. 8724 installFlags |= PackageManager.INSTALL_EXTERNAL; 8725 installFlags &= ~PackageManager.INSTALL_INTERNAL; 8726 } else { 8727 // Make sure the flag for installing on external 8728 // media is unset 8729 installFlags |= PackageManager.INSTALL_INTERNAL; 8730 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 8731 } 8732 } 8733 } 8734 } 8735 8736 final InstallArgs args = createInstallArgs(this); 8737 mArgs = args; 8738 8739 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8740 /* 8741 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 8742 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 8743 */ 8744 int userIdentifier = getUser().getIdentifier(); 8745 if (userIdentifier == UserHandle.USER_ALL 8746 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 8747 userIdentifier = UserHandle.USER_OWNER; 8748 } 8749 8750 /* 8751 * Determine if we have any installed package verifiers. If we 8752 * do, then we'll defer to them to verify the packages. 8753 */ 8754 final int requiredUid = mRequiredVerifierPackage == null ? -1 8755 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 8756 if (!origin.existing && requiredUid != -1 8757 && isVerificationEnabled(userIdentifier, installFlags)) { 8758 final Intent verification = new Intent( 8759 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 8760 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 8761 PACKAGE_MIME_TYPE); 8762 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8763 8764 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 8765 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 8766 0 /* TODO: Which userId? */); 8767 8768 if (DEBUG_VERIFY) { 8769 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 8770 + verification.toString() + " with " + pkgLite.verifiers.length 8771 + " optional verifiers"); 8772 } 8773 8774 final int verificationId = mPendingVerificationToken++; 8775 8776 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8777 8778 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 8779 installerPackageName); 8780 8781 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 8782 installFlags); 8783 8784 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 8785 pkgLite.packageName); 8786 8787 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 8788 pkgLite.versionCode); 8789 8790 if (verificationParams != null) { 8791 if (verificationParams.getVerificationURI() != null) { 8792 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 8793 verificationParams.getVerificationURI()); 8794 } 8795 if (verificationParams.getOriginatingURI() != null) { 8796 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 8797 verificationParams.getOriginatingURI()); 8798 } 8799 if (verificationParams.getReferrer() != null) { 8800 verification.putExtra(Intent.EXTRA_REFERRER, 8801 verificationParams.getReferrer()); 8802 } 8803 if (verificationParams.getOriginatingUid() >= 0) { 8804 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 8805 verificationParams.getOriginatingUid()); 8806 } 8807 if (verificationParams.getInstallerUid() >= 0) { 8808 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 8809 verificationParams.getInstallerUid()); 8810 } 8811 } 8812 8813 final PackageVerificationState verificationState = new PackageVerificationState( 8814 requiredUid, args); 8815 8816 mPendingVerification.append(verificationId, verificationState); 8817 8818 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 8819 receivers, verificationState); 8820 8821 /* 8822 * If any sufficient verifiers were listed in the package 8823 * manifest, attempt to ask them. 8824 */ 8825 if (sufficientVerifiers != null) { 8826 final int N = sufficientVerifiers.size(); 8827 if (N == 0) { 8828 Slog.i(TAG, "Additional verifiers required, but none installed."); 8829 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 8830 } else { 8831 for (int i = 0; i < N; i++) { 8832 final ComponentName verifierComponent = sufficientVerifiers.get(i); 8833 8834 final Intent sufficientIntent = new Intent(verification); 8835 sufficientIntent.setComponent(verifierComponent); 8836 8837 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 8838 } 8839 } 8840 } 8841 8842 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 8843 mRequiredVerifierPackage, receivers); 8844 if (ret == PackageManager.INSTALL_SUCCEEDED 8845 && mRequiredVerifierPackage != null) { 8846 /* 8847 * Send the intent to the required verification agent, 8848 * but only start the verification timeout after the 8849 * target BroadcastReceivers have run. 8850 */ 8851 verification.setComponent(requiredVerifierComponent); 8852 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 8853 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8854 new BroadcastReceiver() { 8855 @Override 8856 public void onReceive(Context context, Intent intent) { 8857 final Message msg = mHandler 8858 .obtainMessage(CHECK_PENDING_VERIFICATION); 8859 msg.arg1 = verificationId; 8860 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 8861 } 8862 }, null, 0, null, null); 8863 8864 /* 8865 * We don't want the copy to proceed until verification 8866 * succeeds, so null out this field. 8867 */ 8868 mArgs = null; 8869 } 8870 } else { 8871 /* 8872 * No package verification is enabled, so immediately start 8873 * the remote call to initiate copy using temporary file. 8874 */ 8875 ret = args.copyApk(mContainerService, true); 8876 } 8877 } 8878 8879 mRet = ret; 8880 } 8881 8882 @Override 8883 void handleReturnCode() { 8884 // If mArgs is null, then MCS couldn't be reached. When it 8885 // reconnects, it will try again to install. At that point, this 8886 // will succeed. 8887 if (mArgs != null) { 8888 processPendingInstall(mArgs, mRet); 8889 } 8890 } 8891 8892 @Override 8893 void handleServiceError() { 8894 mArgs = createInstallArgs(this); 8895 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8896 } 8897 8898 public boolean isForwardLocked() { 8899 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8900 } 8901 } 8902 8903 /** 8904 * Used during creation of InstallArgs 8905 * 8906 * @param installFlags package installation flags 8907 * @return true if should be installed on external storage 8908 */ 8909 private static boolean installOnSd(int installFlags) { 8910 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 8911 return false; 8912 } 8913 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 8914 return true; 8915 } 8916 return false; 8917 } 8918 8919 /** 8920 * Used during creation of InstallArgs 8921 * 8922 * @param installFlags package installation flags 8923 * @return true if should be installed as forward locked 8924 */ 8925 private static boolean installForwardLocked(int installFlags) { 8926 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8927 } 8928 8929 private InstallArgs createInstallArgs(InstallParams params) { 8930 if (installOnSd(params.installFlags) || params.isForwardLocked()) { 8931 return new AsecInstallArgs(params); 8932 } else { 8933 return new FileInstallArgs(params); 8934 } 8935 } 8936 8937 /** 8938 * Create args that describe an existing installed package. Typically used 8939 * when cleaning up old installs, or used as a move source. 8940 */ 8941 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 8942 String resourcePath, String nativeLibraryRoot, String[] instructionSets) { 8943 final boolean isInAsec; 8944 if (installOnSd(installFlags)) { 8945 /* Apps on SD card are always in ASEC containers. */ 8946 isInAsec = true; 8947 } else if (installForwardLocked(installFlags) 8948 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 8949 /* 8950 * Forward-locked apps are only in ASEC containers if they're the 8951 * new style 8952 */ 8953 isInAsec = true; 8954 } else { 8955 isInAsec = false; 8956 } 8957 8958 if (isInAsec) { 8959 return new AsecInstallArgs(codePath, instructionSets, 8960 installOnSd(installFlags), installForwardLocked(installFlags)); 8961 } else { 8962 return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot, 8963 instructionSets); 8964 } 8965 } 8966 8967 static abstract class InstallArgs { 8968 /** @see InstallParams#origin */ 8969 final OriginInfo origin; 8970 8971 final IPackageInstallObserver2 observer; 8972 // Always refers to PackageManager flags only 8973 final int installFlags; 8974 final String installerPackageName; 8975 final ManifestDigest manifestDigest; 8976 final UserHandle user; 8977 final String abiOverride; 8978 8979 // The list of instruction sets supported by this app. This is currently 8980 // only used during the rmdex() phase to clean up resources. We can get rid of this 8981 // if we move dex files under the common app path. 8982 /* nullable */ String[] instructionSets; 8983 8984 InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 8985 String installerPackageName, ManifestDigest manifestDigest, UserHandle user, 8986 String[] instructionSets, String abiOverride) { 8987 this.origin = origin; 8988 this.installFlags = installFlags; 8989 this.observer = observer; 8990 this.installerPackageName = installerPackageName; 8991 this.manifestDigest = manifestDigest; 8992 this.user = user; 8993 this.instructionSets = instructionSets; 8994 this.abiOverride = abiOverride; 8995 } 8996 8997 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 8998 abstract int doPreInstall(int status); 8999 9000 /** 9001 * Rename package into final resting place. All paths on the given 9002 * scanned package should be updated to reflect the rename. 9003 */ 9004 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 9005 abstract int doPostInstall(int status, int uid); 9006 9007 /** @see PackageSettingBase#codePathString */ 9008 abstract String getCodePath(); 9009 /** @see PackageSettingBase#resourcePathString */ 9010 abstract String getResourcePath(); 9011 abstract String getLegacyNativeLibraryPath(); 9012 9013 // Need installer lock especially for dex file removal. 9014 abstract void cleanUpResourcesLI(); 9015 abstract boolean doPostDeleteLI(boolean delete); 9016 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9017 9018 /** 9019 * Called before the source arguments are copied. This is used mostly 9020 * for MoveParams when it needs to read the source file to put it in the 9021 * destination. 9022 */ 9023 int doPreCopy() { 9024 return PackageManager.INSTALL_SUCCEEDED; 9025 } 9026 9027 /** 9028 * Called after the source arguments are copied. This is used mostly for 9029 * MoveParams when it needs to read the source file to put it in the 9030 * destination. 9031 * 9032 * @return 9033 */ 9034 int doPostCopy(int uid) { 9035 return PackageManager.INSTALL_SUCCEEDED; 9036 } 9037 9038 protected boolean isFwdLocked() { 9039 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9040 } 9041 9042 protected boolean isExternal() { 9043 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9044 } 9045 9046 UserHandle getUser() { 9047 return user; 9048 } 9049 } 9050 9051 /** 9052 * Logic to handle installation of non-ASEC applications, including copying 9053 * and renaming logic. 9054 */ 9055 class FileInstallArgs extends InstallArgs { 9056 private File codeFile; 9057 private File resourceFile; 9058 private File legacyNativeLibraryPath; 9059 9060 // Example topology: 9061 // /data/app/com.example/base.apk 9062 // /data/app/com.example/split_foo.apk 9063 // /data/app/com.example/lib/arm/libfoo.so 9064 // /data/app/com.example/lib/arm64/libfoo.so 9065 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 9066 9067 /** New install */ 9068 FileInstallArgs(InstallParams params) { 9069 super(params.origin, params.observer, params.installFlags, 9070 params.installerPackageName, params.getManifestDigest(), params.getUser(), 9071 null /* instruction sets */, params.packageAbiOverride); 9072 if (isFwdLocked()) { 9073 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 9074 } 9075 } 9076 9077 /** Existing install */ 9078 FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath, 9079 String[] instructionSets) { 9080 super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null); 9081 this.codeFile = (codePath != null) ? new File(codePath) : null; 9082 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 9083 this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ? 9084 new File(legacyNativeLibraryPath) : null; 9085 } 9086 9087 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9088 final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(), 9089 isFwdLocked(), abiOverride); 9090 9091 final StorageManager storage = StorageManager.from(mContext); 9092 return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory())); 9093 } 9094 9095 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9096 if (origin.staged) { 9097 Slog.d(TAG, origin.file + " already staged; skipping copy"); 9098 codeFile = origin.file; 9099 resourceFile = origin.file; 9100 return PackageManager.INSTALL_SUCCEEDED; 9101 } 9102 9103 try { 9104 final File tempDir = mInstallerService.allocateInternalStageDirLegacy(); 9105 codeFile = tempDir; 9106 resourceFile = tempDir; 9107 } catch (IOException e) { 9108 Slog.w(TAG, "Failed to create copy file: " + e); 9109 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9110 } 9111 9112 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 9113 @Override 9114 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 9115 if (!FileUtils.isValidExtFilename(name)) { 9116 throw new IllegalArgumentException("Invalid filename: " + name); 9117 } 9118 try { 9119 final File file = new File(codeFile, name); 9120 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 9121 O_RDWR | O_CREAT, 0644); 9122 Os.chmod(file.getAbsolutePath(), 0644); 9123 return new ParcelFileDescriptor(fd); 9124 } catch (ErrnoException e) { 9125 throw new RemoteException("Failed to open: " + e.getMessage()); 9126 } 9127 } 9128 }; 9129 9130 int ret = PackageManager.INSTALL_SUCCEEDED; 9131 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 9132 if (ret != PackageManager.INSTALL_SUCCEEDED) { 9133 Slog.e(TAG, "Failed to copy package"); 9134 return ret; 9135 } 9136 9137 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 9138 NativeLibraryHelper.Handle handle = null; 9139 try { 9140 handle = NativeLibraryHelper.Handle.create(codeFile); 9141 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 9142 abiOverride); 9143 } catch (IOException e) { 9144 Slog.e(TAG, "Copying native libraries failed", e); 9145 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9146 } finally { 9147 IoUtils.closeQuietly(handle); 9148 } 9149 9150 return ret; 9151 } 9152 9153 int doPreInstall(int status) { 9154 if (status != PackageManager.INSTALL_SUCCEEDED) { 9155 cleanUp(); 9156 } 9157 return status; 9158 } 9159 9160 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9161 if (status != PackageManager.INSTALL_SUCCEEDED) { 9162 cleanUp(); 9163 return false; 9164 } else { 9165 final File beforeCodeFile = codeFile; 9166 final File afterCodeFile = getNextCodePath(pkg.packageName); 9167 9168 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 9169 try { 9170 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 9171 } catch (ErrnoException e) { 9172 Slog.d(TAG, "Failed to rename", e); 9173 return false; 9174 } 9175 9176 if (!SELinux.restoreconRecursive(afterCodeFile)) { 9177 Slog.d(TAG, "Failed to restorecon"); 9178 return false; 9179 } 9180 9181 // Reflect the rename internally 9182 codeFile = afterCodeFile; 9183 resourceFile = afterCodeFile; 9184 9185 // Reflect the rename in scanned details 9186 pkg.codePath = afterCodeFile.getAbsolutePath(); 9187 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9188 pkg.baseCodePath); 9189 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9190 pkg.splitCodePaths); 9191 9192 // Reflect the rename in app info 9193 pkg.applicationInfo.setCodePath(pkg.codePath); 9194 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9195 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9196 pkg.applicationInfo.setResourcePath(pkg.codePath); 9197 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9198 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9199 9200 return true; 9201 } 9202 } 9203 9204 int doPostInstall(int status, int uid) { 9205 if (status != PackageManager.INSTALL_SUCCEEDED) { 9206 cleanUp(); 9207 } 9208 return status; 9209 } 9210 9211 @Override 9212 String getCodePath() { 9213 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 9214 } 9215 9216 @Override 9217 String getResourcePath() { 9218 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 9219 } 9220 9221 @Override 9222 String getLegacyNativeLibraryPath() { 9223 return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null; 9224 } 9225 9226 private boolean cleanUp() { 9227 if (codeFile == null || !codeFile.exists()) { 9228 return false; 9229 } 9230 9231 if (codeFile.isDirectory()) { 9232 FileUtils.deleteContents(codeFile); 9233 } 9234 codeFile.delete(); 9235 9236 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 9237 resourceFile.delete(); 9238 } 9239 9240 if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) { 9241 if (!FileUtils.deleteContents(legacyNativeLibraryPath)) { 9242 Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath); 9243 } 9244 legacyNativeLibraryPath.delete(); 9245 } 9246 9247 return true; 9248 } 9249 9250 void cleanUpResourcesLI() { 9251 // Try enumerating all code paths before deleting 9252 List<String> allCodePaths = Collections.EMPTY_LIST; 9253 if (codeFile != null && codeFile.exists()) { 9254 try { 9255 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9256 allCodePaths = pkg.getAllCodePaths(); 9257 } catch (PackageParserException e) { 9258 // Ignored; we tried our best 9259 } 9260 } 9261 9262 cleanUp(); 9263 9264 if (!allCodePaths.isEmpty()) { 9265 if (instructionSets == null) { 9266 throw new IllegalStateException("instructionSet == null"); 9267 } 9268 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9269 for (String codePath : allCodePaths) { 9270 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9271 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9272 if (retCode < 0) { 9273 Slog.w(TAG, "Couldn't remove dex file for package: " 9274 + " at location " + codePath + ", retcode=" + retCode); 9275 // we don't consider this to be a failure of the core package deletion 9276 } 9277 } 9278 } 9279 } 9280 } 9281 9282 boolean doPostDeleteLI(boolean delete) { 9283 // XXX err, shouldn't we respect the delete flag? 9284 cleanUpResourcesLI(); 9285 return true; 9286 } 9287 } 9288 9289 private boolean isAsecExternal(String cid) { 9290 final String asecPath = PackageHelper.getSdFilesystem(cid); 9291 return !asecPath.startsWith(mAsecInternalPath); 9292 } 9293 9294 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 9295 PackageManagerException { 9296 if (copyRet < 0) { 9297 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 9298 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 9299 throw new PackageManagerException(copyRet, message); 9300 } 9301 } 9302 } 9303 9304 /** 9305 * Extract the MountService "container ID" from the full code path of an 9306 * .apk. 9307 */ 9308 static String cidFromCodePath(String fullCodePath) { 9309 int eidx = fullCodePath.lastIndexOf("/"); 9310 String subStr1 = fullCodePath.substring(0, eidx); 9311 int sidx = subStr1.lastIndexOf("/"); 9312 return subStr1.substring(sidx+1, eidx); 9313 } 9314 9315 /** 9316 * Logic to handle installation of ASEC applications, including copying and 9317 * renaming logic. 9318 */ 9319 class AsecInstallArgs extends InstallArgs { 9320 static final String RES_FILE_NAME = "pkg.apk"; 9321 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 9322 9323 String cid; 9324 String packagePath; 9325 String resourcePath; 9326 String legacyNativeLibraryDir; 9327 9328 /** New install */ 9329 AsecInstallArgs(InstallParams params) { 9330 super(params.origin, params.observer, params.installFlags, 9331 params.installerPackageName, params.getManifestDigest(), 9332 params.getUser(), null /* instruction sets */, 9333 params.packageAbiOverride); 9334 } 9335 9336 /** Existing install */ 9337 AsecInstallArgs(String fullCodePath, String[] instructionSets, 9338 boolean isExternal, boolean isForwardLocked) { 9339 super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0) 9340 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9341 instructionSets, null); 9342 // Hackily pretend we're still looking at a full code path 9343 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 9344 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 9345 } 9346 9347 // Extract cid from fullCodePath 9348 int eidx = fullCodePath.lastIndexOf("/"); 9349 String subStr1 = fullCodePath.substring(0, eidx); 9350 int sidx = subStr1.lastIndexOf("/"); 9351 cid = subStr1.substring(sidx+1, eidx); 9352 setMountPath(subStr1); 9353 } 9354 9355 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 9356 super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 9357 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9358 instructionSets, null); 9359 this.cid = cid; 9360 setMountPath(PackageHelper.getSdDir(cid)); 9361 } 9362 9363 void createCopyFile() { 9364 cid = mInstallerService.allocateExternalStageCidLegacy(); 9365 } 9366 9367 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9368 final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(), 9369 abiOverride); 9370 9371 final File target; 9372 if (isExternal()) { 9373 target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory(); 9374 } else { 9375 target = Environment.getDataDirectory(); 9376 } 9377 9378 final StorageManager storage = StorageManager.from(mContext); 9379 return (sizeBytes <= storage.getStorageBytesUntilLow(target)); 9380 } 9381 9382 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9383 if (origin.staged) { 9384 Slog.d(TAG, origin.cid + " already staged; skipping copy"); 9385 cid = origin.cid; 9386 setMountPath(PackageHelper.getSdDir(cid)); 9387 return PackageManager.INSTALL_SUCCEEDED; 9388 } 9389 9390 if (temp) { 9391 createCopyFile(); 9392 } else { 9393 /* 9394 * Pre-emptively destroy the container since it's destroyed if 9395 * copying fails due to it existing anyway. 9396 */ 9397 PackageHelper.destroySdDir(cid); 9398 } 9399 9400 final String newMountPath = imcs.copyPackageToContainer( 9401 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(), 9402 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 9403 9404 if (newMountPath != null) { 9405 setMountPath(newMountPath); 9406 return PackageManager.INSTALL_SUCCEEDED; 9407 } else { 9408 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9409 } 9410 } 9411 9412 @Override 9413 String getCodePath() { 9414 return packagePath; 9415 } 9416 9417 @Override 9418 String getResourcePath() { 9419 return resourcePath; 9420 } 9421 9422 @Override 9423 String getLegacyNativeLibraryPath() { 9424 return legacyNativeLibraryDir; 9425 } 9426 9427 int doPreInstall(int status) { 9428 if (status != PackageManager.INSTALL_SUCCEEDED) { 9429 // Destroy container 9430 PackageHelper.destroySdDir(cid); 9431 } else { 9432 boolean mounted = PackageHelper.isContainerMounted(cid); 9433 if (!mounted) { 9434 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 9435 Process.SYSTEM_UID); 9436 if (newMountPath != null) { 9437 setMountPath(newMountPath); 9438 } else { 9439 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9440 } 9441 } 9442 } 9443 return status; 9444 } 9445 9446 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9447 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 9448 String newMountPath = null; 9449 if (PackageHelper.isContainerMounted(cid)) { 9450 // Unmount the container 9451 if (!PackageHelper.unMountSdDir(cid)) { 9452 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9453 return false; 9454 } 9455 } 9456 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9457 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9458 " which might be stale. Will try to clean up."); 9459 // Clean up the stale container and proceed to recreate. 9460 if (!PackageHelper.destroySdDir(newCacheId)) { 9461 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9462 return false; 9463 } 9464 // Successfully cleaned up stale container. Try to rename again. 9465 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9466 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9467 + " inspite of cleaning it up."); 9468 return false; 9469 } 9470 } 9471 if (!PackageHelper.isContainerMounted(newCacheId)) { 9472 Slog.w(TAG, "Mounting container " + newCacheId); 9473 newMountPath = PackageHelper.mountSdDir(newCacheId, 9474 getEncryptKey(), Process.SYSTEM_UID); 9475 } else { 9476 newMountPath = PackageHelper.getSdDir(newCacheId); 9477 } 9478 if (newMountPath == null) { 9479 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9480 return false; 9481 } 9482 Log.i(TAG, "Succesfully renamed " + cid + 9483 " to " + newCacheId + 9484 " at new path: " + newMountPath); 9485 cid = newCacheId; 9486 9487 final File beforeCodeFile = new File(packagePath); 9488 setMountPath(newMountPath); 9489 final File afterCodeFile = new File(packagePath); 9490 9491 // Reflect the rename in scanned details 9492 pkg.codePath = afterCodeFile.getAbsolutePath(); 9493 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9494 pkg.baseCodePath); 9495 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9496 pkg.splitCodePaths); 9497 9498 // Reflect the rename in app info 9499 pkg.applicationInfo.setCodePath(pkg.codePath); 9500 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9501 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9502 pkg.applicationInfo.setResourcePath(pkg.codePath); 9503 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9504 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9505 9506 return true; 9507 } 9508 9509 private void setMountPath(String mountPath) { 9510 final File mountFile = new File(mountPath); 9511 9512 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 9513 if (monolithicFile.exists()) { 9514 packagePath = monolithicFile.getAbsolutePath(); 9515 if (isFwdLocked()) { 9516 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 9517 } else { 9518 resourcePath = packagePath; 9519 } 9520 } else { 9521 packagePath = mountFile.getAbsolutePath(); 9522 resourcePath = packagePath; 9523 } 9524 9525 legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath(); 9526 } 9527 9528 int doPostInstall(int status, int uid) { 9529 if (status != PackageManager.INSTALL_SUCCEEDED) { 9530 cleanUp(); 9531 } else { 9532 final int groupOwner; 9533 final String protectedFile; 9534 if (isFwdLocked()) { 9535 groupOwner = UserHandle.getSharedAppGid(uid); 9536 protectedFile = RES_FILE_NAME; 9537 } else { 9538 groupOwner = -1; 9539 protectedFile = null; 9540 } 9541 9542 if (uid < Process.FIRST_APPLICATION_UID 9543 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9544 Slog.e(TAG, "Failed to finalize " + cid); 9545 PackageHelper.destroySdDir(cid); 9546 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9547 } 9548 9549 boolean mounted = PackageHelper.isContainerMounted(cid); 9550 if (!mounted) { 9551 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9552 } 9553 } 9554 return status; 9555 } 9556 9557 private void cleanUp() { 9558 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9559 9560 // Destroy secure container 9561 PackageHelper.destroySdDir(cid); 9562 } 9563 9564 private List<String> getAllCodePaths() { 9565 final File codeFile = new File(getCodePath()); 9566 if (codeFile != null && codeFile.exists()) { 9567 try { 9568 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9569 return pkg.getAllCodePaths(); 9570 } catch (PackageParserException e) { 9571 // Ignored; we tried our best 9572 } 9573 } 9574 return Collections.EMPTY_LIST; 9575 } 9576 9577 void cleanUpResourcesLI() { 9578 // Enumerate all code paths before deleting 9579 cleanUpResourcesLI(getAllCodePaths()); 9580 } 9581 9582 private void cleanUpResourcesLI(List<String> allCodePaths) { 9583 cleanUp(); 9584 9585 if (!allCodePaths.isEmpty()) { 9586 if (instructionSets == null) { 9587 throw new IllegalStateException("instructionSet == null"); 9588 } 9589 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9590 for (String codePath : allCodePaths) { 9591 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9592 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9593 if (retCode < 0) { 9594 Slog.w(TAG, "Couldn't remove dex file for package: " 9595 + " at location " + codePath + ", retcode=" + retCode); 9596 // we don't consider this to be a failure of the core package deletion 9597 } 9598 } 9599 } 9600 } 9601 } 9602 9603 boolean matchContainer(String app) { 9604 if (cid.startsWith(app)) { 9605 return true; 9606 } 9607 return false; 9608 } 9609 9610 String getPackageName() { 9611 return getAsecPackageName(cid); 9612 } 9613 9614 boolean doPostDeleteLI(boolean delete) { 9615 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 9616 final List<String> allCodePaths = getAllCodePaths(); 9617 boolean mounted = PackageHelper.isContainerMounted(cid); 9618 if (mounted) { 9619 // Unmount first 9620 if (PackageHelper.unMountSdDir(cid)) { 9621 mounted = false; 9622 } 9623 } 9624 if (!mounted && delete) { 9625 cleanUpResourcesLI(allCodePaths); 9626 } 9627 return !mounted; 9628 } 9629 9630 @Override 9631 int doPreCopy() { 9632 if (isFwdLocked()) { 9633 if (!PackageHelper.fixSdPermissions(cid, 9634 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 9635 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9636 } 9637 } 9638 9639 return PackageManager.INSTALL_SUCCEEDED; 9640 } 9641 9642 @Override 9643 int doPostCopy(int uid) { 9644 if (isFwdLocked()) { 9645 if (uid < Process.FIRST_APPLICATION_UID 9646 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 9647 RES_FILE_NAME)) { 9648 Slog.e(TAG, "Failed to finalize " + cid); 9649 PackageHelper.destroySdDir(cid); 9650 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9651 } 9652 } 9653 9654 return PackageManager.INSTALL_SUCCEEDED; 9655 } 9656 } 9657 9658 static String getAsecPackageName(String packageCid) { 9659 int idx = packageCid.lastIndexOf("-"); 9660 if (idx == -1) { 9661 return packageCid; 9662 } 9663 return packageCid.substring(0, idx); 9664 } 9665 9666 // Utility method used to create code paths based on package name and available index. 9667 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 9668 String idxStr = ""; 9669 int idx = 1; 9670 // Fall back to default value of idx=1 if prefix is not 9671 // part of oldCodePath 9672 if (oldCodePath != null) { 9673 String subStr = oldCodePath; 9674 // Drop the suffix right away 9675 if (suffix != null && subStr.endsWith(suffix)) { 9676 subStr = subStr.substring(0, subStr.length() - suffix.length()); 9677 } 9678 // If oldCodePath already contains prefix find out the 9679 // ending index to either increment or decrement. 9680 int sidx = subStr.lastIndexOf(prefix); 9681 if (sidx != -1) { 9682 subStr = subStr.substring(sidx + prefix.length()); 9683 if (subStr != null) { 9684 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 9685 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 9686 } 9687 try { 9688 idx = Integer.parseInt(subStr); 9689 if (idx <= 1) { 9690 idx++; 9691 } else { 9692 idx--; 9693 } 9694 } catch(NumberFormatException e) { 9695 } 9696 } 9697 } 9698 } 9699 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 9700 return prefix + idxStr; 9701 } 9702 9703 private File getNextCodePath(String packageName) { 9704 int suffix = 1; 9705 File result; 9706 do { 9707 result = new File(mAppInstallDir, packageName + "-" + suffix); 9708 suffix++; 9709 } while (result.exists()); 9710 return result; 9711 } 9712 9713 // Utility method used to ignore ADD/REMOVE events 9714 // by directory observer. 9715 private static boolean ignoreCodePath(String fullPathStr) { 9716 String apkName = deriveCodePathName(fullPathStr); 9717 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 9718 if (idx != -1 && ((idx+1) < apkName.length())) { 9719 // Make sure the package ends with a numeral 9720 String version = apkName.substring(idx+1); 9721 try { 9722 Integer.parseInt(version); 9723 return true; 9724 } catch (NumberFormatException e) {} 9725 } 9726 return false; 9727 } 9728 9729 // Utility method that returns the relative package path with respect 9730 // to the installation directory. Like say for /data/data/com.test-1.apk 9731 // string com.test-1 is returned. 9732 static String deriveCodePathName(String codePath) { 9733 if (codePath == null) { 9734 return null; 9735 } 9736 final File codeFile = new File(codePath); 9737 final String name = codeFile.getName(); 9738 if (codeFile.isDirectory()) { 9739 return name; 9740 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 9741 final int lastDot = name.lastIndexOf('.'); 9742 return name.substring(0, lastDot); 9743 } else { 9744 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 9745 return null; 9746 } 9747 } 9748 9749 class PackageInstalledInfo { 9750 String name; 9751 int uid; 9752 // The set of users that originally had this package installed. 9753 int[] origUsers; 9754 // The set of users that now have this package installed. 9755 int[] newUsers; 9756 PackageParser.Package pkg; 9757 int returnCode; 9758 String returnMsg; 9759 PackageRemovedInfo removedInfo; 9760 9761 public void setError(int code, String msg) { 9762 returnCode = code; 9763 returnMsg = msg; 9764 Slog.w(TAG, msg); 9765 } 9766 9767 public void setError(String msg, PackageParserException e) { 9768 returnCode = e.error; 9769 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9770 Slog.w(TAG, msg, e); 9771 } 9772 9773 public void setError(String msg, PackageManagerException e) { 9774 returnCode = e.error; 9775 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9776 Slog.w(TAG, msg, e); 9777 } 9778 9779 // In some error cases we want to convey more info back to the observer 9780 String origPackage; 9781 String origPermission; 9782 } 9783 9784 /* 9785 * Install a non-existing package. 9786 */ 9787 private void installNewPackageLI(PackageParser.Package pkg, 9788 int parseFlags, int scanFlags, UserHandle user, 9789 String installerPackageName, PackageInstalledInfo res) { 9790 // Remember this for later, in case we need to rollback this install 9791 String pkgName = pkg.packageName; 9792 9793 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 9794 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 9795 synchronized(mPackages) { 9796 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 9797 // A package with the same name is already installed, though 9798 // it has been renamed to an older name. The package we 9799 // are trying to install should be installed as an update to 9800 // the existing one, but that has not been requested, so bail. 9801 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9802 + " without first uninstalling package running as " 9803 + mSettings.mRenamedPackages.get(pkgName)); 9804 return; 9805 } 9806 if (mPackages.containsKey(pkgName)) { 9807 // Don't allow installation over an existing package with the same name. 9808 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9809 + " without first uninstalling."); 9810 return; 9811 } 9812 } 9813 9814 try { 9815 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 9816 System.currentTimeMillis(), user); 9817 9818 updateSettingsLI(newPackage, installerPackageName, null, null, res); 9819 // delete the partially installed application. the data directory will have to be 9820 // restored if it was already existing 9821 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9822 // remove package from internal structures. Note that we want deletePackageX to 9823 // delete the package data and cache directories that it created in 9824 // scanPackageLocked, unless those directories existed before we even tried to 9825 // install. 9826 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 9827 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 9828 res.removedInfo, true); 9829 } 9830 9831 } catch (PackageManagerException e) { 9832 res.setError("Package couldn't be installed in " + pkg.codePath, e); 9833 } 9834 } 9835 9836 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 9837 // Upgrade keysets are being used. Determine if new package has a superset of the 9838 // required keys. 9839 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 9840 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9841 for (int i = 0; i < upgradeKeySets.length; i++) { 9842 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 9843 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 9844 return true; 9845 } 9846 } 9847 return false; 9848 } 9849 9850 private void replacePackageLI(PackageParser.Package pkg, 9851 int parseFlags, int scanFlags, UserHandle user, 9852 String installerPackageName, PackageInstalledInfo res) { 9853 PackageParser.Package oldPackage; 9854 String pkgName = pkg.packageName; 9855 int[] allUsers; 9856 boolean[] perUserInstalled; 9857 9858 // First find the old package info and check signatures 9859 synchronized(mPackages) { 9860 oldPackage = mPackages.get(pkgName); 9861 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 9862 PackageSetting ps = mSettings.mPackages.get(pkgName); 9863 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 9864 // default to original signature matching 9865 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 9866 != PackageManager.SIGNATURE_MATCH) { 9867 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9868 "New package has a different signature: " + pkgName); 9869 return; 9870 } 9871 } else { 9872 if(!checkUpgradeKeySetLP(ps, pkg)) { 9873 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9874 "New package not signed by keys specified by upgrade-keysets: " 9875 + pkgName); 9876 return; 9877 } 9878 } 9879 9880 // In case of rollback, remember per-user/profile install state 9881 allUsers = sUserManager.getUserIds(); 9882 perUserInstalled = new boolean[allUsers.length]; 9883 for (int i = 0; i < allUsers.length; i++) { 9884 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 9885 } 9886 } 9887 9888 boolean sysPkg = (isSystemApp(oldPackage)); 9889 if (sysPkg) { 9890 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 9891 user, allUsers, perUserInstalled, installerPackageName, res); 9892 } else { 9893 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 9894 user, allUsers, perUserInstalled, installerPackageName, res); 9895 } 9896 } 9897 9898 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 9899 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 9900 int[] allUsers, boolean[] perUserInstalled, 9901 String installerPackageName, PackageInstalledInfo res) { 9902 String pkgName = deletedPackage.packageName; 9903 boolean deletedPkg = true; 9904 boolean updatedSettings = false; 9905 9906 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 9907 + deletedPackage); 9908 long origUpdateTime; 9909 if (pkg.mExtras != null) { 9910 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 9911 } else { 9912 origUpdateTime = 0; 9913 } 9914 9915 // First delete the existing package while retaining the data directory 9916 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 9917 res.removedInfo, true)) { 9918 // If the existing package wasn't successfully deleted 9919 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 9920 deletedPkg = false; 9921 } else { 9922 // Successfully deleted the old package; proceed with replace. 9923 9924 // If deleted package lived in a container, give users a chance to 9925 // relinquish resources before killing. 9926 if (isForwardLocked(deletedPackage) || isExternal(deletedPackage)) { 9927 if (DEBUG_INSTALL) { 9928 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 9929 } 9930 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 9931 final ArrayList<String> pkgList = new ArrayList<String>(1); 9932 pkgList.add(deletedPackage.applicationInfo.packageName); 9933 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 9934 } 9935 9936 deleteCodeCacheDirsLI(pkgName); 9937 try { 9938 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 9939 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 9940 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 9941 updatedSettings = true; 9942 } catch (PackageManagerException e) { 9943 res.setError("Package couldn't be installed in " + pkg.codePath, e); 9944 } 9945 } 9946 9947 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9948 // remove package from internal structures. Note that we want deletePackageX to 9949 // delete the package data and cache directories that it created in 9950 // scanPackageLocked, unless those directories existed before we even tried to 9951 // install. 9952 if(updatedSettings) { 9953 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 9954 deletePackageLI( 9955 pkgName, null, true, allUsers, perUserInstalled, 9956 PackageManager.DELETE_KEEP_DATA, 9957 res.removedInfo, true); 9958 } 9959 // Since we failed to install the new package we need to restore the old 9960 // package that we deleted. 9961 if (deletedPkg) { 9962 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 9963 File restoreFile = new File(deletedPackage.codePath); 9964 // Parse old package 9965 boolean oldOnSd = isExternal(deletedPackage); 9966 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 9967 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) | 9968 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 9969 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 9970 try { 9971 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 9972 } catch (PackageManagerException e) { 9973 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 9974 + e.getMessage()); 9975 return; 9976 } 9977 // Restore of old package succeeded. Update permissions. 9978 // writer 9979 synchronized (mPackages) { 9980 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 9981 UPDATE_PERMISSIONS_ALL); 9982 // can downgrade to reader 9983 mSettings.writeLPr(); 9984 } 9985 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 9986 } 9987 } 9988 } 9989 9990 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 9991 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 9992 int[] allUsers, boolean[] perUserInstalled, 9993 String installerPackageName, PackageInstalledInfo res) { 9994 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 9995 + ", old=" + deletedPackage); 9996 boolean updatedSettings = false; 9997 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 9998 if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) { 9999 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10000 } 10001 String packageName = deletedPackage.packageName; 10002 if (packageName == null) { 10003 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10004 "Attempt to delete null packageName."); 10005 return; 10006 } 10007 PackageParser.Package oldPkg; 10008 PackageSetting oldPkgSetting; 10009 // reader 10010 synchronized (mPackages) { 10011 oldPkg = mPackages.get(packageName); 10012 oldPkgSetting = mSettings.mPackages.get(packageName); 10013 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 10014 (oldPkgSetting == null)) { 10015 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10016 "Couldn't find package:" + packageName + " information"); 10017 return; 10018 } 10019 } 10020 10021 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 10022 10023 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10024 res.removedInfo.removedPackage = packageName; 10025 // Remove existing system package 10026 removePackageLI(oldPkgSetting, true); 10027 // writer 10028 synchronized (mPackages) { 10029 if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) { 10030 // We didn't need to disable the .apk as a current system package, 10031 // which means we are replacing another update that is already 10032 // installed. We need to make sure to delete the older one's .apk. 10033 res.removedInfo.args = createInstallArgsForExisting(0, 10034 deletedPackage.applicationInfo.getCodePath(), 10035 deletedPackage.applicationInfo.getResourcePath(), 10036 deletedPackage.applicationInfo.nativeLibraryRootDir, 10037 getAppDexInstructionSets(deletedPackage.applicationInfo)); 10038 } else { 10039 res.removedInfo.args = null; 10040 } 10041 } 10042 10043 // Successfully disabled the old package. Now proceed with re-installation 10044 deleteCodeCacheDirsLI(packageName); 10045 10046 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10047 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10048 10049 PackageParser.Package newPackage = null; 10050 try { 10051 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 10052 if (newPackage.mExtras != null) { 10053 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 10054 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10055 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10056 10057 // is the update attempting to change shared user? that isn't going to work... 10058 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10059 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 10060 "Forbidding shared user change from " + oldPkgSetting.sharedUser 10061 + " to " + newPkgSetting.sharedUser); 10062 updatedSettings = true; 10063 } 10064 } 10065 10066 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10067 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10068 updatedSettings = true; 10069 } 10070 10071 } catch (PackageManagerException e) { 10072 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10073 } 10074 10075 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10076 // Re installation failed. Restore old information 10077 // Remove new pkg information 10078 if (newPackage != null) { 10079 removeInstalledPackageLI(newPackage, true); 10080 } 10081 // Add back the old system package 10082 try { 10083 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 10084 } catch (PackageManagerException e) { 10085 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 10086 } 10087 // Restore the old system information in Settings 10088 synchronized(mPackages) { 10089 if (updatedSettings) { 10090 mSettings.enableSystemPackageLPw(packageName); 10091 mSettings.setInstallerPackageName(packageName, 10092 oldPkgSetting.installerPackageName); 10093 } 10094 mSettings.writeLPr(); 10095 } 10096 } 10097 } 10098 10099 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10100 int[] allUsers, boolean[] perUserInstalled, 10101 PackageInstalledInfo res) { 10102 String pkgName = newPackage.packageName; 10103 synchronized (mPackages) { 10104 //write settings. the installStatus will be incomplete at this stage. 10105 //note that the new package setting would have already been 10106 //added to mPackages. It hasn't been persisted yet. 10107 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10108 mSettings.writeLPr(); 10109 } 10110 10111 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10112 10113 synchronized (mPackages) { 10114 updatePermissionsLPw(newPackage.packageName, newPackage, 10115 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10116 ? UPDATE_PERMISSIONS_ALL : 0)); 10117 // For system-bundled packages, we assume that installing an upgraded version 10118 // of the package implies that the user actually wants to run that new code, 10119 // so we enable the package. 10120 if (isSystemApp(newPackage)) { 10121 // NB: implicit assumption that system package upgrades apply to all users 10122 if (DEBUG_INSTALL) { 10123 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10124 } 10125 PackageSetting ps = mSettings.mPackages.get(pkgName); 10126 if (ps != null) { 10127 if (res.origUsers != null) { 10128 for (int userHandle : res.origUsers) { 10129 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10130 userHandle, installerPackageName); 10131 } 10132 } 10133 // Also convey the prior install/uninstall state 10134 if (allUsers != null && perUserInstalled != null) { 10135 for (int i = 0; i < allUsers.length; i++) { 10136 if (DEBUG_INSTALL) { 10137 Slog.d(TAG, " user " + allUsers[i] 10138 + " => " + perUserInstalled[i]); 10139 } 10140 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10141 } 10142 // these install state changes will be persisted in the 10143 // upcoming call to mSettings.writeLPr(). 10144 } 10145 } 10146 } 10147 res.name = pkgName; 10148 res.uid = newPackage.applicationInfo.uid; 10149 res.pkg = newPackage; 10150 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10151 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10152 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10153 //to update install status 10154 mSettings.writeLPr(); 10155 } 10156 } 10157 10158 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 10159 final int installFlags = args.installFlags; 10160 String installerPackageName = args.installerPackageName; 10161 File tmpPackageFile = new File(args.getCodePath()); 10162 boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10163 boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0); 10164 boolean replace = false; 10165 final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE; 10166 // Result object to be returned 10167 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10168 10169 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10170 // Retrieve PackageSettings and parse package 10171 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10172 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10173 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 10174 PackageParser pp = new PackageParser(); 10175 pp.setSeparateProcesses(mSeparateProcesses); 10176 pp.setDisplayMetrics(mMetrics); 10177 10178 final PackageParser.Package pkg; 10179 try { 10180 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 10181 } catch (PackageParserException e) { 10182 res.setError("Failed parse during installPackageLI", e); 10183 return; 10184 } 10185 10186 // Mark that we have an install time CPU ABI override. 10187 pkg.cpuAbiOverride = args.abiOverride; 10188 10189 String pkgName = res.name = pkg.packageName; 10190 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 10191 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 10192 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 10193 return; 10194 } 10195 } 10196 10197 try { 10198 pp.collectCertificates(pkg, parseFlags); 10199 pp.collectManifestDigest(pkg); 10200 } catch (PackageParserException e) { 10201 res.setError("Failed collect during installPackageLI", e); 10202 return; 10203 } 10204 10205 /* If the installer passed in a manifest digest, compare it now. */ 10206 if (args.manifestDigest != null) { 10207 if (DEBUG_INSTALL) { 10208 final String parsedManifest = pkg.manifestDigest == null ? "null" 10209 : pkg.manifestDigest.toString(); 10210 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 10211 + parsedManifest); 10212 } 10213 10214 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 10215 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 10216 return; 10217 } 10218 } else if (DEBUG_INSTALL) { 10219 final String parsedManifest = pkg.manifestDigest == null 10220 ? "null" : pkg.manifestDigest.toString(); 10221 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 10222 } 10223 10224 // Get rid of all references to package scan path via parser. 10225 pp = null; 10226 String oldCodePath = null; 10227 boolean systemApp = false; 10228 synchronized (mPackages) { 10229 // Check whether the newly-scanned package wants to define an already-defined perm 10230 int N = pkg.permissions.size(); 10231 for (int i = N-1; i >= 0; i--) { 10232 PackageParser.Permission perm = pkg.permissions.get(i); 10233 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 10234 if (bp != null) { 10235 // If the defining package is signed with our cert, it's okay. This 10236 // also includes the "updating the same package" case, of course. 10237 if (compareSignatures(bp.packageSetting.signatures.mSignatures, 10238 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 10239 // If the owning package is the system itself, we log but allow 10240 // install to proceed; we fail the install on all other permission 10241 // redefinitions. 10242 if (!bp.sourcePackage.equals("android")) { 10243 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 10244 + pkg.packageName + " attempting to redeclare permission " 10245 + perm.info.name + " already owned by " + bp.sourcePackage); 10246 res.origPermission = perm.info.name; 10247 res.origPackage = bp.sourcePackage; 10248 return; 10249 } else { 10250 Slog.w(TAG, "Package " + pkg.packageName 10251 + " attempting to redeclare system permission " 10252 + perm.info.name + "; ignoring new declaration"); 10253 pkg.permissions.remove(i); 10254 } 10255 } 10256 } 10257 } 10258 10259 // Check if installing already existing package 10260 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10261 String oldName = mSettings.mRenamedPackages.get(pkgName); 10262 if (pkg.mOriginalPackages != null 10263 && pkg.mOriginalPackages.contains(oldName) 10264 && mPackages.containsKey(oldName)) { 10265 // This package is derived from an original package, 10266 // and this device has been updating from that original 10267 // name. We must continue using the original name, so 10268 // rename the new package here. 10269 pkg.setPackageName(oldName); 10270 pkgName = pkg.packageName; 10271 replace = true; 10272 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 10273 + oldName + " pkgName=" + pkgName); 10274 } else if (mPackages.containsKey(pkgName)) { 10275 // This package, under its official name, already exists 10276 // on the device; we should replace it. 10277 replace = true; 10278 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 10279 } 10280 } 10281 PackageSetting ps = mSettings.mPackages.get(pkgName); 10282 if (ps != null) { 10283 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 10284 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 10285 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 10286 systemApp = (ps.pkg.applicationInfo.flags & 10287 ApplicationInfo.FLAG_SYSTEM) != 0; 10288 } 10289 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10290 } 10291 } 10292 10293 if (systemApp && onSd) { 10294 // Disable updates to system apps on sdcard 10295 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 10296 "Cannot install updates to system apps on sdcard"); 10297 return; 10298 } 10299 10300 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 10301 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 10302 return; 10303 } 10304 10305 if (replace) { 10306 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 10307 installerPackageName, res); 10308 } else { 10309 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 10310 args.user, installerPackageName, res); 10311 } 10312 synchronized (mPackages) { 10313 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10314 if (ps != null) { 10315 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10316 } 10317 } 10318 } 10319 10320 private static boolean isForwardLocked(PackageParser.Package pkg) { 10321 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10322 } 10323 10324 private static boolean isForwardLocked(ApplicationInfo info) { 10325 return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10326 } 10327 10328 private boolean isForwardLocked(PackageSetting ps) { 10329 return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10330 } 10331 10332 private static boolean isMultiArch(PackageSetting ps) { 10333 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10334 } 10335 10336 private static boolean isMultiArch(ApplicationInfo info) { 10337 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10338 } 10339 10340 private static boolean isExternal(PackageParser.Package pkg) { 10341 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10342 } 10343 10344 private static boolean isExternal(PackageSetting ps) { 10345 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10346 } 10347 10348 private static boolean isExternal(ApplicationInfo info) { 10349 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10350 } 10351 10352 private static boolean isSystemApp(PackageParser.Package pkg) { 10353 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10354 } 10355 10356 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 10357 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0; 10358 } 10359 10360 private static boolean isSystemApp(ApplicationInfo info) { 10361 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10362 } 10363 10364 private static boolean isSystemApp(PackageSetting ps) { 10365 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 10366 } 10367 10368 private static boolean isUpdatedSystemApp(PackageSetting ps) { 10369 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10370 } 10371 10372 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 10373 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10374 } 10375 10376 private static boolean isUpdatedSystemApp(ApplicationInfo info) { 10377 return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10378 } 10379 10380 private int packageFlagsToInstallFlags(PackageSetting ps) { 10381 int installFlags = 0; 10382 if (isExternal(ps)) { 10383 installFlags |= PackageManager.INSTALL_EXTERNAL; 10384 } 10385 if (isForwardLocked(ps)) { 10386 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 10387 } 10388 return installFlags; 10389 } 10390 10391 private void deleteTempPackageFiles() { 10392 final FilenameFilter filter = new FilenameFilter() { 10393 public boolean accept(File dir, String name) { 10394 return name.startsWith("vmdl") && name.endsWith(".tmp"); 10395 } 10396 }; 10397 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 10398 file.delete(); 10399 } 10400 } 10401 10402 @Override 10403 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 10404 int flags) { 10405 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 10406 flags); 10407 } 10408 10409 @Override 10410 public void deletePackage(final String packageName, 10411 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 10412 mContext.enforceCallingOrSelfPermission( 10413 android.Manifest.permission.DELETE_PACKAGES, null); 10414 final int uid = Binder.getCallingUid(); 10415 if (UserHandle.getUserId(uid) != userId) { 10416 mContext.enforceCallingPermission( 10417 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 10418 "deletePackage for user " + userId); 10419 } 10420 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 10421 try { 10422 observer.onPackageDeleted(packageName, 10423 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 10424 } catch (RemoteException re) { 10425 } 10426 return; 10427 } 10428 10429 boolean uninstallBlocked = false; 10430 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 10431 int[] users = sUserManager.getUserIds(); 10432 for (int i = 0; i < users.length; ++i) { 10433 if (getBlockUninstallForUser(packageName, users[i])) { 10434 uninstallBlocked = true; 10435 break; 10436 } 10437 } 10438 } else { 10439 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 10440 } 10441 if (uninstallBlocked) { 10442 try { 10443 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 10444 null); 10445 } catch (RemoteException re) { 10446 } 10447 return; 10448 } 10449 10450 if (DEBUG_REMOVE) { 10451 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 10452 } 10453 // Queue up an async operation since the package deletion may take a little while. 10454 mHandler.post(new Runnable() { 10455 public void run() { 10456 mHandler.removeCallbacks(this); 10457 final int returnCode = deletePackageX(packageName, userId, flags); 10458 if (observer != null) { 10459 try { 10460 observer.onPackageDeleted(packageName, returnCode, null); 10461 } catch (RemoteException e) { 10462 Log.i(TAG, "Observer no longer exists."); 10463 } //end catch 10464 } //end if 10465 } //end run 10466 }); 10467 } 10468 10469 private boolean isPackageDeviceAdmin(String packageName, int userId) { 10470 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 10471 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 10472 try { 10473 if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId) 10474 || dpm.isDeviceOwner(packageName))) { 10475 return true; 10476 } 10477 } catch (RemoteException e) { 10478 } 10479 return false; 10480 } 10481 10482 /** 10483 * This method is an internal method that could be get invoked either 10484 * to delete an installed package or to clean up a failed installation. 10485 * After deleting an installed package, a broadcast is sent to notify any 10486 * listeners that the package has been installed. For cleaning up a failed 10487 * installation, the broadcast is not necessary since the package's 10488 * installation wouldn't have sent the initial broadcast either 10489 * The key steps in deleting a package are 10490 * deleting the package information in internal structures like mPackages, 10491 * deleting the packages base directories through installd 10492 * updating mSettings to reflect current status 10493 * persisting settings for later use 10494 * sending a broadcast if necessary 10495 */ 10496 private int deletePackageX(String packageName, int userId, int flags) { 10497 final PackageRemovedInfo info = new PackageRemovedInfo(); 10498 final boolean res; 10499 10500 if (isPackageDeviceAdmin(packageName, userId)) { 10501 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 10502 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 10503 } 10504 10505 boolean removedForAllUsers = false; 10506 boolean systemUpdate = false; 10507 10508 // for the uninstall-updates case and restricted profiles, remember the per- 10509 // userhandle installed state 10510 int[] allUsers; 10511 boolean[] perUserInstalled; 10512 synchronized (mPackages) { 10513 PackageSetting ps = mSettings.mPackages.get(packageName); 10514 allUsers = sUserManager.getUserIds(); 10515 perUserInstalled = new boolean[allUsers.length]; 10516 for (int i = 0; i < allUsers.length; i++) { 10517 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10518 } 10519 } 10520 10521 synchronized (mInstallLock) { 10522 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 10523 res = deletePackageLI(packageName, 10524 (flags & PackageManager.DELETE_ALL_USERS) != 0 10525 ? UserHandle.ALL : new UserHandle(userId), 10526 true, allUsers, perUserInstalled, 10527 flags | REMOVE_CHATTY, info, true); 10528 systemUpdate = info.isRemovedPackageSystemUpdate; 10529 if (res && !systemUpdate && mPackages.get(packageName) == null) { 10530 removedForAllUsers = true; 10531 } 10532 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 10533 + " removedForAllUsers=" + removedForAllUsers); 10534 } 10535 10536 if (res) { 10537 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 10538 10539 // If the removed package was a system update, the old system package 10540 // was re-enabled; we need to broadcast this information 10541 if (systemUpdate) { 10542 Bundle extras = new Bundle(1); 10543 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 10544 ? info.removedAppId : info.uid); 10545 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10546 10547 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 10548 extras, null, null, null); 10549 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 10550 extras, null, null, null); 10551 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 10552 null, packageName, null, null); 10553 } 10554 } 10555 // Force a gc here. 10556 Runtime.getRuntime().gc(); 10557 // Delete the resources here after sending the broadcast to let 10558 // other processes clean up before deleting resources. 10559 if (info.args != null) { 10560 synchronized (mInstallLock) { 10561 info.args.doPostDeleteLI(true); 10562 } 10563 } 10564 10565 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10566 } 10567 10568 static class PackageRemovedInfo { 10569 String removedPackage; 10570 int uid = -1; 10571 int removedAppId = -1; 10572 int[] removedUsers = null; 10573 boolean isRemovedPackageSystemUpdate = false; 10574 // Clean up resources deleted packages. 10575 InstallArgs args = null; 10576 10577 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 10578 Bundle extras = new Bundle(1); 10579 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 10580 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 10581 if (replacing) { 10582 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10583 } 10584 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 10585 if (removedPackage != null) { 10586 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 10587 extras, null, null, removedUsers); 10588 if (fullRemove && !replacing) { 10589 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 10590 extras, null, null, removedUsers); 10591 } 10592 } 10593 if (removedAppId >= 0) { 10594 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 10595 removedUsers); 10596 } 10597 } 10598 } 10599 10600 /* 10601 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 10602 * flag is not set, the data directory is removed as well. 10603 * make sure this flag is set for partially installed apps. If not its meaningless to 10604 * delete a partially installed application. 10605 */ 10606 private void removePackageDataLI(PackageSetting ps, 10607 int[] allUserHandles, boolean[] perUserInstalled, 10608 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 10609 String packageName = ps.name; 10610 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 10611 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 10612 // Retrieve object to delete permissions for shared user later on 10613 final PackageSetting deletedPs; 10614 // reader 10615 synchronized (mPackages) { 10616 deletedPs = mSettings.mPackages.get(packageName); 10617 if (outInfo != null) { 10618 outInfo.removedPackage = packageName; 10619 outInfo.removedUsers = deletedPs != null 10620 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 10621 : null; 10622 } 10623 } 10624 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10625 removeDataDirsLI(packageName); 10626 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 10627 } 10628 // writer 10629 synchronized (mPackages) { 10630 if (deletedPs != null) { 10631 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10632 if (outInfo != null) { 10633 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 10634 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 10635 } 10636 if (deletedPs != null) { 10637 updatePermissionsLPw(deletedPs.name, null, 0); 10638 if (deletedPs.sharedUser != null) { 10639 // remove permissions associated with package 10640 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 10641 } 10642 } 10643 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 10644 } 10645 // make sure to preserve per-user disabled state if this removal was just 10646 // a downgrade of a system app to the factory package 10647 if (allUserHandles != null && perUserInstalled != null) { 10648 if (DEBUG_REMOVE) { 10649 Slog.d(TAG, "Propagating install state across downgrade"); 10650 } 10651 for (int i = 0; i < allUserHandles.length; i++) { 10652 if (DEBUG_REMOVE) { 10653 Slog.d(TAG, " user " + allUserHandles[i] 10654 + " => " + perUserInstalled[i]); 10655 } 10656 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10657 } 10658 } 10659 } 10660 // can downgrade to reader 10661 if (writeSettings) { 10662 // Save settings now 10663 mSettings.writeLPr(); 10664 } 10665 } 10666 if (outInfo != null) { 10667 // A user ID was deleted here. Go through all users and remove it 10668 // from KeyStore. 10669 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 10670 } 10671 } 10672 10673 static boolean locationIsPrivileged(File path) { 10674 try { 10675 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 10676 .getCanonicalPath(); 10677 return path.getCanonicalPath().startsWith(privilegedAppDir); 10678 } catch (IOException e) { 10679 Slog.e(TAG, "Unable to access code path " + path); 10680 } 10681 return false; 10682 } 10683 10684 /* 10685 * Tries to delete system package. 10686 */ 10687 private boolean deleteSystemPackageLI(PackageSetting newPs, 10688 int[] allUserHandles, boolean[] perUserInstalled, 10689 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 10690 final boolean applyUserRestrictions 10691 = (allUserHandles != null) && (perUserInstalled != null); 10692 PackageSetting disabledPs = null; 10693 // Confirm if the system package has been updated 10694 // An updated system app can be deleted. This will also have to restore 10695 // the system pkg from system partition 10696 // reader 10697 synchronized (mPackages) { 10698 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 10699 } 10700 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 10701 + " disabledPs=" + disabledPs); 10702 if (disabledPs == null) { 10703 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 10704 return false; 10705 } else if (DEBUG_REMOVE) { 10706 Slog.d(TAG, "Deleting system pkg from data partition"); 10707 } 10708 if (DEBUG_REMOVE) { 10709 if (applyUserRestrictions) { 10710 Slog.d(TAG, "Remembering install states:"); 10711 for (int i = 0; i < allUserHandles.length; i++) { 10712 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 10713 } 10714 } 10715 } 10716 // Delete the updated package 10717 outInfo.isRemovedPackageSystemUpdate = true; 10718 if (disabledPs.versionCode < newPs.versionCode) { 10719 // Delete data for downgrades 10720 flags &= ~PackageManager.DELETE_KEEP_DATA; 10721 } else { 10722 // Preserve data by setting flag 10723 flags |= PackageManager.DELETE_KEEP_DATA; 10724 } 10725 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 10726 allUserHandles, perUserInstalled, outInfo, writeSettings); 10727 if (!ret) { 10728 return false; 10729 } 10730 // writer 10731 synchronized (mPackages) { 10732 // Reinstate the old system package 10733 mSettings.enableSystemPackageLPw(newPs.name); 10734 // Remove any native libraries from the upgraded package. 10735 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 10736 } 10737 // Install the system package 10738 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 10739 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 10740 if (locationIsPrivileged(disabledPs.codePath)) { 10741 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10742 } 10743 10744 final PackageParser.Package newPkg; 10745 try { 10746 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 10747 } catch (PackageManagerException e) { 10748 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 10749 return false; 10750 } 10751 10752 // writer 10753 synchronized (mPackages) { 10754 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 10755 updatePermissionsLPw(newPkg.packageName, newPkg, 10756 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 10757 if (applyUserRestrictions) { 10758 if (DEBUG_REMOVE) { 10759 Slog.d(TAG, "Propagating install state across reinstall"); 10760 } 10761 for (int i = 0; i < allUserHandles.length; i++) { 10762 if (DEBUG_REMOVE) { 10763 Slog.d(TAG, " user " + allUserHandles[i] 10764 + " => " + perUserInstalled[i]); 10765 } 10766 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10767 } 10768 // Regardless of writeSettings we need to ensure that this restriction 10769 // state propagation is persisted 10770 mSettings.writeAllUsersPackageRestrictionsLPr(); 10771 } 10772 // can downgrade to reader here 10773 if (writeSettings) { 10774 mSettings.writeLPr(); 10775 } 10776 } 10777 return true; 10778 } 10779 10780 private boolean deleteInstalledPackageLI(PackageSetting ps, 10781 boolean deleteCodeAndResources, int flags, 10782 int[] allUserHandles, boolean[] perUserInstalled, 10783 PackageRemovedInfo outInfo, boolean writeSettings) { 10784 if (outInfo != null) { 10785 outInfo.uid = ps.appId; 10786 } 10787 10788 // Delete package data from internal structures and also remove data if flag is set 10789 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 10790 10791 // Delete application code and resources 10792 if (deleteCodeAndResources && (outInfo != null)) { 10793 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 10794 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 10795 getAppDexInstructionSets(ps)); 10796 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 10797 } 10798 return true; 10799 } 10800 10801 @Override 10802 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 10803 int userId) { 10804 mContext.enforceCallingOrSelfPermission( 10805 android.Manifest.permission.DELETE_PACKAGES, null); 10806 synchronized (mPackages) { 10807 PackageSetting ps = mSettings.mPackages.get(packageName); 10808 if (ps == null) { 10809 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 10810 return false; 10811 } 10812 if (!ps.getInstalled(userId)) { 10813 // Can't block uninstall for an app that is not installed or enabled. 10814 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 10815 return false; 10816 } 10817 ps.setBlockUninstall(blockUninstall, userId); 10818 mSettings.writePackageRestrictionsLPr(userId); 10819 } 10820 return true; 10821 } 10822 10823 @Override 10824 public boolean getBlockUninstallForUser(String packageName, int userId) { 10825 synchronized (mPackages) { 10826 PackageSetting ps = mSettings.mPackages.get(packageName); 10827 if (ps == null) { 10828 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 10829 return false; 10830 } 10831 return ps.getBlockUninstall(userId); 10832 } 10833 } 10834 10835 /* 10836 * This method handles package deletion in general 10837 */ 10838 private boolean deletePackageLI(String packageName, UserHandle user, 10839 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 10840 int flags, PackageRemovedInfo outInfo, 10841 boolean writeSettings) { 10842 if (packageName == null) { 10843 Slog.w(TAG, "Attempt to delete null packageName."); 10844 return false; 10845 } 10846 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 10847 PackageSetting ps; 10848 boolean dataOnly = false; 10849 int removeUser = -1; 10850 int appId = -1; 10851 synchronized (mPackages) { 10852 ps = mSettings.mPackages.get(packageName); 10853 if (ps == null) { 10854 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 10855 return false; 10856 } 10857 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 10858 && user.getIdentifier() != UserHandle.USER_ALL) { 10859 // The caller is asking that the package only be deleted for a single 10860 // user. To do this, we just mark its uninstalled state and delete 10861 // its data. If this is a system app, we only allow this to happen if 10862 // they have set the special DELETE_SYSTEM_APP which requests different 10863 // semantics than normal for uninstalling system apps. 10864 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 10865 ps.setUserState(user.getIdentifier(), 10866 COMPONENT_ENABLED_STATE_DEFAULT, 10867 false, //installed 10868 true, //stopped 10869 true, //notLaunched 10870 false, //hidden 10871 null, null, null, 10872 false // blockUninstall 10873 ); 10874 if (!isSystemApp(ps)) { 10875 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 10876 // Other user still have this package installed, so all 10877 // we need to do is clear this user's data and save that 10878 // it is uninstalled. 10879 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 10880 removeUser = user.getIdentifier(); 10881 appId = ps.appId; 10882 mSettings.writePackageRestrictionsLPr(removeUser); 10883 } else { 10884 // We need to set it back to 'installed' so the uninstall 10885 // broadcasts will be sent correctly. 10886 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 10887 ps.setInstalled(true, user.getIdentifier()); 10888 } 10889 } else { 10890 // This is a system app, so we assume that the 10891 // other users still have this package installed, so all 10892 // we need to do is clear this user's data and save that 10893 // it is uninstalled. 10894 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 10895 removeUser = user.getIdentifier(); 10896 appId = ps.appId; 10897 mSettings.writePackageRestrictionsLPr(removeUser); 10898 } 10899 } 10900 } 10901 10902 if (removeUser >= 0) { 10903 // From above, we determined that we are deleting this only 10904 // for a single user. Continue the work here. 10905 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 10906 if (outInfo != null) { 10907 outInfo.removedPackage = packageName; 10908 outInfo.removedAppId = appId; 10909 outInfo.removedUsers = new int[] {removeUser}; 10910 } 10911 mInstaller.clearUserData(packageName, removeUser); 10912 removeKeystoreDataIfNeeded(removeUser, appId); 10913 schedulePackageCleaning(packageName, removeUser, false); 10914 return true; 10915 } 10916 10917 if (dataOnly) { 10918 // Delete application data first 10919 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 10920 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 10921 return true; 10922 } 10923 10924 boolean ret = false; 10925 if (isSystemApp(ps)) { 10926 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 10927 // When an updated system application is deleted we delete the existing resources as well and 10928 // fall back to existing code in system partition 10929 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 10930 flags, outInfo, writeSettings); 10931 } else { 10932 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 10933 // Kill application pre-emptively especially for apps on sd. 10934 killApplication(packageName, ps.appId, "uninstall pkg"); 10935 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 10936 allUserHandles, perUserInstalled, 10937 outInfo, writeSettings); 10938 } 10939 10940 return ret; 10941 } 10942 10943 private final class ClearStorageConnection implements ServiceConnection { 10944 IMediaContainerService mContainerService; 10945 10946 @Override 10947 public void onServiceConnected(ComponentName name, IBinder service) { 10948 synchronized (this) { 10949 mContainerService = IMediaContainerService.Stub.asInterface(service); 10950 notifyAll(); 10951 } 10952 } 10953 10954 @Override 10955 public void onServiceDisconnected(ComponentName name) { 10956 } 10957 } 10958 10959 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 10960 final boolean mounted; 10961 if (Environment.isExternalStorageEmulated()) { 10962 mounted = true; 10963 } else { 10964 final String status = Environment.getExternalStorageState(); 10965 10966 mounted = status.equals(Environment.MEDIA_MOUNTED) 10967 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 10968 } 10969 10970 if (!mounted) { 10971 return; 10972 } 10973 10974 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 10975 int[] users; 10976 if (userId == UserHandle.USER_ALL) { 10977 users = sUserManager.getUserIds(); 10978 } else { 10979 users = new int[] { userId }; 10980 } 10981 final ClearStorageConnection conn = new ClearStorageConnection(); 10982 if (mContext.bindServiceAsUser( 10983 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 10984 try { 10985 for (int curUser : users) { 10986 long timeout = SystemClock.uptimeMillis() + 5000; 10987 synchronized (conn) { 10988 long now = SystemClock.uptimeMillis(); 10989 while (conn.mContainerService == null && now < timeout) { 10990 try { 10991 conn.wait(timeout - now); 10992 } catch (InterruptedException e) { 10993 } 10994 } 10995 } 10996 if (conn.mContainerService == null) { 10997 return; 10998 } 10999 11000 final UserEnvironment userEnv = new UserEnvironment(curUser); 11001 clearDirectory(conn.mContainerService, 11002 userEnv.buildExternalStorageAppCacheDirs(packageName)); 11003 if (allData) { 11004 clearDirectory(conn.mContainerService, 11005 userEnv.buildExternalStorageAppDataDirs(packageName)); 11006 clearDirectory(conn.mContainerService, 11007 userEnv.buildExternalStorageAppMediaDirs(packageName)); 11008 } 11009 } 11010 } finally { 11011 mContext.unbindService(conn); 11012 } 11013 } 11014 } 11015 11016 @Override 11017 public void clearApplicationUserData(final String packageName, 11018 final IPackageDataObserver observer, final int userId) { 11019 mContext.enforceCallingOrSelfPermission( 11020 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 11021 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data"); 11022 // Queue up an async operation since the package deletion may take a little while. 11023 mHandler.post(new Runnable() { 11024 public void run() { 11025 mHandler.removeCallbacks(this); 11026 final boolean succeeded; 11027 synchronized (mInstallLock) { 11028 succeeded = clearApplicationUserDataLI(packageName, userId); 11029 } 11030 clearExternalStorageDataSync(packageName, userId, true); 11031 if (succeeded) { 11032 // invoke DeviceStorageMonitor's update method to clear any notifications 11033 DeviceStorageMonitorInternal 11034 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 11035 if (dsm != null) { 11036 dsm.checkMemory(); 11037 } 11038 } 11039 if(observer != null) { 11040 try { 11041 observer.onRemoveCompleted(packageName, succeeded); 11042 } catch (RemoteException e) { 11043 Log.i(TAG, "Observer no longer exists."); 11044 } 11045 } //end if observer 11046 } //end run 11047 }); 11048 } 11049 11050 private boolean clearApplicationUserDataLI(String packageName, int userId) { 11051 if (packageName == null) { 11052 Slog.w(TAG, "Attempt to delete null packageName."); 11053 return false; 11054 } 11055 PackageParser.Package pkg; 11056 boolean dataOnly = false; 11057 final int appId; 11058 synchronized (mPackages) { 11059 pkg = mPackages.get(packageName); 11060 if (pkg == null) { 11061 dataOnly = true; 11062 PackageSetting ps = mSettings.mPackages.get(packageName); 11063 if ((ps == null) || (ps.pkg == null)) { 11064 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11065 return false; 11066 } 11067 pkg = ps.pkg; 11068 } 11069 if (!dataOnly) { 11070 // need to check this only for fully installed applications 11071 if (pkg == null) { 11072 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11073 return false; 11074 } 11075 final ApplicationInfo applicationInfo = pkg.applicationInfo; 11076 if (applicationInfo == null) { 11077 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11078 return false; 11079 } 11080 } 11081 if (pkg != null && pkg.applicationInfo != null) { 11082 appId = pkg.applicationInfo.uid; 11083 } else { 11084 appId = -1; 11085 } 11086 } 11087 int retCode = mInstaller.clearUserData(packageName, userId); 11088 if (retCode < 0) { 11089 Slog.w(TAG, "Couldn't remove cache files for package: " 11090 + packageName); 11091 return false; 11092 } 11093 removeKeystoreDataIfNeeded(userId, appId); 11094 11095 // Create a native library symlink only if we have native libraries 11096 // and if the native libraries are 32 bit libraries. We do not provide 11097 // this symlink for 64 bit libraries. 11098 if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null && 11099 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 11100 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 11101 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 11102 Slog.w(TAG, "Failed linking native library dir"); 11103 return false; 11104 } 11105 } 11106 11107 return true; 11108 } 11109 11110 /** 11111 * Remove entries from the keystore daemon. Will only remove it if the 11112 * {@code appId} is valid. 11113 */ 11114 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 11115 if (appId < 0) { 11116 return; 11117 } 11118 11119 final KeyStore keyStore = KeyStore.getInstance(); 11120 if (keyStore != null) { 11121 if (userId == UserHandle.USER_ALL) { 11122 for (final int individual : sUserManager.getUserIds()) { 11123 keyStore.clearUid(UserHandle.getUid(individual, appId)); 11124 } 11125 } else { 11126 keyStore.clearUid(UserHandle.getUid(userId, appId)); 11127 } 11128 } else { 11129 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 11130 } 11131 } 11132 11133 @Override 11134 public void deleteApplicationCacheFiles(final String packageName, 11135 final IPackageDataObserver observer) { 11136 mContext.enforceCallingOrSelfPermission( 11137 android.Manifest.permission.DELETE_CACHE_FILES, null); 11138 // Queue up an async operation since the package deletion may take a little while. 11139 final int userId = UserHandle.getCallingUserId(); 11140 mHandler.post(new Runnable() { 11141 public void run() { 11142 mHandler.removeCallbacks(this); 11143 final boolean succeded; 11144 synchronized (mInstallLock) { 11145 succeded = deleteApplicationCacheFilesLI(packageName, userId); 11146 } 11147 clearExternalStorageDataSync(packageName, userId, false); 11148 if(observer != null) { 11149 try { 11150 observer.onRemoveCompleted(packageName, succeded); 11151 } catch (RemoteException e) { 11152 Log.i(TAG, "Observer no longer exists."); 11153 } 11154 } //end if observer 11155 } //end run 11156 }); 11157 } 11158 11159 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 11160 if (packageName == null) { 11161 Slog.w(TAG, "Attempt to delete null packageName."); 11162 return false; 11163 } 11164 PackageParser.Package p; 11165 synchronized (mPackages) { 11166 p = mPackages.get(packageName); 11167 } 11168 if (p == null) { 11169 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11170 return false; 11171 } 11172 final ApplicationInfo applicationInfo = p.applicationInfo; 11173 if (applicationInfo == null) { 11174 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11175 return false; 11176 } 11177 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 11178 if (retCode < 0) { 11179 Slog.w(TAG, "Couldn't remove cache files for package: " 11180 + packageName + " u" + userId); 11181 return false; 11182 } 11183 return true; 11184 } 11185 11186 @Override 11187 public void getPackageSizeInfo(final String packageName, int userHandle, 11188 final IPackageStatsObserver observer) { 11189 mContext.enforceCallingOrSelfPermission( 11190 android.Manifest.permission.GET_PACKAGE_SIZE, null); 11191 if (packageName == null) { 11192 throw new IllegalArgumentException("Attempt to get size of null packageName"); 11193 } 11194 11195 PackageStats stats = new PackageStats(packageName, userHandle); 11196 11197 /* 11198 * Queue up an async operation since the package measurement may take a 11199 * little while. 11200 */ 11201 Message msg = mHandler.obtainMessage(INIT_COPY); 11202 msg.obj = new MeasureParams(stats, observer); 11203 mHandler.sendMessage(msg); 11204 } 11205 11206 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 11207 PackageStats pStats) { 11208 if (packageName == null) { 11209 Slog.w(TAG, "Attempt to get size of null packageName."); 11210 return false; 11211 } 11212 PackageParser.Package p; 11213 boolean dataOnly = false; 11214 String libDirRoot = null; 11215 String asecPath = null; 11216 PackageSetting ps = null; 11217 synchronized (mPackages) { 11218 p = mPackages.get(packageName); 11219 ps = mSettings.mPackages.get(packageName); 11220 if(p == null) { 11221 dataOnly = true; 11222 if((ps == null) || (ps.pkg == null)) { 11223 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11224 return false; 11225 } 11226 p = ps.pkg; 11227 } 11228 if (ps != null) { 11229 libDirRoot = ps.legacyNativeLibraryPathString; 11230 } 11231 if (p != null && (isExternal(p) || isForwardLocked(p))) { 11232 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 11233 if (secureContainerId != null) { 11234 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 11235 } 11236 } 11237 } 11238 String publicSrcDir = null; 11239 if(!dataOnly) { 11240 final ApplicationInfo applicationInfo = p.applicationInfo; 11241 if (applicationInfo == null) { 11242 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11243 return false; 11244 } 11245 if (isForwardLocked(p)) { 11246 publicSrcDir = applicationInfo.getBaseResourcePath(); 11247 } 11248 } 11249 // TODO: extend to measure size of split APKs 11250 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 11251 // not just the first level. 11252 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 11253 // just the primary. 11254 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 11255 int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot, 11256 publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 11257 if (res < 0) { 11258 return false; 11259 } 11260 11261 // Fix-up for forward-locked applications in ASEC containers. 11262 if (!isExternal(p)) { 11263 pStats.codeSize += pStats.externalCodeSize; 11264 pStats.externalCodeSize = 0L; 11265 } 11266 11267 return true; 11268 } 11269 11270 11271 @Override 11272 public void addPackageToPreferred(String packageName) { 11273 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 11274 } 11275 11276 @Override 11277 public void removePackageFromPreferred(String packageName) { 11278 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 11279 } 11280 11281 @Override 11282 public List<PackageInfo> getPreferredPackages(int flags) { 11283 return new ArrayList<PackageInfo>(); 11284 } 11285 11286 private int getUidTargetSdkVersionLockedLPr(int uid) { 11287 Object obj = mSettings.getUserIdLPr(uid); 11288 if (obj instanceof SharedUserSetting) { 11289 final SharedUserSetting sus = (SharedUserSetting) obj; 11290 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 11291 final Iterator<PackageSetting> it = sus.packages.iterator(); 11292 while (it.hasNext()) { 11293 final PackageSetting ps = it.next(); 11294 if (ps.pkg != null) { 11295 int v = ps.pkg.applicationInfo.targetSdkVersion; 11296 if (v < vers) vers = v; 11297 } 11298 } 11299 return vers; 11300 } else if (obj instanceof PackageSetting) { 11301 final PackageSetting ps = (PackageSetting) obj; 11302 if (ps.pkg != null) { 11303 return ps.pkg.applicationInfo.targetSdkVersion; 11304 } 11305 } 11306 return Build.VERSION_CODES.CUR_DEVELOPMENT; 11307 } 11308 11309 @Override 11310 public void addPreferredActivity(IntentFilter filter, int match, 11311 ComponentName[] set, ComponentName activity, int userId) { 11312 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11313 "Adding preferred"); 11314 } 11315 11316 private void addPreferredActivityInternal(IntentFilter filter, int match, 11317 ComponentName[] set, ComponentName activity, boolean always, int userId, 11318 String opname) { 11319 // writer 11320 int callingUid = Binder.getCallingUid(); 11321 enforceCrossUserPermission(callingUid, userId, true, "add preferred activity"); 11322 if (filter.countActions() == 0) { 11323 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11324 return; 11325 } 11326 synchronized (mPackages) { 11327 if (mContext.checkCallingOrSelfPermission( 11328 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11329 != PackageManager.PERMISSION_GRANTED) { 11330 if (getUidTargetSdkVersionLockedLPr(callingUid) 11331 < Build.VERSION_CODES.FROYO) { 11332 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 11333 + callingUid); 11334 return; 11335 } 11336 mContext.enforceCallingOrSelfPermission( 11337 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11338 } 11339 11340 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 11341 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 11342 + userId + ":"); 11343 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11344 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 11345 mSettings.writePackageRestrictionsLPr(userId); 11346 } 11347 } 11348 11349 @Override 11350 public void replacePreferredActivity(IntentFilter filter, int match, 11351 ComponentName[] set, ComponentName activity, int userId) { 11352 if (filter.countActions() != 1) { 11353 throw new IllegalArgumentException( 11354 "replacePreferredActivity expects filter to have only 1 action."); 11355 } 11356 if (filter.countDataAuthorities() != 0 11357 || filter.countDataPaths() != 0 11358 || filter.countDataSchemes() > 1 11359 || filter.countDataTypes() != 0) { 11360 throw new IllegalArgumentException( 11361 "replacePreferredActivity expects filter to have no data authorities, " + 11362 "paths, or types; and at most one scheme."); 11363 } 11364 11365 final int callingUid = Binder.getCallingUid(); 11366 enforceCrossUserPermission(callingUid, userId, true, "replace preferred activity"); 11367 synchronized (mPackages) { 11368 if (mContext.checkCallingOrSelfPermission( 11369 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11370 != PackageManager.PERMISSION_GRANTED) { 11371 if (getUidTargetSdkVersionLockedLPr(callingUid) 11372 < Build.VERSION_CODES.FROYO) { 11373 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 11374 + Binder.getCallingUid()); 11375 return; 11376 } 11377 mContext.enforceCallingOrSelfPermission( 11378 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11379 } 11380 11381 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11382 if (pir != null) { 11383 // Get all of the existing entries that exactly match this filter. 11384 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 11385 if (existing != null && existing.size() == 1) { 11386 PreferredActivity cur = existing.get(0); 11387 if (DEBUG_PREFERRED) { 11388 Slog.i(TAG, "Checking replace of preferred:"); 11389 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11390 if (!cur.mPref.mAlways) { 11391 Slog.i(TAG, " -- CUR; not mAlways!"); 11392 } else { 11393 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 11394 Slog.i(TAG, " -- CUR: mSet=" 11395 + Arrays.toString(cur.mPref.mSetComponents)); 11396 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 11397 Slog.i(TAG, " -- NEW: mMatch=" 11398 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 11399 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 11400 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 11401 } 11402 } 11403 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 11404 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 11405 && cur.mPref.sameSet(set)) { 11406 if (DEBUG_PREFERRED) { 11407 Slog.i(TAG, "Replacing with same preferred activity " 11408 + cur.mPref.mShortComponent + " for user " 11409 + userId + ":"); 11410 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11411 } else { 11412 Slog.i(TAG, "Replacing with same preferred activity " 11413 + cur.mPref.mShortComponent + " for user " 11414 + userId); 11415 } 11416 return; 11417 } 11418 } 11419 11420 if (existing != null) { 11421 if (DEBUG_PREFERRED) { 11422 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 11423 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11424 } 11425 for (int i = 0; i < existing.size(); i++) { 11426 PreferredActivity pa = existing.get(i); 11427 if (DEBUG_PREFERRED) { 11428 Slog.i(TAG, "Removing existing preferred activity " 11429 + pa.mPref.mComponent + ":"); 11430 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 11431 } 11432 pir.removeFilter(pa); 11433 } 11434 } 11435 } 11436 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11437 "Replacing preferred"); 11438 } 11439 } 11440 11441 @Override 11442 public void clearPackagePreferredActivities(String packageName) { 11443 final int uid = Binder.getCallingUid(); 11444 // writer 11445 synchronized (mPackages) { 11446 PackageParser.Package pkg = mPackages.get(packageName); 11447 if (pkg == null || pkg.applicationInfo.uid != uid) { 11448 if (mContext.checkCallingOrSelfPermission( 11449 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11450 != PackageManager.PERMISSION_GRANTED) { 11451 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11452 < Build.VERSION_CODES.FROYO) { 11453 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 11454 + Binder.getCallingUid()); 11455 return; 11456 } 11457 mContext.enforceCallingOrSelfPermission( 11458 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11459 } 11460 } 11461 11462 int user = UserHandle.getCallingUserId(); 11463 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 11464 mSettings.writePackageRestrictionsLPr(user); 11465 scheduleWriteSettingsLocked(); 11466 } 11467 } 11468 } 11469 11470 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 11471 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 11472 ArrayList<PreferredActivity> removed = null; 11473 boolean changed = false; 11474 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11475 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 11476 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11477 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 11478 continue; 11479 } 11480 Iterator<PreferredActivity> it = pir.filterIterator(); 11481 while (it.hasNext()) { 11482 PreferredActivity pa = it.next(); 11483 // Mark entry for removal only if it matches the package name 11484 // and the entry is of type "always". 11485 if (packageName == null || 11486 (pa.mPref.mComponent.getPackageName().equals(packageName) 11487 && pa.mPref.mAlways)) { 11488 if (removed == null) { 11489 removed = new ArrayList<PreferredActivity>(); 11490 } 11491 removed.add(pa); 11492 } 11493 } 11494 if (removed != null) { 11495 for (int j=0; j<removed.size(); j++) { 11496 PreferredActivity pa = removed.get(j); 11497 pir.removeFilter(pa); 11498 } 11499 changed = true; 11500 } 11501 } 11502 return changed; 11503 } 11504 11505 @Override 11506 public void resetPreferredActivities(int userId) { 11507 mContext.enforceCallingOrSelfPermission( 11508 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11509 // writer 11510 synchronized (mPackages) { 11511 int user = UserHandle.getCallingUserId(); 11512 clearPackagePreferredActivitiesLPw(null, user); 11513 mSettings.readDefaultPreferredAppsLPw(this, user); 11514 mSettings.writePackageRestrictionsLPr(user); 11515 scheduleWriteSettingsLocked(); 11516 } 11517 } 11518 11519 @Override 11520 public int getPreferredActivities(List<IntentFilter> outFilters, 11521 List<ComponentName> outActivities, String packageName) { 11522 11523 int num = 0; 11524 final int userId = UserHandle.getCallingUserId(); 11525 // reader 11526 synchronized (mPackages) { 11527 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11528 if (pir != null) { 11529 final Iterator<PreferredActivity> it = pir.filterIterator(); 11530 while (it.hasNext()) { 11531 final PreferredActivity pa = it.next(); 11532 if (packageName == null 11533 || (pa.mPref.mComponent.getPackageName().equals(packageName) 11534 && pa.mPref.mAlways)) { 11535 if (outFilters != null) { 11536 outFilters.add(new IntentFilter(pa)); 11537 } 11538 if (outActivities != null) { 11539 outActivities.add(pa.mPref.mComponent); 11540 } 11541 } 11542 } 11543 } 11544 } 11545 11546 return num; 11547 } 11548 11549 @Override 11550 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 11551 int userId) { 11552 int callingUid = Binder.getCallingUid(); 11553 if (callingUid != Process.SYSTEM_UID) { 11554 throw new SecurityException( 11555 "addPersistentPreferredActivity can only be run by the system"); 11556 } 11557 if (filter.countActions() == 0) { 11558 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11559 return; 11560 } 11561 synchronized (mPackages) { 11562 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 11563 " :"); 11564 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11565 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 11566 new PersistentPreferredActivity(filter, activity)); 11567 mSettings.writePackageRestrictionsLPr(userId); 11568 } 11569 } 11570 11571 @Override 11572 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 11573 int callingUid = Binder.getCallingUid(); 11574 if (callingUid != Process.SYSTEM_UID) { 11575 throw new SecurityException( 11576 "clearPackagePersistentPreferredActivities can only be run by the system"); 11577 } 11578 ArrayList<PersistentPreferredActivity> removed = null; 11579 boolean changed = false; 11580 synchronized (mPackages) { 11581 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 11582 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 11583 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 11584 .valueAt(i); 11585 if (userId != thisUserId) { 11586 continue; 11587 } 11588 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 11589 while (it.hasNext()) { 11590 PersistentPreferredActivity ppa = it.next(); 11591 // Mark entry for removal only if it matches the package name. 11592 if (ppa.mComponent.getPackageName().equals(packageName)) { 11593 if (removed == null) { 11594 removed = new ArrayList<PersistentPreferredActivity>(); 11595 } 11596 removed.add(ppa); 11597 } 11598 } 11599 if (removed != null) { 11600 for (int j=0; j<removed.size(); j++) { 11601 PersistentPreferredActivity ppa = removed.get(j); 11602 ppir.removeFilter(ppa); 11603 } 11604 changed = true; 11605 } 11606 } 11607 11608 if (changed) { 11609 mSettings.writePackageRestrictionsLPr(userId); 11610 } 11611 } 11612 } 11613 11614 @Override 11615 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 11616 int ownerUserId, int sourceUserId, int targetUserId, int flags) { 11617 mContext.enforceCallingOrSelfPermission( 11618 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11619 int callingUid = Binder.getCallingUid(); 11620 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11621 if (intentFilter.countActions() == 0) { 11622 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 11623 return; 11624 } 11625 synchronized (mPackages) { 11626 CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter, 11627 ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags); 11628 mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter); 11629 mSettings.writePackageRestrictionsLPr(sourceUserId); 11630 } 11631 } 11632 11633 @Override 11634 public void addCrossProfileIntentsForPackage(String packageName, 11635 int sourceUserId, int targetUserId) { 11636 mContext.enforceCallingOrSelfPermission( 11637 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11638 mSettings.addCrossProfilePackage(packageName, sourceUserId, targetUserId); 11639 mSettings.writePackageRestrictionsLPr(sourceUserId); 11640 } 11641 11642 @Override 11643 public void removeCrossProfileIntentsForPackage(String packageName, 11644 int sourceUserId, int targetUserId) { 11645 mContext.enforceCallingOrSelfPermission( 11646 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11647 mSettings.removeCrossProfilePackage(packageName, sourceUserId, targetUserId); 11648 mSettings.writePackageRestrictionsLPr(sourceUserId); 11649 } 11650 11651 @Override 11652 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage, 11653 int ownerUserId) { 11654 mContext.enforceCallingOrSelfPermission( 11655 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11656 int callingUid = Binder.getCallingUid(); 11657 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11658 int callingUserId = UserHandle.getUserId(callingUid); 11659 synchronized (mPackages) { 11660 CrossProfileIntentResolver resolver = 11661 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11662 HashSet<CrossProfileIntentFilter> set = 11663 new HashSet<CrossProfileIntentFilter>(resolver.filterSet()); 11664 for (CrossProfileIntentFilter filter : set) { 11665 if (filter.getOwnerPackage().equals(ownerPackage) 11666 && filter.getOwnerUserId() == callingUserId) { 11667 resolver.removeFilter(filter); 11668 } 11669 } 11670 mSettings.writePackageRestrictionsLPr(sourceUserId); 11671 } 11672 } 11673 11674 // Enforcing that callingUid is owning pkg on userId 11675 private void enforceOwnerRights(String pkg, int userId, int callingUid) { 11676 // The system owns everything. 11677 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 11678 return; 11679 } 11680 int callingUserId = UserHandle.getUserId(callingUid); 11681 if (callingUserId != userId) { 11682 throw new SecurityException("calling uid " + callingUid 11683 + " pretends to own " + pkg + " on user " + userId + " but belongs to user " 11684 + callingUserId); 11685 } 11686 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 11687 if (pi == null) { 11688 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 11689 + callingUserId); 11690 } 11691 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 11692 throw new SecurityException("Calling uid " + callingUid 11693 + " does not own package " + pkg); 11694 } 11695 } 11696 11697 @Override 11698 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 11699 Intent intent = new Intent(Intent.ACTION_MAIN); 11700 intent.addCategory(Intent.CATEGORY_HOME); 11701 11702 final int callingUserId = UserHandle.getCallingUserId(); 11703 List<ResolveInfo> list = queryIntentActivities(intent, null, 11704 PackageManager.GET_META_DATA, callingUserId); 11705 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 11706 true, false, false, callingUserId); 11707 11708 allHomeCandidates.clear(); 11709 if (list != null) { 11710 for (ResolveInfo ri : list) { 11711 allHomeCandidates.add(ri); 11712 } 11713 } 11714 return (preferred == null || preferred.activityInfo == null) 11715 ? null 11716 : new ComponentName(preferred.activityInfo.packageName, 11717 preferred.activityInfo.name); 11718 } 11719 11720 /** 11721 * Check if calling UID is the current home app. This handles both the case 11722 * where the user has selected a specific home app, and where there is only 11723 * one home app. 11724 */ 11725 public boolean checkCallerIsHomeApp() { 11726 final Intent intent = new Intent(Intent.ACTION_MAIN); 11727 intent.addCategory(Intent.CATEGORY_HOME); 11728 11729 final int callingUid = Binder.getCallingUid(); 11730 final int callingUserId = UserHandle.getCallingUserId(); 11731 final List<ResolveInfo> allHomes = queryIntentActivities(intent, null, 0, callingUserId); 11732 final ResolveInfo preferredHome = findPreferredActivity(intent, null, 0, allHomes, 0, true, 11733 false, false, callingUserId); 11734 11735 if (preferredHome != null) { 11736 if (callingUid == preferredHome.activityInfo.applicationInfo.uid) { 11737 return true; 11738 } 11739 } else { 11740 for (ResolveInfo info : allHomes) { 11741 if (callingUid == info.activityInfo.applicationInfo.uid) { 11742 return true; 11743 } 11744 } 11745 } 11746 11747 return false; 11748 } 11749 11750 /** 11751 * Enforce that calling UID is the current home app. This handles both the 11752 * case where the user has selected a specific home app, and where there is 11753 * only one home app. 11754 */ 11755 public void enforceCallerIsHomeApp() { 11756 if (!checkCallerIsHomeApp()) { 11757 throw new SecurityException("Caller is not currently selected home app"); 11758 } 11759 } 11760 11761 @Override 11762 public void setApplicationEnabledSetting(String appPackageName, 11763 int newState, int flags, int userId, String callingPackage) { 11764 if (!sUserManager.exists(userId)) return; 11765 if (callingPackage == null) { 11766 callingPackage = Integer.toString(Binder.getCallingUid()); 11767 } 11768 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 11769 } 11770 11771 @Override 11772 public void setComponentEnabledSetting(ComponentName componentName, 11773 int newState, int flags, int userId) { 11774 if (!sUserManager.exists(userId)) return; 11775 setEnabledSetting(componentName.getPackageName(), 11776 componentName.getClassName(), newState, flags, userId, null); 11777 } 11778 11779 private void setEnabledSetting(final String packageName, String className, int newState, 11780 final int flags, int userId, String callingPackage) { 11781 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 11782 || newState == COMPONENT_ENABLED_STATE_ENABLED 11783 || newState == COMPONENT_ENABLED_STATE_DISABLED 11784 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 11785 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 11786 throw new IllegalArgumentException("Invalid new component state: " 11787 + newState); 11788 } 11789 PackageSetting pkgSetting; 11790 final int uid = Binder.getCallingUid(); 11791 final int permission = mContext.checkCallingOrSelfPermission( 11792 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11793 enforceCrossUserPermission(uid, userId, false, "set enabled"); 11794 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11795 boolean sendNow = false; 11796 boolean isApp = (className == null); 11797 String componentName = isApp ? packageName : className; 11798 int packageUid = -1; 11799 ArrayList<String> components; 11800 11801 // writer 11802 synchronized (mPackages) { 11803 pkgSetting = mSettings.mPackages.get(packageName); 11804 if (pkgSetting == null) { 11805 if (className == null) { 11806 throw new IllegalArgumentException( 11807 "Unknown package: " + packageName); 11808 } 11809 throw new IllegalArgumentException( 11810 "Unknown component: " + packageName 11811 + "/" + className); 11812 } 11813 // Allow root and verify that userId is not being specified by a different user 11814 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 11815 throw new SecurityException( 11816 "Permission Denial: attempt to change component state from pid=" 11817 + Binder.getCallingPid() 11818 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 11819 } 11820 if (className == null) { 11821 // We're dealing with an application/package level state change 11822 if (pkgSetting.getEnabled(userId) == newState) { 11823 // Nothing to do 11824 return; 11825 } 11826 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 11827 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 11828 // Don't care about who enables an app. 11829 callingPackage = null; 11830 } 11831 pkgSetting.setEnabled(newState, userId, callingPackage); 11832 // pkgSetting.pkg.mSetEnabled = newState; 11833 } else { 11834 // We're dealing with a component level state change 11835 // First, verify that this is a valid class name. 11836 PackageParser.Package pkg = pkgSetting.pkg; 11837 if (pkg == null || !pkg.hasComponentClassName(className)) { 11838 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 11839 throw new IllegalArgumentException("Component class " + className 11840 + " does not exist in " + packageName); 11841 } else { 11842 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 11843 + className + " does not exist in " + packageName); 11844 } 11845 } 11846 switch (newState) { 11847 case COMPONENT_ENABLED_STATE_ENABLED: 11848 if (!pkgSetting.enableComponentLPw(className, userId)) { 11849 return; 11850 } 11851 break; 11852 case COMPONENT_ENABLED_STATE_DISABLED: 11853 if (!pkgSetting.disableComponentLPw(className, userId)) { 11854 return; 11855 } 11856 break; 11857 case COMPONENT_ENABLED_STATE_DEFAULT: 11858 if (!pkgSetting.restoreComponentLPw(className, userId)) { 11859 return; 11860 } 11861 break; 11862 default: 11863 Slog.e(TAG, "Invalid new component state: " + newState); 11864 return; 11865 } 11866 } 11867 mSettings.writePackageRestrictionsLPr(userId); 11868 components = mPendingBroadcasts.get(userId, packageName); 11869 final boolean newPackage = components == null; 11870 if (newPackage) { 11871 components = new ArrayList<String>(); 11872 } 11873 if (!components.contains(componentName)) { 11874 components.add(componentName); 11875 } 11876 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 11877 sendNow = true; 11878 // Purge entry from pending broadcast list if another one exists already 11879 // since we are sending one right away. 11880 mPendingBroadcasts.remove(userId, packageName); 11881 } else { 11882 if (newPackage) { 11883 mPendingBroadcasts.put(userId, packageName, components); 11884 } 11885 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 11886 // Schedule a message 11887 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 11888 } 11889 } 11890 } 11891 11892 long callingId = Binder.clearCallingIdentity(); 11893 try { 11894 if (sendNow) { 11895 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 11896 sendPackageChangedBroadcast(packageName, 11897 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 11898 } 11899 } finally { 11900 Binder.restoreCallingIdentity(callingId); 11901 } 11902 } 11903 11904 private void sendPackageChangedBroadcast(String packageName, 11905 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 11906 if (DEBUG_INSTALL) 11907 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 11908 + componentNames); 11909 Bundle extras = new Bundle(4); 11910 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 11911 String nameList[] = new String[componentNames.size()]; 11912 componentNames.toArray(nameList); 11913 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 11914 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 11915 extras.putInt(Intent.EXTRA_UID, packageUid); 11916 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 11917 new int[] {UserHandle.getUserId(packageUid)}); 11918 } 11919 11920 @Override 11921 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 11922 if (!sUserManager.exists(userId)) return; 11923 final int uid = Binder.getCallingUid(); 11924 final int permission = mContext.checkCallingOrSelfPermission( 11925 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11926 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11927 enforceCrossUserPermission(uid, userId, true, "stop package"); 11928 // writer 11929 synchronized (mPackages) { 11930 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 11931 uid, userId)) { 11932 scheduleWritePackageRestrictionsLocked(userId); 11933 } 11934 } 11935 } 11936 11937 @Override 11938 public String getInstallerPackageName(String packageName) { 11939 // reader 11940 synchronized (mPackages) { 11941 return mSettings.getInstallerPackageNameLPr(packageName); 11942 } 11943 } 11944 11945 @Override 11946 public int getApplicationEnabledSetting(String packageName, int userId) { 11947 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11948 int uid = Binder.getCallingUid(); 11949 enforceCrossUserPermission(uid, userId, false, "get enabled"); 11950 // reader 11951 synchronized (mPackages) { 11952 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 11953 } 11954 } 11955 11956 @Override 11957 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 11958 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11959 int uid = Binder.getCallingUid(); 11960 enforceCrossUserPermission(uid, userId, false, "get component enabled"); 11961 // reader 11962 synchronized (mPackages) { 11963 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 11964 } 11965 } 11966 11967 @Override 11968 public void enterSafeMode() { 11969 enforceSystemOrRoot("Only the system can request entering safe mode"); 11970 11971 if (!mSystemReady) { 11972 mSafeMode = true; 11973 } 11974 } 11975 11976 @Override 11977 public void systemReady() { 11978 mSystemReady = true; 11979 11980 // Read the compatibilty setting when the system is ready. 11981 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 11982 mContext.getContentResolver(), 11983 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 11984 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 11985 if (DEBUG_SETTINGS) { 11986 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 11987 } 11988 11989 synchronized (mPackages) { 11990 // Verify that all of the preferred activity components actually 11991 // exist. It is possible for applications to be updated and at 11992 // that point remove a previously declared activity component that 11993 // had been set as a preferred activity. We try to clean this up 11994 // the next time we encounter that preferred activity, but it is 11995 // possible for the user flow to never be able to return to that 11996 // situation so here we do a sanity check to make sure we haven't 11997 // left any junk around. 11998 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 11999 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12000 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12001 removed.clear(); 12002 for (PreferredActivity pa : pir.filterSet()) { 12003 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 12004 removed.add(pa); 12005 } 12006 } 12007 if (removed.size() > 0) { 12008 for (int r=0; r<removed.size(); r++) { 12009 PreferredActivity pa = removed.get(r); 12010 Slog.w(TAG, "Removing dangling preferred activity: " 12011 + pa.mPref.mComponent); 12012 pir.removeFilter(pa); 12013 } 12014 mSettings.writePackageRestrictionsLPr( 12015 mSettings.mPreferredActivities.keyAt(i)); 12016 } 12017 } 12018 } 12019 sUserManager.systemReady(); 12020 } 12021 12022 @Override 12023 public boolean isSafeMode() { 12024 return mSafeMode; 12025 } 12026 12027 @Override 12028 public boolean hasSystemUidErrors() { 12029 return mHasSystemUidErrors; 12030 } 12031 12032 static String arrayToString(int[] array) { 12033 StringBuffer buf = new StringBuffer(128); 12034 buf.append('['); 12035 if (array != null) { 12036 for (int i=0; i<array.length; i++) { 12037 if (i > 0) buf.append(", "); 12038 buf.append(array[i]); 12039 } 12040 } 12041 buf.append(']'); 12042 return buf.toString(); 12043 } 12044 12045 static class DumpState { 12046 public static final int DUMP_LIBS = 1 << 0; 12047 public static final int DUMP_FEATURES = 1 << 1; 12048 public static final int DUMP_RESOLVERS = 1 << 2; 12049 public static final int DUMP_PERMISSIONS = 1 << 3; 12050 public static final int DUMP_PACKAGES = 1 << 4; 12051 public static final int DUMP_SHARED_USERS = 1 << 5; 12052 public static final int DUMP_MESSAGES = 1 << 6; 12053 public static final int DUMP_PROVIDERS = 1 << 7; 12054 public static final int DUMP_VERIFIERS = 1 << 8; 12055 public static final int DUMP_PREFERRED = 1 << 9; 12056 public static final int DUMP_PREFERRED_XML = 1 << 10; 12057 public static final int DUMP_KEYSETS = 1 << 11; 12058 public static final int DUMP_VERSION = 1 << 12; 12059 public static final int DUMP_INSTALLS = 1 << 13; 12060 12061 public static final int OPTION_SHOW_FILTERS = 1 << 0; 12062 12063 private int mTypes; 12064 12065 private int mOptions; 12066 12067 private boolean mTitlePrinted; 12068 12069 private SharedUserSetting mSharedUser; 12070 12071 public boolean isDumping(int type) { 12072 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 12073 return true; 12074 } 12075 12076 return (mTypes & type) != 0; 12077 } 12078 12079 public void setDump(int type) { 12080 mTypes |= type; 12081 } 12082 12083 public boolean isOptionEnabled(int option) { 12084 return (mOptions & option) != 0; 12085 } 12086 12087 public void setOptionEnabled(int option) { 12088 mOptions |= option; 12089 } 12090 12091 public boolean onTitlePrinted() { 12092 final boolean printed = mTitlePrinted; 12093 mTitlePrinted = true; 12094 return printed; 12095 } 12096 12097 public boolean getTitlePrinted() { 12098 return mTitlePrinted; 12099 } 12100 12101 public void setTitlePrinted(boolean enabled) { 12102 mTitlePrinted = enabled; 12103 } 12104 12105 public SharedUserSetting getSharedUser() { 12106 return mSharedUser; 12107 } 12108 12109 public void setSharedUser(SharedUserSetting user) { 12110 mSharedUser = user; 12111 } 12112 } 12113 12114 @Override 12115 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 12116 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 12117 != PackageManager.PERMISSION_GRANTED) { 12118 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 12119 + Binder.getCallingPid() 12120 + ", uid=" + Binder.getCallingUid() 12121 + " without permission " 12122 + android.Manifest.permission.DUMP); 12123 return; 12124 } 12125 12126 DumpState dumpState = new DumpState(); 12127 boolean fullPreferred = false; 12128 boolean checkin = false; 12129 12130 String packageName = null; 12131 12132 int opti = 0; 12133 while (opti < args.length) { 12134 String opt = args[opti]; 12135 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 12136 break; 12137 } 12138 opti++; 12139 if ("-a".equals(opt)) { 12140 // Right now we only know how to print all. 12141 } else if ("-h".equals(opt)) { 12142 pw.println("Package manager dump options:"); 12143 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 12144 pw.println(" --checkin: dump for a checkin"); 12145 pw.println(" -f: print details of intent filters"); 12146 pw.println(" -h: print this help"); 12147 pw.println(" cmd may be one of:"); 12148 pw.println(" l[ibraries]: list known shared libraries"); 12149 pw.println(" f[ibraries]: list device features"); 12150 pw.println(" k[eysets]: print known keysets"); 12151 pw.println(" r[esolvers]: dump intent resolvers"); 12152 pw.println(" perm[issions]: dump permissions"); 12153 pw.println(" pref[erred]: print preferred package settings"); 12154 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 12155 pw.println(" prov[iders]: dump content providers"); 12156 pw.println(" p[ackages]: dump installed packages"); 12157 pw.println(" s[hared-users]: dump shared user IDs"); 12158 pw.println(" m[essages]: print collected runtime messages"); 12159 pw.println(" v[erifiers]: print package verifier info"); 12160 pw.println(" version: print database version info"); 12161 pw.println(" write: write current settings now"); 12162 pw.println(" <package.name>: info about given package"); 12163 pw.println(" installs: details about install sessions"); 12164 return; 12165 } else if ("--checkin".equals(opt)) { 12166 checkin = true; 12167 } else if ("-f".equals(opt)) { 12168 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12169 } else { 12170 pw.println("Unknown argument: " + opt + "; use -h for help"); 12171 } 12172 } 12173 12174 // Is the caller requesting to dump a particular piece of data? 12175 if (opti < args.length) { 12176 String cmd = args[opti]; 12177 opti++; 12178 // Is this a package name? 12179 if ("android".equals(cmd) || cmd.contains(".")) { 12180 packageName = cmd; 12181 // When dumping a single package, we always dump all of its 12182 // filter information since the amount of data will be reasonable. 12183 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12184 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 12185 dumpState.setDump(DumpState.DUMP_LIBS); 12186 } else if ("f".equals(cmd) || "features".equals(cmd)) { 12187 dumpState.setDump(DumpState.DUMP_FEATURES); 12188 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 12189 dumpState.setDump(DumpState.DUMP_RESOLVERS); 12190 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 12191 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 12192 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 12193 dumpState.setDump(DumpState.DUMP_PREFERRED); 12194 } else if ("preferred-xml".equals(cmd)) { 12195 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 12196 if (opti < args.length && "--full".equals(args[opti])) { 12197 fullPreferred = true; 12198 opti++; 12199 } 12200 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 12201 dumpState.setDump(DumpState.DUMP_PACKAGES); 12202 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 12203 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 12204 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 12205 dumpState.setDump(DumpState.DUMP_PROVIDERS); 12206 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 12207 dumpState.setDump(DumpState.DUMP_MESSAGES); 12208 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 12209 dumpState.setDump(DumpState.DUMP_VERIFIERS); 12210 } else if ("version".equals(cmd)) { 12211 dumpState.setDump(DumpState.DUMP_VERSION); 12212 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 12213 dumpState.setDump(DumpState.DUMP_KEYSETS); 12214 } else if ("write".equals(cmd)) { 12215 synchronized (mPackages) { 12216 mSettings.writeLPr(); 12217 pw.println("Settings written."); 12218 return; 12219 } 12220 } else if ("installs".equals(cmd)) { 12221 dumpState.setDump(DumpState.DUMP_INSTALLS); 12222 } 12223 } 12224 12225 if (checkin) { 12226 pw.println("vers,1"); 12227 } 12228 12229 // reader 12230 synchronized (mPackages) { 12231 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 12232 if (!checkin) { 12233 if (dumpState.onTitlePrinted()) 12234 pw.println(); 12235 pw.println("Database versions:"); 12236 pw.print(" SDK Version:"); 12237 pw.print(" internal="); 12238 pw.print(mSettings.mInternalSdkPlatform); 12239 pw.print(" external="); 12240 pw.println(mSettings.mExternalSdkPlatform); 12241 pw.print(" DB Version:"); 12242 pw.print(" internal="); 12243 pw.print(mSettings.mInternalDatabaseVersion); 12244 pw.print(" external="); 12245 pw.println(mSettings.mExternalDatabaseVersion); 12246 } 12247 } 12248 12249 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 12250 if (!checkin) { 12251 if (dumpState.onTitlePrinted()) 12252 pw.println(); 12253 pw.println("Verifiers:"); 12254 pw.print(" Required: "); 12255 pw.print(mRequiredVerifierPackage); 12256 pw.print(" (uid="); 12257 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 12258 pw.println(")"); 12259 } else if (mRequiredVerifierPackage != null) { 12260 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 12261 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 12262 } 12263 } 12264 12265 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 12266 boolean printedHeader = false; 12267 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 12268 while (it.hasNext()) { 12269 String name = it.next(); 12270 SharedLibraryEntry ent = mSharedLibraries.get(name); 12271 if (!checkin) { 12272 if (!printedHeader) { 12273 if (dumpState.onTitlePrinted()) 12274 pw.println(); 12275 pw.println("Libraries:"); 12276 printedHeader = true; 12277 } 12278 pw.print(" "); 12279 } else { 12280 pw.print("lib,"); 12281 } 12282 pw.print(name); 12283 if (!checkin) { 12284 pw.print(" -> "); 12285 } 12286 if (ent.path != null) { 12287 if (!checkin) { 12288 pw.print("(jar) "); 12289 pw.print(ent.path); 12290 } else { 12291 pw.print(",jar,"); 12292 pw.print(ent.path); 12293 } 12294 } else { 12295 if (!checkin) { 12296 pw.print("(apk) "); 12297 pw.print(ent.apk); 12298 } else { 12299 pw.print(",apk,"); 12300 pw.print(ent.apk); 12301 } 12302 } 12303 pw.println(); 12304 } 12305 } 12306 12307 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 12308 if (dumpState.onTitlePrinted()) 12309 pw.println(); 12310 if (!checkin) { 12311 pw.println("Features:"); 12312 } 12313 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 12314 while (it.hasNext()) { 12315 String name = it.next(); 12316 if (!checkin) { 12317 pw.print(" "); 12318 } else { 12319 pw.print("feat,"); 12320 } 12321 pw.println(name); 12322 } 12323 } 12324 12325 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 12326 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 12327 : "Activity Resolver Table:", " ", packageName, 12328 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12329 dumpState.setTitlePrinted(true); 12330 } 12331 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 12332 : "Receiver Resolver Table:", " ", packageName, 12333 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12334 dumpState.setTitlePrinted(true); 12335 } 12336 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 12337 : "Service Resolver Table:", " ", packageName, 12338 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12339 dumpState.setTitlePrinted(true); 12340 } 12341 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 12342 : "Provider Resolver Table:", " ", packageName, 12343 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12344 dumpState.setTitlePrinted(true); 12345 } 12346 } 12347 12348 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 12349 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12350 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12351 int user = mSettings.mPreferredActivities.keyAt(i); 12352 if (pir.dump(pw, 12353 dumpState.getTitlePrinted() 12354 ? "\nPreferred Activities User " + user + ":" 12355 : "Preferred Activities User " + user + ":", " ", 12356 packageName, true)) { 12357 dumpState.setTitlePrinted(true); 12358 } 12359 } 12360 } 12361 12362 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 12363 pw.flush(); 12364 FileOutputStream fout = new FileOutputStream(fd); 12365 BufferedOutputStream str = new BufferedOutputStream(fout); 12366 XmlSerializer serializer = new FastXmlSerializer(); 12367 try { 12368 serializer.setOutput(str, "utf-8"); 12369 serializer.startDocument(null, true); 12370 serializer.setFeature( 12371 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 12372 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 12373 serializer.endDocument(); 12374 serializer.flush(); 12375 } catch (IllegalArgumentException e) { 12376 pw.println("Failed writing: " + e); 12377 } catch (IllegalStateException e) { 12378 pw.println("Failed writing: " + e); 12379 } catch (IOException e) { 12380 pw.println("Failed writing: " + e); 12381 } 12382 } 12383 12384 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 12385 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 12386 if (packageName == null) { 12387 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 12388 if (iperm == 0) { 12389 if (dumpState.onTitlePrinted()) 12390 pw.println(); 12391 pw.println("AppOp Permissions:"); 12392 } 12393 pw.print(" AppOp Permission "); 12394 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 12395 pw.println(":"); 12396 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 12397 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 12398 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 12399 } 12400 } 12401 } 12402 } 12403 12404 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 12405 boolean printedSomething = false; 12406 for (PackageParser.Provider p : mProviders.mProviders.values()) { 12407 if (packageName != null && !packageName.equals(p.info.packageName)) { 12408 continue; 12409 } 12410 if (!printedSomething) { 12411 if (dumpState.onTitlePrinted()) 12412 pw.println(); 12413 pw.println("Registered ContentProviders:"); 12414 printedSomething = true; 12415 } 12416 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 12417 pw.print(" "); pw.println(p.toString()); 12418 } 12419 printedSomething = false; 12420 for (Map.Entry<String, PackageParser.Provider> entry : 12421 mProvidersByAuthority.entrySet()) { 12422 PackageParser.Provider p = entry.getValue(); 12423 if (packageName != null && !packageName.equals(p.info.packageName)) { 12424 continue; 12425 } 12426 if (!printedSomething) { 12427 if (dumpState.onTitlePrinted()) 12428 pw.println(); 12429 pw.println("ContentProvider Authorities:"); 12430 printedSomething = true; 12431 } 12432 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 12433 pw.print(" "); pw.println(p.toString()); 12434 if (p.info != null && p.info.applicationInfo != null) { 12435 final String appInfo = p.info.applicationInfo.toString(); 12436 pw.print(" applicationInfo="); pw.println(appInfo); 12437 } 12438 } 12439 } 12440 12441 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 12442 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 12443 } 12444 12445 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 12446 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 12447 } 12448 12449 if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 12450 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState); 12451 } 12452 12453 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS)) { 12454 if (dumpState.onTitlePrinted()) pw.println(); 12455 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 12456 } 12457 12458 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 12459 if (dumpState.onTitlePrinted()) pw.println(); 12460 mSettings.dumpReadMessagesLPr(pw, dumpState); 12461 12462 pw.println(); 12463 pw.println("Package warning messages:"); 12464 final File fname = getSettingsProblemFile(); 12465 FileInputStream in = null; 12466 try { 12467 in = new FileInputStream(fname); 12468 final int avail = in.available(); 12469 final byte[] data = new byte[avail]; 12470 in.read(data); 12471 pw.print(new String(data)); 12472 } catch (FileNotFoundException e) { 12473 } catch (IOException e) { 12474 } finally { 12475 if (in != null) { 12476 try { 12477 in.close(); 12478 } catch (IOException e) { 12479 } 12480 } 12481 } 12482 } 12483 } 12484 } 12485 12486 // ------- apps on sdcard specific code ------- 12487 static final boolean DEBUG_SD_INSTALL = false; 12488 12489 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 12490 12491 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 12492 12493 private boolean mMediaMounted = false; 12494 12495 static String getEncryptKey() { 12496 try { 12497 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 12498 SD_ENCRYPTION_KEYSTORE_NAME); 12499 if (sdEncKey == null) { 12500 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 12501 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 12502 if (sdEncKey == null) { 12503 Slog.e(TAG, "Failed to create encryption keys"); 12504 return null; 12505 } 12506 } 12507 return sdEncKey; 12508 } catch (NoSuchAlgorithmException nsae) { 12509 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 12510 return null; 12511 } catch (IOException ioe) { 12512 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 12513 return null; 12514 } 12515 } 12516 12517 /* 12518 * Update media status on PackageManager. 12519 */ 12520 @Override 12521 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 12522 int callingUid = Binder.getCallingUid(); 12523 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 12524 throw new SecurityException("Media status can only be updated by the system"); 12525 } 12526 // reader; this apparently protects mMediaMounted, but should probably 12527 // be a different lock in that case. 12528 synchronized (mPackages) { 12529 Log.i(TAG, "Updating external media status from " 12530 + (mMediaMounted ? "mounted" : "unmounted") + " to " 12531 + (mediaStatus ? "mounted" : "unmounted")); 12532 if (DEBUG_SD_INSTALL) 12533 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 12534 + ", mMediaMounted=" + mMediaMounted); 12535 if (mediaStatus == mMediaMounted) { 12536 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 12537 : 0, -1); 12538 mHandler.sendMessage(msg); 12539 return; 12540 } 12541 mMediaMounted = mediaStatus; 12542 } 12543 // Queue up an async operation since the package installation may take a 12544 // little while. 12545 mHandler.post(new Runnable() { 12546 public void run() { 12547 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 12548 } 12549 }); 12550 } 12551 12552 /** 12553 * Called by MountService when the initial ASECs to scan are available. 12554 * Should block until all the ASEC containers are finished being scanned. 12555 */ 12556 public void scanAvailableAsecs() { 12557 updateExternalMediaStatusInner(true, false, false); 12558 if (mShouldRestoreconData) { 12559 SELinuxMMAC.setRestoreconDone(); 12560 mShouldRestoreconData = false; 12561 } 12562 } 12563 12564 /* 12565 * Collect information of applications on external media, map them against 12566 * existing containers and update information based on current mount status. 12567 * Please note that we always have to report status if reportStatus has been 12568 * set to true especially when unloading packages. 12569 */ 12570 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 12571 boolean externalStorage) { 12572 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 12573 int[] uidArr = EmptyArray.INT; 12574 12575 final String[] list = PackageHelper.getSecureContainerList(); 12576 if (ArrayUtils.isEmpty(list)) { 12577 Log.i(TAG, "No secure containers found"); 12578 } else { 12579 // Process list of secure containers and categorize them 12580 // as active or stale based on their package internal state. 12581 12582 // reader 12583 synchronized (mPackages) { 12584 for (String cid : list) { 12585 // Leave stages untouched for now; installer service owns them 12586 if (PackageInstallerService.isStageName(cid)) continue; 12587 12588 if (DEBUG_SD_INSTALL) 12589 Log.i(TAG, "Processing container " + cid); 12590 String pkgName = getAsecPackageName(cid); 12591 if (pkgName == null) { 12592 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 12593 continue; 12594 } 12595 if (DEBUG_SD_INSTALL) 12596 Log.i(TAG, "Looking for pkg : " + pkgName); 12597 12598 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12599 if (ps == null) { 12600 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 12601 continue; 12602 } 12603 12604 /* 12605 * Skip packages that are not external if we're unmounting 12606 * external storage. 12607 */ 12608 if (externalStorage && !isMounted && !isExternal(ps)) { 12609 continue; 12610 } 12611 12612 final AsecInstallArgs args = new AsecInstallArgs(cid, 12613 getAppDexInstructionSets(ps), isForwardLocked(ps)); 12614 // The package status is changed only if the code path 12615 // matches between settings and the container id. 12616 if (ps.codePathString != null 12617 && ps.codePathString.startsWith(args.getCodePath())) { 12618 if (DEBUG_SD_INSTALL) { 12619 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 12620 + " at code path: " + ps.codePathString); 12621 } 12622 12623 // We do have a valid package installed on sdcard 12624 processCids.put(args, ps.codePathString); 12625 final int uid = ps.appId; 12626 if (uid != -1) { 12627 uidArr = ArrayUtils.appendInt(uidArr, uid); 12628 } 12629 } else { 12630 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 12631 + ps.codePathString); 12632 } 12633 } 12634 } 12635 12636 Arrays.sort(uidArr); 12637 } 12638 12639 // Process packages with valid entries. 12640 if (isMounted) { 12641 if (DEBUG_SD_INSTALL) 12642 Log.i(TAG, "Loading packages"); 12643 loadMediaPackages(processCids, uidArr); 12644 startCleaningPackages(); 12645 mInstallerService.onSecureContainersAvailable(); 12646 } else { 12647 if (DEBUG_SD_INSTALL) 12648 Log.i(TAG, "Unloading packages"); 12649 unloadMediaPackages(processCids, uidArr, reportStatus); 12650 } 12651 } 12652 12653 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 12654 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 12655 int size = pkgList.size(); 12656 if (size > 0) { 12657 // Send broadcasts here 12658 Bundle extras = new Bundle(); 12659 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 12660 .toArray(new String[size])); 12661 if (uidArr != null) { 12662 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 12663 } 12664 if (replacing) { 12665 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 12666 } 12667 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 12668 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 12669 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 12670 } 12671 } 12672 12673 /* 12674 * Look at potentially valid container ids from processCids If package 12675 * information doesn't match the one on record or package scanning fails, 12676 * the cid is added to list of removeCids. We currently don't delete stale 12677 * containers. 12678 */ 12679 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 12680 ArrayList<String> pkgList = new ArrayList<String>(); 12681 Set<AsecInstallArgs> keys = processCids.keySet(); 12682 12683 for (AsecInstallArgs args : keys) { 12684 String codePath = processCids.get(args); 12685 if (DEBUG_SD_INSTALL) 12686 Log.i(TAG, "Loading container : " + args.cid); 12687 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12688 try { 12689 // Make sure there are no container errors first. 12690 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 12691 Slog.e(TAG, "Failed to mount cid : " + args.cid 12692 + " when installing from sdcard"); 12693 continue; 12694 } 12695 // Check code path here. 12696 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 12697 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 12698 + " does not match one in settings " + codePath); 12699 continue; 12700 } 12701 // Parse package 12702 int parseFlags = mDefParseFlags; 12703 if (args.isExternal()) { 12704 parseFlags |= PackageParser.PARSE_ON_SDCARD; 12705 } 12706 if (args.isFwdLocked()) { 12707 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 12708 } 12709 12710 synchronized (mInstallLock) { 12711 PackageParser.Package pkg = null; 12712 try { 12713 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 12714 } catch (PackageManagerException e) { 12715 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 12716 } 12717 // Scan the package 12718 if (pkg != null) { 12719 /* 12720 * TODO why is the lock being held? doPostInstall is 12721 * called in other places without the lock. This needs 12722 * to be straightened out. 12723 */ 12724 // writer 12725 synchronized (mPackages) { 12726 retCode = PackageManager.INSTALL_SUCCEEDED; 12727 pkgList.add(pkg.packageName); 12728 // Post process args 12729 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 12730 pkg.applicationInfo.uid); 12731 } 12732 } else { 12733 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 12734 } 12735 } 12736 12737 } finally { 12738 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 12739 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 12740 } 12741 } 12742 } 12743 // writer 12744 synchronized (mPackages) { 12745 // If the platform SDK has changed since the last time we booted, 12746 // we need to re-grant app permission to catch any new ones that 12747 // appear. This is really a hack, and means that apps can in some 12748 // cases get permissions that the user didn't initially explicitly 12749 // allow... it would be nice to have some better way to handle 12750 // this situation. 12751 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 12752 if (regrantPermissions) 12753 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 12754 + mSdkVersion + "; regranting permissions for external storage"); 12755 mSettings.mExternalSdkPlatform = mSdkVersion; 12756 12757 // Make sure group IDs have been assigned, and any permission 12758 // changes in other apps are accounted for 12759 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 12760 | (regrantPermissions 12761 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 12762 : 0)); 12763 12764 mSettings.updateExternalDatabaseVersion(); 12765 12766 // can downgrade to reader 12767 // Persist settings 12768 mSettings.writeLPr(); 12769 } 12770 // Send a broadcast to let everyone know we are done processing 12771 if (pkgList.size() > 0) { 12772 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12773 } 12774 } 12775 12776 /* 12777 * Utility method to unload a list of specified containers 12778 */ 12779 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 12780 // Just unmount all valid containers. 12781 for (AsecInstallArgs arg : cidArgs) { 12782 synchronized (mInstallLock) { 12783 arg.doPostDeleteLI(false); 12784 } 12785 } 12786 } 12787 12788 /* 12789 * Unload packages mounted on external media. This involves deleting package 12790 * data from internal structures, sending broadcasts about diabled packages, 12791 * gc'ing to free up references, unmounting all secure containers 12792 * corresponding to packages on external media, and posting a 12793 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 12794 * that we always have to post this message if status has been requested no 12795 * matter what. 12796 */ 12797 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 12798 final boolean reportStatus) { 12799 if (DEBUG_SD_INSTALL) 12800 Log.i(TAG, "unloading media packages"); 12801 ArrayList<String> pkgList = new ArrayList<String>(); 12802 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 12803 final Set<AsecInstallArgs> keys = processCids.keySet(); 12804 for (AsecInstallArgs args : keys) { 12805 String pkgName = args.getPackageName(); 12806 if (DEBUG_SD_INSTALL) 12807 Log.i(TAG, "Trying to unload pkg : " + pkgName); 12808 // Delete package internally 12809 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 12810 synchronized (mInstallLock) { 12811 boolean res = deletePackageLI(pkgName, null, false, null, null, 12812 PackageManager.DELETE_KEEP_DATA, outInfo, false); 12813 if (res) { 12814 pkgList.add(pkgName); 12815 } else { 12816 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 12817 failedList.add(args); 12818 } 12819 } 12820 } 12821 12822 // reader 12823 synchronized (mPackages) { 12824 // We didn't update the settings after removing each package; 12825 // write them now for all packages. 12826 mSettings.writeLPr(); 12827 } 12828 12829 // We have to absolutely send UPDATED_MEDIA_STATUS only 12830 // after confirming that all the receivers processed the ordered 12831 // broadcast when packages get disabled, force a gc to clean things up. 12832 // and unload all the containers. 12833 if (pkgList.size() > 0) { 12834 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 12835 new IIntentReceiver.Stub() { 12836 public void performReceive(Intent intent, int resultCode, String data, 12837 Bundle extras, boolean ordered, boolean sticky, 12838 int sendingUser) throws RemoteException { 12839 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 12840 reportStatus ? 1 : 0, 1, keys); 12841 mHandler.sendMessage(msg); 12842 } 12843 }); 12844 } else { 12845 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 12846 keys); 12847 mHandler.sendMessage(msg); 12848 } 12849 } 12850 12851 /** Binder call */ 12852 @Override 12853 public void movePackage(final String packageName, final IPackageMoveObserver observer, 12854 final int flags) { 12855 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 12856 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 12857 int returnCode = PackageManager.MOVE_SUCCEEDED; 12858 int currInstallFlags = 0; 12859 int newInstallFlags = 0; 12860 12861 File codeFile = null; 12862 String installerPackageName = null; 12863 String packageAbiOverride = null; 12864 12865 // reader 12866 synchronized (mPackages) { 12867 final PackageParser.Package pkg = mPackages.get(packageName); 12868 final PackageSetting ps = mSettings.mPackages.get(packageName); 12869 if (pkg == null || ps == null) { 12870 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12871 } else { 12872 // Disable moving fwd locked apps and system packages 12873 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 12874 Slog.w(TAG, "Cannot move system application"); 12875 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 12876 } else if (pkg.mOperationPending) { 12877 Slog.w(TAG, "Attempt to move package which has pending operations"); 12878 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 12879 } else { 12880 // Find install location first 12881 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 12882 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 12883 Slog.w(TAG, "Ambigous flags specified for move location."); 12884 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12885 } else { 12886 newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 12887 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 12888 currInstallFlags = isExternal(pkg) 12889 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 12890 12891 if (newInstallFlags == currInstallFlags) { 12892 Slog.w(TAG, "No move required. Trying to move to same location"); 12893 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12894 } else { 12895 if (isForwardLocked(pkg)) { 12896 currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12897 newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12898 } 12899 } 12900 } 12901 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12902 pkg.mOperationPending = true; 12903 } 12904 } 12905 12906 codeFile = new File(pkg.codePath); 12907 installerPackageName = ps.installerPackageName; 12908 packageAbiOverride = ps.cpuAbiOverrideString; 12909 } 12910 } 12911 12912 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 12913 try { 12914 observer.packageMoved(packageName, returnCode); 12915 } catch (RemoteException ignored) { 12916 } 12917 return; 12918 } 12919 12920 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 12921 @Override 12922 public void onUserActionRequired(Intent intent) throws RemoteException { 12923 throw new IllegalStateException(); 12924 } 12925 12926 @Override 12927 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 12928 Bundle extras) throws RemoteException { 12929 Slog.d(TAG, "Install result for move: " 12930 + PackageManager.installStatusToString(returnCode, msg)); 12931 12932 // We usually have a new package now after the install, but if 12933 // we failed we need to clear the pending flag on the original 12934 // package object. 12935 synchronized (mPackages) { 12936 final PackageParser.Package pkg = mPackages.get(packageName); 12937 if (pkg != null) { 12938 pkg.mOperationPending = false; 12939 } 12940 } 12941 12942 final int status = PackageManager.installStatusToPublicStatus(returnCode); 12943 switch (status) { 12944 case PackageInstaller.STATUS_SUCCESS: 12945 observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED); 12946 break; 12947 case PackageInstaller.STATUS_FAILURE_STORAGE: 12948 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 12949 break; 12950 default: 12951 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR); 12952 break; 12953 } 12954 } 12955 }; 12956 12957 // Treat a move like reinstalling an existing app, which ensures that we 12958 // process everythign uniformly, like unpacking native libraries. 12959 newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 12960 12961 final Message msg = mHandler.obtainMessage(INIT_COPY); 12962 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 12963 msg.obj = new InstallParams(origin, installObserver, newInstallFlags, 12964 installerPackageName, null, user, packageAbiOverride); 12965 mHandler.sendMessage(msg); 12966 } 12967 12968 @Override 12969 public boolean setInstallLocation(int loc) { 12970 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 12971 null); 12972 if (getInstallLocation() == loc) { 12973 return true; 12974 } 12975 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 12976 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 12977 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 12978 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 12979 return true; 12980 } 12981 return false; 12982 } 12983 12984 @Override 12985 public int getInstallLocation() { 12986 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12987 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 12988 PackageHelper.APP_INSTALL_AUTO); 12989 } 12990 12991 /** Called by UserManagerService */ 12992 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 12993 mDirtyUsers.remove(userHandle); 12994 mSettings.removeUserLPw(userHandle); 12995 mPendingBroadcasts.remove(userHandle); 12996 if (mInstaller != null) { 12997 // Technically, we shouldn't be doing this with the package lock 12998 // held. However, this is very rare, and there is already so much 12999 // other disk I/O going on, that we'll let it slide for now. 13000 mInstaller.removeUserDataDirs(userHandle); 13001 } 13002 mUserNeedsBadging.delete(userHandle); 13003 removeUnusedPackagesLILPw(userManager, userHandle); 13004 } 13005 13006 /** 13007 * We're removing userHandle and would like to remove any downloaded packages 13008 * that are no longer in use by any other user. 13009 * @param userHandle the user being removed 13010 */ 13011 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 13012 final boolean DEBUG_CLEAN_APKS = false; 13013 int [] users = userManager.getUserIdsLPr(); 13014 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 13015 while (psit.hasNext()) { 13016 PackageSetting ps = psit.next(); 13017 final String packageName = ps.pkg.packageName; 13018 // Skip over if system app 13019 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 13020 continue; 13021 } 13022 if (DEBUG_CLEAN_APKS) { 13023 Slog.i(TAG, "Checking package " + packageName); 13024 } 13025 boolean keep = false; 13026 for (int i = 0; i < users.length; i++) { 13027 if (users[i] != userHandle && ps.getInstalled(users[i])) { 13028 keep = true; 13029 if (DEBUG_CLEAN_APKS) { 13030 Slog.i(TAG, " Keeping package " + packageName + " for user " 13031 + users[i]); 13032 } 13033 break; 13034 } 13035 } 13036 if (!keep) { 13037 if (DEBUG_CLEAN_APKS) { 13038 Slog.i(TAG, " Removing package " + packageName); 13039 } 13040 mHandler.post(new Runnable() { 13041 public void run() { 13042 deletePackageX(packageName, userHandle, 0); 13043 } //end run 13044 }); 13045 } 13046 } 13047 } 13048 13049 /** Called by UserManagerService */ 13050 void createNewUserLILPw(int userHandle, File path) { 13051 if (mInstaller != null) { 13052 mInstaller.createUserConfig(userHandle); 13053 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 13054 } 13055 } 13056 13057 @Override 13058 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 13059 mContext.enforceCallingOrSelfPermission( 13060 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13061 "Only package verification agents can read the verifier device identity"); 13062 13063 synchronized (mPackages) { 13064 return mSettings.getVerifierDeviceIdentityLPw(); 13065 } 13066 } 13067 13068 @Override 13069 public void setPermissionEnforced(String permission, boolean enforced) { 13070 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 13071 if (READ_EXTERNAL_STORAGE.equals(permission)) { 13072 synchronized (mPackages) { 13073 if (mSettings.mReadExternalStorageEnforced == null 13074 || mSettings.mReadExternalStorageEnforced != enforced) { 13075 mSettings.mReadExternalStorageEnforced = enforced; 13076 mSettings.writeLPr(); 13077 } 13078 } 13079 // kill any non-foreground processes so we restart them and 13080 // grant/revoke the GID. 13081 final IActivityManager am = ActivityManagerNative.getDefault(); 13082 if (am != null) { 13083 final long token = Binder.clearCallingIdentity(); 13084 try { 13085 am.killProcessesBelowForeground("setPermissionEnforcement"); 13086 } catch (RemoteException e) { 13087 } finally { 13088 Binder.restoreCallingIdentity(token); 13089 } 13090 } 13091 } else { 13092 throw new IllegalArgumentException("No selective enforcement for " + permission); 13093 } 13094 } 13095 13096 @Override 13097 @Deprecated 13098 public boolean isPermissionEnforced(String permission) { 13099 return true; 13100 } 13101 13102 @Override 13103 public boolean isStorageLow() { 13104 final long token = Binder.clearCallingIdentity(); 13105 try { 13106 final DeviceStorageMonitorInternal 13107 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13108 if (dsm != null) { 13109 return dsm.isMemoryLow(); 13110 } else { 13111 return false; 13112 } 13113 } finally { 13114 Binder.restoreCallingIdentity(token); 13115 } 13116 } 13117 13118 @Override 13119 public IPackageInstaller getPackageInstaller() { 13120 return mInstallerService; 13121 } 13122 13123 private boolean userNeedsBadging(int userId) { 13124 int index = mUserNeedsBadging.indexOfKey(userId); 13125 if (index < 0) { 13126 final UserInfo userInfo; 13127 final long token = Binder.clearCallingIdentity(); 13128 try { 13129 userInfo = sUserManager.getUserInfo(userId); 13130 } finally { 13131 Binder.restoreCallingIdentity(token); 13132 } 13133 final boolean b; 13134 if (userInfo != null && userInfo.isManagedProfile()) { 13135 b = true; 13136 } else { 13137 b = false; 13138 } 13139 mUserNeedsBadging.put(userId, b); 13140 return b; 13141 } 13142 return mUserNeedsBadging.valueAt(index); 13143 } 13144 13145 @Override 13146 public KeySet getKeySetByAlias(String packageName, String alias) { 13147 if (packageName == null || alias == null) { 13148 return null; 13149 } 13150 synchronized(mPackages) { 13151 final PackageParser.Package pkg = mPackages.get(packageName); 13152 if (pkg == null) { 13153 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13154 throw new IllegalArgumentException("Unknown package: " + packageName); 13155 } 13156 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13157 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 13158 } 13159 } 13160 13161 @Override 13162 public KeySet getSigningKeySet(String packageName) { 13163 if (packageName == null) { 13164 return null; 13165 } 13166 synchronized(mPackages) { 13167 final PackageParser.Package pkg = mPackages.get(packageName); 13168 if (pkg == null) { 13169 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13170 throw new IllegalArgumentException("Unknown package: " + packageName); 13171 } 13172 if (pkg.applicationInfo.uid != Binder.getCallingUid() 13173 && Process.SYSTEM_UID != Binder.getCallingUid()) { 13174 throw new SecurityException("May not access signing KeySet of other apps."); 13175 } 13176 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13177 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 13178 } 13179 } 13180 13181 @Override 13182 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 13183 if (packageName == null || ks == null) { 13184 return false; 13185 } 13186 synchronized(mPackages) { 13187 final PackageParser.Package pkg = mPackages.get(packageName); 13188 if (pkg == null) { 13189 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13190 throw new IllegalArgumentException("Unknown package: " + packageName); 13191 } 13192 IBinder ksh = ks.getToken(); 13193 if (ksh instanceof KeySetHandle) { 13194 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13195 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 13196 } 13197 return false; 13198 } 13199 } 13200 13201 @Override 13202 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 13203 if (packageName == null || ks == null) { 13204 return false; 13205 } 13206 synchronized(mPackages) { 13207 final PackageParser.Package pkg = mPackages.get(packageName); 13208 if (pkg == null) { 13209 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13210 throw new IllegalArgumentException("Unknown package: " + packageName); 13211 } 13212 IBinder ksh = ks.getToken(); 13213 if (ksh instanceof KeySetHandle) { 13214 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13215 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 13216 } 13217 return false; 13218 } 13219 } 13220} 13221