PackageManagerService.java revision 43789f56147f7d028a5ca1da3a3332adf7542b28
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 boolean mLazyDexOpt; 321 final DisplayMetrics mMetrics; 322 final int mDefParseFlags; 323 final String[] mSeparateProcesses; 324 325 // This is where all application persistent data goes. 326 final File mAppDataDir; 327 328 // This is where all application persistent data goes for secondary users. 329 final File mUserAppDataDir; 330 331 /** The location for ASEC container files on internal storage. */ 332 final String mAsecInternalPath; 333 334 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 335 // LOCK HELD. Can be called with mInstallLock held. 336 final Installer mInstaller; 337 338 /** Directory where installed third-party apps stored */ 339 final File mAppInstallDir; 340 341 /** 342 * Directory to which applications installed internally have their 343 * 32 bit native libraries copied. 344 */ 345 private File mAppLib32InstallDir; 346 347 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 348 // apps. 349 final File mDrmAppPrivateInstallDir; 350 351 // ---------------------------------------------------------------- 352 353 // Lock for state used when installing and doing other long running 354 // operations. Methods that must be called with this lock held have 355 // the suffix "LI". 356 final Object mInstallLock = new Object(); 357 358 // ---------------------------------------------------------------- 359 360 // Keys are String (package name), values are Package. This also serves 361 // as the lock for the global state. Methods that must be called with 362 // this lock held have the prefix "LP". 363 final HashMap<String, PackageParser.Package> mPackages = 364 new HashMap<String, PackageParser.Package>(); 365 366 // Tracks available target package names -> overlay package paths. 367 final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays = 368 new HashMap<String, HashMap<String, PackageParser.Package>>(); 369 370 final Settings mSettings; 371 boolean mRestoredSettings; 372 373 // System configuration read by SystemConfig. 374 final int[] mGlobalGids; 375 final SparseArray<HashSet<String>> mSystemPermissions; 376 final HashMap<String, FeatureInfo> mAvailableFeatures; 377 378 // If mac_permissions.xml was found for seinfo labeling. 379 boolean mFoundPolicyFile; 380 381 // If a recursive restorecon of /data/data/<pkg> is needed. 382 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 383 384 public static final class SharedLibraryEntry { 385 public final String path; 386 public final String apk; 387 388 SharedLibraryEntry(String _path, String _apk) { 389 path = _path; 390 apk = _apk; 391 } 392 } 393 394 // Currently known shared libraries. 395 final HashMap<String, SharedLibraryEntry> mSharedLibraries = 396 new HashMap<String, SharedLibraryEntry>(); 397 398 // All available activities, for your resolving pleasure. 399 final ActivityIntentResolver mActivities = 400 new ActivityIntentResolver(); 401 402 // All available receivers, for your resolving pleasure. 403 final ActivityIntentResolver mReceivers = 404 new ActivityIntentResolver(); 405 406 // All available services, for your resolving pleasure. 407 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 408 409 // All available providers, for your resolving pleasure. 410 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 411 412 // Mapping from provider base names (first directory in content URI codePath) 413 // to the provider information. 414 final HashMap<String, PackageParser.Provider> mProvidersByAuthority = 415 new HashMap<String, PackageParser.Provider>(); 416 417 // Mapping from instrumentation class names to info about them. 418 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 419 new HashMap<ComponentName, PackageParser.Instrumentation>(); 420 421 // Mapping from permission names to info about them. 422 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups = 423 new HashMap<String, PackageParser.PermissionGroup>(); 424 425 // Packages whose data we have transfered into another package, thus 426 // should no longer exist. 427 final HashSet<String> mTransferedPackages = new HashSet<String>(); 428 429 // Broadcast actions that are only available to the system. 430 final HashSet<String> mProtectedBroadcasts = new HashSet<String>(); 431 432 /** List of packages waiting for verification. */ 433 final SparseArray<PackageVerificationState> mPendingVerification 434 = new SparseArray<PackageVerificationState>(); 435 436 /** Set of packages associated with each app op permission. */ 437 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 438 439 final PackageInstallerService mInstallerService; 440 441 HashSet<PackageParser.Package> mDeferredDexOpt = null; 442 443 // Cache of users who need badging. 444 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 445 446 /** Token for keys in mPendingVerification. */ 447 private int mPendingVerificationToken = 0; 448 449 boolean mSystemReady; 450 boolean mSafeMode; 451 boolean mHasSystemUidErrors; 452 453 ApplicationInfo mAndroidApplication; 454 final ActivityInfo mResolveActivity = new ActivityInfo(); 455 final ResolveInfo mResolveInfo = new ResolveInfo(); 456 ComponentName mResolveComponentName; 457 PackageParser.Package mPlatformPackage; 458 ComponentName mCustomResolverComponentName; 459 460 boolean mResolverReplaced = false; 461 462 // Set of pending broadcasts for aggregating enable/disable of components. 463 static class PendingPackageBroadcasts { 464 // for each user id, a map of <package name -> components within that package> 465 final SparseArray<HashMap<String, ArrayList<String>>> mUidMap; 466 467 public PendingPackageBroadcasts() { 468 mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2); 469 } 470 471 public ArrayList<String> get(int userId, String packageName) { 472 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 473 return packages.get(packageName); 474 } 475 476 public void put(int userId, String packageName, ArrayList<String> components) { 477 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 478 packages.put(packageName, components); 479 } 480 481 public void remove(int userId, String packageName) { 482 HashMap<String, ArrayList<String>> packages = mUidMap.get(userId); 483 if (packages != null) { 484 packages.remove(packageName); 485 } 486 } 487 488 public void remove(int userId) { 489 mUidMap.remove(userId); 490 } 491 492 public int userIdCount() { 493 return mUidMap.size(); 494 } 495 496 public int userIdAt(int n) { 497 return mUidMap.keyAt(n); 498 } 499 500 public HashMap<String, ArrayList<String>> packagesForUserId(int userId) { 501 return mUidMap.get(userId); 502 } 503 504 public int size() { 505 // total number of pending broadcast entries across all userIds 506 int num = 0; 507 for (int i = 0; i< mUidMap.size(); i++) { 508 num += mUidMap.valueAt(i).size(); 509 } 510 return num; 511 } 512 513 public void clear() { 514 mUidMap.clear(); 515 } 516 517 private HashMap<String, ArrayList<String>> getOrAllocate(int userId) { 518 HashMap<String, ArrayList<String>> map = mUidMap.get(userId); 519 if (map == null) { 520 map = new HashMap<String, ArrayList<String>>(); 521 mUidMap.put(userId, map); 522 } 523 return map; 524 } 525 } 526 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 527 528 // Service Connection to remote media container service to copy 529 // package uri's from external media onto secure containers 530 // or internal storage. 531 private IMediaContainerService mContainerService = null; 532 533 static final int SEND_PENDING_BROADCAST = 1; 534 static final int MCS_BOUND = 3; 535 static final int END_COPY = 4; 536 static final int INIT_COPY = 5; 537 static final int MCS_UNBIND = 6; 538 static final int START_CLEANING_PACKAGE = 7; 539 static final int FIND_INSTALL_LOC = 8; 540 static final int POST_INSTALL = 9; 541 static final int MCS_RECONNECT = 10; 542 static final int MCS_GIVE_UP = 11; 543 static final int UPDATED_MEDIA_STATUS = 12; 544 static final int WRITE_SETTINGS = 13; 545 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 546 static final int PACKAGE_VERIFIED = 15; 547 static final int CHECK_PENDING_VERIFICATION = 16; 548 549 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 550 551 // Delay time in millisecs 552 static final int BROADCAST_DELAY = 10 * 1000; 553 554 static UserManagerService sUserManager; 555 556 // Stores a list of users whose package restrictions file needs to be updated 557 private HashSet<Integer> mDirtyUsers = new HashSet<Integer>(); 558 559 final private DefaultContainerConnection mDefContainerConn = 560 new DefaultContainerConnection(); 561 class DefaultContainerConnection implements ServiceConnection { 562 public void onServiceConnected(ComponentName name, IBinder service) { 563 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 564 IMediaContainerService imcs = 565 IMediaContainerService.Stub.asInterface(service); 566 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 567 } 568 569 public void onServiceDisconnected(ComponentName name) { 570 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 571 } 572 }; 573 574 // Recordkeeping of restore-after-install operations that are currently in flight 575 // between the Package Manager and the Backup Manager 576 class PostInstallData { 577 public InstallArgs args; 578 public PackageInstalledInfo res; 579 580 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 581 args = _a; 582 res = _r; 583 } 584 }; 585 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 586 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 587 588 private final String mRequiredVerifierPackage; 589 590 private final PackageUsage mPackageUsage = new PackageUsage(); 591 592 private class PackageUsage { 593 private static final int WRITE_INTERVAL 594 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 595 596 private final Object mFileLock = new Object(); 597 private final AtomicLong mLastWritten = new AtomicLong(0); 598 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 599 600 private boolean mIsHistoricalPackageUsageAvailable = true; 601 602 boolean isHistoricalPackageUsageAvailable() { 603 return mIsHistoricalPackageUsageAvailable; 604 } 605 606 void write(boolean force) { 607 if (force) { 608 writeInternal(); 609 return; 610 } 611 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 612 && !DEBUG_DEXOPT) { 613 return; 614 } 615 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 616 new Thread("PackageUsage_DiskWriter") { 617 @Override 618 public void run() { 619 try { 620 writeInternal(); 621 } finally { 622 mBackgroundWriteRunning.set(false); 623 } 624 } 625 }.start(); 626 } 627 } 628 629 private void writeInternal() { 630 synchronized (mPackages) { 631 synchronized (mFileLock) { 632 AtomicFile file = getFile(); 633 FileOutputStream f = null; 634 try { 635 f = file.startWrite(); 636 BufferedOutputStream out = new BufferedOutputStream(f); 637 FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID); 638 StringBuilder sb = new StringBuilder(); 639 for (PackageParser.Package pkg : mPackages.values()) { 640 if (pkg.mLastPackageUsageTimeInMills == 0) { 641 continue; 642 } 643 sb.setLength(0); 644 sb.append(pkg.packageName); 645 sb.append(' '); 646 sb.append((long)pkg.mLastPackageUsageTimeInMills); 647 sb.append('\n'); 648 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 649 } 650 out.flush(); 651 file.finishWrite(f); 652 } catch (IOException e) { 653 if (f != null) { 654 file.failWrite(f); 655 } 656 Log.e(TAG, "Failed to write package usage times", e); 657 } 658 } 659 } 660 mLastWritten.set(SystemClock.elapsedRealtime()); 661 } 662 663 void readLP() { 664 synchronized (mFileLock) { 665 AtomicFile file = getFile(); 666 BufferedInputStream in = null; 667 try { 668 in = new BufferedInputStream(file.openRead()); 669 StringBuffer sb = new StringBuffer(); 670 while (true) { 671 String packageName = readToken(in, sb, ' '); 672 if (packageName == null) { 673 break; 674 } 675 String timeInMillisString = readToken(in, sb, '\n'); 676 if (timeInMillisString == null) { 677 throw new IOException("Failed to find last usage time for package " 678 + packageName); 679 } 680 PackageParser.Package pkg = mPackages.get(packageName); 681 if (pkg == null) { 682 continue; 683 } 684 long timeInMillis; 685 try { 686 timeInMillis = Long.parseLong(timeInMillisString.toString()); 687 } catch (NumberFormatException e) { 688 throw new IOException("Failed to parse " + timeInMillisString 689 + " as a long.", e); 690 } 691 pkg.mLastPackageUsageTimeInMills = timeInMillis; 692 } 693 } catch (FileNotFoundException expected) { 694 mIsHistoricalPackageUsageAvailable = false; 695 } catch (IOException e) { 696 Log.w(TAG, "Failed to read package usage times", e); 697 } finally { 698 IoUtils.closeQuietly(in); 699 } 700 } 701 mLastWritten.set(SystemClock.elapsedRealtime()); 702 } 703 704 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 705 throws IOException { 706 sb.setLength(0); 707 while (true) { 708 int ch = in.read(); 709 if (ch == -1) { 710 if (sb.length() == 0) { 711 return null; 712 } 713 throw new IOException("Unexpected EOF"); 714 } 715 if (ch == endOfToken) { 716 return sb.toString(); 717 } 718 sb.append((char)ch); 719 } 720 } 721 722 private AtomicFile getFile() { 723 File dataDir = Environment.getDataDirectory(); 724 File systemDir = new File(dataDir, "system"); 725 File fname = new File(systemDir, "package-usage.list"); 726 return new AtomicFile(fname); 727 } 728 } 729 730 class PackageHandler extends Handler { 731 private boolean mBound = false; 732 final ArrayList<HandlerParams> mPendingInstalls = 733 new ArrayList<HandlerParams>(); 734 735 private boolean connectToService() { 736 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 737 " DefaultContainerService"); 738 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 739 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 740 if (mContext.bindServiceAsUser(service, mDefContainerConn, 741 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 742 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 743 mBound = true; 744 return true; 745 } 746 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 747 return false; 748 } 749 750 private void disconnectService() { 751 mContainerService = null; 752 mBound = false; 753 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 754 mContext.unbindService(mDefContainerConn); 755 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 756 } 757 758 PackageHandler(Looper looper) { 759 super(looper); 760 } 761 762 public void handleMessage(Message msg) { 763 try { 764 doHandleMessage(msg); 765 } finally { 766 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 767 } 768 } 769 770 void doHandleMessage(Message msg) { 771 switch (msg.what) { 772 case INIT_COPY: { 773 HandlerParams params = (HandlerParams) msg.obj; 774 int idx = mPendingInstalls.size(); 775 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 776 // If a bind was already initiated we dont really 777 // need to do anything. The pending install 778 // will be processed later on. 779 if (!mBound) { 780 // If this is the only one pending we might 781 // have to bind to the service again. 782 if (!connectToService()) { 783 Slog.e(TAG, "Failed to bind to media container service"); 784 params.serviceError(); 785 return; 786 } else { 787 // Once we bind to the service, the first 788 // pending request will be processed. 789 mPendingInstalls.add(idx, params); 790 } 791 } else { 792 mPendingInstalls.add(idx, params); 793 // Already bound to the service. Just make 794 // sure we trigger off processing the first request. 795 if (idx == 0) { 796 mHandler.sendEmptyMessage(MCS_BOUND); 797 } 798 } 799 break; 800 } 801 case MCS_BOUND: { 802 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 803 if (msg.obj != null) { 804 mContainerService = (IMediaContainerService) msg.obj; 805 } 806 if (mContainerService == null) { 807 // Something seriously wrong. Bail out 808 Slog.e(TAG, "Cannot bind to media container service"); 809 for (HandlerParams params : mPendingInstalls) { 810 // Indicate service bind error 811 params.serviceError(); 812 } 813 mPendingInstalls.clear(); 814 } else if (mPendingInstalls.size() > 0) { 815 HandlerParams params = mPendingInstalls.get(0); 816 if (params != null) { 817 if (params.startCopy()) { 818 // We are done... look for more work or to 819 // go idle. 820 if (DEBUG_SD_INSTALL) Log.i(TAG, 821 "Checking for more work or unbind..."); 822 // Delete pending install 823 if (mPendingInstalls.size() > 0) { 824 mPendingInstalls.remove(0); 825 } 826 if (mPendingInstalls.size() == 0) { 827 if (mBound) { 828 if (DEBUG_SD_INSTALL) Log.i(TAG, 829 "Posting delayed MCS_UNBIND"); 830 removeMessages(MCS_UNBIND); 831 Message ubmsg = obtainMessage(MCS_UNBIND); 832 // Unbind after a little delay, to avoid 833 // continual thrashing. 834 sendMessageDelayed(ubmsg, 10000); 835 } 836 } else { 837 // There are more pending requests in queue. 838 // Just post MCS_BOUND message to trigger processing 839 // of next pending install. 840 if (DEBUG_SD_INSTALL) Log.i(TAG, 841 "Posting MCS_BOUND for next work"); 842 mHandler.sendEmptyMessage(MCS_BOUND); 843 } 844 } 845 } 846 } else { 847 // Should never happen ideally. 848 Slog.w(TAG, "Empty queue"); 849 } 850 break; 851 } 852 case MCS_RECONNECT: { 853 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 854 if (mPendingInstalls.size() > 0) { 855 if (mBound) { 856 disconnectService(); 857 } 858 if (!connectToService()) { 859 Slog.e(TAG, "Failed to bind to media container service"); 860 for (HandlerParams params : mPendingInstalls) { 861 // Indicate service bind error 862 params.serviceError(); 863 } 864 mPendingInstalls.clear(); 865 } 866 } 867 break; 868 } 869 case MCS_UNBIND: { 870 // If there is no actual work left, then time to unbind. 871 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 872 873 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 874 if (mBound) { 875 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 876 877 disconnectService(); 878 } 879 } else if (mPendingInstalls.size() > 0) { 880 // There are more pending requests in queue. 881 // Just post MCS_BOUND message to trigger processing 882 // of next pending install. 883 mHandler.sendEmptyMessage(MCS_BOUND); 884 } 885 886 break; 887 } 888 case MCS_GIVE_UP: { 889 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 890 mPendingInstalls.remove(0); 891 break; 892 } 893 case SEND_PENDING_BROADCAST: { 894 String packages[]; 895 ArrayList<String> components[]; 896 int size = 0; 897 int uids[]; 898 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 899 synchronized (mPackages) { 900 if (mPendingBroadcasts == null) { 901 return; 902 } 903 size = mPendingBroadcasts.size(); 904 if (size <= 0) { 905 // Nothing to be done. Just return 906 return; 907 } 908 packages = new String[size]; 909 components = new ArrayList[size]; 910 uids = new int[size]; 911 int i = 0; // filling out the above arrays 912 913 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 914 int packageUserId = mPendingBroadcasts.userIdAt(n); 915 Iterator<Map.Entry<String, ArrayList<String>>> it 916 = mPendingBroadcasts.packagesForUserId(packageUserId) 917 .entrySet().iterator(); 918 while (it.hasNext() && i < size) { 919 Map.Entry<String, ArrayList<String>> ent = it.next(); 920 packages[i] = ent.getKey(); 921 components[i] = ent.getValue(); 922 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 923 uids[i] = (ps != null) 924 ? UserHandle.getUid(packageUserId, ps.appId) 925 : -1; 926 i++; 927 } 928 } 929 size = i; 930 mPendingBroadcasts.clear(); 931 } 932 // Send broadcasts 933 for (int i = 0; i < size; i++) { 934 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 935 } 936 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 937 break; 938 } 939 case START_CLEANING_PACKAGE: { 940 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 941 final String packageName = (String)msg.obj; 942 final int userId = msg.arg1; 943 final boolean andCode = msg.arg2 != 0; 944 synchronized (mPackages) { 945 if (userId == UserHandle.USER_ALL) { 946 int[] users = sUserManager.getUserIds(); 947 for (int user : users) { 948 mSettings.addPackageToCleanLPw( 949 new PackageCleanItem(user, packageName, andCode)); 950 } 951 } else { 952 mSettings.addPackageToCleanLPw( 953 new PackageCleanItem(userId, packageName, andCode)); 954 } 955 } 956 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 957 startCleaningPackages(); 958 } break; 959 case POST_INSTALL: { 960 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 961 PostInstallData data = mRunningInstalls.get(msg.arg1); 962 mRunningInstalls.delete(msg.arg1); 963 boolean deleteOld = false; 964 965 if (data != null) { 966 InstallArgs args = data.args; 967 PackageInstalledInfo res = data.res; 968 969 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 970 res.removedInfo.sendBroadcast(false, true, false); 971 Bundle extras = new Bundle(1); 972 extras.putInt(Intent.EXTRA_UID, res.uid); 973 // Determine the set of users who are adding this 974 // package for the first time vs. those who are seeing 975 // an update. 976 int[] firstUsers; 977 int[] updateUsers = new int[0]; 978 if (res.origUsers == null || res.origUsers.length == 0) { 979 firstUsers = res.newUsers; 980 } else { 981 firstUsers = new int[0]; 982 for (int i=0; i<res.newUsers.length; i++) { 983 int user = res.newUsers[i]; 984 boolean isNew = true; 985 for (int j=0; j<res.origUsers.length; j++) { 986 if (res.origUsers[j] == user) { 987 isNew = false; 988 break; 989 } 990 } 991 if (isNew) { 992 int[] newFirst = new int[firstUsers.length+1]; 993 System.arraycopy(firstUsers, 0, newFirst, 0, 994 firstUsers.length); 995 newFirst[firstUsers.length] = user; 996 firstUsers = newFirst; 997 } else { 998 int[] newUpdate = new int[updateUsers.length+1]; 999 System.arraycopy(updateUsers, 0, newUpdate, 0, 1000 updateUsers.length); 1001 newUpdate[updateUsers.length] = user; 1002 updateUsers = newUpdate; 1003 } 1004 } 1005 } 1006 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1007 res.pkg.applicationInfo.packageName, 1008 extras, null, null, firstUsers); 1009 final boolean update = res.removedInfo.removedPackage != null; 1010 if (update) { 1011 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1012 } 1013 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1014 res.pkg.applicationInfo.packageName, 1015 extras, null, null, updateUsers); 1016 if (update) { 1017 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1018 res.pkg.applicationInfo.packageName, 1019 extras, null, null, updateUsers); 1020 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1021 null, null, 1022 res.pkg.applicationInfo.packageName, null, updateUsers); 1023 1024 // treat asec-hosted packages like removable media on upgrade 1025 if (isForwardLocked(res.pkg) || isExternal(res.pkg)) { 1026 if (DEBUG_INSTALL) { 1027 Slog.i(TAG, "upgrading pkg " + res.pkg 1028 + " is ASEC-hosted -> AVAILABLE"); 1029 } 1030 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1031 ArrayList<String> pkgList = new ArrayList<String>(1); 1032 pkgList.add(res.pkg.applicationInfo.packageName); 1033 sendResourcesChangedBroadcast(true, true, 1034 pkgList,uidArray, null); 1035 } 1036 } 1037 if (res.removedInfo.args != null) { 1038 // Remove the replaced package's older resources safely now 1039 deleteOld = true; 1040 } 1041 1042 // Log current value of "unknown sources" setting 1043 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1044 getUnknownSourcesSettings()); 1045 } 1046 // Force a gc to clear up things 1047 Runtime.getRuntime().gc(); 1048 // We delete after a gc for applications on sdcard. 1049 if (deleteOld) { 1050 synchronized (mInstallLock) { 1051 res.removedInfo.args.doPostDeleteLI(true); 1052 } 1053 } 1054 if (args.observer != null) { 1055 try { 1056 Bundle extras = extrasForInstallResult(res); 1057 args.observer.onPackageInstalled(res.name, res.returnCode, 1058 res.returnMsg, extras); 1059 } catch (RemoteException e) { 1060 Slog.i(TAG, "Observer no longer exists."); 1061 } 1062 } 1063 } else { 1064 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1065 } 1066 } break; 1067 case UPDATED_MEDIA_STATUS: { 1068 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1069 boolean reportStatus = msg.arg1 == 1; 1070 boolean doGc = msg.arg2 == 1; 1071 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1072 if (doGc) { 1073 // Force a gc to clear up stale containers. 1074 Runtime.getRuntime().gc(); 1075 } 1076 if (msg.obj != null) { 1077 @SuppressWarnings("unchecked") 1078 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1079 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1080 // Unload containers 1081 unloadAllContainers(args); 1082 } 1083 if (reportStatus) { 1084 try { 1085 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1086 PackageHelper.getMountService().finishMediaUpdate(); 1087 } catch (RemoteException e) { 1088 Log.e(TAG, "MountService not running?"); 1089 } 1090 } 1091 } break; 1092 case WRITE_SETTINGS: { 1093 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1094 synchronized (mPackages) { 1095 removeMessages(WRITE_SETTINGS); 1096 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1097 mSettings.writeLPr(); 1098 mDirtyUsers.clear(); 1099 } 1100 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1101 } break; 1102 case WRITE_PACKAGE_RESTRICTIONS: { 1103 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1104 synchronized (mPackages) { 1105 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1106 for (int userId : mDirtyUsers) { 1107 mSettings.writePackageRestrictionsLPr(userId); 1108 } 1109 mDirtyUsers.clear(); 1110 } 1111 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1112 } break; 1113 case CHECK_PENDING_VERIFICATION: { 1114 final int verificationId = msg.arg1; 1115 final PackageVerificationState state = mPendingVerification.get(verificationId); 1116 1117 if ((state != null) && !state.timeoutExtended()) { 1118 final InstallArgs args = state.getInstallArgs(); 1119 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1120 1121 Slog.i(TAG, "Verification timed out for " + originUri); 1122 mPendingVerification.remove(verificationId); 1123 1124 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1125 1126 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1127 Slog.i(TAG, "Continuing with installation of " + originUri); 1128 state.setVerifierResponse(Binder.getCallingUid(), 1129 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1130 broadcastPackageVerified(verificationId, originUri, 1131 PackageManager.VERIFICATION_ALLOW, 1132 state.getInstallArgs().getUser()); 1133 try { 1134 ret = args.copyApk(mContainerService, true); 1135 } catch (RemoteException e) { 1136 Slog.e(TAG, "Could not contact the ContainerService"); 1137 } 1138 } else { 1139 broadcastPackageVerified(verificationId, originUri, 1140 PackageManager.VERIFICATION_REJECT, 1141 state.getInstallArgs().getUser()); 1142 } 1143 1144 processPendingInstall(args, ret); 1145 mHandler.sendEmptyMessage(MCS_UNBIND); 1146 } 1147 break; 1148 } 1149 case PACKAGE_VERIFIED: { 1150 final int verificationId = msg.arg1; 1151 1152 final PackageVerificationState state = mPendingVerification.get(verificationId); 1153 if (state == null) { 1154 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1155 break; 1156 } 1157 1158 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1159 1160 state.setVerifierResponse(response.callerUid, response.code); 1161 1162 if (state.isVerificationComplete()) { 1163 mPendingVerification.remove(verificationId); 1164 1165 final InstallArgs args = state.getInstallArgs(); 1166 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1167 1168 int ret; 1169 if (state.isInstallAllowed()) { 1170 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1171 broadcastPackageVerified(verificationId, originUri, 1172 response.code, state.getInstallArgs().getUser()); 1173 try { 1174 ret = args.copyApk(mContainerService, true); 1175 } catch (RemoteException e) { 1176 Slog.e(TAG, "Could not contact the ContainerService"); 1177 } 1178 } else { 1179 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1180 } 1181 1182 processPendingInstall(args, ret); 1183 1184 mHandler.sendEmptyMessage(MCS_UNBIND); 1185 } 1186 1187 break; 1188 } 1189 } 1190 } 1191 } 1192 1193 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1194 Bundle extras = null; 1195 switch (res.returnCode) { 1196 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1197 extras = new Bundle(); 1198 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1199 res.origPermission); 1200 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1201 res.origPackage); 1202 break; 1203 } 1204 } 1205 return extras; 1206 } 1207 1208 void scheduleWriteSettingsLocked() { 1209 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1210 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1211 } 1212 } 1213 1214 void scheduleWritePackageRestrictionsLocked(int userId) { 1215 if (!sUserManager.exists(userId)) return; 1216 mDirtyUsers.add(userId); 1217 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1218 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1219 } 1220 } 1221 1222 public static final PackageManagerService main(Context context, Installer installer, 1223 boolean factoryTest, boolean onlyCore) { 1224 PackageManagerService m = new PackageManagerService(context, installer, 1225 factoryTest, onlyCore); 1226 ServiceManager.addService("package", m); 1227 return m; 1228 } 1229 1230 static String[] splitString(String str, char sep) { 1231 int count = 1; 1232 int i = 0; 1233 while ((i=str.indexOf(sep, i)) >= 0) { 1234 count++; 1235 i++; 1236 } 1237 1238 String[] res = new String[count]; 1239 i=0; 1240 count = 0; 1241 int lastI=0; 1242 while ((i=str.indexOf(sep, i)) >= 0) { 1243 res[count] = str.substring(lastI, i); 1244 count++; 1245 i++; 1246 lastI = i; 1247 } 1248 res[count] = str.substring(lastI, str.length()); 1249 return res; 1250 } 1251 1252 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1253 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1254 Context.DISPLAY_SERVICE); 1255 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1256 } 1257 1258 public PackageManagerService(Context context, Installer installer, 1259 boolean factoryTest, boolean onlyCore) { 1260 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1261 SystemClock.uptimeMillis()); 1262 1263 if (mSdkVersion <= 0) { 1264 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1265 } 1266 1267 mContext = context; 1268 mFactoryTest = factoryTest; 1269 mOnlyCore = onlyCore; 1270 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1271 mMetrics = new DisplayMetrics(); 1272 mSettings = new Settings(context); 1273 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1274 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1275 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1276 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1277 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1278 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1279 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1280 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1281 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1282 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1283 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1284 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1285 1286 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1287 if (separateProcesses != null && separateProcesses.length() > 0) { 1288 if ("*".equals(separateProcesses)) { 1289 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1290 mSeparateProcesses = null; 1291 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1292 } else { 1293 mDefParseFlags = 0; 1294 mSeparateProcesses = separateProcesses.split(","); 1295 Slog.w(TAG, "Running with debug.separate_processes: " 1296 + separateProcesses); 1297 } 1298 } else { 1299 mDefParseFlags = 0; 1300 mSeparateProcesses = null; 1301 } 1302 1303 mInstaller = installer; 1304 1305 getDefaultDisplayMetrics(context, mMetrics); 1306 1307 SystemConfig systemConfig = SystemConfig.getInstance(); 1308 mGlobalGids = systemConfig.getGlobalGids(); 1309 mSystemPermissions = systemConfig.getSystemPermissions(); 1310 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1311 1312 synchronized (mInstallLock) { 1313 // writer 1314 synchronized (mPackages) { 1315 mHandlerThread = new ServiceThread(TAG, 1316 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1317 mHandlerThread.start(); 1318 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1319 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1320 1321 File dataDir = Environment.getDataDirectory(); 1322 mAppDataDir = new File(dataDir, "data"); 1323 mAppInstallDir = new File(dataDir, "app"); 1324 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1325 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1326 mUserAppDataDir = new File(dataDir, "user"); 1327 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1328 1329 sUserManager = new UserManagerService(context, this, 1330 mInstallLock, mPackages); 1331 1332 // Propagate permission configuration in to package manager. 1333 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1334 = systemConfig.getPermissions(); 1335 for (int i=0; i<permConfig.size(); i++) { 1336 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1337 BasePermission bp = mSettings.mPermissions.get(perm.name); 1338 if (bp == null) { 1339 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1340 mSettings.mPermissions.put(perm.name, bp); 1341 } 1342 if (perm.gids != null) { 1343 bp.gids = appendInts(bp.gids, perm.gids); 1344 } 1345 } 1346 1347 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1348 for (int i=0; i<libConfig.size(); i++) { 1349 mSharedLibraries.put(libConfig.keyAt(i), 1350 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1351 } 1352 1353 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1354 1355 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1356 mSdkVersion, mOnlyCore); 1357 1358 String customResolverActivity = Resources.getSystem().getString( 1359 R.string.config_customResolverActivity); 1360 if (TextUtils.isEmpty(customResolverActivity)) { 1361 customResolverActivity = null; 1362 } else { 1363 mCustomResolverComponentName = ComponentName.unflattenFromString( 1364 customResolverActivity); 1365 } 1366 1367 long startTime = SystemClock.uptimeMillis(); 1368 1369 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1370 startTime); 1371 1372 // Set flag to monitor and not change apk file paths when 1373 // scanning install directories. 1374 int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1375 1376 final HashSet<String> alreadyDexOpted = new HashSet<String>(); 1377 1378 /** 1379 * Add everything in the in the boot class path to the 1380 * list of process files because dexopt will have been run 1381 * if necessary during zygote startup. 1382 */ 1383 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1384 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1385 1386 if (bootClassPath != null) { 1387 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1388 for (String element : bootClassPathElements) { 1389 alreadyDexOpted.add(element); 1390 } 1391 } else { 1392 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1393 } 1394 1395 if (systemServerClassPath != null) { 1396 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1397 for (String element : systemServerClassPathElements) { 1398 alreadyDexOpted.add(element); 1399 } 1400 } else { 1401 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1402 } 1403 1404 boolean didDexOptLibraryOrTool = false; 1405 1406 final List<String> allInstructionSets = getAllInstructionSets(); 1407 final String[] dexCodeInstructionSets = 1408 getDexCodeInstructionSets(allInstructionSets.toArray(new String[allInstructionSets.size()])); 1409 1410 /** 1411 * Ensure all external libraries have had dexopt run on them. 1412 */ 1413 if (mSharedLibraries.size() > 0) { 1414 // NOTE: For now, we're compiling these system "shared libraries" 1415 // (and framework jars) into all available architectures. It's possible 1416 // to compile them only when we come across an app that uses them (there's 1417 // already logic for that in scanPackageLI) but that adds some complexity. 1418 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1419 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1420 final String lib = libEntry.path; 1421 if (lib == null) { 1422 continue; 1423 } 1424 1425 try { 1426 byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null, 1427 dexCodeInstructionSet, 1428 false); 1429 if (dexoptRequired != DexFile.UP_TO_DATE) { 1430 alreadyDexOpted.add(lib); 1431 1432 // The list of "shared libraries" we have at this point is 1433 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1434 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1435 } else { 1436 mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1437 } 1438 didDexOptLibraryOrTool = true; 1439 } 1440 } catch (FileNotFoundException e) { 1441 Slog.w(TAG, "Library not found: " + lib); 1442 } catch (IOException e) { 1443 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1444 + e.getMessage()); 1445 } 1446 } 1447 } 1448 } 1449 1450 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1451 1452 // Gross hack for now: we know this file doesn't contain any 1453 // code, so don't dexopt it to avoid the resulting log spew. 1454 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1455 1456 // Gross hack for now: we know this file is only part of 1457 // the boot class path for art, so don't dexopt it to 1458 // avoid the resulting log spew. 1459 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1460 1461 /** 1462 * And there are a number of commands implemented in Java, which 1463 * we currently need to do the dexopt on so that they can be 1464 * run from a non-root shell. 1465 */ 1466 String[] frameworkFiles = frameworkDir.list(); 1467 if (frameworkFiles != null) { 1468 // TODO: We could compile these only for the most preferred ABI. We should 1469 // first double check that the dex files for these commands are not referenced 1470 // by other system apps. 1471 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1472 for (int i=0; i<frameworkFiles.length; i++) { 1473 File libPath = new File(frameworkDir, frameworkFiles[i]); 1474 String path = libPath.getPath(); 1475 // Skip the file if we already did it. 1476 if (alreadyDexOpted.contains(path)) { 1477 continue; 1478 } 1479 // Skip the file if it is not a type we want to dexopt. 1480 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1481 continue; 1482 } 1483 try { 1484 byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null, 1485 dexCodeInstructionSet, 1486 false); 1487 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1488 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1489 didDexOptLibraryOrTool = true; 1490 } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) { 1491 mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1492 didDexOptLibraryOrTool = true; 1493 } 1494 } catch (FileNotFoundException e) { 1495 Slog.w(TAG, "Jar not found: " + path); 1496 } catch (IOException e) { 1497 Slog.w(TAG, "Exception reading jar: " + path, e); 1498 } 1499 } 1500 } 1501 } 1502 1503 // Collect vendor overlay packages. 1504 // (Do this before scanning any apps.) 1505 // For security and version matching reason, only consider 1506 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1507 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1508 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1509 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1510 1511 // Find base frameworks (resource packages without code). 1512 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1513 | PackageParser.PARSE_IS_SYSTEM_DIR 1514 | PackageParser.PARSE_IS_PRIVILEGED, 1515 scanFlags | SCAN_NO_DEX, 0); 1516 1517 // Collected privileged system packages. 1518 File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1519 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1520 | PackageParser.PARSE_IS_SYSTEM_DIR 1521 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1522 1523 // Collect ordinary system packages. 1524 File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1525 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1526 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1527 1528 // Collect all vendor packages. 1529 File vendorAppDir = new File("/vendor/app"); 1530 try { 1531 vendorAppDir = vendorAppDir.getCanonicalFile(); 1532 } catch (IOException e) { 1533 // failed to look up canonical path, continue with original one 1534 } 1535 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1536 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1537 1538 // Collect all OEM packages. 1539 File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1540 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1541 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1542 1543 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1544 mInstaller.moveFiles(); 1545 1546 // Prune any system packages that no longer exist. 1547 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1548 if (!mOnlyCore) { 1549 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1550 while (psit.hasNext()) { 1551 PackageSetting ps = psit.next(); 1552 1553 /* 1554 * If this is not a system app, it can't be a 1555 * disable system app. 1556 */ 1557 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1558 continue; 1559 } 1560 1561 /* 1562 * If the package is scanned, it's not erased. 1563 */ 1564 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1565 if (scannedPkg != null) { 1566 /* 1567 * If the system app is both scanned and in the 1568 * disabled packages list, then it must have been 1569 * added via OTA. Remove it from the currently 1570 * scanned package so the previously user-installed 1571 * application can be scanned. 1572 */ 1573 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1574 Slog.i(TAG, "Expecting better updatd system app for " + ps.name 1575 + "; removing system app"); 1576 removePackageLI(ps, true); 1577 } 1578 1579 continue; 1580 } 1581 1582 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1583 psit.remove(); 1584 String msg = "System package " + ps.name 1585 + " no longer exists; wiping its data"; 1586 reportSettingsProblem(Log.WARN, msg); 1587 removeDataDirsLI(ps.name); 1588 } else { 1589 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1590 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1591 possiblyDeletedUpdatedSystemApps.add(ps.name); 1592 } 1593 } 1594 } 1595 } 1596 1597 //look for any incomplete package installations 1598 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1599 //clean up list 1600 for(int i = 0; i < deletePkgsList.size(); i++) { 1601 //clean up here 1602 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1603 } 1604 //delete tmp files 1605 deleteTempPackageFiles(); 1606 1607 // Remove any shared userIDs that have no associated packages 1608 mSettings.pruneSharedUsersLPw(); 1609 1610 if (!mOnlyCore) { 1611 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 1612 SystemClock.uptimeMillis()); 1613 scanDirLI(mAppInstallDir, 0, scanFlags, 0); 1614 1615 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 1616 scanFlags, 0); 1617 1618 /** 1619 * Remove disable package settings for any updated system 1620 * apps that were removed via an OTA. If they're not a 1621 * previously-updated app, remove them completely. 1622 * Otherwise, just revoke their system-level permissions. 1623 */ 1624 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 1625 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 1626 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 1627 1628 String msg; 1629 if (deletedPkg == null) { 1630 msg = "Updated system package " + deletedAppName 1631 + " no longer exists; wiping its data"; 1632 removeDataDirsLI(deletedAppName); 1633 } else { 1634 msg = "Updated system app + " + deletedAppName 1635 + " no longer present; removing system privileges for " 1636 + deletedAppName; 1637 1638 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 1639 1640 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 1641 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 1642 } 1643 reportSettingsProblem(Log.WARN, msg); 1644 } 1645 } 1646 1647 // Now that we know all of the shared libraries, update all clients to have 1648 // the correct library paths. 1649 updateAllSharedLibrariesLPw(); 1650 1651 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 1652 // NOTE: We ignore potential failures here during a system scan (like 1653 // the rest of the commands above) because there's precious little we 1654 // can do about it. A settings error is reported, though. 1655 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 1656 false /* force dexopt */, false /* defer dexopt */); 1657 } 1658 1659 // Now that we know all the packages we are keeping, 1660 // read and update their last usage times. 1661 mPackageUsage.readLP(); 1662 1663 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 1664 SystemClock.uptimeMillis()); 1665 Slog.i(TAG, "Time to scan packages: " 1666 + ((SystemClock.uptimeMillis()-startTime)/1000f) 1667 + " seconds"); 1668 1669 // If the platform SDK has changed since the last time we booted, 1670 // we need to re-grant app permission to catch any new ones that 1671 // appear. This is really a hack, and means that apps can in some 1672 // cases get permissions that the user didn't initially explicitly 1673 // allow... it would be nice to have some better way to handle 1674 // this situation. 1675 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 1676 != mSdkVersion; 1677 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 1678 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 1679 + "; regranting permissions for internal storage"); 1680 mSettings.mInternalSdkPlatform = mSdkVersion; 1681 1682 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 1683 | (regrantPermissions 1684 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 1685 : 0)); 1686 1687 // If this is the first boot, and it is a normal boot, then 1688 // we need to initialize the default preferred apps. 1689 if (!mRestoredSettings && !onlyCore) { 1690 mSettings.readDefaultPreferredAppsLPw(this, 0); 1691 } 1692 1693 // If this is first boot after an OTA, and a normal boot, then 1694 // we need to clear code cache directories. 1695 if (!Build.FINGERPRINT.equals(mSettings.mFingerprint) && !onlyCore) { 1696 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 1697 for (String pkgName : mSettings.mPackages.keySet()) { 1698 deleteCodeCacheDirsLI(pkgName); 1699 } 1700 mSettings.mFingerprint = Build.FINGERPRINT; 1701 } 1702 1703 // All the changes are done during package scanning. 1704 mSettings.updateInternalDatabaseVersion(); 1705 1706 // can downgrade to reader 1707 mSettings.writeLPr(); 1708 1709 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 1710 SystemClock.uptimeMillis()); 1711 1712 1713 mRequiredVerifierPackage = getRequiredVerifierLPr(); 1714 } // synchronized (mPackages) 1715 } // synchronized (mInstallLock) 1716 1717 mInstallerService = new PackageInstallerService(context, this, mAppInstallDir); 1718 1719 // Now after opening every single application zip, make sure they 1720 // are all flushed. Not really needed, but keeps things nice and 1721 // tidy. 1722 Runtime.getRuntime().gc(); 1723 } 1724 1725 @Override 1726 public boolean isFirstBoot() { 1727 return !mRestoredSettings; 1728 } 1729 1730 @Override 1731 public boolean isOnlyCoreApps() { 1732 return mOnlyCore; 1733 } 1734 1735 private String getRequiredVerifierLPr() { 1736 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 1737 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 1738 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 1739 1740 String requiredVerifier = null; 1741 1742 final int N = receivers.size(); 1743 for (int i = 0; i < N; i++) { 1744 final ResolveInfo info = receivers.get(i); 1745 1746 if (info.activityInfo == null) { 1747 continue; 1748 } 1749 1750 final String packageName = info.activityInfo.packageName; 1751 1752 final PackageSetting ps = mSettings.mPackages.get(packageName); 1753 if (ps == null) { 1754 continue; 1755 } 1756 1757 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1758 if (!gp.grantedPermissions 1759 .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) { 1760 continue; 1761 } 1762 1763 if (requiredVerifier != null) { 1764 throw new RuntimeException("There can be only one required verifier"); 1765 } 1766 1767 requiredVerifier = packageName; 1768 } 1769 1770 return requiredVerifier; 1771 } 1772 1773 @Override 1774 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 1775 throws RemoteException { 1776 try { 1777 return super.onTransact(code, data, reply, flags); 1778 } catch (RuntimeException e) { 1779 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 1780 Slog.wtf(TAG, "Package Manager Crash", e); 1781 } 1782 throw e; 1783 } 1784 } 1785 1786 void cleanupInstallFailedPackage(PackageSetting ps) { 1787 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name); 1788 removeDataDirsLI(ps.name); 1789 1790 // TODO: try cleaning up codePath directory contents first, since it 1791 // might be a cluster 1792 1793 if (ps.codePath != null) { 1794 if (!ps.codePath.delete()) { 1795 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath); 1796 } 1797 } 1798 if (ps.resourcePath != null) { 1799 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) { 1800 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath); 1801 } 1802 } 1803 mSettings.removePackageLPw(ps.name); 1804 } 1805 1806 static int[] appendInts(int[] cur, int[] add) { 1807 if (add == null) return cur; 1808 if (cur == null) return add; 1809 final int N = add.length; 1810 for (int i=0; i<N; i++) { 1811 cur = appendInt(cur, add[i]); 1812 } 1813 return cur; 1814 } 1815 1816 static int[] removeInts(int[] cur, int[] rem) { 1817 if (rem == null) return cur; 1818 if (cur == null) return cur; 1819 final int N = rem.length; 1820 for (int i=0; i<N; i++) { 1821 cur = removeInt(cur, rem[i]); 1822 } 1823 return cur; 1824 } 1825 1826 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 1827 if (!sUserManager.exists(userId)) return null; 1828 final PackageSetting ps = (PackageSetting) p.mExtras; 1829 if (ps == null) { 1830 return null; 1831 } 1832 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1833 final PackageUserState state = ps.readUserState(userId); 1834 return PackageParser.generatePackageInfo(p, gp.gids, flags, 1835 ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions, 1836 state, userId); 1837 } 1838 1839 @Override 1840 public boolean isPackageAvailable(String packageName, int userId) { 1841 if (!sUserManager.exists(userId)) return false; 1842 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available"); 1843 synchronized (mPackages) { 1844 PackageParser.Package p = mPackages.get(packageName); 1845 if (p != null) { 1846 final PackageSetting ps = (PackageSetting) p.mExtras; 1847 if (ps != null) { 1848 final PackageUserState state = ps.readUserState(userId); 1849 if (state != null) { 1850 return PackageParser.isAvailable(state); 1851 } 1852 } 1853 } 1854 } 1855 return false; 1856 } 1857 1858 @Override 1859 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 1860 if (!sUserManager.exists(userId)) return null; 1861 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info"); 1862 // reader 1863 synchronized (mPackages) { 1864 PackageParser.Package p = mPackages.get(packageName); 1865 if (DEBUG_PACKAGE_INFO) 1866 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 1867 if (p != null) { 1868 return generatePackageInfo(p, flags, userId); 1869 } 1870 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 1871 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 1872 } 1873 } 1874 return null; 1875 } 1876 1877 @Override 1878 public String[] currentToCanonicalPackageNames(String[] names) { 1879 String[] out = new String[names.length]; 1880 // reader 1881 synchronized (mPackages) { 1882 for (int i=names.length-1; i>=0; i--) { 1883 PackageSetting ps = mSettings.mPackages.get(names[i]); 1884 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 1885 } 1886 } 1887 return out; 1888 } 1889 1890 @Override 1891 public String[] canonicalToCurrentPackageNames(String[] names) { 1892 String[] out = new String[names.length]; 1893 // reader 1894 synchronized (mPackages) { 1895 for (int i=names.length-1; i>=0; i--) { 1896 String cur = mSettings.mRenamedPackages.get(names[i]); 1897 out[i] = cur != null ? cur : names[i]; 1898 } 1899 } 1900 return out; 1901 } 1902 1903 @Override 1904 public int getPackageUid(String packageName, int userId) { 1905 if (!sUserManager.exists(userId)) return -1; 1906 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid"); 1907 // reader 1908 synchronized (mPackages) { 1909 PackageParser.Package p = mPackages.get(packageName); 1910 if(p != null) { 1911 return UserHandle.getUid(userId, p.applicationInfo.uid); 1912 } 1913 PackageSetting ps = mSettings.mPackages.get(packageName); 1914 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 1915 return -1; 1916 } 1917 p = ps.pkg; 1918 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 1919 } 1920 } 1921 1922 @Override 1923 public int[] getPackageGids(String packageName) { 1924 // reader 1925 synchronized (mPackages) { 1926 PackageParser.Package p = mPackages.get(packageName); 1927 if (DEBUG_PACKAGE_INFO) 1928 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 1929 if (p != null) { 1930 final PackageSetting ps = (PackageSetting)p.mExtras; 1931 return ps.getGids(); 1932 } 1933 } 1934 // stupid thing to indicate an error. 1935 return new int[0]; 1936 } 1937 1938 static final PermissionInfo generatePermissionInfo( 1939 BasePermission bp, int flags) { 1940 if (bp.perm != null) { 1941 return PackageParser.generatePermissionInfo(bp.perm, flags); 1942 } 1943 PermissionInfo pi = new PermissionInfo(); 1944 pi.name = bp.name; 1945 pi.packageName = bp.sourcePackage; 1946 pi.nonLocalizedLabel = bp.name; 1947 pi.protectionLevel = bp.protectionLevel; 1948 return pi; 1949 } 1950 1951 @Override 1952 public PermissionInfo getPermissionInfo(String name, int flags) { 1953 // reader 1954 synchronized (mPackages) { 1955 final BasePermission p = mSettings.mPermissions.get(name); 1956 if (p != null) { 1957 return generatePermissionInfo(p, flags); 1958 } 1959 return null; 1960 } 1961 } 1962 1963 @Override 1964 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 1965 // reader 1966 synchronized (mPackages) { 1967 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 1968 for (BasePermission p : mSettings.mPermissions.values()) { 1969 if (group == null) { 1970 if (p.perm == null || p.perm.info.group == null) { 1971 out.add(generatePermissionInfo(p, flags)); 1972 } 1973 } else { 1974 if (p.perm != null && group.equals(p.perm.info.group)) { 1975 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 1976 } 1977 } 1978 } 1979 1980 if (out.size() > 0) { 1981 return out; 1982 } 1983 return mPermissionGroups.containsKey(group) ? out : null; 1984 } 1985 } 1986 1987 @Override 1988 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 1989 // reader 1990 synchronized (mPackages) { 1991 return PackageParser.generatePermissionGroupInfo( 1992 mPermissionGroups.get(name), flags); 1993 } 1994 } 1995 1996 @Override 1997 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 1998 // reader 1999 synchronized (mPackages) { 2000 final int N = mPermissionGroups.size(); 2001 ArrayList<PermissionGroupInfo> out 2002 = new ArrayList<PermissionGroupInfo>(N); 2003 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2004 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2005 } 2006 return out; 2007 } 2008 } 2009 2010 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2011 int userId) { 2012 if (!sUserManager.exists(userId)) return null; 2013 PackageSetting ps = mSettings.mPackages.get(packageName); 2014 if (ps != null) { 2015 if (ps.pkg == null) { 2016 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2017 flags, userId); 2018 if (pInfo != null) { 2019 return pInfo.applicationInfo; 2020 } 2021 return null; 2022 } 2023 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2024 ps.readUserState(userId), userId); 2025 } 2026 return null; 2027 } 2028 2029 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2030 int userId) { 2031 if (!sUserManager.exists(userId)) return null; 2032 PackageSetting ps = mSettings.mPackages.get(packageName); 2033 if (ps != null) { 2034 PackageParser.Package pkg = ps.pkg; 2035 if (pkg == null) { 2036 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2037 return null; 2038 } 2039 // Only data remains, so we aren't worried about code paths 2040 pkg = new PackageParser.Package(packageName); 2041 pkg.applicationInfo.packageName = packageName; 2042 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2043 pkg.applicationInfo.dataDir = 2044 getDataPathForPackage(packageName, 0).getPath(); 2045 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2046 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2047 } 2048 return generatePackageInfo(pkg, flags, userId); 2049 } 2050 return null; 2051 } 2052 2053 @Override 2054 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2055 if (!sUserManager.exists(userId)) return null; 2056 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info"); 2057 // writer 2058 synchronized (mPackages) { 2059 PackageParser.Package p = mPackages.get(packageName); 2060 if (DEBUG_PACKAGE_INFO) Log.v( 2061 TAG, "getApplicationInfo " + packageName 2062 + ": " + p); 2063 if (p != null) { 2064 PackageSetting ps = mSettings.mPackages.get(packageName); 2065 if (ps == null) return null; 2066 // Note: isEnabledLP() does not apply here - always return info 2067 return PackageParser.generateApplicationInfo( 2068 p, flags, ps.readUserState(userId), userId); 2069 } 2070 if ("android".equals(packageName)||"system".equals(packageName)) { 2071 return mAndroidApplication; 2072 } 2073 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2074 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2075 } 2076 } 2077 return null; 2078 } 2079 2080 2081 @Override 2082 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2083 mContext.enforceCallingOrSelfPermission( 2084 android.Manifest.permission.CLEAR_APP_CACHE, null); 2085 // Queue up an async operation since clearing cache may take a little while. 2086 mHandler.post(new Runnable() { 2087 public void run() { 2088 mHandler.removeCallbacks(this); 2089 int retCode = -1; 2090 synchronized (mInstallLock) { 2091 retCode = mInstaller.freeCache(freeStorageSize); 2092 if (retCode < 0) { 2093 Slog.w(TAG, "Couldn't clear application caches"); 2094 } 2095 } 2096 if (observer != null) { 2097 try { 2098 observer.onRemoveCompleted(null, (retCode >= 0)); 2099 } catch (RemoteException e) { 2100 Slog.w(TAG, "RemoveException when invoking call back"); 2101 } 2102 } 2103 } 2104 }); 2105 } 2106 2107 @Override 2108 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2109 mContext.enforceCallingOrSelfPermission( 2110 android.Manifest.permission.CLEAR_APP_CACHE, null); 2111 // Queue up an async operation since clearing cache may take a little while. 2112 mHandler.post(new Runnable() { 2113 public void run() { 2114 mHandler.removeCallbacks(this); 2115 int retCode = -1; 2116 synchronized (mInstallLock) { 2117 retCode = mInstaller.freeCache(freeStorageSize); 2118 if (retCode < 0) { 2119 Slog.w(TAG, "Couldn't clear application caches"); 2120 } 2121 } 2122 if(pi != null) { 2123 try { 2124 // Callback via pending intent 2125 int code = (retCode >= 0) ? 1 : 0; 2126 pi.sendIntent(null, code, null, 2127 null, null); 2128 } catch (SendIntentException e1) { 2129 Slog.i(TAG, "Failed to send pending intent"); 2130 } 2131 } 2132 } 2133 }); 2134 } 2135 2136 void freeStorage(long freeStorageSize) throws IOException { 2137 synchronized (mInstallLock) { 2138 if (mInstaller.freeCache(freeStorageSize) < 0) { 2139 throw new IOException("Failed to free enough space"); 2140 } 2141 } 2142 } 2143 2144 @Override 2145 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2146 if (!sUserManager.exists(userId)) return null; 2147 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info"); 2148 synchronized (mPackages) { 2149 PackageParser.Activity a = mActivities.mActivities.get(component); 2150 2151 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2152 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2153 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2154 if (ps == null) return null; 2155 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2156 userId); 2157 } 2158 if (mResolveComponentName.equals(component)) { 2159 return mResolveActivity; 2160 } 2161 } 2162 return null; 2163 } 2164 2165 @Override 2166 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2167 String resolvedType) { 2168 synchronized (mPackages) { 2169 PackageParser.Activity a = mActivities.mActivities.get(component); 2170 if (a == null) { 2171 return false; 2172 } 2173 for (int i=0; i<a.intents.size(); i++) { 2174 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2175 intent.getData(), intent.getCategories(), TAG) >= 0) { 2176 return true; 2177 } 2178 } 2179 return false; 2180 } 2181 } 2182 2183 @Override 2184 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2185 if (!sUserManager.exists(userId)) return null; 2186 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info"); 2187 synchronized (mPackages) { 2188 PackageParser.Activity a = mReceivers.mActivities.get(component); 2189 if (DEBUG_PACKAGE_INFO) Log.v( 2190 TAG, "getReceiverInfo " + component + ": " + a); 2191 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2192 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2193 if (ps == null) return null; 2194 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2195 userId); 2196 } 2197 } 2198 return null; 2199 } 2200 2201 @Override 2202 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2203 if (!sUserManager.exists(userId)) return null; 2204 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info"); 2205 synchronized (mPackages) { 2206 PackageParser.Service s = mServices.mServices.get(component); 2207 if (DEBUG_PACKAGE_INFO) Log.v( 2208 TAG, "getServiceInfo " + component + ": " + s); 2209 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2210 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2211 if (ps == null) return null; 2212 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2213 userId); 2214 } 2215 } 2216 return null; 2217 } 2218 2219 @Override 2220 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2221 if (!sUserManager.exists(userId)) return null; 2222 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info"); 2223 synchronized (mPackages) { 2224 PackageParser.Provider p = mProviders.mProviders.get(component); 2225 if (DEBUG_PACKAGE_INFO) Log.v( 2226 TAG, "getProviderInfo " + component + ": " + p); 2227 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2228 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2229 if (ps == null) return null; 2230 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2231 userId); 2232 } 2233 } 2234 return null; 2235 } 2236 2237 @Override 2238 public String[] getSystemSharedLibraryNames() { 2239 Set<String> libSet; 2240 synchronized (mPackages) { 2241 libSet = mSharedLibraries.keySet(); 2242 int size = libSet.size(); 2243 if (size > 0) { 2244 String[] libs = new String[size]; 2245 libSet.toArray(libs); 2246 return libs; 2247 } 2248 } 2249 return null; 2250 } 2251 2252 @Override 2253 public FeatureInfo[] getSystemAvailableFeatures() { 2254 Collection<FeatureInfo> featSet; 2255 synchronized (mPackages) { 2256 featSet = mAvailableFeatures.values(); 2257 int size = featSet.size(); 2258 if (size > 0) { 2259 FeatureInfo[] features = new FeatureInfo[size+1]; 2260 featSet.toArray(features); 2261 FeatureInfo fi = new FeatureInfo(); 2262 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2263 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2264 features[size] = fi; 2265 return features; 2266 } 2267 } 2268 return null; 2269 } 2270 2271 @Override 2272 public boolean hasSystemFeature(String name) { 2273 synchronized (mPackages) { 2274 return mAvailableFeatures.containsKey(name); 2275 } 2276 } 2277 2278 private void checkValidCaller(int uid, int userId) { 2279 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2280 return; 2281 2282 throw new SecurityException("Caller uid=" + uid 2283 + " is not privileged to communicate with user=" + userId); 2284 } 2285 2286 @Override 2287 public int checkPermission(String permName, String pkgName) { 2288 synchronized (mPackages) { 2289 PackageParser.Package p = mPackages.get(pkgName); 2290 if (p != null && p.mExtras != null) { 2291 PackageSetting ps = (PackageSetting)p.mExtras; 2292 if (ps.sharedUser != null) { 2293 if (ps.sharedUser.grantedPermissions.contains(permName)) { 2294 return PackageManager.PERMISSION_GRANTED; 2295 } 2296 } else if (ps.grantedPermissions.contains(permName)) { 2297 return PackageManager.PERMISSION_GRANTED; 2298 } 2299 } 2300 } 2301 return PackageManager.PERMISSION_DENIED; 2302 } 2303 2304 @Override 2305 public int checkUidPermission(String permName, int uid) { 2306 synchronized (mPackages) { 2307 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2308 if (obj != null) { 2309 GrantedPermissions gp = (GrantedPermissions)obj; 2310 if (gp.grantedPermissions.contains(permName)) { 2311 return PackageManager.PERMISSION_GRANTED; 2312 } 2313 } else { 2314 HashSet<String> perms = mSystemPermissions.get(uid); 2315 if (perms != null && perms.contains(permName)) { 2316 return PackageManager.PERMISSION_GRANTED; 2317 } 2318 } 2319 } 2320 return PackageManager.PERMISSION_DENIED; 2321 } 2322 2323 /** 2324 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2325 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2326 * @param message the message to log on security exception 2327 */ 2328 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2329 String message) { 2330 if (userId < 0) { 2331 throw new IllegalArgumentException("Invalid userId " + userId); 2332 } 2333 if (userId == UserHandle.getUserId(callingUid)) return; 2334 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2335 if (requireFullPermission) { 2336 mContext.enforceCallingOrSelfPermission( 2337 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2338 } else { 2339 try { 2340 mContext.enforceCallingOrSelfPermission( 2341 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2342 } catch (SecurityException se) { 2343 mContext.enforceCallingOrSelfPermission( 2344 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2345 } 2346 } 2347 } 2348 } 2349 2350 private BasePermission findPermissionTreeLP(String permName) { 2351 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2352 if (permName.startsWith(bp.name) && 2353 permName.length() > bp.name.length() && 2354 permName.charAt(bp.name.length()) == '.') { 2355 return bp; 2356 } 2357 } 2358 return null; 2359 } 2360 2361 private BasePermission checkPermissionTreeLP(String permName) { 2362 if (permName != null) { 2363 BasePermission bp = findPermissionTreeLP(permName); 2364 if (bp != null) { 2365 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2366 return bp; 2367 } 2368 throw new SecurityException("Calling uid " 2369 + Binder.getCallingUid() 2370 + " is not allowed to add to permission tree " 2371 + bp.name + " owned by uid " + bp.uid); 2372 } 2373 } 2374 throw new SecurityException("No permission tree found for " + permName); 2375 } 2376 2377 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2378 if (s1 == null) { 2379 return s2 == null; 2380 } 2381 if (s2 == null) { 2382 return false; 2383 } 2384 if (s1.getClass() != s2.getClass()) { 2385 return false; 2386 } 2387 return s1.equals(s2); 2388 } 2389 2390 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2391 if (pi1.icon != pi2.icon) return false; 2392 if (pi1.logo != pi2.logo) return false; 2393 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2394 if (!compareStrings(pi1.name, pi2.name)) return false; 2395 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2396 // We'll take care of setting this one. 2397 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2398 // These are not currently stored in settings. 2399 //if (!compareStrings(pi1.group, pi2.group)) return false; 2400 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2401 //if (pi1.labelRes != pi2.labelRes) return false; 2402 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2403 return true; 2404 } 2405 2406 int permissionInfoFootprint(PermissionInfo info) { 2407 int size = info.name.length(); 2408 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2409 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2410 return size; 2411 } 2412 2413 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2414 int size = 0; 2415 for (BasePermission perm : mSettings.mPermissions.values()) { 2416 if (perm.uid == tree.uid) { 2417 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2418 } 2419 } 2420 return size; 2421 } 2422 2423 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2424 // We calculate the max size of permissions defined by this uid and throw 2425 // if that plus the size of 'info' would exceed our stated maximum. 2426 if (tree.uid != Process.SYSTEM_UID) { 2427 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2428 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2429 throw new SecurityException("Permission tree size cap exceeded"); 2430 } 2431 } 2432 } 2433 2434 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2435 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2436 throw new SecurityException("Label must be specified in permission"); 2437 } 2438 BasePermission tree = checkPermissionTreeLP(info.name); 2439 BasePermission bp = mSettings.mPermissions.get(info.name); 2440 boolean added = bp == null; 2441 boolean changed = true; 2442 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2443 if (added) { 2444 enforcePermissionCapLocked(info, tree); 2445 bp = new BasePermission(info.name, tree.sourcePackage, 2446 BasePermission.TYPE_DYNAMIC); 2447 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2448 throw new SecurityException( 2449 "Not allowed to modify non-dynamic permission " 2450 + info.name); 2451 } else { 2452 if (bp.protectionLevel == fixedLevel 2453 && bp.perm.owner.equals(tree.perm.owner) 2454 && bp.uid == tree.uid 2455 && comparePermissionInfos(bp.perm.info, info)) { 2456 changed = false; 2457 } 2458 } 2459 bp.protectionLevel = fixedLevel; 2460 info = new PermissionInfo(info); 2461 info.protectionLevel = fixedLevel; 2462 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 2463 bp.perm.info.packageName = tree.perm.info.packageName; 2464 bp.uid = tree.uid; 2465 if (added) { 2466 mSettings.mPermissions.put(info.name, bp); 2467 } 2468 if (changed) { 2469 if (!async) { 2470 mSettings.writeLPr(); 2471 } else { 2472 scheduleWriteSettingsLocked(); 2473 } 2474 } 2475 return added; 2476 } 2477 2478 @Override 2479 public boolean addPermission(PermissionInfo info) { 2480 synchronized (mPackages) { 2481 return addPermissionLocked(info, false); 2482 } 2483 } 2484 2485 @Override 2486 public boolean addPermissionAsync(PermissionInfo info) { 2487 synchronized (mPackages) { 2488 return addPermissionLocked(info, true); 2489 } 2490 } 2491 2492 @Override 2493 public void removePermission(String name) { 2494 synchronized (mPackages) { 2495 checkPermissionTreeLP(name); 2496 BasePermission bp = mSettings.mPermissions.get(name); 2497 if (bp != null) { 2498 if (bp.type != BasePermission.TYPE_DYNAMIC) { 2499 throw new SecurityException( 2500 "Not allowed to modify non-dynamic permission " 2501 + name); 2502 } 2503 mSettings.mPermissions.remove(name); 2504 mSettings.writeLPr(); 2505 } 2506 } 2507 } 2508 2509 private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) { 2510 int index = pkg.requestedPermissions.indexOf(bp.name); 2511 if (index == -1) { 2512 throw new SecurityException("Package " + pkg.packageName 2513 + " has not requested permission " + bp.name); 2514 } 2515 boolean isNormal = 2516 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2517 == PermissionInfo.PROTECTION_NORMAL); 2518 boolean isDangerous = 2519 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2520 == PermissionInfo.PROTECTION_DANGEROUS); 2521 boolean isDevelopment = 2522 ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0); 2523 2524 if (!isNormal && !isDangerous && !isDevelopment) { 2525 throw new SecurityException("Permission " + bp.name 2526 + " is not a changeable permission type"); 2527 } 2528 2529 if (isNormal || isDangerous) { 2530 if (pkg.requestedPermissionsRequired.get(index)) { 2531 throw new SecurityException("Can't change " + bp.name 2532 + ". It is required by the application"); 2533 } 2534 } 2535 } 2536 2537 @Override 2538 public void grantPermission(String packageName, String permissionName) { 2539 mContext.enforceCallingOrSelfPermission( 2540 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2541 synchronized (mPackages) { 2542 final PackageParser.Package pkg = mPackages.get(packageName); 2543 if (pkg == null) { 2544 throw new IllegalArgumentException("Unknown package: " + packageName); 2545 } 2546 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2547 if (bp == null) { 2548 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2549 } 2550 2551 checkGrantRevokePermissions(pkg, bp); 2552 2553 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2554 if (ps == null) { 2555 return; 2556 } 2557 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2558 if (gp.grantedPermissions.add(permissionName)) { 2559 if (ps.haveGids) { 2560 gp.gids = appendInts(gp.gids, bp.gids); 2561 } 2562 mSettings.writeLPr(); 2563 } 2564 } 2565 } 2566 2567 @Override 2568 public void revokePermission(String packageName, String permissionName) { 2569 int changedAppId = -1; 2570 2571 synchronized (mPackages) { 2572 final PackageParser.Package pkg = mPackages.get(packageName); 2573 if (pkg == null) { 2574 throw new IllegalArgumentException("Unknown package: " + packageName); 2575 } 2576 if (pkg.applicationInfo.uid != Binder.getCallingUid()) { 2577 mContext.enforceCallingOrSelfPermission( 2578 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2579 } 2580 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2581 if (bp == null) { 2582 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2583 } 2584 2585 checkGrantRevokePermissions(pkg, bp); 2586 2587 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2588 if (ps == null) { 2589 return; 2590 } 2591 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2592 if (gp.grantedPermissions.remove(permissionName)) { 2593 gp.grantedPermissions.remove(permissionName); 2594 if (ps.haveGids) { 2595 gp.gids = removeInts(gp.gids, bp.gids); 2596 } 2597 mSettings.writeLPr(); 2598 changedAppId = ps.appId; 2599 } 2600 } 2601 2602 if (changedAppId >= 0) { 2603 // We changed the perm on someone, kill its processes. 2604 IActivityManager am = ActivityManagerNative.getDefault(); 2605 if (am != null) { 2606 final int callingUserId = UserHandle.getCallingUserId(); 2607 final long ident = Binder.clearCallingIdentity(); 2608 try { 2609 //XXX we should only revoke for the calling user's app permissions, 2610 // but for now we impact all users. 2611 //am.killUid(UserHandle.getUid(callingUserId, changedAppId), 2612 // "revoke " + permissionName); 2613 int[] users = sUserManager.getUserIds(); 2614 for (int user : users) { 2615 am.killUid(UserHandle.getUid(user, changedAppId), 2616 "revoke " + permissionName); 2617 } 2618 } catch (RemoteException e) { 2619 } finally { 2620 Binder.restoreCallingIdentity(ident); 2621 } 2622 } 2623 } 2624 } 2625 2626 @Override 2627 public boolean isProtectedBroadcast(String actionName) { 2628 synchronized (mPackages) { 2629 return mProtectedBroadcasts.contains(actionName); 2630 } 2631 } 2632 2633 @Override 2634 public int checkSignatures(String pkg1, String pkg2) { 2635 synchronized (mPackages) { 2636 final PackageParser.Package p1 = mPackages.get(pkg1); 2637 final PackageParser.Package p2 = mPackages.get(pkg2); 2638 if (p1 == null || p1.mExtras == null 2639 || p2 == null || p2.mExtras == null) { 2640 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2641 } 2642 return compareSignatures(p1.mSignatures, p2.mSignatures); 2643 } 2644 } 2645 2646 @Override 2647 public int checkUidSignatures(int uid1, int uid2) { 2648 // Map to base uids. 2649 uid1 = UserHandle.getAppId(uid1); 2650 uid2 = UserHandle.getAppId(uid2); 2651 // reader 2652 synchronized (mPackages) { 2653 Signature[] s1; 2654 Signature[] s2; 2655 Object obj = mSettings.getUserIdLPr(uid1); 2656 if (obj != null) { 2657 if (obj instanceof SharedUserSetting) { 2658 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 2659 } else if (obj instanceof PackageSetting) { 2660 s1 = ((PackageSetting)obj).signatures.mSignatures; 2661 } else { 2662 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2663 } 2664 } else { 2665 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2666 } 2667 obj = mSettings.getUserIdLPr(uid2); 2668 if (obj != null) { 2669 if (obj instanceof SharedUserSetting) { 2670 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 2671 } else if (obj instanceof PackageSetting) { 2672 s2 = ((PackageSetting)obj).signatures.mSignatures; 2673 } else { 2674 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2675 } 2676 } else { 2677 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2678 } 2679 return compareSignatures(s1, s2); 2680 } 2681 } 2682 2683 /** 2684 * Compares two sets of signatures. Returns: 2685 * <br /> 2686 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 2687 * <br /> 2688 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 2689 * <br /> 2690 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 2691 * <br /> 2692 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 2693 * <br /> 2694 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 2695 */ 2696 static int compareSignatures(Signature[] s1, Signature[] s2) { 2697 if (s1 == null) { 2698 return s2 == null 2699 ? PackageManager.SIGNATURE_NEITHER_SIGNED 2700 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 2701 } 2702 2703 if (s2 == null) { 2704 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 2705 } 2706 2707 if (s1.length != s2.length) { 2708 return PackageManager.SIGNATURE_NO_MATCH; 2709 } 2710 2711 // Since both signature sets are of size 1, we can compare without HashSets. 2712 if (s1.length == 1) { 2713 return s1[0].equals(s2[0]) ? 2714 PackageManager.SIGNATURE_MATCH : 2715 PackageManager.SIGNATURE_NO_MATCH; 2716 } 2717 2718 HashSet<Signature> set1 = new HashSet<Signature>(); 2719 for (Signature sig : s1) { 2720 set1.add(sig); 2721 } 2722 HashSet<Signature> set2 = new HashSet<Signature>(); 2723 for (Signature sig : s2) { 2724 set2.add(sig); 2725 } 2726 // Make sure s2 contains all signatures in s1. 2727 if (set1.equals(set2)) { 2728 return PackageManager.SIGNATURE_MATCH; 2729 } 2730 return PackageManager.SIGNATURE_NO_MATCH; 2731 } 2732 2733 /** 2734 * If the database version for this type of package (internal storage or 2735 * external storage) is less than the version where package signatures 2736 * were updated, return true. 2737 */ 2738 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2739 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 2740 DatabaseVersion.SIGNATURE_END_ENTITY)) 2741 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 2742 DatabaseVersion.SIGNATURE_END_ENTITY)); 2743 } 2744 2745 /** 2746 * Used for backward compatibility to make sure any packages with 2747 * certificate chains get upgraded to the new style. {@code existingSigs} 2748 * will be in the old format (since they were stored on disk from before the 2749 * system upgrade) and {@code scannedSigs} will be in the newer format. 2750 */ 2751 private int compareSignaturesCompat(PackageSignatures existingSigs, 2752 PackageParser.Package scannedPkg) { 2753 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 2754 return PackageManager.SIGNATURE_NO_MATCH; 2755 } 2756 2757 HashSet<Signature> existingSet = new HashSet<Signature>(); 2758 for (Signature sig : existingSigs.mSignatures) { 2759 existingSet.add(sig); 2760 } 2761 HashSet<Signature> scannedCompatSet = new HashSet<Signature>(); 2762 for (Signature sig : scannedPkg.mSignatures) { 2763 try { 2764 Signature[] chainSignatures = sig.getChainSignatures(); 2765 for (Signature chainSig : chainSignatures) { 2766 scannedCompatSet.add(chainSig); 2767 } 2768 } catch (CertificateEncodingException e) { 2769 scannedCompatSet.add(sig); 2770 } 2771 } 2772 /* 2773 * Make sure the expanded scanned set contains all signatures in the 2774 * existing one. 2775 */ 2776 if (scannedCompatSet.equals(existingSet)) { 2777 // Migrate the old signatures to the new scheme. 2778 existingSigs.assignSignatures(scannedPkg.mSignatures); 2779 // The new KeySets will be re-added later in the scanning process. 2780 synchronized (mPackages) { 2781 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 2782 } 2783 return PackageManager.SIGNATURE_MATCH; 2784 } 2785 return PackageManager.SIGNATURE_NO_MATCH; 2786 } 2787 2788 @Override 2789 public String[] getPackagesForUid(int uid) { 2790 uid = UserHandle.getAppId(uid); 2791 // reader 2792 synchronized (mPackages) { 2793 Object obj = mSettings.getUserIdLPr(uid); 2794 if (obj instanceof SharedUserSetting) { 2795 final SharedUserSetting sus = (SharedUserSetting) obj; 2796 final int N = sus.packages.size(); 2797 final String[] res = new String[N]; 2798 final Iterator<PackageSetting> it = sus.packages.iterator(); 2799 int i = 0; 2800 while (it.hasNext()) { 2801 res[i++] = it.next().name; 2802 } 2803 return res; 2804 } else if (obj instanceof PackageSetting) { 2805 final PackageSetting ps = (PackageSetting) obj; 2806 return new String[] { ps.name }; 2807 } 2808 } 2809 return null; 2810 } 2811 2812 @Override 2813 public String getNameForUid(int uid) { 2814 // reader 2815 synchronized (mPackages) { 2816 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2817 if (obj instanceof SharedUserSetting) { 2818 final SharedUserSetting sus = (SharedUserSetting) obj; 2819 return sus.name + ":" + sus.userId; 2820 } else if (obj instanceof PackageSetting) { 2821 final PackageSetting ps = (PackageSetting) obj; 2822 return ps.name; 2823 } 2824 } 2825 return null; 2826 } 2827 2828 @Override 2829 public int getUidForSharedUser(String sharedUserName) { 2830 if(sharedUserName == null) { 2831 return -1; 2832 } 2833 // reader 2834 synchronized (mPackages) { 2835 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false); 2836 if (suid == null) { 2837 return -1; 2838 } 2839 return suid.userId; 2840 } 2841 } 2842 2843 @Override 2844 public int getFlagsForUid(int uid) { 2845 synchronized (mPackages) { 2846 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2847 if (obj instanceof SharedUserSetting) { 2848 final SharedUserSetting sus = (SharedUserSetting) obj; 2849 return sus.pkgFlags; 2850 } else if (obj instanceof PackageSetting) { 2851 final PackageSetting ps = (PackageSetting) obj; 2852 return ps.pkgFlags; 2853 } 2854 } 2855 return 0; 2856 } 2857 2858 @Override 2859 public String[] getAppOpPermissionPackages(String permissionName) { 2860 synchronized (mPackages) { 2861 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 2862 if (pkgs == null) { 2863 return null; 2864 } 2865 return pkgs.toArray(new String[pkgs.size()]); 2866 } 2867 } 2868 2869 @Override 2870 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 2871 int flags, int userId) { 2872 if (!sUserManager.exists(userId)) return null; 2873 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent"); 2874 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2875 return chooseBestActivity(intent, resolvedType, flags, query, userId); 2876 } 2877 2878 @Override 2879 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 2880 IntentFilter filter, int match, ComponentName activity) { 2881 final int userId = UserHandle.getCallingUserId(); 2882 if (DEBUG_PREFERRED) { 2883 Log.v(TAG, "setLastChosenActivity intent=" + intent 2884 + " resolvedType=" + resolvedType 2885 + " flags=" + flags 2886 + " filter=" + filter 2887 + " match=" + match 2888 + " activity=" + activity); 2889 filter.dump(new PrintStreamPrinter(System.out), " "); 2890 } 2891 intent.setComponent(null); 2892 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2893 // Find any earlier preferred or last chosen entries and nuke them 2894 findPreferredActivity(intent, resolvedType, 2895 flags, query, 0, false, true, false, userId); 2896 // Add the new activity as the last chosen for this filter 2897 addPreferredActivityInternal(filter, match, null, activity, false, userId, 2898 "Setting last chosen"); 2899 } 2900 2901 @Override 2902 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 2903 final int userId = UserHandle.getCallingUserId(); 2904 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 2905 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2906 return findPreferredActivity(intent, resolvedType, flags, query, 0, 2907 false, false, false, userId); 2908 } 2909 2910 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 2911 int flags, List<ResolveInfo> query, int userId) { 2912 if (query != null) { 2913 final int N = query.size(); 2914 if (N == 1) { 2915 return query.get(0); 2916 } else if (N > 1) { 2917 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 2918 // If there is more than one activity with the same priority, 2919 // then let the user decide between them. 2920 ResolveInfo r0 = query.get(0); 2921 ResolveInfo r1 = query.get(1); 2922 if (DEBUG_INTENT_MATCHING || debug) { 2923 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 2924 + r1.activityInfo.name + "=" + r1.priority); 2925 } 2926 // If the first activity has a higher priority, or a different 2927 // default, then it is always desireable to pick it. 2928 if (r0.priority != r1.priority 2929 || r0.preferredOrder != r1.preferredOrder 2930 || r0.isDefault != r1.isDefault) { 2931 return query.get(0); 2932 } 2933 // If we have saved a preference for a preferred activity for 2934 // this Intent, use that. 2935 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 2936 flags, query, r0.priority, true, false, debug, userId); 2937 if (ri != null) { 2938 return ri; 2939 } 2940 if (userId != 0) { 2941 ri = new ResolveInfo(mResolveInfo); 2942 ri.activityInfo = new ActivityInfo(ri.activityInfo); 2943 ri.activityInfo.applicationInfo = new ApplicationInfo( 2944 ri.activityInfo.applicationInfo); 2945 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 2946 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 2947 return ri; 2948 } 2949 return mResolveInfo; 2950 } 2951 } 2952 return null; 2953 } 2954 2955 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 2956 int flags, List<ResolveInfo> query, boolean debug, int userId) { 2957 final int N = query.size(); 2958 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 2959 .get(userId); 2960 // Get the list of persistent preferred activities that handle the intent 2961 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 2962 List<PersistentPreferredActivity> pprefs = ppir != null 2963 ? ppir.queryIntent(intent, resolvedType, 2964 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 2965 : null; 2966 if (pprefs != null && pprefs.size() > 0) { 2967 final int M = pprefs.size(); 2968 for (int i=0; i<M; i++) { 2969 final PersistentPreferredActivity ppa = pprefs.get(i); 2970 if (DEBUG_PREFERRED || debug) { 2971 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 2972 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 2973 + "\n component=" + ppa.mComponent); 2974 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 2975 } 2976 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 2977 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 2978 if (DEBUG_PREFERRED || debug) { 2979 Slog.v(TAG, "Found persistent preferred activity:"); 2980 if (ai != null) { 2981 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 2982 } else { 2983 Slog.v(TAG, " null"); 2984 } 2985 } 2986 if (ai == null) { 2987 // This previously registered persistent preferred activity 2988 // component is no longer known. Ignore it and do NOT remove it. 2989 continue; 2990 } 2991 for (int j=0; j<N; j++) { 2992 final ResolveInfo ri = query.get(j); 2993 if (!ri.activityInfo.applicationInfo.packageName 2994 .equals(ai.applicationInfo.packageName)) { 2995 continue; 2996 } 2997 if (!ri.activityInfo.name.equals(ai.name)) { 2998 continue; 2999 } 3000 // Found a persistent preference that can handle the intent. 3001 if (DEBUG_PREFERRED || debug) { 3002 Slog.v(TAG, "Returning persistent preferred activity: " + 3003 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3004 } 3005 return ri; 3006 } 3007 } 3008 } 3009 return null; 3010 } 3011 3012 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3013 List<ResolveInfo> query, int priority, boolean always, 3014 boolean removeMatches, boolean debug, int userId) { 3015 if (!sUserManager.exists(userId)) return null; 3016 // writer 3017 synchronized (mPackages) { 3018 if (intent.getSelector() != null) { 3019 intent = intent.getSelector(); 3020 } 3021 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3022 3023 // Try to find a matching persistent preferred activity. 3024 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3025 debug, userId); 3026 3027 // If a persistent preferred activity matched, use it. 3028 if (pri != null) { 3029 return pri; 3030 } 3031 3032 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3033 // Get the list of preferred activities that handle the intent 3034 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3035 List<PreferredActivity> prefs = pir != null 3036 ? pir.queryIntent(intent, resolvedType, 3037 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3038 : null; 3039 if (prefs != null && prefs.size() > 0) { 3040 boolean changed = false; 3041 try { 3042 // First figure out how good the original match set is. 3043 // We will only allow preferred activities that came 3044 // from the same match quality. 3045 int match = 0; 3046 3047 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3048 3049 final int N = query.size(); 3050 for (int j=0; j<N; j++) { 3051 final ResolveInfo ri = query.get(j); 3052 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3053 + ": 0x" + Integer.toHexString(match)); 3054 if (ri.match > match) { 3055 match = ri.match; 3056 } 3057 } 3058 3059 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3060 + Integer.toHexString(match)); 3061 3062 match &= IntentFilter.MATCH_CATEGORY_MASK; 3063 final int M = prefs.size(); 3064 for (int i=0; i<M; i++) { 3065 final PreferredActivity pa = prefs.get(i); 3066 if (DEBUG_PREFERRED || debug) { 3067 Slog.v(TAG, "Checking PreferredActivity ds=" 3068 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3069 + "\n component=" + pa.mPref.mComponent); 3070 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3071 } 3072 if (pa.mPref.mMatch != match) { 3073 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3074 + Integer.toHexString(pa.mPref.mMatch)); 3075 continue; 3076 } 3077 // If it's not an "always" type preferred activity and that's what we're 3078 // looking for, skip it. 3079 if (always && !pa.mPref.mAlways) { 3080 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3081 continue; 3082 } 3083 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3084 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3085 if (DEBUG_PREFERRED || debug) { 3086 Slog.v(TAG, "Found preferred activity:"); 3087 if (ai != null) { 3088 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3089 } else { 3090 Slog.v(TAG, " null"); 3091 } 3092 } 3093 if (ai == null) { 3094 // This previously registered preferred activity 3095 // component is no longer known. Most likely an update 3096 // to the app was installed and in the new version this 3097 // component no longer exists. Clean it up by removing 3098 // it from the preferred activities list, and skip it. 3099 Slog.w(TAG, "Removing dangling preferred activity: " 3100 + pa.mPref.mComponent); 3101 pir.removeFilter(pa); 3102 changed = true; 3103 continue; 3104 } 3105 for (int j=0; j<N; j++) { 3106 final ResolveInfo ri = query.get(j); 3107 if (!ri.activityInfo.applicationInfo.packageName 3108 .equals(ai.applicationInfo.packageName)) { 3109 continue; 3110 } 3111 if (!ri.activityInfo.name.equals(ai.name)) { 3112 continue; 3113 } 3114 3115 if (removeMatches) { 3116 pir.removeFilter(pa); 3117 changed = true; 3118 if (DEBUG_PREFERRED) { 3119 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3120 } 3121 break; 3122 } 3123 3124 // Okay we found a previously set preferred or last chosen app. 3125 // If the result set is different from when this 3126 // was created, we need to clear it and re-ask the 3127 // user their preference, if we're looking for an "always" type entry. 3128 if (always && !pa.mPref.sameSet(query, priority)) { 3129 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3130 + intent + " type " + resolvedType); 3131 if (DEBUG_PREFERRED) { 3132 Slog.v(TAG, "Removing preferred activity since set changed " 3133 + pa.mPref.mComponent); 3134 } 3135 pir.removeFilter(pa); 3136 // Re-add the filter as a "last chosen" entry (!always) 3137 PreferredActivity lastChosen = new PreferredActivity( 3138 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3139 pir.addFilter(lastChosen); 3140 changed = true; 3141 return null; 3142 } 3143 3144 // Yay! Either the set matched or we're looking for the last chosen 3145 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3146 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3147 return ri; 3148 } 3149 } 3150 } finally { 3151 if (changed) { 3152 if (DEBUG_PREFERRED) { 3153 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 3154 } 3155 mSettings.writePackageRestrictionsLPr(userId); 3156 } 3157 } 3158 } 3159 } 3160 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3161 return null; 3162 } 3163 3164 /* 3165 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3166 */ 3167 @Override 3168 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3169 int targetUserId) { 3170 mContext.enforceCallingOrSelfPermission( 3171 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3172 List<CrossProfileIntentFilter> matches = 3173 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3174 if (matches != null) { 3175 int size = matches.size(); 3176 for (int i = 0; i < size; i++) { 3177 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3178 } 3179 } 3180 ArrayList<String> packageNames = null; 3181 SparseArray<ArrayList<String>> fromSource = 3182 mSettings.mCrossProfilePackageInfo.get(sourceUserId); 3183 if (fromSource != null) { 3184 packageNames = fromSource.get(targetUserId); 3185 if (packageNames != null) { 3186 // We need the package name, so we try to resolve with the loosest flags possible 3187 List<ResolveInfo> resolveInfos = mActivities.queryIntent(intent, resolvedType, 3188 PackageManager.GET_UNINSTALLED_PACKAGES, targetUserId); 3189 int count = resolveInfos.size(); 3190 for (int i = 0; i < count; i++) { 3191 ResolveInfo resolveInfo = resolveInfos.get(i); 3192 if (packageNames.contains(resolveInfo.activityInfo.packageName)) { 3193 return true; 3194 } 3195 } 3196 } 3197 } 3198 return false; 3199 } 3200 3201 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3202 String resolvedType, int userId) { 3203 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3204 if (resolver != null) { 3205 return resolver.queryIntent(intent, resolvedType, false, userId); 3206 } 3207 return null; 3208 } 3209 3210 @Override 3211 public List<ResolveInfo> queryIntentActivities(Intent intent, 3212 String resolvedType, int flags, int userId) { 3213 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3214 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities"); 3215 ComponentName comp = intent.getComponent(); 3216 if (comp == null) { 3217 if (intent.getSelector() != null) { 3218 intent = intent.getSelector(); 3219 comp = intent.getComponent(); 3220 } 3221 } 3222 3223 if (comp != null) { 3224 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3225 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3226 if (ai != null) { 3227 final ResolveInfo ri = new ResolveInfo(); 3228 ri.activityInfo = ai; 3229 list.add(ri); 3230 } 3231 return list; 3232 } 3233 3234 // reader 3235 synchronized (mPackages) { 3236 final String pkgName = intent.getPackage(); 3237 boolean queryCrossProfile = (flags & PackageManager.NO_CROSS_PROFILE) == 0; 3238 if (pkgName == null) { 3239 ResolveInfo resolveInfo = null; 3240 if (queryCrossProfile) { 3241 // Check if the intent needs to be forwarded to another user for this package 3242 ArrayList<ResolveInfo> crossProfileResult = 3243 queryIntentActivitiesCrossProfilePackage( 3244 intent, resolvedType, flags, userId); 3245 if (!crossProfileResult.isEmpty()) { 3246 // Skip the current profile 3247 return crossProfileResult; 3248 } 3249 List<CrossProfileIntentFilter> matchingFilters = 3250 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3251 // Check for results that need to skip the current profile. 3252 resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3253 resolvedType, flags, userId); 3254 if (resolveInfo != null) { 3255 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3256 result.add(resolveInfo); 3257 return result; 3258 } 3259 // Check for cross profile results. 3260 resolveInfo = queryCrossProfileIntents( 3261 matchingFilters, intent, resolvedType, flags, userId); 3262 } 3263 // Check for results in the current profile. 3264 List<ResolveInfo> result = mActivities.queryIntent( 3265 intent, resolvedType, flags, userId); 3266 if (resolveInfo != null) { 3267 result.add(resolveInfo); 3268 Collections.sort(result, mResolvePrioritySorter); 3269 } 3270 return result; 3271 } 3272 final PackageParser.Package pkg = mPackages.get(pkgName); 3273 if (pkg != null) { 3274 if (queryCrossProfile) { 3275 ArrayList<ResolveInfo> crossProfileResult = 3276 queryIntentActivitiesCrossProfilePackage( 3277 intent, resolvedType, flags, userId, pkg, pkgName); 3278 if (!crossProfileResult.isEmpty()) { 3279 // Skip the current profile 3280 return crossProfileResult; 3281 } 3282 } 3283 return mActivities.queryIntentForPackage(intent, resolvedType, flags, 3284 pkg.activities, userId); 3285 } 3286 return new ArrayList<ResolveInfo>(); 3287 } 3288 } 3289 3290 private ResolveInfo querySkipCurrentProfileIntents( 3291 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3292 int flags, int sourceUserId) { 3293 if (matchingFilters != null) { 3294 int size = matchingFilters.size(); 3295 for (int i = 0; i < size; i ++) { 3296 CrossProfileIntentFilter filter = matchingFilters.get(i); 3297 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 3298 // Checking if there are activities in the target user that can handle the 3299 // intent. 3300 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3301 flags, sourceUserId); 3302 if (resolveInfo != null) { 3303 return resolveInfo; 3304 } 3305 } 3306 } 3307 } 3308 return null; 3309 } 3310 3311 private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage( 3312 Intent intent, String resolvedType, int flags, int userId) { 3313 ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>(); 3314 SparseArray<ArrayList<String>> sourceForwardingInfo = 3315 mSettings.mCrossProfilePackageInfo.get(userId); 3316 if (sourceForwardingInfo != null) { 3317 int NI = sourceForwardingInfo.size(); 3318 for (int i = 0; i < NI; i++) { 3319 int targetUserId = sourceForwardingInfo.keyAt(i); 3320 ArrayList<String> packageNames = sourceForwardingInfo.valueAt(i); 3321 List<ResolveInfo> resolveInfos = mActivities.queryIntent( 3322 intent, resolvedType, flags, targetUserId); 3323 int NJ = resolveInfos.size(); 3324 for (int j = 0; j < NJ; j++) { 3325 ResolveInfo resolveInfo = resolveInfos.get(j); 3326 if (packageNames.contains(resolveInfo.activityInfo.packageName)) { 3327 matchingResolveInfos.add(createForwardingResolveInfo( 3328 resolveInfo.filter, userId, targetUserId)); 3329 } 3330 } 3331 } 3332 } 3333 return matchingResolveInfos; 3334 } 3335 3336 private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage( 3337 Intent intent, String resolvedType, int flags, int userId, PackageParser.Package pkg, 3338 String packageName) { 3339 ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>(); 3340 SparseArray<ArrayList<String>> sourceForwardingInfo = 3341 mSettings.mCrossProfilePackageInfo.get(userId); 3342 if (sourceForwardingInfo != null) { 3343 int NI = sourceForwardingInfo.size(); 3344 for (int i = 0; i < NI; i++) { 3345 int targetUserId = sourceForwardingInfo.keyAt(i); 3346 if (sourceForwardingInfo.valueAt(i).contains(packageName)) { 3347 List<ResolveInfo> resolveInfos = mActivities.queryIntentForPackage( 3348 intent, resolvedType, flags, pkg.activities, targetUserId); 3349 int NJ = resolveInfos.size(); 3350 for (int j = 0; j < NJ; j++) { 3351 ResolveInfo resolveInfo = resolveInfos.get(j); 3352 matchingResolveInfos.add(createForwardingResolveInfo( 3353 resolveInfo.filter, userId, targetUserId)); 3354 } 3355 } 3356 } 3357 } 3358 return matchingResolveInfos; 3359 } 3360 3361 // Return matching ResolveInfo if any for skip current profile intent filters. 3362 private ResolveInfo queryCrossProfileIntents( 3363 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3364 int flags, int sourceUserId) { 3365 if (matchingFilters != null) { 3366 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 3367 // match the same intent. For performance reasons, it is better not to 3368 // run queryIntent twice for the same userId 3369 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 3370 int size = matchingFilters.size(); 3371 for (int i = 0; i < size; i++) { 3372 CrossProfileIntentFilter filter = matchingFilters.get(i); 3373 int targetUserId = filter.getTargetUserId(); 3374 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 3375 && !alreadyTriedUserIds.get(targetUserId)) { 3376 // Checking if there are activities in the target user that can handle the 3377 // intent. 3378 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3379 flags, sourceUserId); 3380 if (resolveInfo != null) return resolveInfo; 3381 alreadyTriedUserIds.put(targetUserId, true); 3382 } 3383 } 3384 } 3385 return null; 3386 } 3387 3388 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 3389 String resolvedType, int flags, int sourceUserId) { 3390 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 3391 resolvedType, flags, filter.getTargetUserId()); 3392 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 3393 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 3394 } 3395 return null; 3396 } 3397 3398 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 3399 int sourceUserId, int targetUserId) { 3400 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 3401 String className; 3402 if (targetUserId == UserHandle.USER_OWNER) { 3403 className = FORWARD_INTENT_TO_USER_OWNER; 3404 } else { 3405 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 3406 } 3407 ComponentName forwardingActivityComponentName = new ComponentName( 3408 mAndroidApplication.packageName, className); 3409 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 3410 sourceUserId); 3411 if (targetUserId == UserHandle.USER_OWNER) { 3412 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 3413 forwardingResolveInfo.noResourceId = true; 3414 } 3415 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 3416 forwardingResolveInfo.priority = 0; 3417 forwardingResolveInfo.preferredOrder = 0; 3418 forwardingResolveInfo.match = 0; 3419 forwardingResolveInfo.isDefault = true; 3420 forwardingResolveInfo.filter = filter; 3421 forwardingResolveInfo.targetUserId = targetUserId; 3422 return forwardingResolveInfo; 3423 } 3424 3425 @Override 3426 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 3427 Intent[] specifics, String[] specificTypes, Intent intent, 3428 String resolvedType, int flags, int userId) { 3429 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3430 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 3431 "query intent activity options"); 3432 final String resultsAction = intent.getAction(); 3433 3434 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 3435 | PackageManager.GET_RESOLVED_FILTER, userId); 3436 3437 if (DEBUG_INTENT_MATCHING) { 3438 Log.v(TAG, "Query " + intent + ": " + results); 3439 } 3440 3441 int specificsPos = 0; 3442 int N; 3443 3444 // todo: note that the algorithm used here is O(N^2). This 3445 // isn't a problem in our current environment, but if we start running 3446 // into situations where we have more than 5 or 10 matches then this 3447 // should probably be changed to something smarter... 3448 3449 // First we go through and resolve each of the specific items 3450 // that were supplied, taking care of removing any corresponding 3451 // duplicate items in the generic resolve list. 3452 if (specifics != null) { 3453 for (int i=0; i<specifics.length; i++) { 3454 final Intent sintent = specifics[i]; 3455 if (sintent == null) { 3456 continue; 3457 } 3458 3459 if (DEBUG_INTENT_MATCHING) { 3460 Log.v(TAG, "Specific #" + i + ": " + sintent); 3461 } 3462 3463 String action = sintent.getAction(); 3464 if (resultsAction != null && resultsAction.equals(action)) { 3465 // If this action was explicitly requested, then don't 3466 // remove things that have it. 3467 action = null; 3468 } 3469 3470 ResolveInfo ri = null; 3471 ActivityInfo ai = null; 3472 3473 ComponentName comp = sintent.getComponent(); 3474 if (comp == null) { 3475 ri = resolveIntent( 3476 sintent, 3477 specificTypes != null ? specificTypes[i] : null, 3478 flags, userId); 3479 if (ri == null) { 3480 continue; 3481 } 3482 if (ri == mResolveInfo) { 3483 // ACK! Must do something better with this. 3484 } 3485 ai = ri.activityInfo; 3486 comp = new ComponentName(ai.applicationInfo.packageName, 3487 ai.name); 3488 } else { 3489 ai = getActivityInfo(comp, flags, userId); 3490 if (ai == null) { 3491 continue; 3492 } 3493 } 3494 3495 // Look for any generic query activities that are duplicates 3496 // of this specific one, and remove them from the results. 3497 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 3498 N = results.size(); 3499 int j; 3500 for (j=specificsPos; j<N; j++) { 3501 ResolveInfo sri = results.get(j); 3502 if ((sri.activityInfo.name.equals(comp.getClassName()) 3503 && sri.activityInfo.applicationInfo.packageName.equals( 3504 comp.getPackageName())) 3505 || (action != null && sri.filter.matchAction(action))) { 3506 results.remove(j); 3507 if (DEBUG_INTENT_MATCHING) Log.v( 3508 TAG, "Removing duplicate item from " + j 3509 + " due to specific " + specificsPos); 3510 if (ri == null) { 3511 ri = sri; 3512 } 3513 j--; 3514 N--; 3515 } 3516 } 3517 3518 // Add this specific item to its proper place. 3519 if (ri == null) { 3520 ri = new ResolveInfo(); 3521 ri.activityInfo = ai; 3522 } 3523 results.add(specificsPos, ri); 3524 ri.specificIndex = i; 3525 specificsPos++; 3526 } 3527 } 3528 3529 // Now we go through the remaining generic results and remove any 3530 // duplicate actions that are found here. 3531 N = results.size(); 3532 for (int i=specificsPos; i<N-1; i++) { 3533 final ResolveInfo rii = results.get(i); 3534 if (rii.filter == null) { 3535 continue; 3536 } 3537 3538 // Iterate over all of the actions of this result's intent 3539 // filter... typically this should be just one. 3540 final Iterator<String> it = rii.filter.actionsIterator(); 3541 if (it == null) { 3542 continue; 3543 } 3544 while (it.hasNext()) { 3545 final String action = it.next(); 3546 if (resultsAction != null && resultsAction.equals(action)) { 3547 // If this action was explicitly requested, then don't 3548 // remove things that have it. 3549 continue; 3550 } 3551 for (int j=i+1; j<N; j++) { 3552 final ResolveInfo rij = results.get(j); 3553 if (rij.filter != null && rij.filter.hasAction(action)) { 3554 results.remove(j); 3555 if (DEBUG_INTENT_MATCHING) Log.v( 3556 TAG, "Removing duplicate item from " + j 3557 + " due to action " + action + " at " + i); 3558 j--; 3559 N--; 3560 } 3561 } 3562 } 3563 3564 // If the caller didn't request filter information, drop it now 3565 // so we don't have to marshall/unmarshall it. 3566 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3567 rii.filter = null; 3568 } 3569 } 3570 3571 // Filter out the caller activity if so requested. 3572 if (caller != null) { 3573 N = results.size(); 3574 for (int i=0; i<N; i++) { 3575 ActivityInfo ainfo = results.get(i).activityInfo; 3576 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 3577 && caller.getClassName().equals(ainfo.name)) { 3578 results.remove(i); 3579 break; 3580 } 3581 } 3582 } 3583 3584 // If the caller didn't request filter information, 3585 // drop them now so we don't have to 3586 // marshall/unmarshall it. 3587 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3588 N = results.size(); 3589 for (int i=0; i<N; i++) { 3590 results.get(i).filter = null; 3591 } 3592 } 3593 3594 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 3595 return results; 3596 } 3597 3598 @Override 3599 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 3600 int userId) { 3601 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3602 ComponentName comp = intent.getComponent(); 3603 if (comp == null) { 3604 if (intent.getSelector() != null) { 3605 intent = intent.getSelector(); 3606 comp = intent.getComponent(); 3607 } 3608 } 3609 if (comp != null) { 3610 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3611 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 3612 if (ai != null) { 3613 ResolveInfo ri = new ResolveInfo(); 3614 ri.activityInfo = ai; 3615 list.add(ri); 3616 } 3617 return list; 3618 } 3619 3620 // reader 3621 synchronized (mPackages) { 3622 String pkgName = intent.getPackage(); 3623 if (pkgName == null) { 3624 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 3625 } 3626 final PackageParser.Package pkg = mPackages.get(pkgName); 3627 if (pkg != null) { 3628 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 3629 userId); 3630 } 3631 return null; 3632 } 3633 } 3634 3635 @Override 3636 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 3637 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 3638 if (!sUserManager.exists(userId)) return null; 3639 if (query != null) { 3640 if (query.size() >= 1) { 3641 // If there is more than one service with the same priority, 3642 // just arbitrarily pick the first one. 3643 return query.get(0); 3644 } 3645 } 3646 return null; 3647 } 3648 3649 @Override 3650 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 3651 int userId) { 3652 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3653 ComponentName comp = intent.getComponent(); 3654 if (comp == null) { 3655 if (intent.getSelector() != null) { 3656 intent = intent.getSelector(); 3657 comp = intent.getComponent(); 3658 } 3659 } 3660 if (comp != null) { 3661 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3662 final ServiceInfo si = getServiceInfo(comp, flags, userId); 3663 if (si != null) { 3664 final ResolveInfo ri = new ResolveInfo(); 3665 ri.serviceInfo = si; 3666 list.add(ri); 3667 } 3668 return list; 3669 } 3670 3671 // reader 3672 synchronized (mPackages) { 3673 String pkgName = intent.getPackage(); 3674 if (pkgName == null) { 3675 return mServices.queryIntent(intent, resolvedType, flags, userId); 3676 } 3677 final PackageParser.Package pkg = mPackages.get(pkgName); 3678 if (pkg != null) { 3679 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 3680 userId); 3681 } 3682 return null; 3683 } 3684 } 3685 3686 @Override 3687 public List<ResolveInfo> queryIntentContentProviders( 3688 Intent intent, String resolvedType, int flags, int userId) { 3689 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3690 ComponentName comp = intent.getComponent(); 3691 if (comp == null) { 3692 if (intent.getSelector() != null) { 3693 intent = intent.getSelector(); 3694 comp = intent.getComponent(); 3695 } 3696 } 3697 if (comp != null) { 3698 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3699 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 3700 if (pi != null) { 3701 final ResolveInfo ri = new ResolveInfo(); 3702 ri.providerInfo = pi; 3703 list.add(ri); 3704 } 3705 return list; 3706 } 3707 3708 // reader 3709 synchronized (mPackages) { 3710 String pkgName = intent.getPackage(); 3711 if (pkgName == null) { 3712 return mProviders.queryIntent(intent, resolvedType, flags, userId); 3713 } 3714 final PackageParser.Package pkg = mPackages.get(pkgName); 3715 if (pkg != null) { 3716 return mProviders.queryIntentForPackage( 3717 intent, resolvedType, flags, pkg.providers, userId); 3718 } 3719 return null; 3720 } 3721 } 3722 3723 @Override 3724 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 3725 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3726 3727 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages"); 3728 3729 // writer 3730 synchronized (mPackages) { 3731 ArrayList<PackageInfo> list; 3732 if (listUninstalled) { 3733 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 3734 for (PackageSetting ps : mSettings.mPackages.values()) { 3735 PackageInfo pi; 3736 if (ps.pkg != null) { 3737 pi = generatePackageInfo(ps.pkg, flags, userId); 3738 } else { 3739 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3740 } 3741 if (pi != null) { 3742 list.add(pi); 3743 } 3744 } 3745 } else { 3746 list = new ArrayList<PackageInfo>(mPackages.size()); 3747 for (PackageParser.Package p : mPackages.values()) { 3748 PackageInfo pi = generatePackageInfo(p, flags, userId); 3749 if (pi != null) { 3750 list.add(pi); 3751 } 3752 } 3753 } 3754 3755 return new ParceledListSlice<PackageInfo>(list); 3756 } 3757 } 3758 3759 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 3760 String[] permissions, boolean[] tmp, int flags, int userId) { 3761 int numMatch = 0; 3762 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 3763 for (int i=0; i<permissions.length; i++) { 3764 if (gp.grantedPermissions.contains(permissions[i])) { 3765 tmp[i] = true; 3766 numMatch++; 3767 } else { 3768 tmp[i] = false; 3769 } 3770 } 3771 if (numMatch == 0) { 3772 return; 3773 } 3774 PackageInfo pi; 3775 if (ps.pkg != null) { 3776 pi = generatePackageInfo(ps.pkg, flags, userId); 3777 } else { 3778 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3779 } 3780 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 3781 if (numMatch == permissions.length) { 3782 pi.requestedPermissions = permissions; 3783 } else { 3784 pi.requestedPermissions = new String[numMatch]; 3785 numMatch = 0; 3786 for (int i=0; i<permissions.length; i++) { 3787 if (tmp[i]) { 3788 pi.requestedPermissions[numMatch] = permissions[i]; 3789 numMatch++; 3790 } 3791 } 3792 } 3793 } 3794 list.add(pi); 3795 } 3796 3797 @Override 3798 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 3799 String[] permissions, int flags, int userId) { 3800 if (!sUserManager.exists(userId)) return null; 3801 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3802 3803 // writer 3804 synchronized (mPackages) { 3805 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 3806 boolean[] tmpBools = new boolean[permissions.length]; 3807 if (listUninstalled) { 3808 for (PackageSetting ps : mSettings.mPackages.values()) { 3809 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 3810 } 3811 } else { 3812 for (PackageParser.Package pkg : mPackages.values()) { 3813 PackageSetting ps = (PackageSetting)pkg.mExtras; 3814 if (ps != null) { 3815 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 3816 userId); 3817 } 3818 } 3819 } 3820 3821 return new ParceledListSlice<PackageInfo>(list); 3822 } 3823 } 3824 3825 @Override 3826 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 3827 if (!sUserManager.exists(userId)) return null; 3828 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3829 3830 // writer 3831 synchronized (mPackages) { 3832 ArrayList<ApplicationInfo> list; 3833 if (listUninstalled) { 3834 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 3835 for (PackageSetting ps : mSettings.mPackages.values()) { 3836 ApplicationInfo ai; 3837 if (ps.pkg != null) { 3838 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3839 ps.readUserState(userId), userId); 3840 } else { 3841 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 3842 } 3843 if (ai != null) { 3844 list.add(ai); 3845 } 3846 } 3847 } else { 3848 list = new ArrayList<ApplicationInfo>(mPackages.size()); 3849 for (PackageParser.Package p : mPackages.values()) { 3850 if (p.mExtras != null) { 3851 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3852 ((PackageSetting)p.mExtras).readUserState(userId), userId); 3853 if (ai != null) { 3854 list.add(ai); 3855 } 3856 } 3857 } 3858 } 3859 3860 return new ParceledListSlice<ApplicationInfo>(list); 3861 } 3862 } 3863 3864 public List<ApplicationInfo> getPersistentApplications(int flags) { 3865 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 3866 3867 // reader 3868 synchronized (mPackages) { 3869 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 3870 final int userId = UserHandle.getCallingUserId(); 3871 while (i.hasNext()) { 3872 final PackageParser.Package p = i.next(); 3873 if (p.applicationInfo != null 3874 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 3875 && (!mSafeMode || isSystemApp(p))) { 3876 PackageSetting ps = mSettings.mPackages.get(p.packageName); 3877 if (ps != null) { 3878 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3879 ps.readUserState(userId), userId); 3880 if (ai != null) { 3881 finalList.add(ai); 3882 } 3883 } 3884 } 3885 } 3886 } 3887 3888 return finalList; 3889 } 3890 3891 @Override 3892 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 3893 if (!sUserManager.exists(userId)) return null; 3894 // reader 3895 synchronized (mPackages) { 3896 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 3897 PackageSetting ps = provider != null 3898 ? mSettings.mPackages.get(provider.owner.packageName) 3899 : null; 3900 return ps != null 3901 && mSettings.isEnabledLPr(provider.info, flags, userId) 3902 && (!mSafeMode || (provider.info.applicationInfo.flags 3903 &ApplicationInfo.FLAG_SYSTEM) != 0) 3904 ? PackageParser.generateProviderInfo(provider, flags, 3905 ps.readUserState(userId), userId) 3906 : null; 3907 } 3908 } 3909 3910 /** 3911 * @deprecated 3912 */ 3913 @Deprecated 3914 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 3915 // reader 3916 synchronized (mPackages) { 3917 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 3918 .entrySet().iterator(); 3919 final int userId = UserHandle.getCallingUserId(); 3920 while (i.hasNext()) { 3921 Map.Entry<String, PackageParser.Provider> entry = i.next(); 3922 PackageParser.Provider p = entry.getValue(); 3923 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3924 3925 if (ps != null && p.syncable 3926 && (!mSafeMode || (p.info.applicationInfo.flags 3927 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 3928 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 3929 ps.readUserState(userId), userId); 3930 if (info != null) { 3931 outNames.add(entry.getKey()); 3932 outInfo.add(info); 3933 } 3934 } 3935 } 3936 } 3937 } 3938 3939 @Override 3940 public List<ProviderInfo> queryContentProviders(String processName, 3941 int uid, int flags) { 3942 ArrayList<ProviderInfo> finalList = null; 3943 // reader 3944 synchronized (mPackages) { 3945 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 3946 final int userId = processName != null ? 3947 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 3948 while (i.hasNext()) { 3949 final PackageParser.Provider p = i.next(); 3950 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3951 if (ps != null && p.info.authority != null 3952 && (processName == null 3953 || (p.info.processName.equals(processName) 3954 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 3955 && mSettings.isEnabledLPr(p.info, flags, userId) 3956 && (!mSafeMode 3957 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 3958 if (finalList == null) { 3959 finalList = new ArrayList<ProviderInfo>(3); 3960 } 3961 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 3962 ps.readUserState(userId), userId); 3963 if (info != null) { 3964 finalList.add(info); 3965 } 3966 } 3967 } 3968 } 3969 3970 if (finalList != null) { 3971 Collections.sort(finalList, mProviderInitOrderSorter); 3972 } 3973 3974 return finalList; 3975 } 3976 3977 @Override 3978 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 3979 int flags) { 3980 // reader 3981 synchronized (mPackages) { 3982 final PackageParser.Instrumentation i = mInstrumentation.get(name); 3983 return PackageParser.generateInstrumentationInfo(i, flags); 3984 } 3985 } 3986 3987 @Override 3988 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 3989 int flags) { 3990 ArrayList<InstrumentationInfo> finalList = 3991 new ArrayList<InstrumentationInfo>(); 3992 3993 // reader 3994 synchronized (mPackages) { 3995 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 3996 while (i.hasNext()) { 3997 final PackageParser.Instrumentation p = i.next(); 3998 if (targetPackage == null 3999 || targetPackage.equals(p.info.targetPackage)) { 4000 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4001 flags); 4002 if (ii != null) { 4003 finalList.add(ii); 4004 } 4005 } 4006 } 4007 } 4008 4009 return finalList; 4010 } 4011 4012 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4013 HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4014 if (overlays == null) { 4015 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4016 return; 4017 } 4018 for (PackageParser.Package opkg : overlays.values()) { 4019 // Not much to do if idmap fails: we already logged the error 4020 // and we certainly don't want to abort installation of pkg simply 4021 // because an overlay didn't fit properly. For these reasons, 4022 // ignore the return value of createIdmapForPackagePairLI. 4023 createIdmapForPackagePairLI(pkg, opkg); 4024 } 4025 } 4026 4027 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4028 PackageParser.Package opkg) { 4029 if (!opkg.mTrustedOverlay) { 4030 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4031 opkg.baseCodePath + ": overlay not trusted"); 4032 return false; 4033 } 4034 HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4035 if (overlaySet == null) { 4036 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4037 opkg.baseCodePath + " but target package has no known overlays"); 4038 return false; 4039 } 4040 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4041 // TODO: generate idmap for split APKs 4042 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4043 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4044 + opkg.baseCodePath); 4045 return false; 4046 } 4047 PackageParser.Package[] overlayArray = 4048 overlaySet.values().toArray(new PackageParser.Package[0]); 4049 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4050 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4051 return p1.mOverlayPriority - p2.mOverlayPriority; 4052 } 4053 }; 4054 Arrays.sort(overlayArray, cmp); 4055 4056 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4057 int i = 0; 4058 for (PackageParser.Package p : overlayArray) { 4059 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4060 } 4061 return true; 4062 } 4063 4064 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 4065 final File[] files = dir.listFiles(); 4066 if (ArrayUtils.isEmpty(files)) { 4067 Log.d(TAG, "No files in app dir " + dir); 4068 return; 4069 } 4070 4071 if (DEBUG_PACKAGE_SCANNING) { 4072 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 4073 + " flags=0x" + Integer.toHexString(parseFlags)); 4074 } 4075 4076 for (File file : files) { 4077 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 4078 && !PackageInstallerService.isStageName(file.getName()); 4079 if (!isPackage) { 4080 // Ignore entries which are not packages 4081 continue; 4082 } 4083 try { 4084 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 4085 scanFlags, currentTime, null); 4086 } catch (PackageManagerException e) { 4087 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4088 4089 // Delete invalid userdata apps 4090 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4091 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4092 Slog.w(TAG, "Deleting invalid package at " + file); 4093 if (file.isDirectory()) { 4094 FileUtils.deleteContents(file); 4095 } 4096 file.delete(); 4097 } 4098 } 4099 } 4100 } 4101 4102 private static File getSettingsProblemFile() { 4103 File dataDir = Environment.getDataDirectory(); 4104 File systemDir = new File(dataDir, "system"); 4105 File fname = new File(systemDir, "uiderrors.txt"); 4106 return fname; 4107 } 4108 4109 static void reportSettingsProblem(int priority, String msg) { 4110 try { 4111 File fname = getSettingsProblemFile(); 4112 FileOutputStream out = new FileOutputStream(fname, true); 4113 PrintWriter pw = new FastPrintWriter(out); 4114 SimpleDateFormat formatter = new SimpleDateFormat(); 4115 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4116 pw.println(dateString + ": " + msg); 4117 pw.close(); 4118 FileUtils.setPermissions( 4119 fname.toString(), 4120 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4121 -1, -1); 4122 } catch (java.io.IOException e) { 4123 } 4124 Slog.println(priority, TAG, msg); 4125 } 4126 4127 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 4128 PackageParser.Package pkg, File srcFile, int parseFlags) 4129 throws PackageManagerException { 4130 if (ps != null 4131 && ps.codePath.equals(srcFile) 4132 && ps.timeStamp == srcFile.lastModified() 4133 && !isCompatSignatureUpdateNeeded(pkg)) { 4134 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4135 if (ps.signatures.mSignatures != null 4136 && ps.signatures.mSignatures.length != 0 4137 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4138 // Optimization: reuse the existing cached certificates 4139 // if the package appears to be unchanged. 4140 pkg.mSignatures = ps.signatures.mSignatures; 4141 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4142 synchronized (mPackages) { 4143 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 4144 } 4145 return; 4146 } 4147 4148 Slog.w(TAG, "PackageSetting for " + ps.name 4149 + " is missing signatures. Collecting certs again to recover them."); 4150 } else { 4151 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4152 } 4153 4154 try { 4155 pp.collectCertificates(pkg, parseFlags); 4156 pp.collectManifestDigest(pkg); 4157 } catch (PackageParserException e) { 4158 throw new PackageManagerException(e.error, "Failed to collect certificates for " 4159 + pkg.packageName + ": " + e.getMessage()); 4160 } 4161 } 4162 4163 /* 4164 * Scan a package and return the newly parsed package. 4165 * Returns null in case of errors and the error code is stored in mLastScanError 4166 */ 4167 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 4168 long currentTime, UserHandle user) throws PackageManagerException { 4169 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4170 parseFlags |= mDefParseFlags; 4171 PackageParser pp = new PackageParser(); 4172 pp.setSeparateProcesses(mSeparateProcesses); 4173 pp.setOnlyCoreApps(mOnlyCore); 4174 pp.setDisplayMetrics(mMetrics); 4175 4176 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 4177 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4178 } 4179 4180 final PackageParser.Package pkg; 4181 try { 4182 pkg = pp.parsePackage(scanFile, parseFlags); 4183 } catch (PackageParserException e) { 4184 throw new PackageManagerException(e.error, 4185 "Failed to scan " + scanFile + ": " + e.getMessage()); 4186 } 4187 4188 PackageSetting ps = null; 4189 PackageSetting updatedPkg; 4190 // reader 4191 synchronized (mPackages) { 4192 // Look to see if we already know about this package. 4193 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4194 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4195 // This package has been renamed to its original name. Let's 4196 // use that. 4197 ps = mSettings.peekPackageLPr(oldName); 4198 } 4199 // If there was no original package, see one for the real package name. 4200 if (ps == null) { 4201 ps = mSettings.peekPackageLPr(pkg.packageName); 4202 } 4203 // Check to see if this package could be hiding/updating a system 4204 // package. Must look for it either under the original or real 4205 // package name depending on our state. 4206 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4207 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4208 } 4209 boolean updatedPkgBetter = false; 4210 // First check if this is a system package that may involve an update 4211 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4212 if (ps != null && !ps.codePath.equals(scanFile)) { 4213 // The path has changed from what was last scanned... check the 4214 // version of the new path against what we have stored to determine 4215 // what to do. 4216 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4217 if (pkg.mVersionCode < ps.versionCode) { 4218 // The system package has been updated and the code path does not match 4219 // Ignore entry. Skip it. 4220 Log.i(TAG, "Package " + ps.name + " at " + scanFile 4221 + " ignored: updated version " + ps.versionCode 4222 + " better than this " + pkg.mVersionCode); 4223 if (!updatedPkg.codePath.equals(scanFile)) { 4224 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4225 + ps.name + " changing from " + updatedPkg.codePathString 4226 + " to " + scanFile); 4227 updatedPkg.codePath = scanFile; 4228 updatedPkg.codePathString = scanFile.toString(); 4229 // This is the point at which we know that the system-disk APK 4230 // for this package has moved during a reboot (e.g. due to an OTA), 4231 // so we need to reevaluate it for privilege policy. 4232 if (locationIsPrivileged(scanFile)) { 4233 updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED; 4234 } 4235 } 4236 updatedPkg.pkg = pkg; 4237 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 4238 } else { 4239 // The current app on the system partition is better than 4240 // what we have updated to on the data partition; switch 4241 // back to the system partition version. 4242 // At this point, its safely assumed that package installation for 4243 // apps in system partition will go through. If not there won't be a working 4244 // version of the app 4245 // writer 4246 synchronized (mPackages) { 4247 // Just remove the loaded entries from package lists. 4248 mPackages.remove(ps.name); 4249 } 4250 Slog.w(TAG, "Package " + ps.name + " at " + scanFile 4251 + "reverting from " + ps.codePathString 4252 + ": new version " + pkg.mVersionCode 4253 + " better than installed " + ps.versionCode); 4254 4255 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4256 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4257 getAppDexInstructionSets(ps)); 4258 synchronized (mInstallLock) { 4259 args.cleanUpResourcesLI(); 4260 } 4261 synchronized (mPackages) { 4262 mSettings.enableSystemPackageLPw(ps.name); 4263 } 4264 updatedPkgBetter = true; 4265 } 4266 } 4267 } 4268 4269 if (updatedPkg != null) { 4270 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4271 // initially 4272 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4273 4274 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4275 // flag set initially 4276 if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) { 4277 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4278 } 4279 } 4280 4281 // Verify certificates against what was last scanned 4282 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 4283 4284 /* 4285 * A new system app appeared, but we already had a non-system one of the 4286 * same name installed earlier. 4287 */ 4288 boolean shouldHideSystemApp = false; 4289 if (updatedPkg == null && ps != null 4290 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4291 /* 4292 * Check to make sure the signatures match first. If they don't, 4293 * wipe the installed application and its data. 4294 */ 4295 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4296 != PackageManager.SIGNATURE_MATCH) { 4297 if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!"); 4298 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4299 ps = null; 4300 } else { 4301 /* 4302 * If the newly-added system app is an older version than the 4303 * already installed version, hide it. It will be scanned later 4304 * and re-added like an update. 4305 */ 4306 if (pkg.mVersionCode < ps.versionCode) { 4307 shouldHideSystemApp = true; 4308 } else { 4309 /* 4310 * The newly found system app is a newer version that the 4311 * one previously installed. Simply remove the 4312 * already-installed application and replace it with our own 4313 * while keeping the application data. 4314 */ 4315 Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from " 4316 + ps.codePathString + ": new version " + pkg.mVersionCode 4317 + " better than installed " + ps.versionCode); 4318 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4319 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4320 getAppDexInstructionSets(ps)); 4321 synchronized (mInstallLock) { 4322 args.cleanUpResourcesLI(); 4323 } 4324 } 4325 } 4326 } 4327 4328 // The apk is forward locked (not public) if its code and resources 4329 // are kept in different files. (except for app in either system or 4330 // vendor path). 4331 // TODO grab this value from PackageSettings 4332 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4333 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4334 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 4335 } 4336 } 4337 4338 // TODO: extend to support forward-locked splits 4339 String resourcePath = null; 4340 String baseResourcePath = null; 4341 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 4342 if (ps != null && ps.resourcePathString != null) { 4343 resourcePath = ps.resourcePathString; 4344 baseResourcePath = ps.resourcePathString; 4345 } else { 4346 // Should not happen at all. Just log an error. 4347 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 4348 } 4349 } else { 4350 resourcePath = pkg.codePath; 4351 baseResourcePath = pkg.baseCodePath; 4352 } 4353 4354 // Set application objects path explicitly. 4355 pkg.applicationInfo.setCodePath(pkg.codePath); 4356 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 4357 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 4358 pkg.applicationInfo.setResourcePath(resourcePath); 4359 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 4360 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 4361 4362 // Note that we invoke the following method only if we are about to unpack an application 4363 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 4364 | SCAN_UPDATE_SIGNATURE, currentTime, user); 4365 4366 /* 4367 * If the system app should be overridden by a previously installed 4368 * data, hide the system app now and let the /data/app scan pick it up 4369 * again. 4370 */ 4371 if (shouldHideSystemApp) { 4372 synchronized (mPackages) { 4373 /* 4374 * We have to grant systems permissions before we hide, because 4375 * grantPermissions will assume the package update is trying to 4376 * expand its permissions. 4377 */ 4378 grantPermissionsLPw(pkg, true); 4379 mSettings.disableSystemPackageLPw(pkg.packageName); 4380 } 4381 } 4382 4383 return scannedPkg; 4384 } 4385 4386 private static String fixProcessName(String defProcessName, 4387 String processName, int uid) { 4388 if (processName == null) { 4389 return defProcessName; 4390 } 4391 return processName; 4392 } 4393 4394 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 4395 throws PackageManagerException { 4396 if (pkgSetting.signatures.mSignatures != null) { 4397 // Already existing package. Make sure signatures match 4398 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 4399 == PackageManager.SIGNATURE_MATCH; 4400 if (!match) { 4401 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 4402 == PackageManager.SIGNATURE_MATCH; 4403 } 4404 if (!match) { 4405 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 4406 + pkg.packageName + " signatures do not match the " 4407 + "previously installed version; ignoring!"); 4408 } 4409 } 4410 4411 // Check for shared user signatures 4412 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 4413 // Already existing package. Make sure signatures match 4414 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4415 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 4416 if (!match) { 4417 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 4418 == PackageManager.SIGNATURE_MATCH; 4419 } 4420 if (!match) { 4421 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 4422 "Package " + pkg.packageName 4423 + " has no signatures that match those in shared user " 4424 + pkgSetting.sharedUser.name + "; ignoring!"); 4425 } 4426 } 4427 } 4428 4429 /** 4430 * Enforces that only the system UID or root's UID can call a method exposed 4431 * via Binder. 4432 * 4433 * @param message used as message if SecurityException is thrown 4434 * @throws SecurityException if the caller is not system or root 4435 */ 4436 private static final void enforceSystemOrRoot(String message) { 4437 final int uid = Binder.getCallingUid(); 4438 if (uid != Process.SYSTEM_UID && uid != 0) { 4439 throw new SecurityException(message); 4440 } 4441 } 4442 4443 @Override 4444 public void performBootDexOpt() { 4445 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4446 4447 final HashSet<PackageParser.Package> pkgs; 4448 synchronized (mPackages) { 4449 pkgs = mDeferredDexOpt; 4450 mDeferredDexOpt = null; 4451 } 4452 4453 if (pkgs != null) { 4454 // Filter out packages that aren't recently used. 4455 // 4456 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 4457 // should do a full dexopt. 4458 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 4459 // TODO: add a property to control this? 4460 long dexOptLRUThresholdInMinutes; 4461 if (mLazyDexOpt) { 4462 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 4463 } else { 4464 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 4465 } 4466 long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 4467 4468 int total = pkgs.size(); 4469 int skipped = 0; 4470 long now = System.currentTimeMillis(); 4471 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 4472 PackageParser.Package pkg = i.next(); 4473 long then = pkg.mLastPackageUsageTimeInMills; 4474 if (then + dexOptLRUThresholdInMills < now) { 4475 if (DEBUG_DEXOPT) { 4476 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 4477 ((then == 0) ? "never" : new Date(then))); 4478 } 4479 i.remove(); 4480 skipped++; 4481 } 4482 } 4483 if (DEBUG_DEXOPT) { 4484 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 4485 } 4486 } 4487 4488 int i = 0; 4489 for (PackageParser.Package pkg : pkgs) { 4490 i++; 4491 if (DEBUG_DEXOPT) { 4492 Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size() 4493 + ": " + pkg.packageName); 4494 } 4495 if (!isFirstBoot()) { 4496 try { 4497 ActivityManagerNative.getDefault().showBootMessage( 4498 mContext.getResources().getString( 4499 R.string.android_upgrading_apk, 4500 i, pkgs.size()), true); 4501 } catch (RemoteException e) { 4502 } 4503 } 4504 PackageParser.Package p = pkg; 4505 synchronized (mInstallLock) { 4506 performDexOptLI(p, null /* instruction sets */, false /* force dex */, false /* defer */, 4507 true /* include dependencies */); 4508 } 4509 } 4510 } 4511 } 4512 4513 @Override 4514 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 4515 return performDexOpt(packageName, instructionSet, true); 4516 } 4517 4518 private static String getPrimaryInstructionSet(ApplicationInfo info) { 4519 if (info.primaryCpuAbi == null) { 4520 return getPreferredInstructionSet(); 4521 } 4522 4523 return VMRuntime.getInstructionSet(info.primaryCpuAbi); 4524 } 4525 4526 public boolean performDexOpt(String packageName, String instructionSet, boolean updateUsage) { 4527 if (!mLazyDexOpt) { 4528 return false; 4529 } 4530 PackageParser.Package p; 4531 final String targetInstructionSet; 4532 synchronized (mPackages) { 4533 p = mPackages.get(packageName); 4534 if (p == null) { 4535 return false; 4536 } 4537 if (updateUsage) { 4538 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 4539 } 4540 mPackageUsage.write(false); 4541 4542 targetInstructionSet = instructionSet != null ? instructionSet : 4543 getPrimaryInstructionSet(p.applicationInfo); 4544 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 4545 return false; 4546 } 4547 } 4548 4549 synchronized (mInstallLock) { 4550 final String[] instructionSets = new String[] { targetInstructionSet }; 4551 return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */, 4552 true /* include dependencies */) == DEX_OPT_PERFORMED; 4553 } 4554 } 4555 4556 public HashSet<String> getPackagesThatNeedDexOpt() { 4557 HashSet<String> pkgs = null; 4558 synchronized (mPackages) { 4559 for (PackageParser.Package p : mPackages.values()) { 4560 if (DEBUG_DEXOPT) { 4561 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 4562 } 4563 if (!p.mDexOptPerformed.isEmpty()) { 4564 continue; 4565 } 4566 if (pkgs == null) { 4567 pkgs = new HashSet<String>(); 4568 } 4569 pkgs.add(p.packageName); 4570 } 4571 } 4572 return pkgs; 4573 } 4574 4575 public void shutdown() { 4576 mPackageUsage.write(true); 4577 } 4578 4579 private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets, 4580 boolean forceDex, boolean defer, HashSet<String> done) { 4581 for (int i=0; i<libs.size(); i++) { 4582 PackageParser.Package libPkg; 4583 String libName; 4584 synchronized (mPackages) { 4585 libName = libs.get(i); 4586 SharedLibraryEntry lib = mSharedLibraries.get(libName); 4587 if (lib != null && lib.apk != null) { 4588 libPkg = mPackages.get(lib.apk); 4589 } else { 4590 libPkg = null; 4591 } 4592 } 4593 if (libPkg != null && !done.contains(libName)) { 4594 performDexOptLI(libPkg, instructionSets, forceDex, defer, done); 4595 } 4596 } 4597 } 4598 4599 static final int DEX_OPT_SKIPPED = 0; 4600 static final int DEX_OPT_PERFORMED = 1; 4601 static final int DEX_OPT_DEFERRED = 2; 4602 static final int DEX_OPT_FAILED = -1; 4603 4604 private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets, 4605 boolean forceDex, boolean defer, HashSet<String> done) { 4606 final String[] instructionSets = targetInstructionSets != null ? 4607 targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo); 4608 4609 if (done != null) { 4610 done.add(pkg.packageName); 4611 if (pkg.usesLibraries != null) { 4612 performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done); 4613 } 4614 if (pkg.usesOptionalLibraries != null) { 4615 performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done); 4616 } 4617 } 4618 4619 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) { 4620 return DEX_OPT_SKIPPED; 4621 } 4622 4623 final boolean vmSafeMode = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0; 4624 4625 final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly(); 4626 boolean performedDexOpt = false; 4627 // There are three basic cases here: 4628 // 1.) we need to dexopt, either because we are forced or it is needed 4629 // 2.) we are defering a needed dexopt 4630 // 3.) we are skipping an unneeded dexopt 4631 final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 4632 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 4633 if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) { 4634 continue; 4635 } 4636 4637 for (String path : paths) { 4638 try { 4639 // This will return DEXOPT_NEEDED if we either cannot find any odex file for this 4640 // patckage or the one we find does not match the image checksum (i.e. it was 4641 // compiled against an old image). It will return PATCHOAT_NEEDED if we can find a 4642 // odex file and it matches the checksum of the image but not its base address, 4643 // meaning we need to move it. 4644 final byte isDexOptNeeded = DexFile.isDexOptNeededInternal(path, 4645 pkg.packageName, dexCodeInstructionSet, defer); 4646 if (forceDex || (!defer && isDexOptNeeded == DexFile.DEXOPT_NEEDED)) { 4647 Log.i(TAG, "Running dexopt on: " + path + " pkg=" 4648 + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet 4649 + " vmSafeMode=" + vmSafeMode); 4650 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4651 final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg), 4652 pkg.packageName, dexCodeInstructionSet, vmSafeMode); 4653 4654 if (ret < 0) { 4655 // Don't bother running dexopt again if we failed, it will probably 4656 // just result in an error again. Also, don't bother dexopting for other 4657 // paths & ISAs. 4658 return DEX_OPT_FAILED; 4659 } 4660 4661 performedDexOpt = true; 4662 } else if (!defer && isDexOptNeeded == DexFile.PATCHOAT_NEEDED) { 4663 Log.i(TAG, "Running patchoat on: " + pkg.applicationInfo.packageName); 4664 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4665 final int ret = mInstaller.patchoat(path, sharedGid, !isForwardLocked(pkg), 4666 pkg.packageName, dexCodeInstructionSet); 4667 4668 if (ret < 0) { 4669 // Don't bother running patchoat again if we failed, it will probably 4670 // just result in an error again. Also, don't bother dexopting for other 4671 // paths & ISAs. 4672 return DEX_OPT_FAILED; 4673 } 4674 4675 performedDexOpt = true; 4676 } 4677 4678 // We're deciding to defer a needed dexopt. Don't bother dexopting for other 4679 // paths and instruction sets. We'll deal with them all together when we process 4680 // our list of deferred dexopts. 4681 if (defer && isDexOptNeeded != DexFile.UP_TO_DATE) { 4682 if (mDeferredDexOpt == null) { 4683 mDeferredDexOpt = new HashSet<PackageParser.Package>(); 4684 } 4685 mDeferredDexOpt.add(pkg); 4686 return DEX_OPT_DEFERRED; 4687 } 4688 } catch (FileNotFoundException e) { 4689 Slog.w(TAG, "Apk not found for dexopt: " + path); 4690 return DEX_OPT_FAILED; 4691 } catch (IOException e) { 4692 Slog.w(TAG, "IOException reading apk: " + path, e); 4693 return DEX_OPT_FAILED; 4694 } catch (StaleDexCacheError e) { 4695 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e); 4696 return DEX_OPT_FAILED; 4697 } catch (Exception e) { 4698 Slog.w(TAG, "Exception when doing dexopt : ", e); 4699 return DEX_OPT_FAILED; 4700 } 4701 } 4702 4703 // At this point we haven't failed dexopt and we haven't deferred dexopt. We must 4704 // either have either succeeded dexopt, or have had isDexOptNeededInternal tell us 4705 // it isn't required. We therefore mark that this package doesn't need dexopt unless 4706 // it's forced. performedDexOpt will tell us whether we performed dex-opt or skipped 4707 // it. 4708 pkg.mDexOptPerformed.add(dexCodeInstructionSet); 4709 } 4710 4711 // If we've gotten here, we're sure that no error occurred and that we haven't 4712 // deferred dex-opt. We've either dex-opted one more paths or instruction sets or 4713 // we've skipped all of them because they are up to date. In both cases this 4714 // package doesn't need dexopt any longer. 4715 return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED; 4716 } 4717 4718 private static String[] getAppDexInstructionSets(ApplicationInfo info) { 4719 if (info.primaryCpuAbi != null) { 4720 if (info.secondaryCpuAbi != null) { 4721 return new String[] { 4722 VMRuntime.getInstructionSet(info.primaryCpuAbi), 4723 VMRuntime.getInstructionSet(info.secondaryCpuAbi) }; 4724 } else { 4725 return new String[] { 4726 VMRuntime.getInstructionSet(info.primaryCpuAbi) }; 4727 } 4728 } 4729 4730 return new String[] { getPreferredInstructionSet() }; 4731 } 4732 4733 private static String[] getAppDexInstructionSets(PackageSetting ps) { 4734 if (ps.primaryCpuAbiString != null) { 4735 if (ps.secondaryCpuAbiString != null) { 4736 return new String[] { 4737 VMRuntime.getInstructionSet(ps.primaryCpuAbiString), 4738 VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) }; 4739 } else { 4740 return new String[] { 4741 VMRuntime.getInstructionSet(ps.primaryCpuAbiString) }; 4742 } 4743 } 4744 4745 return new String[] { getPreferredInstructionSet() }; 4746 } 4747 4748 private static String getPreferredInstructionSet() { 4749 if (sPreferredInstructionSet == null) { 4750 sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]); 4751 } 4752 4753 return sPreferredInstructionSet; 4754 } 4755 4756 private static List<String> getAllInstructionSets() { 4757 final String[] allAbis = Build.SUPPORTED_ABIS; 4758 final List<String> allInstructionSets = new ArrayList<String>(allAbis.length); 4759 4760 for (String abi : allAbis) { 4761 final String instructionSet = VMRuntime.getInstructionSet(abi); 4762 if (!allInstructionSets.contains(instructionSet)) { 4763 allInstructionSets.add(instructionSet); 4764 } 4765 } 4766 4767 return allInstructionSets; 4768 } 4769 4770 /** 4771 * Returns the instruction set that should be used to compile dex code. In the presence of 4772 * a native bridge this might be different than the one shared libraries use. 4773 */ 4774 private static String getDexCodeInstructionSet(String sharedLibraryIsa) { 4775 String dexCodeIsa = SystemProperties.get("ro.dalvik.vm.isa." + sharedLibraryIsa); 4776 return (dexCodeIsa.isEmpty() ? sharedLibraryIsa : dexCodeIsa); 4777 } 4778 4779 private static String[] getDexCodeInstructionSets(String[] instructionSets) { 4780 HashSet<String> dexCodeInstructionSets = new HashSet<String>(instructionSets.length); 4781 for (String instructionSet : instructionSets) { 4782 dexCodeInstructionSets.add(getDexCodeInstructionSet(instructionSet)); 4783 } 4784 return dexCodeInstructionSets.toArray(new String[dexCodeInstructionSets.size()]); 4785 } 4786 4787 @Override 4788 public void forceDexOpt(String packageName) { 4789 enforceSystemOrRoot("forceDexOpt"); 4790 4791 PackageParser.Package pkg; 4792 synchronized (mPackages) { 4793 pkg = mPackages.get(packageName); 4794 if (pkg == null) { 4795 throw new IllegalArgumentException("Missing package: " + packageName); 4796 } 4797 } 4798 4799 synchronized (mInstallLock) { 4800 final String[] instructionSets = new String[] { 4801 getPrimaryInstructionSet(pkg.applicationInfo) }; 4802 final int res = performDexOptLI(pkg, instructionSets, true, false, true); 4803 if (res != DEX_OPT_PERFORMED) { 4804 throw new IllegalStateException("Failed to dexopt: " + res); 4805 } 4806 } 4807 } 4808 4809 private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets, 4810 boolean forceDex, boolean defer, boolean inclDependencies) { 4811 HashSet<String> done; 4812 if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) { 4813 done = new HashSet<String>(); 4814 done.add(pkg.packageName); 4815 } else { 4816 done = null; 4817 } 4818 return performDexOptLI(pkg, instructionSets, forceDex, defer, done); 4819 } 4820 4821 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 4822 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 4823 Slog.w(TAG, "Unable to update from " + oldPkg.name 4824 + " to " + newPkg.packageName 4825 + ": old package not in system partition"); 4826 return false; 4827 } else if (mPackages.get(oldPkg.name) != null) { 4828 Slog.w(TAG, "Unable to update from " + oldPkg.name 4829 + " to " + newPkg.packageName 4830 + ": old package still exists"); 4831 return false; 4832 } 4833 return true; 4834 } 4835 4836 File getDataPathForUser(int userId) { 4837 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId); 4838 } 4839 4840 private File getDataPathForPackage(String packageName, int userId) { 4841 /* 4842 * Until we fully support multiple users, return the directory we 4843 * previously would have. The PackageManagerTests will need to be 4844 * revised when this is changed back.. 4845 */ 4846 if (userId == 0) { 4847 return new File(mAppDataDir, packageName); 4848 } else { 4849 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 4850 + File.separator + packageName); 4851 } 4852 } 4853 4854 private int createDataDirsLI(String packageName, int uid, String seinfo) { 4855 int[] users = sUserManager.getUserIds(); 4856 int res = mInstaller.install(packageName, uid, uid, seinfo); 4857 if (res < 0) { 4858 return res; 4859 } 4860 for (int user : users) { 4861 if (user != 0) { 4862 res = mInstaller.createUserData(packageName, 4863 UserHandle.getUid(user, uid), user, seinfo); 4864 if (res < 0) { 4865 return res; 4866 } 4867 } 4868 } 4869 return res; 4870 } 4871 4872 private int removeDataDirsLI(String packageName) { 4873 int[] users = sUserManager.getUserIds(); 4874 int res = 0; 4875 for (int user : users) { 4876 int resInner = mInstaller.remove(packageName, user); 4877 if (resInner < 0) { 4878 res = resInner; 4879 } 4880 } 4881 4882 return res; 4883 } 4884 4885 private int deleteCodeCacheDirsLI(String packageName) { 4886 int[] users = sUserManager.getUserIds(); 4887 int res = 0; 4888 for (int user : users) { 4889 int resInner = mInstaller.deleteCodeCacheFiles(packageName, user); 4890 if (resInner < 0) { 4891 res = resInner; 4892 } 4893 } 4894 return res; 4895 } 4896 4897 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 4898 PackageParser.Package changingLib) { 4899 if (file.path != null) { 4900 usesLibraryFiles.add(file.path); 4901 return; 4902 } 4903 PackageParser.Package p = mPackages.get(file.apk); 4904 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 4905 // If we are doing this while in the middle of updating a library apk, 4906 // then we need to make sure to use that new apk for determining the 4907 // dependencies here. (We haven't yet finished committing the new apk 4908 // to the package manager state.) 4909 if (p == null || p.packageName.equals(changingLib.packageName)) { 4910 p = changingLib; 4911 } 4912 } 4913 if (p != null) { 4914 usesLibraryFiles.addAll(p.getAllCodePaths()); 4915 } 4916 } 4917 4918 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 4919 PackageParser.Package changingLib) throws PackageManagerException { 4920 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 4921 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 4922 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 4923 for (int i=0; i<N; i++) { 4924 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 4925 if (file == null) { 4926 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 4927 "Package " + pkg.packageName + " requires unavailable shared library " 4928 + pkg.usesLibraries.get(i) + "; failing!"); 4929 } 4930 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4931 } 4932 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 4933 for (int i=0; i<N; i++) { 4934 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 4935 if (file == null) { 4936 Slog.w(TAG, "Package " + pkg.packageName 4937 + " desires unavailable shared library " 4938 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 4939 } else { 4940 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 4941 } 4942 } 4943 N = usesLibraryFiles.size(); 4944 if (N > 0) { 4945 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 4946 } else { 4947 pkg.usesLibraryFiles = null; 4948 } 4949 } 4950 } 4951 4952 private static boolean hasString(List<String> list, List<String> which) { 4953 if (list == null) { 4954 return false; 4955 } 4956 for (int i=list.size()-1; i>=0; i--) { 4957 for (int j=which.size()-1; j>=0; j--) { 4958 if (which.get(j).equals(list.get(i))) { 4959 return true; 4960 } 4961 } 4962 } 4963 return false; 4964 } 4965 4966 private void updateAllSharedLibrariesLPw() { 4967 for (PackageParser.Package pkg : mPackages.values()) { 4968 try { 4969 updateSharedLibrariesLPw(pkg, null); 4970 } catch (PackageManagerException e) { 4971 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 4972 } 4973 } 4974 } 4975 4976 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 4977 PackageParser.Package changingPkg) { 4978 ArrayList<PackageParser.Package> res = null; 4979 for (PackageParser.Package pkg : mPackages.values()) { 4980 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 4981 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 4982 if (res == null) { 4983 res = new ArrayList<PackageParser.Package>(); 4984 } 4985 res.add(pkg); 4986 try { 4987 updateSharedLibrariesLPw(pkg, changingPkg); 4988 } catch (PackageManagerException e) { 4989 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 4990 } 4991 } 4992 } 4993 return res; 4994 } 4995 4996 /** 4997 * Derive the value of the {@code cpuAbiOverride} based on the provided 4998 * value and an optional stored value from the package settings. 4999 */ 5000 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5001 String cpuAbiOverride = null; 5002 5003 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5004 cpuAbiOverride = null; 5005 } else if (abiOverride != null) { 5006 cpuAbiOverride = abiOverride; 5007 } else if (settings != null) { 5008 cpuAbiOverride = settings.cpuAbiOverrideString; 5009 } 5010 5011 return cpuAbiOverride; 5012 } 5013 5014 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5015 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5016 final File scanFile = new File(pkg.codePath); 5017 if (pkg.applicationInfo.getCodePath() == null || 5018 pkg.applicationInfo.getResourcePath() == null) { 5019 // Bail out. The resource and code paths haven't been set. 5020 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5021 "Code and resource paths haven't been set correctly"); 5022 } 5023 5024 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5025 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5026 } 5027 5028 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5029 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED; 5030 } 5031 5032 if (mCustomResolverComponentName != null && 5033 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5034 setUpCustomResolverActivity(pkg); 5035 } 5036 5037 if (pkg.packageName.equals("android")) { 5038 synchronized (mPackages) { 5039 if (mAndroidApplication != null) { 5040 Slog.w(TAG, "*************************************************"); 5041 Slog.w(TAG, "Core android package being redefined. Skipping."); 5042 Slog.w(TAG, " file=" + scanFile); 5043 Slog.w(TAG, "*************************************************"); 5044 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5045 "Core android package being redefined. Skipping."); 5046 } 5047 5048 // Set up information for our fall-back user intent resolution activity. 5049 mPlatformPackage = pkg; 5050 pkg.mVersionCode = mSdkVersion; 5051 mAndroidApplication = pkg.applicationInfo; 5052 5053 if (!mResolverReplaced) { 5054 mResolveActivity.applicationInfo = mAndroidApplication; 5055 mResolveActivity.name = ResolverActivity.class.getName(); 5056 mResolveActivity.packageName = mAndroidApplication.packageName; 5057 mResolveActivity.processName = "system:ui"; 5058 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5059 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5060 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5061 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5062 mResolveActivity.exported = true; 5063 mResolveActivity.enabled = true; 5064 mResolveInfo.activityInfo = mResolveActivity; 5065 mResolveInfo.priority = 0; 5066 mResolveInfo.preferredOrder = 0; 5067 mResolveInfo.match = 0; 5068 mResolveComponentName = new ComponentName( 5069 mAndroidApplication.packageName, mResolveActivity.name); 5070 } 5071 } 5072 } 5073 5074 if (DEBUG_PACKAGE_SCANNING) { 5075 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5076 Log.d(TAG, "Scanning package " + pkg.packageName); 5077 } 5078 5079 if (mPackages.containsKey(pkg.packageName) 5080 || mSharedLibraries.containsKey(pkg.packageName)) { 5081 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5082 "Application package " + pkg.packageName 5083 + " already installed. Skipping duplicate."); 5084 } 5085 5086 // Initialize package source and resource directories 5087 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5088 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5089 5090 SharedUserSetting suid = null; 5091 PackageSetting pkgSetting = null; 5092 5093 if (!isSystemApp(pkg)) { 5094 // Only system apps can use these features. 5095 pkg.mOriginalPackages = null; 5096 pkg.mRealPackage = null; 5097 pkg.mAdoptPermissions = null; 5098 } 5099 5100 // writer 5101 synchronized (mPackages) { 5102 if (pkg.mSharedUserId != null) { 5103 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true); 5104 if (suid == null) { 5105 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5106 "Creating application package " + pkg.packageName 5107 + " for shared user failed"); 5108 } 5109 if (DEBUG_PACKAGE_SCANNING) { 5110 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5111 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5112 + "): packages=" + suid.packages); 5113 } 5114 } 5115 5116 // Check if we are renaming from an original package name. 5117 PackageSetting origPackage = null; 5118 String realName = null; 5119 if (pkg.mOriginalPackages != null) { 5120 // This package may need to be renamed to a previously 5121 // installed name. Let's check on that... 5122 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5123 if (pkg.mOriginalPackages.contains(renamed)) { 5124 // This package had originally been installed as the 5125 // original name, and we have already taken care of 5126 // transitioning to the new one. Just update the new 5127 // one to continue using the old name. 5128 realName = pkg.mRealPackage; 5129 if (!pkg.packageName.equals(renamed)) { 5130 // Callers into this function may have already taken 5131 // care of renaming the package; only do it here if 5132 // it is not already done. 5133 pkg.setPackageName(renamed); 5134 } 5135 5136 } else { 5137 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5138 if ((origPackage = mSettings.peekPackageLPr( 5139 pkg.mOriginalPackages.get(i))) != null) { 5140 // We do have the package already installed under its 5141 // original name... should we use it? 5142 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5143 // New package is not compatible with original. 5144 origPackage = null; 5145 continue; 5146 } else if (origPackage.sharedUser != null) { 5147 // Make sure uid is compatible between packages. 5148 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5149 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5150 + " to " + pkg.packageName + ": old uid " 5151 + origPackage.sharedUser.name 5152 + " differs from " + pkg.mSharedUserId); 5153 origPackage = null; 5154 continue; 5155 } 5156 } else { 5157 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5158 + pkg.packageName + " to old name " + origPackage.name); 5159 } 5160 break; 5161 } 5162 } 5163 } 5164 } 5165 5166 if (mTransferedPackages.contains(pkg.packageName)) { 5167 Slog.w(TAG, "Package " + pkg.packageName 5168 + " was transferred to another, but its .apk remains"); 5169 } 5170 5171 // Just create the setting, don't add it yet. For already existing packages 5172 // the PkgSetting exists already and doesn't have to be created. 5173 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5174 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 5175 pkg.applicationInfo.primaryCpuAbi, 5176 pkg.applicationInfo.secondaryCpuAbi, 5177 pkg.applicationInfo.flags, user, false); 5178 if (pkgSetting == null) { 5179 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5180 "Creating application package " + pkg.packageName + " failed"); 5181 } 5182 5183 if (pkgSetting.origPackage != null) { 5184 // If we are first transitioning from an original package, 5185 // fix up the new package's name now. We need to do this after 5186 // looking up the package under its new name, so getPackageLP 5187 // can take care of fiddling things correctly. 5188 pkg.setPackageName(origPackage.name); 5189 5190 // File a report about this. 5191 String msg = "New package " + pkgSetting.realName 5192 + " renamed to replace old package " + pkgSetting.name; 5193 reportSettingsProblem(Log.WARN, msg); 5194 5195 // Make a note of it. 5196 mTransferedPackages.add(origPackage.name); 5197 5198 // No longer need to retain this. 5199 pkgSetting.origPackage = null; 5200 } 5201 5202 if (realName != null) { 5203 // Make a note of it. 5204 mTransferedPackages.add(pkg.packageName); 5205 } 5206 5207 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5208 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5209 } 5210 5211 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5212 // Check all shared libraries and map to their actual file path. 5213 // We only do this here for apps not on a system dir, because those 5214 // are the only ones that can fail an install due to this. We 5215 // will take care of the system apps by updating all of their 5216 // library paths after the scan is done. 5217 updateSharedLibrariesLPw(pkg, null); 5218 } 5219 5220 if (mFoundPolicyFile) { 5221 SELinuxMMAC.assignSeinfoValue(pkg); 5222 } 5223 5224 pkg.applicationInfo.uid = pkgSetting.appId; 5225 pkg.mExtras = pkgSetting; 5226 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5227 try { 5228 verifySignaturesLP(pkgSetting, pkg); 5229 } catch (PackageManagerException e) { 5230 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5231 throw e; 5232 } 5233 // The signature has changed, but this package is in the system 5234 // image... let's recover! 5235 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5236 // However... if this package is part of a shared user, but it 5237 // doesn't match the signature of the shared user, let's fail. 5238 // What this means is that you can't change the signatures 5239 // associated with an overall shared user, which doesn't seem all 5240 // that unreasonable. 5241 if (pkgSetting.sharedUser != null) { 5242 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5243 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5244 throw new PackageManagerException( 5245 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 5246 "Signature mismatch for shared user : " 5247 + pkgSetting.sharedUser); 5248 } 5249 } 5250 // File a report about this. 5251 String msg = "System package " + pkg.packageName 5252 + " signature changed; retaining data."; 5253 reportSettingsProblem(Log.WARN, msg); 5254 } 5255 } else { 5256 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 5257 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5258 + pkg.packageName + " upgrade keys do not match the " 5259 + "previously installed version"); 5260 } else { 5261 // signatures may have changed as result of upgrade 5262 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5263 } 5264 } 5265 // Verify that this new package doesn't have any content providers 5266 // that conflict with existing packages. Only do this if the 5267 // package isn't already installed, since we don't want to break 5268 // things that are installed. 5269 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 5270 final int N = pkg.providers.size(); 5271 int i; 5272 for (i=0; i<N; i++) { 5273 PackageParser.Provider p = pkg.providers.get(i); 5274 if (p.info.authority != null) { 5275 String names[] = p.info.authority.split(";"); 5276 for (int j = 0; j < names.length; j++) { 5277 if (mProvidersByAuthority.containsKey(names[j])) { 5278 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5279 final String otherPackageName = 5280 ((other != null && other.getComponentName() != null) ? 5281 other.getComponentName().getPackageName() : "?"); 5282 throw new PackageManagerException( 5283 INSTALL_FAILED_CONFLICTING_PROVIDER, 5284 "Can't install because provider name " + names[j] 5285 + " (in package " + pkg.applicationInfo.packageName 5286 + ") is already used by " + otherPackageName); 5287 } 5288 } 5289 } 5290 } 5291 } 5292 5293 if (pkg.mAdoptPermissions != null) { 5294 // This package wants to adopt ownership of permissions from 5295 // another package. 5296 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 5297 final String origName = pkg.mAdoptPermissions.get(i); 5298 final PackageSetting orig = mSettings.peekPackageLPr(origName); 5299 if (orig != null) { 5300 if (verifyPackageUpdateLPr(orig, pkg)) { 5301 Slog.i(TAG, "Adopting permissions from " + origName + " to " 5302 + pkg.packageName); 5303 mSettings.transferPermissionsLPw(origName, pkg.packageName); 5304 } 5305 } 5306 } 5307 } 5308 } 5309 5310 final String pkgName = pkg.packageName; 5311 5312 final long scanFileTime = scanFile.lastModified(); 5313 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 5314 pkg.applicationInfo.processName = fixProcessName( 5315 pkg.applicationInfo.packageName, 5316 pkg.applicationInfo.processName, 5317 pkg.applicationInfo.uid); 5318 5319 File dataPath; 5320 if (mPlatformPackage == pkg) { 5321 // The system package is special. 5322 dataPath = new File (Environment.getDataDirectory(), "system"); 5323 pkg.applicationInfo.dataDir = dataPath.getPath(); 5324 5325 } else { 5326 // This is a normal package, need to make its data directory. 5327 dataPath = getDataPathForPackage(pkg.packageName, 0); 5328 5329 boolean uidError = false; 5330 5331 if (dataPath.exists()) { 5332 int currentUid = 0; 5333 try { 5334 StructStat stat = Os.stat(dataPath.getPath()); 5335 currentUid = stat.st_uid; 5336 } catch (ErrnoException e) { 5337 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 5338 } 5339 5340 // If we have mismatched owners for the data path, we have a problem. 5341 if (currentUid != pkg.applicationInfo.uid) { 5342 boolean recovered = false; 5343 if (currentUid == 0) { 5344 // The directory somehow became owned by root. Wow. 5345 // This is probably because the system was stopped while 5346 // installd was in the middle of messing with its libs 5347 // directory. Ask installd to fix that. 5348 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 5349 pkg.applicationInfo.uid); 5350 if (ret >= 0) { 5351 recovered = true; 5352 String msg = "Package " + pkg.packageName 5353 + " unexpectedly changed to uid 0; recovered to " + 5354 + pkg.applicationInfo.uid; 5355 reportSettingsProblem(Log.WARN, msg); 5356 } 5357 } 5358 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5359 || (scanFlags&SCAN_BOOTING) != 0)) { 5360 // If this is a system app, we can at least delete its 5361 // current data so the application will still work. 5362 int ret = removeDataDirsLI(pkgName); 5363 if (ret >= 0) { 5364 // TODO: Kill the processes first 5365 // Old data gone! 5366 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5367 ? "System package " : "Third party package "; 5368 String msg = prefix + pkg.packageName 5369 + " has changed from uid: " 5370 + currentUid + " to " 5371 + pkg.applicationInfo.uid + "; old data erased"; 5372 reportSettingsProblem(Log.WARN, msg); 5373 recovered = true; 5374 5375 // And now re-install the app. 5376 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5377 pkg.applicationInfo.seinfo); 5378 if (ret == -1) { 5379 // Ack should not happen! 5380 msg = prefix + pkg.packageName 5381 + " could not have data directory re-created after delete."; 5382 reportSettingsProblem(Log.WARN, msg); 5383 throw new PackageManagerException( 5384 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 5385 } 5386 } 5387 if (!recovered) { 5388 mHasSystemUidErrors = true; 5389 } 5390 } else if (!recovered) { 5391 // If we allow this install to proceed, we will be broken. 5392 // Abort, abort! 5393 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 5394 "scanPackageLI"); 5395 } 5396 if (!recovered) { 5397 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 5398 + pkg.applicationInfo.uid + "/fs_" 5399 + currentUid; 5400 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 5401 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 5402 String msg = "Package " + pkg.packageName 5403 + " has mismatched uid: " 5404 + currentUid + " on disk, " 5405 + pkg.applicationInfo.uid + " in settings"; 5406 // writer 5407 synchronized (mPackages) { 5408 mSettings.mReadMessages.append(msg); 5409 mSettings.mReadMessages.append('\n'); 5410 uidError = true; 5411 if (!pkgSetting.uidError) { 5412 reportSettingsProblem(Log.ERROR, msg); 5413 } 5414 } 5415 } 5416 } 5417 pkg.applicationInfo.dataDir = dataPath.getPath(); 5418 if (mShouldRestoreconData) { 5419 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 5420 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 5421 pkg.applicationInfo.uid); 5422 } 5423 } else { 5424 if (DEBUG_PACKAGE_SCANNING) { 5425 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5426 Log.v(TAG, "Want this data dir: " + dataPath); 5427 } 5428 //invoke installer to do the actual installation 5429 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5430 pkg.applicationInfo.seinfo); 5431 if (ret < 0) { 5432 // Error from installer 5433 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5434 "Unable to create data dirs [errorCode=" + ret + "]"); 5435 } 5436 5437 if (dataPath.exists()) { 5438 pkg.applicationInfo.dataDir = dataPath.getPath(); 5439 } else { 5440 Slog.w(TAG, "Unable to create data directory: " + dataPath); 5441 pkg.applicationInfo.dataDir = null; 5442 } 5443 } 5444 5445 pkgSetting.uidError = uidError; 5446 } 5447 5448 final String path = scanFile.getPath(); 5449 final String codePath = pkg.applicationInfo.getCodePath(); 5450 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 5451 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 5452 setBundledAppAbisAndRoots(pkg, pkgSetting); 5453 5454 // If we haven't found any native libraries for the app, check if it has 5455 // renderscript code. We'll need to force the app to 32 bit if it has 5456 // renderscript bitcode. 5457 if (pkg.applicationInfo.primaryCpuAbi == null 5458 && pkg.applicationInfo.secondaryCpuAbi == null 5459 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5460 NativeLibraryHelper.Handle handle = null; 5461 try { 5462 handle = NativeLibraryHelper.Handle.create(scanFile); 5463 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5464 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 5465 } 5466 } catch (IOException ioe) { 5467 Slog.w(TAG, "Error scanning system app : " + ioe); 5468 } finally { 5469 IoUtils.closeQuietly(handle); 5470 } 5471 } 5472 5473 setNativeLibraryPaths(pkg); 5474 } else { 5475 // TODO: We can probably be smarter about this stuff. For installed apps, 5476 // we can calculate this information at install time once and for all. For 5477 // system apps, we can probably assume that this information doesn't change 5478 // after the first boot scan. As things stand, we do lots of unnecessary work. 5479 5480 // Give ourselves some initial paths; we'll come back for another 5481 // pass once we've determined ABI below. 5482 setNativeLibraryPaths(pkg); 5483 5484 final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg); 5485 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 5486 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 5487 5488 NativeLibraryHelper.Handle handle = null; 5489 try { 5490 handle = NativeLibraryHelper.Handle.create(scanFile); 5491 // TODO(multiArch): This can be null for apps that didn't go through the 5492 // usual installation process. We can calculate it again, like we 5493 // do during install time. 5494 // 5495 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 5496 // unnecessary. 5497 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 5498 5499 // Null out the abis so that they can be recalculated. 5500 pkg.applicationInfo.primaryCpuAbi = null; 5501 pkg.applicationInfo.secondaryCpuAbi = null; 5502 if (isMultiArch(pkg.applicationInfo)) { 5503 // Warn if we've set an abiOverride for multi-lib packages.. 5504 // By definition, we need to copy both 32 and 64 bit libraries for 5505 // such packages. 5506 if (pkg.cpuAbiOverride != null 5507 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 5508 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 5509 } 5510 5511 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 5512 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 5513 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 5514 if (isAsec) { 5515 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 5516 } else { 5517 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5518 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 5519 useIsaSpecificSubdirs); 5520 } 5521 } 5522 5523 maybeThrowExceptionForMultiArchCopy( 5524 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 5525 5526 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5527 if (isAsec) { 5528 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 5529 } else { 5530 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5531 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 5532 useIsaSpecificSubdirs); 5533 } 5534 } 5535 5536 maybeThrowExceptionForMultiArchCopy( 5537 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 5538 5539 if (abi64 >= 0) { 5540 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 5541 } 5542 5543 if (abi32 >= 0) { 5544 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 5545 if (abi64 >= 0) { 5546 pkg.applicationInfo.secondaryCpuAbi = abi; 5547 } else { 5548 pkg.applicationInfo.primaryCpuAbi = abi; 5549 } 5550 } 5551 } else { 5552 String[] abiList = (cpuAbiOverride != null) ? 5553 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 5554 5555 // Enable gross and lame hacks for apps that are built with old 5556 // SDK tools. We must scan their APKs for renderscript bitcode and 5557 // not launch them if it's present. Don't bother checking on devices 5558 // that don't have 64 bit support. 5559 boolean needsRenderScriptOverride = false; 5560 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 5561 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5562 abiList = Build.SUPPORTED_32_BIT_ABIS; 5563 needsRenderScriptOverride = true; 5564 } 5565 5566 final int copyRet; 5567 if (isAsec) { 5568 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 5569 } else { 5570 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5571 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 5572 } 5573 5574 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5575 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5576 "Error unpackaging native libs for app, errorCode=" + copyRet); 5577 } 5578 5579 if (copyRet >= 0) { 5580 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 5581 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 5582 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 5583 } else if (needsRenderScriptOverride) { 5584 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 5585 } 5586 } 5587 } catch (IOException ioe) { 5588 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 5589 } finally { 5590 IoUtils.closeQuietly(handle); 5591 } 5592 5593 // Now that we've calculated the ABIs and determined if it's an internal app, 5594 // we will go ahead and populate the nativeLibraryPath. 5595 setNativeLibraryPaths(pkg); 5596 5597 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 5598 final int[] userIds = sUserManager.getUserIds(); 5599 synchronized (mInstallLock) { 5600 // Create a native library symlink only if we have native libraries 5601 // and if the native libraries are 32 bit libraries. We do not provide 5602 // this symlink for 64 bit libraries. 5603 if (pkg.applicationInfo.primaryCpuAbi != null && 5604 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 5605 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 5606 for (int userId : userIds) { 5607 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 5608 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5609 "Failed linking native library dir (user=" + userId + ")"); 5610 } 5611 } 5612 } 5613 } 5614 } 5615 5616 // This is a special case for the "system" package, where the ABI is 5617 // dictated by the zygote configuration (and init.rc). We should keep track 5618 // of this ABI so that we can deal with "normal" applications that run under 5619 // the same UID correctly. 5620 if (mPlatformPackage == pkg) { 5621 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 5622 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 5623 } 5624 5625 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 5626 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 5627 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 5628 // Copy the derived override back to the parsed package, so that we can 5629 // update the package settings accordingly. 5630 pkg.cpuAbiOverride = cpuAbiOverride; 5631 5632 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 5633 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 5634 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 5635 5636 // Push the derived path down into PackageSettings so we know what to 5637 // clean up at uninstall time. 5638 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 5639 5640 if (DEBUG_ABI_SELECTION) { 5641 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 5642 " primary=" + pkg.applicationInfo.primaryCpuAbi + 5643 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 5644 } 5645 5646 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 5647 // We don't do this here during boot because we can do it all 5648 // at once after scanning all existing packages. 5649 // 5650 // We also do this *before* we perform dexopt on this package, so that 5651 // we can avoid redundant dexopts, and also to make sure we've got the 5652 // code and package path correct. 5653 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 5654 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 5655 } 5656 5657 if ((scanFlags&SCAN_NO_DEX) == 0) { 5658 if (performDexOptLI(pkg, null /* instruction sets */, forceDex, (scanFlags&SCAN_DEFER_DEX) != 0, false) 5659 == DEX_OPT_FAILED) { 5660 if ((scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5661 removeDataDirsLI(pkg.packageName); 5662 } 5663 5664 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 5665 } 5666 } 5667 5668 if (mFactoryTest && pkg.requestedPermissions.contains( 5669 android.Manifest.permission.FACTORY_TEST)) { 5670 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 5671 } 5672 5673 ArrayList<PackageParser.Package> clientLibPkgs = null; 5674 5675 // writer 5676 synchronized (mPackages) { 5677 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5678 // Only system apps can add new shared libraries. 5679 if (pkg.libraryNames != null) { 5680 for (int i=0; i<pkg.libraryNames.size(); i++) { 5681 String name = pkg.libraryNames.get(i); 5682 boolean allowed = false; 5683 if (isUpdatedSystemApp(pkg)) { 5684 // New library entries can only be added through the 5685 // system image. This is important to get rid of a lot 5686 // of nasty edge cases: for example if we allowed a non- 5687 // system update of the app to add a library, then uninstalling 5688 // the update would make the library go away, and assumptions 5689 // we made such as through app install filtering would now 5690 // have allowed apps on the device which aren't compatible 5691 // with it. Better to just have the restriction here, be 5692 // conservative, and create many fewer cases that can negatively 5693 // impact the user experience. 5694 final PackageSetting sysPs = mSettings 5695 .getDisabledSystemPkgLPr(pkg.packageName); 5696 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 5697 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 5698 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 5699 allowed = true; 5700 allowed = true; 5701 break; 5702 } 5703 } 5704 } 5705 } else { 5706 allowed = true; 5707 } 5708 if (allowed) { 5709 if (!mSharedLibraries.containsKey(name)) { 5710 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 5711 } else if (!name.equals(pkg.packageName)) { 5712 Slog.w(TAG, "Package " + pkg.packageName + " library " 5713 + name + " already exists; skipping"); 5714 } 5715 } else { 5716 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 5717 + name + " that is not declared on system image; skipping"); 5718 } 5719 } 5720 if ((scanFlags&SCAN_BOOTING) == 0) { 5721 // If we are not booting, we need to update any applications 5722 // that are clients of our shared library. If we are booting, 5723 // this will all be done once the scan is complete. 5724 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 5725 } 5726 } 5727 } 5728 } 5729 5730 // We also need to dexopt any apps that are dependent on this library. Note that 5731 // if these fail, we should abort the install since installing the library will 5732 // result in some apps being broken. 5733 if (clientLibPkgs != null) { 5734 if ((scanFlags&SCAN_NO_DEX) == 0) { 5735 for (int i=0; i<clientLibPkgs.size(); i++) { 5736 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5737 if (performDexOptLI(clientPkg, null /* instruction sets */, 5738 forceDex, (scanFlags&SCAN_DEFER_DEX) != 0, false) 5739 == DEX_OPT_FAILED) { 5740 if ((scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5741 removeDataDirsLI(pkg.packageName); 5742 } 5743 5744 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 5745 "scanPackageLI failed to dexopt clientLibPkgs"); 5746 } 5747 } 5748 } 5749 } 5750 5751 // Request the ActivityManager to kill the process(only for existing packages) 5752 // so that we do not end up in a confused state while the user is still using the older 5753 // version of the application while the new one gets installed. 5754 if ((scanFlags & SCAN_REPLACING) != 0) { 5755 killApplication(pkg.applicationInfo.packageName, 5756 pkg.applicationInfo.uid, "update pkg"); 5757 } 5758 5759 // Also need to kill any apps that are dependent on the library. 5760 if (clientLibPkgs != null) { 5761 for (int i=0; i<clientLibPkgs.size(); i++) { 5762 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5763 killApplication(clientPkg.applicationInfo.packageName, 5764 clientPkg.applicationInfo.uid, "update lib"); 5765 } 5766 } 5767 5768 // writer 5769 synchronized (mPackages) { 5770 // We don't expect installation to fail beyond this point 5771 5772 // Add the new setting to mSettings 5773 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 5774 // Add the new setting to mPackages 5775 mPackages.put(pkg.applicationInfo.packageName, pkg); 5776 // Make sure we don't accidentally delete its data. 5777 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 5778 while (iter.hasNext()) { 5779 PackageCleanItem item = iter.next(); 5780 if (pkgName.equals(item.packageName)) { 5781 iter.remove(); 5782 } 5783 } 5784 5785 // Take care of first install / last update times. 5786 if (currentTime != 0) { 5787 if (pkgSetting.firstInstallTime == 0) { 5788 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 5789 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 5790 pkgSetting.lastUpdateTime = currentTime; 5791 } 5792 } else if (pkgSetting.firstInstallTime == 0) { 5793 // We need *something*. Take time time stamp of the file. 5794 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 5795 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 5796 if (scanFileTime != pkgSetting.timeStamp) { 5797 // A package on the system image has changed; consider this 5798 // to be an update. 5799 pkgSetting.lastUpdateTime = scanFileTime; 5800 } 5801 } 5802 5803 // Add the package's KeySets to the global KeySetManagerService 5804 KeySetManagerService ksms = mSettings.mKeySetManagerService; 5805 try { 5806 // Old KeySetData no longer valid. 5807 ksms.removeAppKeySetDataLPw(pkg.packageName); 5808 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 5809 if (pkg.mKeySetMapping != null) { 5810 for (Map.Entry<String, ArraySet<PublicKey>> entry : 5811 pkg.mKeySetMapping.entrySet()) { 5812 if (entry.getValue() != null) { 5813 ksms.addDefinedKeySetToPackageLPw(pkg.packageName, 5814 entry.getValue(), entry.getKey()); 5815 } 5816 } 5817 if (pkg.mUpgradeKeySets != null) { 5818 for (String upgradeAlias : pkg.mUpgradeKeySets) { 5819 ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias); 5820 } 5821 } 5822 } 5823 } catch (NullPointerException e) { 5824 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 5825 } catch (IllegalArgumentException e) { 5826 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 5827 } 5828 5829 int N = pkg.providers.size(); 5830 StringBuilder r = null; 5831 int i; 5832 for (i=0; i<N; i++) { 5833 PackageParser.Provider p = pkg.providers.get(i); 5834 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 5835 p.info.processName, pkg.applicationInfo.uid); 5836 mProviders.addProvider(p); 5837 p.syncable = p.info.isSyncable; 5838 if (p.info.authority != null) { 5839 String names[] = p.info.authority.split(";"); 5840 p.info.authority = null; 5841 for (int j = 0; j < names.length; j++) { 5842 if (j == 1 && p.syncable) { 5843 // We only want the first authority for a provider to possibly be 5844 // syncable, so if we already added this provider using a different 5845 // authority clear the syncable flag. We copy the provider before 5846 // changing it because the mProviders object contains a reference 5847 // to a provider that we don't want to change. 5848 // Only do this for the second authority since the resulting provider 5849 // object can be the same for all future authorities for this provider. 5850 p = new PackageParser.Provider(p); 5851 p.syncable = false; 5852 } 5853 if (!mProvidersByAuthority.containsKey(names[j])) { 5854 mProvidersByAuthority.put(names[j], p); 5855 if (p.info.authority == null) { 5856 p.info.authority = names[j]; 5857 } else { 5858 p.info.authority = p.info.authority + ";" + names[j]; 5859 } 5860 if (DEBUG_PACKAGE_SCANNING) { 5861 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5862 Log.d(TAG, "Registered content provider: " + names[j] 5863 + ", className = " + p.info.name + ", isSyncable = " 5864 + p.info.isSyncable); 5865 } 5866 } else { 5867 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5868 Slog.w(TAG, "Skipping provider name " + names[j] + 5869 " (in package " + pkg.applicationInfo.packageName + 5870 "): name already used by " 5871 + ((other != null && other.getComponentName() != null) 5872 ? other.getComponentName().getPackageName() : "?")); 5873 } 5874 } 5875 } 5876 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5877 if (r == null) { 5878 r = new StringBuilder(256); 5879 } else { 5880 r.append(' '); 5881 } 5882 r.append(p.info.name); 5883 } 5884 } 5885 if (r != null) { 5886 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 5887 } 5888 5889 N = pkg.services.size(); 5890 r = null; 5891 for (i=0; i<N; i++) { 5892 PackageParser.Service s = pkg.services.get(i); 5893 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 5894 s.info.processName, pkg.applicationInfo.uid); 5895 mServices.addService(s); 5896 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5897 if (r == null) { 5898 r = new StringBuilder(256); 5899 } else { 5900 r.append(' '); 5901 } 5902 r.append(s.info.name); 5903 } 5904 } 5905 if (r != null) { 5906 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 5907 } 5908 5909 N = pkg.receivers.size(); 5910 r = null; 5911 for (i=0; i<N; i++) { 5912 PackageParser.Activity a = pkg.receivers.get(i); 5913 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5914 a.info.processName, pkg.applicationInfo.uid); 5915 mReceivers.addActivity(a, "receiver"); 5916 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5917 if (r == null) { 5918 r = new StringBuilder(256); 5919 } else { 5920 r.append(' '); 5921 } 5922 r.append(a.info.name); 5923 } 5924 } 5925 if (r != null) { 5926 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 5927 } 5928 5929 N = pkg.activities.size(); 5930 r = null; 5931 for (i=0; i<N; i++) { 5932 PackageParser.Activity a = pkg.activities.get(i); 5933 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5934 a.info.processName, pkg.applicationInfo.uid); 5935 mActivities.addActivity(a, "activity"); 5936 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5937 if (r == null) { 5938 r = new StringBuilder(256); 5939 } else { 5940 r.append(' '); 5941 } 5942 r.append(a.info.name); 5943 } 5944 } 5945 if (r != null) { 5946 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 5947 } 5948 5949 N = pkg.permissionGroups.size(); 5950 r = null; 5951 for (i=0; i<N; i++) { 5952 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 5953 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 5954 if (cur == null) { 5955 mPermissionGroups.put(pg.info.name, pg); 5956 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5957 if (r == null) { 5958 r = new StringBuilder(256); 5959 } else { 5960 r.append(' '); 5961 } 5962 r.append(pg.info.name); 5963 } 5964 } else { 5965 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 5966 + pg.info.packageName + " ignored: original from " 5967 + cur.info.packageName); 5968 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5969 if (r == null) { 5970 r = new StringBuilder(256); 5971 } else { 5972 r.append(' '); 5973 } 5974 r.append("DUP:"); 5975 r.append(pg.info.name); 5976 } 5977 } 5978 } 5979 if (r != null) { 5980 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 5981 } 5982 5983 N = pkg.permissions.size(); 5984 r = null; 5985 for (i=0; i<N; i++) { 5986 PackageParser.Permission p = pkg.permissions.get(i); 5987 HashMap<String, BasePermission> permissionMap = 5988 p.tree ? mSettings.mPermissionTrees 5989 : mSettings.mPermissions; 5990 p.group = mPermissionGroups.get(p.info.group); 5991 if (p.info.group == null || p.group != null) { 5992 BasePermission bp = permissionMap.get(p.info.name); 5993 if (bp == null) { 5994 bp = new BasePermission(p.info.name, p.info.packageName, 5995 BasePermission.TYPE_NORMAL); 5996 permissionMap.put(p.info.name, bp); 5997 } 5998 if (bp.perm == null) { 5999 if (bp.sourcePackage != null 6000 && !bp.sourcePackage.equals(p.info.packageName)) { 6001 // If this is a permission that was formerly defined by a non-system 6002 // app, but is now defined by a system app (following an upgrade), 6003 // discard the previous declaration and consider the system's to be 6004 // canonical. 6005 if (isSystemApp(p.owner)) { 6006 String msg = "New decl " + p.owner + " of permission " 6007 + p.info.name + " is system"; 6008 reportSettingsProblem(Log.WARN, msg); 6009 bp.sourcePackage = null; 6010 } 6011 } 6012 if (bp.sourcePackage == null 6013 || bp.sourcePackage.equals(p.info.packageName)) { 6014 BasePermission tree = findPermissionTreeLP(p.info.name); 6015 if (tree == null 6016 || tree.sourcePackage.equals(p.info.packageName)) { 6017 bp.packageSetting = pkgSetting; 6018 bp.perm = p; 6019 bp.uid = pkg.applicationInfo.uid; 6020 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6021 if (r == null) { 6022 r = new StringBuilder(256); 6023 } else { 6024 r.append(' '); 6025 } 6026 r.append(p.info.name); 6027 } 6028 } else { 6029 Slog.w(TAG, "Permission " + p.info.name + " from package " 6030 + p.info.packageName + " ignored: base tree " 6031 + tree.name + " is from package " 6032 + tree.sourcePackage); 6033 } 6034 } else { 6035 Slog.w(TAG, "Permission " + p.info.name + " from package " 6036 + p.info.packageName + " ignored: original from " 6037 + bp.sourcePackage); 6038 } 6039 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6040 if (r == null) { 6041 r = new StringBuilder(256); 6042 } else { 6043 r.append(' '); 6044 } 6045 r.append("DUP:"); 6046 r.append(p.info.name); 6047 } 6048 if (bp.perm == p) { 6049 bp.protectionLevel = p.info.protectionLevel; 6050 } 6051 } else { 6052 Slog.w(TAG, "Permission " + p.info.name + " from package " 6053 + p.info.packageName + " ignored: no group " 6054 + p.group); 6055 } 6056 } 6057 if (r != null) { 6058 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6059 } 6060 6061 N = pkg.instrumentation.size(); 6062 r = null; 6063 for (i=0; i<N; i++) { 6064 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6065 a.info.packageName = pkg.applicationInfo.packageName; 6066 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6067 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6068 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6069 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6070 a.info.dataDir = pkg.applicationInfo.dataDir; 6071 6072 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6073 // need other information about the application, like the ABI and what not ? 6074 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6075 mInstrumentation.put(a.getComponentName(), a); 6076 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6077 if (r == null) { 6078 r = new StringBuilder(256); 6079 } else { 6080 r.append(' '); 6081 } 6082 r.append(a.info.name); 6083 } 6084 } 6085 if (r != null) { 6086 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6087 } 6088 6089 if (pkg.protectedBroadcasts != null) { 6090 N = pkg.protectedBroadcasts.size(); 6091 for (i=0; i<N; i++) { 6092 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6093 } 6094 } 6095 6096 pkgSetting.setTimeStamp(scanFileTime); 6097 6098 // Create idmap files for pairs of (packages, overlay packages). 6099 // Note: "android", ie framework-res.apk, is handled by native layers. 6100 if (pkg.mOverlayTarget != null) { 6101 // This is an overlay package. 6102 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6103 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6104 mOverlays.put(pkg.mOverlayTarget, 6105 new HashMap<String, PackageParser.Package>()); 6106 } 6107 HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6108 map.put(pkg.packageName, pkg); 6109 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6110 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6111 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6112 "scanPackageLI failed to createIdmap"); 6113 } 6114 } 6115 } else if (mOverlays.containsKey(pkg.packageName) && 6116 !pkg.packageName.equals("android")) { 6117 // This is a regular package, with one or more known overlay packages. 6118 createIdmapsForPackageLI(pkg); 6119 } 6120 } 6121 6122 return pkg; 6123 } 6124 6125 /** 6126 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6127 * i.e, so that all packages can be run inside a single process if required. 6128 * 6129 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6130 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6131 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6132 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6133 * updating a package that belongs to a shared user. 6134 * 6135 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6136 * adds unnecessary complexity. 6137 */ 6138 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6139 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6140 String requiredInstructionSet = null; 6141 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6142 requiredInstructionSet = VMRuntime.getInstructionSet( 6143 scannedPackage.applicationInfo.primaryCpuAbi); 6144 } 6145 6146 PackageSetting requirer = null; 6147 for (PackageSetting ps : packagesForUser) { 6148 // If packagesForUser contains scannedPackage, we skip it. This will happen 6149 // when scannedPackage is an update of an existing package. Without this check, 6150 // we will never be able to change the ABI of any package belonging to a shared 6151 // user, even if it's compatible with other packages. 6152 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6153 if (ps.primaryCpuAbiString == null) { 6154 continue; 6155 } 6156 6157 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6158 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6159 // We have a mismatch between instruction sets (say arm vs arm64) warn about 6160 // this but there's not much we can do. 6161 String errorMessage = "Instruction set mismatch, " 6162 + ((requirer == null) ? "[caller]" : requirer) 6163 + " requires " + requiredInstructionSet + " whereas " + ps 6164 + " requires " + instructionSet; 6165 Slog.w(TAG, errorMessage); 6166 } 6167 6168 if (requiredInstructionSet == null) { 6169 requiredInstructionSet = instructionSet; 6170 requirer = ps; 6171 } 6172 } 6173 } 6174 6175 if (requiredInstructionSet != null) { 6176 String adjustedAbi; 6177 if (requirer != null) { 6178 // requirer != null implies that either scannedPackage was null or that scannedPackage 6179 // did not require an ABI, in which case we have to adjust scannedPackage to match 6180 // the ABI of the set (which is the same as requirer's ABI) 6181 adjustedAbi = requirer.primaryCpuAbiString; 6182 if (scannedPackage != null) { 6183 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6184 } 6185 } else { 6186 // requirer == null implies that we're updating all ABIs in the set to 6187 // match scannedPackage. 6188 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6189 } 6190 6191 for (PackageSetting ps : packagesForUser) { 6192 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6193 if (ps.primaryCpuAbiString != null) { 6194 continue; 6195 } 6196 6197 ps.primaryCpuAbiString = adjustedAbi; 6198 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6199 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6200 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6201 6202 if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt, 6203 deferDexOpt, true) == DEX_OPT_FAILED) { 6204 ps.primaryCpuAbiString = null; 6205 ps.pkg.applicationInfo.primaryCpuAbi = null; 6206 return; 6207 } else { 6208 mInstaller.rmdex(ps.codePathString, 6209 getDexCodeInstructionSet(getPreferredInstructionSet())); 6210 } 6211 } 6212 } 6213 } 6214 } 6215 } 6216 6217 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6218 synchronized (mPackages) { 6219 mResolverReplaced = true; 6220 // Set up information for custom user intent resolution activity. 6221 mResolveActivity.applicationInfo = pkg.applicationInfo; 6222 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6223 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6224 mResolveActivity.processName = null; 6225 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6226 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6227 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6228 mResolveActivity.theme = 0; 6229 mResolveActivity.exported = true; 6230 mResolveActivity.enabled = true; 6231 mResolveInfo.activityInfo = mResolveActivity; 6232 mResolveInfo.priority = 0; 6233 mResolveInfo.preferredOrder = 0; 6234 mResolveInfo.match = 0; 6235 mResolveComponentName = mCustomResolverComponentName; 6236 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6237 mResolveComponentName); 6238 } 6239 } 6240 6241 private static String calculateBundledApkRoot(final String codePathString) { 6242 final File codePath = new File(codePathString); 6243 final File codeRoot; 6244 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6245 codeRoot = Environment.getRootDirectory(); 6246 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6247 codeRoot = Environment.getOemDirectory(); 6248 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6249 codeRoot = Environment.getVendorDirectory(); 6250 } else { 6251 // Unrecognized code path; take its top real segment as the apk root: 6252 // e.g. /something/app/blah.apk => /something 6253 try { 6254 File f = codePath.getCanonicalFile(); 6255 File parent = f.getParentFile(); // non-null because codePath is a file 6256 File tmp; 6257 while ((tmp = parent.getParentFile()) != null) { 6258 f = parent; 6259 parent = tmp; 6260 } 6261 codeRoot = f; 6262 Slog.w(TAG, "Unrecognized code path " 6263 + codePath + " - using " + codeRoot); 6264 } catch (IOException e) { 6265 // Can't canonicalize the code path -- shenanigans? 6266 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6267 return Environment.getRootDirectory().getPath(); 6268 } 6269 } 6270 return codeRoot.getPath(); 6271 } 6272 6273 /** 6274 * Derive and set the location of native libraries for the given package, 6275 * which varies depending on where and how the package was installed. 6276 */ 6277 private void setNativeLibraryPaths(PackageParser.Package pkg) { 6278 final ApplicationInfo info = pkg.applicationInfo; 6279 final String codePath = pkg.codePath; 6280 final File codeFile = new File(codePath); 6281 final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info); 6282 final boolean asecApp = isForwardLocked(info) || isExternal(info); 6283 6284 info.nativeLibraryRootDir = null; 6285 info.nativeLibraryRootRequiresIsa = false; 6286 info.nativeLibraryDir = null; 6287 info.secondaryNativeLibraryDir = null; 6288 6289 if (isApkFile(codeFile)) { 6290 // Monolithic install 6291 if (bundledApp) { 6292 // If "/system/lib64/apkname" exists, assume that is the per-package 6293 // native library directory to use; otherwise use "/system/lib/apkname". 6294 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 6295 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 6296 getPrimaryInstructionSet(info)); 6297 6298 // This is a bundled system app so choose the path based on the ABI. 6299 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 6300 // is just the default path. 6301 final String apkName = deriveCodePathName(codePath); 6302 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 6303 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 6304 apkName).getAbsolutePath(); 6305 6306 if (info.secondaryCpuAbi != null) { 6307 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 6308 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 6309 secondaryLibDir, apkName).getAbsolutePath(); 6310 } 6311 } else if (asecApp) { 6312 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 6313 .getAbsolutePath(); 6314 } else { 6315 final String apkName = deriveCodePathName(codePath); 6316 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 6317 .getAbsolutePath(); 6318 } 6319 6320 info.nativeLibraryRootRequiresIsa = false; 6321 info.nativeLibraryDir = info.nativeLibraryRootDir; 6322 } else { 6323 // Cluster install 6324 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 6325 info.nativeLibraryRootRequiresIsa = true; 6326 6327 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 6328 getPrimaryInstructionSet(info)).getAbsolutePath(); 6329 6330 if (info.secondaryCpuAbi != null) { 6331 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 6332 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 6333 } 6334 } 6335 } 6336 6337 /** 6338 * Calculate the abis and roots for a bundled app. These can uniquely 6339 * be determined from the contents of the system partition, i.e whether 6340 * it contains 64 or 32 bit shared libraries etc. We do not validate any 6341 * of this information, and instead assume that the system was built 6342 * sensibly. 6343 */ 6344 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 6345 PackageSetting pkgSetting) { 6346 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 6347 6348 // If "/system/lib64/apkname" exists, assume that is the per-package 6349 // native library directory to use; otherwise use "/system/lib/apkname". 6350 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 6351 setBundledAppAbi(pkg, apkRoot, apkName); 6352 // pkgSetting might be null during rescan following uninstall of updates 6353 // to a bundled app, so accommodate that possibility. The settings in 6354 // that case will be established later from the parsed package. 6355 // 6356 // If the settings aren't null, sync them up with what we've just derived. 6357 // note that apkRoot isn't stored in the package settings. 6358 if (pkgSetting != null) { 6359 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6360 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6361 } 6362 } 6363 6364 /** 6365 * Deduces the ABI of a bundled app and sets the relevant fields on the 6366 * parsed pkg object. 6367 * 6368 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 6369 * under which system libraries are installed. 6370 * @param apkName the name of the installed package. 6371 */ 6372 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 6373 final File codeFile = new File(pkg.codePath); 6374 6375 final boolean has64BitLibs; 6376 final boolean has32BitLibs; 6377 if (isApkFile(codeFile)) { 6378 // Monolithic install 6379 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 6380 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 6381 } else { 6382 // Cluster install 6383 final File rootDir = new File(codeFile, LIB_DIR_NAME); 6384 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 6385 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 6386 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 6387 has64BitLibs = (new File(rootDir, isa)).exists(); 6388 } else { 6389 has64BitLibs = false; 6390 } 6391 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 6392 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 6393 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 6394 has32BitLibs = (new File(rootDir, isa)).exists(); 6395 } else { 6396 has32BitLibs = false; 6397 } 6398 } 6399 6400 if (has64BitLibs && !has32BitLibs) { 6401 // The package has 64 bit libs, but not 32 bit libs. Its primary 6402 // ABI should be 64 bit. We can safely assume here that the bundled 6403 // native libraries correspond to the most preferred ABI in the list. 6404 6405 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6406 pkg.applicationInfo.secondaryCpuAbi = null; 6407 } else if (has32BitLibs && !has64BitLibs) { 6408 // The package has 32 bit libs but not 64 bit libs. Its primary 6409 // ABI should be 32 bit. 6410 6411 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6412 pkg.applicationInfo.secondaryCpuAbi = null; 6413 } else if (has32BitLibs && has64BitLibs) { 6414 // The application has both 64 and 32 bit bundled libraries. We check 6415 // here that the app declares multiArch support, and warn if it doesn't. 6416 // 6417 // We will be lenient here and record both ABIs. The primary will be the 6418 // ABI that's higher on the list, i.e, a device that's configured to prefer 6419 // 64 bit apps will see a 64 bit primary ABI, 6420 6421 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 6422 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 6423 } 6424 6425 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 6426 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6427 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6428 } else { 6429 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6430 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6431 } 6432 } else { 6433 pkg.applicationInfo.primaryCpuAbi = null; 6434 pkg.applicationInfo.secondaryCpuAbi = null; 6435 } 6436 } 6437 6438 private void killApplication(String pkgName, int appId, String reason) { 6439 // Request the ActivityManager to kill the process(only for existing packages) 6440 // so that we do not end up in a confused state while the user is still using the older 6441 // version of the application while the new one gets installed. 6442 IActivityManager am = ActivityManagerNative.getDefault(); 6443 if (am != null) { 6444 try { 6445 am.killApplicationWithAppId(pkgName, appId, reason); 6446 } catch (RemoteException e) { 6447 } 6448 } 6449 } 6450 6451 void removePackageLI(PackageSetting ps, boolean chatty) { 6452 if (DEBUG_INSTALL) { 6453 if (chatty) 6454 Log.d(TAG, "Removing package " + ps.name); 6455 } 6456 6457 // writer 6458 synchronized (mPackages) { 6459 mPackages.remove(ps.name); 6460 final PackageParser.Package pkg = ps.pkg; 6461 if (pkg != null) { 6462 cleanPackageDataStructuresLILPw(pkg, chatty); 6463 } 6464 } 6465 } 6466 6467 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 6468 if (DEBUG_INSTALL) { 6469 if (chatty) 6470 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 6471 } 6472 6473 // writer 6474 synchronized (mPackages) { 6475 mPackages.remove(pkg.applicationInfo.packageName); 6476 cleanPackageDataStructuresLILPw(pkg, chatty); 6477 } 6478 } 6479 6480 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 6481 int N = pkg.providers.size(); 6482 StringBuilder r = null; 6483 int i; 6484 for (i=0; i<N; i++) { 6485 PackageParser.Provider p = pkg.providers.get(i); 6486 mProviders.removeProvider(p); 6487 if (p.info.authority == null) { 6488 6489 /* There was another ContentProvider with this authority when 6490 * this app was installed so this authority is null, 6491 * Ignore it as we don't have to unregister the provider. 6492 */ 6493 continue; 6494 } 6495 String names[] = p.info.authority.split(";"); 6496 for (int j = 0; j < names.length; j++) { 6497 if (mProvidersByAuthority.get(names[j]) == p) { 6498 mProvidersByAuthority.remove(names[j]); 6499 if (DEBUG_REMOVE) { 6500 if (chatty) 6501 Log.d(TAG, "Unregistered content provider: " + names[j] 6502 + ", className = " + p.info.name + ", isSyncable = " 6503 + p.info.isSyncable); 6504 } 6505 } 6506 } 6507 if (DEBUG_REMOVE && chatty) { 6508 if (r == null) { 6509 r = new StringBuilder(256); 6510 } else { 6511 r.append(' '); 6512 } 6513 r.append(p.info.name); 6514 } 6515 } 6516 if (r != null) { 6517 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 6518 } 6519 6520 N = pkg.services.size(); 6521 r = null; 6522 for (i=0; i<N; i++) { 6523 PackageParser.Service s = pkg.services.get(i); 6524 mServices.removeService(s); 6525 if (chatty) { 6526 if (r == null) { 6527 r = new StringBuilder(256); 6528 } else { 6529 r.append(' '); 6530 } 6531 r.append(s.info.name); 6532 } 6533 } 6534 if (r != null) { 6535 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 6536 } 6537 6538 N = pkg.receivers.size(); 6539 r = null; 6540 for (i=0; i<N; i++) { 6541 PackageParser.Activity a = pkg.receivers.get(i); 6542 mReceivers.removeActivity(a, "receiver"); 6543 if (DEBUG_REMOVE && chatty) { 6544 if (r == null) { 6545 r = new StringBuilder(256); 6546 } else { 6547 r.append(' '); 6548 } 6549 r.append(a.info.name); 6550 } 6551 } 6552 if (r != null) { 6553 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 6554 } 6555 6556 N = pkg.activities.size(); 6557 r = null; 6558 for (i=0; i<N; i++) { 6559 PackageParser.Activity a = pkg.activities.get(i); 6560 mActivities.removeActivity(a, "activity"); 6561 if (DEBUG_REMOVE && chatty) { 6562 if (r == null) { 6563 r = new StringBuilder(256); 6564 } else { 6565 r.append(' '); 6566 } 6567 r.append(a.info.name); 6568 } 6569 } 6570 if (r != null) { 6571 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 6572 } 6573 6574 N = pkg.permissions.size(); 6575 r = null; 6576 for (i=0; i<N; i++) { 6577 PackageParser.Permission p = pkg.permissions.get(i); 6578 BasePermission bp = mSettings.mPermissions.get(p.info.name); 6579 if (bp == null) { 6580 bp = mSettings.mPermissionTrees.get(p.info.name); 6581 } 6582 if (bp != null && bp.perm == p) { 6583 bp.perm = null; 6584 if (DEBUG_REMOVE && chatty) { 6585 if (r == null) { 6586 r = new StringBuilder(256); 6587 } else { 6588 r.append(' '); 6589 } 6590 r.append(p.info.name); 6591 } 6592 } 6593 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6594 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 6595 if (appOpPerms != null) { 6596 appOpPerms.remove(pkg.packageName); 6597 } 6598 } 6599 } 6600 if (r != null) { 6601 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6602 } 6603 6604 N = pkg.requestedPermissions.size(); 6605 r = null; 6606 for (i=0; i<N; i++) { 6607 String perm = pkg.requestedPermissions.get(i); 6608 BasePermission bp = mSettings.mPermissions.get(perm); 6609 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6610 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 6611 if (appOpPerms != null) { 6612 appOpPerms.remove(pkg.packageName); 6613 if (appOpPerms.isEmpty()) { 6614 mAppOpPermissionPackages.remove(perm); 6615 } 6616 } 6617 } 6618 } 6619 if (r != null) { 6620 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6621 } 6622 6623 N = pkg.instrumentation.size(); 6624 r = null; 6625 for (i=0; i<N; i++) { 6626 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6627 mInstrumentation.remove(a.getComponentName()); 6628 if (DEBUG_REMOVE && chatty) { 6629 if (r == null) { 6630 r = new StringBuilder(256); 6631 } else { 6632 r.append(' '); 6633 } 6634 r.append(a.info.name); 6635 } 6636 } 6637 if (r != null) { 6638 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 6639 } 6640 6641 r = null; 6642 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6643 // Only system apps can hold shared libraries. 6644 if (pkg.libraryNames != null) { 6645 for (i=0; i<pkg.libraryNames.size(); i++) { 6646 String name = pkg.libraryNames.get(i); 6647 SharedLibraryEntry cur = mSharedLibraries.get(name); 6648 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 6649 mSharedLibraries.remove(name); 6650 if (DEBUG_REMOVE && chatty) { 6651 if (r == null) { 6652 r = new StringBuilder(256); 6653 } else { 6654 r.append(' '); 6655 } 6656 r.append(name); 6657 } 6658 } 6659 } 6660 } 6661 } 6662 if (r != null) { 6663 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 6664 } 6665 } 6666 6667 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 6668 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 6669 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 6670 return true; 6671 } 6672 } 6673 return false; 6674 } 6675 6676 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 6677 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 6678 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 6679 6680 private void updatePermissionsLPw(String changingPkg, 6681 PackageParser.Package pkgInfo, int flags) { 6682 // Make sure there are no dangling permission trees. 6683 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 6684 while (it.hasNext()) { 6685 final BasePermission bp = it.next(); 6686 if (bp.packageSetting == null) { 6687 // We may not yet have parsed the package, so just see if 6688 // we still know about its settings. 6689 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6690 } 6691 if (bp.packageSetting == null) { 6692 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 6693 + " from package " + bp.sourcePackage); 6694 it.remove(); 6695 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6696 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6697 Slog.i(TAG, "Removing old permission tree: " + bp.name 6698 + " from package " + bp.sourcePackage); 6699 flags |= UPDATE_PERMISSIONS_ALL; 6700 it.remove(); 6701 } 6702 } 6703 } 6704 6705 // Make sure all dynamic permissions have been assigned to a package, 6706 // and make sure there are no dangling permissions. 6707 it = mSettings.mPermissions.values().iterator(); 6708 while (it.hasNext()) { 6709 final BasePermission bp = it.next(); 6710 if (bp.type == BasePermission.TYPE_DYNAMIC) { 6711 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 6712 + bp.name + " pkg=" + bp.sourcePackage 6713 + " info=" + bp.pendingInfo); 6714 if (bp.packageSetting == null && bp.pendingInfo != null) { 6715 final BasePermission tree = findPermissionTreeLP(bp.name); 6716 if (tree != null && tree.perm != null) { 6717 bp.packageSetting = tree.packageSetting; 6718 bp.perm = new PackageParser.Permission(tree.perm.owner, 6719 new PermissionInfo(bp.pendingInfo)); 6720 bp.perm.info.packageName = tree.perm.info.packageName; 6721 bp.perm.info.name = bp.name; 6722 bp.uid = tree.uid; 6723 } 6724 } 6725 } 6726 if (bp.packageSetting == null) { 6727 // We may not yet have parsed the package, so just see if 6728 // we still know about its settings. 6729 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6730 } 6731 if (bp.packageSetting == null) { 6732 Slog.w(TAG, "Removing dangling permission: " + bp.name 6733 + " from package " + bp.sourcePackage); 6734 it.remove(); 6735 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6736 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6737 Slog.i(TAG, "Removing old permission: " + bp.name 6738 + " from package " + bp.sourcePackage); 6739 flags |= UPDATE_PERMISSIONS_ALL; 6740 it.remove(); 6741 } 6742 } 6743 } 6744 6745 // Now update the permissions for all packages, in particular 6746 // replace the granted permissions of the system packages. 6747 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 6748 for (PackageParser.Package pkg : mPackages.values()) { 6749 if (pkg != pkgInfo) { 6750 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0); 6751 } 6752 } 6753 } 6754 6755 if (pkgInfo != null) { 6756 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0); 6757 } 6758 } 6759 6760 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) { 6761 final PackageSetting ps = (PackageSetting) pkg.mExtras; 6762 if (ps == null) { 6763 return; 6764 } 6765 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 6766 HashSet<String> origPermissions = gp.grantedPermissions; 6767 boolean changedPermission = false; 6768 6769 if (replace) { 6770 ps.permissionsFixed = false; 6771 if (gp == ps) { 6772 origPermissions = new HashSet<String>(gp.grantedPermissions); 6773 gp.grantedPermissions.clear(); 6774 gp.gids = mGlobalGids; 6775 } 6776 } 6777 6778 if (gp.gids == null) { 6779 gp.gids = mGlobalGids; 6780 } 6781 6782 final int N = pkg.requestedPermissions.size(); 6783 for (int i=0; i<N; i++) { 6784 final String name = pkg.requestedPermissions.get(i); 6785 final boolean required = pkg.requestedPermissionsRequired.get(i); 6786 final BasePermission bp = mSettings.mPermissions.get(name); 6787 if (DEBUG_INSTALL) { 6788 if (gp != ps) { 6789 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 6790 } 6791 } 6792 6793 if (bp == null || bp.packageSetting == null) { 6794 Slog.w(TAG, "Unknown permission " + name 6795 + " in package " + pkg.packageName); 6796 continue; 6797 } 6798 6799 final String perm = bp.name; 6800 boolean allowed; 6801 boolean allowedSig = false; 6802 if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6803 // Keep track of app op permissions. 6804 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 6805 if (pkgs == null) { 6806 pkgs = new ArraySet<>(); 6807 mAppOpPermissionPackages.put(bp.name, pkgs); 6808 } 6809 pkgs.add(pkg.packageName); 6810 } 6811 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 6812 if (level == PermissionInfo.PROTECTION_NORMAL 6813 || level == PermissionInfo.PROTECTION_DANGEROUS) { 6814 // We grant a normal or dangerous permission if any of the following 6815 // are true: 6816 // 1) The permission is required 6817 // 2) The permission is optional, but was granted in the past 6818 // 3) The permission is optional, but was requested by an 6819 // app in /system (not /data) 6820 // 6821 // Otherwise, reject the permission. 6822 allowed = (required || origPermissions.contains(perm) 6823 || (isSystemApp(ps) && !isUpdatedSystemApp(ps))); 6824 } else if (bp.packageSetting == null) { 6825 // This permission is invalid; skip it. 6826 allowed = false; 6827 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 6828 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions); 6829 if (allowed) { 6830 allowedSig = true; 6831 } 6832 } else { 6833 allowed = false; 6834 } 6835 if (DEBUG_INSTALL) { 6836 if (gp != ps) { 6837 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 6838 } 6839 } 6840 if (allowed) { 6841 if (!isSystemApp(ps) && ps.permissionsFixed) { 6842 // If this is an existing, non-system package, then 6843 // we can't add any new permissions to it. 6844 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 6845 // Except... if this is a permission that was added 6846 // to the platform (note: need to only do this when 6847 // updating the platform). 6848 allowed = isNewPlatformPermissionForPackage(perm, pkg); 6849 } 6850 } 6851 if (allowed) { 6852 if (!gp.grantedPermissions.contains(perm)) { 6853 changedPermission = true; 6854 gp.grantedPermissions.add(perm); 6855 gp.gids = appendInts(gp.gids, bp.gids); 6856 } else if (!ps.haveGids) { 6857 gp.gids = appendInts(gp.gids, bp.gids); 6858 } 6859 } else { 6860 Slog.w(TAG, "Not granting permission " + perm 6861 + " to package " + pkg.packageName 6862 + " because it was previously installed without"); 6863 } 6864 } else { 6865 if (gp.grantedPermissions.remove(perm)) { 6866 changedPermission = true; 6867 gp.gids = removeInts(gp.gids, bp.gids); 6868 Slog.i(TAG, "Un-granting permission " + perm 6869 + " from package " + pkg.packageName 6870 + " (protectionLevel=" + bp.protectionLevel 6871 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6872 + ")"); 6873 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 6874 // Don't print warning for app op permissions, since it is fine for them 6875 // not to be granted, there is a UI for the user to decide. 6876 Slog.w(TAG, "Not granting permission " + perm 6877 + " to package " + pkg.packageName 6878 + " (protectionLevel=" + bp.protectionLevel 6879 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6880 + ")"); 6881 } 6882 } 6883 } 6884 6885 if ((changedPermission || replace) && !ps.permissionsFixed && 6886 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 6887 // This is the first that we have heard about this package, so the 6888 // permissions we have now selected are fixed until explicitly 6889 // changed. 6890 ps.permissionsFixed = true; 6891 } 6892 ps.haveGids = true; 6893 } 6894 6895 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 6896 boolean allowed = false; 6897 final int NP = PackageParser.NEW_PERMISSIONS.length; 6898 for (int ip=0; ip<NP; ip++) { 6899 final PackageParser.NewPermissionInfo npi 6900 = PackageParser.NEW_PERMISSIONS[ip]; 6901 if (npi.name.equals(perm) 6902 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 6903 allowed = true; 6904 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 6905 + pkg.packageName); 6906 break; 6907 } 6908 } 6909 return allowed; 6910 } 6911 6912 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 6913 BasePermission bp, HashSet<String> origPermissions) { 6914 boolean allowed; 6915 allowed = (compareSignatures( 6916 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 6917 == PackageManager.SIGNATURE_MATCH) 6918 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 6919 == PackageManager.SIGNATURE_MATCH); 6920 if (!allowed && (bp.protectionLevel 6921 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 6922 if (isSystemApp(pkg)) { 6923 // For updated system applications, a system permission 6924 // is granted only if it had been defined by the original application. 6925 if (isUpdatedSystemApp(pkg)) { 6926 final PackageSetting sysPs = mSettings 6927 .getDisabledSystemPkgLPr(pkg.packageName); 6928 final GrantedPermissions origGp = sysPs.sharedUser != null 6929 ? sysPs.sharedUser : sysPs; 6930 6931 if (origGp.grantedPermissions.contains(perm)) { 6932 // If the original was granted this permission, we take 6933 // that grant decision as read and propagate it to the 6934 // update. 6935 allowed = true; 6936 } else { 6937 // The system apk may have been updated with an older 6938 // version of the one on the data partition, but which 6939 // granted a new system permission that it didn't have 6940 // before. In this case we do want to allow the app to 6941 // now get the new permission if the ancestral apk is 6942 // privileged to get it. 6943 if (sysPs.pkg != null && sysPs.isPrivileged()) { 6944 for (int j=0; 6945 j<sysPs.pkg.requestedPermissions.size(); j++) { 6946 if (perm.equals( 6947 sysPs.pkg.requestedPermissions.get(j))) { 6948 allowed = true; 6949 break; 6950 } 6951 } 6952 } 6953 } 6954 } else { 6955 allowed = isPrivilegedApp(pkg); 6956 } 6957 } 6958 } 6959 if (!allowed && (bp.protectionLevel 6960 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 6961 // For development permissions, a development permission 6962 // is granted only if it was already granted. 6963 allowed = origPermissions.contains(perm); 6964 } 6965 return allowed; 6966 } 6967 6968 final class ActivityIntentResolver 6969 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 6970 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 6971 boolean defaultOnly, int userId) { 6972 if (!sUserManager.exists(userId)) return null; 6973 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 6974 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 6975 } 6976 6977 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 6978 int userId) { 6979 if (!sUserManager.exists(userId)) return null; 6980 mFlags = flags; 6981 return super.queryIntent(intent, resolvedType, 6982 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 6983 } 6984 6985 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 6986 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 6987 if (!sUserManager.exists(userId)) return null; 6988 if (packageActivities == null) { 6989 return null; 6990 } 6991 mFlags = flags; 6992 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 6993 final int N = packageActivities.size(); 6994 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 6995 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 6996 6997 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 6998 for (int i = 0; i < N; ++i) { 6999 intentFilters = packageActivities.get(i).intents; 7000 if (intentFilters != null && intentFilters.size() > 0) { 7001 PackageParser.ActivityIntentInfo[] array = 7002 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 7003 intentFilters.toArray(array); 7004 listCut.add(array); 7005 } 7006 } 7007 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7008 } 7009 7010 public final void addActivity(PackageParser.Activity a, String type) { 7011 final boolean systemApp = isSystemApp(a.info.applicationInfo); 7012 mActivities.put(a.getComponentName(), a); 7013 if (DEBUG_SHOW_INFO) 7014 Log.v( 7015 TAG, " " + type + " " + 7016 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 7017 if (DEBUG_SHOW_INFO) 7018 Log.v(TAG, " Class=" + a.info.name); 7019 final int NI = a.intents.size(); 7020 for (int j=0; j<NI; j++) { 7021 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7022 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 7023 intent.setPriority(0); 7024 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 7025 + a.className + " with priority > 0, forcing to 0"); 7026 } 7027 if (DEBUG_SHOW_INFO) { 7028 Log.v(TAG, " IntentFilter:"); 7029 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7030 } 7031 if (!intent.debugCheck()) { 7032 Log.w(TAG, "==> For Activity " + a.info.name); 7033 } 7034 addFilter(intent); 7035 } 7036 } 7037 7038 public final void removeActivity(PackageParser.Activity a, String type) { 7039 mActivities.remove(a.getComponentName()); 7040 if (DEBUG_SHOW_INFO) { 7041 Log.v(TAG, " " + type + " " 7042 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 7043 : a.info.name) + ":"); 7044 Log.v(TAG, " Class=" + a.info.name); 7045 } 7046 final int NI = a.intents.size(); 7047 for (int j=0; j<NI; j++) { 7048 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7049 if (DEBUG_SHOW_INFO) { 7050 Log.v(TAG, " IntentFilter:"); 7051 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7052 } 7053 removeFilter(intent); 7054 } 7055 } 7056 7057 @Override 7058 protected boolean allowFilterResult( 7059 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 7060 ActivityInfo filterAi = filter.activity.info; 7061 for (int i=dest.size()-1; i>=0; i--) { 7062 ActivityInfo destAi = dest.get(i).activityInfo; 7063 if (destAi.name == filterAi.name 7064 && destAi.packageName == filterAi.packageName) { 7065 return false; 7066 } 7067 } 7068 return true; 7069 } 7070 7071 @Override 7072 protected ActivityIntentInfo[] newArray(int size) { 7073 return new ActivityIntentInfo[size]; 7074 } 7075 7076 @Override 7077 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 7078 if (!sUserManager.exists(userId)) return true; 7079 PackageParser.Package p = filter.activity.owner; 7080 if (p != null) { 7081 PackageSetting ps = (PackageSetting)p.mExtras; 7082 if (ps != null) { 7083 // System apps are never considered stopped for purposes of 7084 // filtering, because there may be no way for the user to 7085 // actually re-launch them. 7086 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 7087 && ps.getStopped(userId); 7088 } 7089 } 7090 return false; 7091 } 7092 7093 @Override 7094 protected boolean isPackageForFilter(String packageName, 7095 PackageParser.ActivityIntentInfo info) { 7096 return packageName.equals(info.activity.owner.packageName); 7097 } 7098 7099 @Override 7100 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7101 int match, int userId) { 7102 if (!sUserManager.exists(userId)) return null; 7103 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7104 return null; 7105 } 7106 final PackageParser.Activity activity = info.activity; 7107 if (mSafeMode && (activity.info.applicationInfo.flags 7108 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7109 return null; 7110 } 7111 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7112 if (ps == null) { 7113 return null; 7114 } 7115 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7116 ps.readUserState(userId), userId); 7117 if (ai == null) { 7118 return null; 7119 } 7120 final ResolveInfo res = new ResolveInfo(); 7121 res.activityInfo = ai; 7122 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7123 res.filter = info; 7124 } 7125 res.priority = info.getPriority(); 7126 res.preferredOrder = activity.owner.mPreferredOrder; 7127 //System.out.println("Result: " + res.activityInfo.className + 7128 // " = " + res.priority); 7129 res.match = match; 7130 res.isDefault = info.hasDefault; 7131 res.labelRes = info.labelRes; 7132 res.nonLocalizedLabel = info.nonLocalizedLabel; 7133 if (userNeedsBadging(userId)) { 7134 res.noResourceId = true; 7135 } else { 7136 res.icon = info.icon; 7137 } 7138 res.system = isSystemApp(res.activityInfo.applicationInfo); 7139 return res; 7140 } 7141 7142 @Override 7143 protected void sortResults(List<ResolveInfo> results) { 7144 Collections.sort(results, mResolvePrioritySorter); 7145 } 7146 7147 @Override 7148 protected void dumpFilter(PrintWriter out, String prefix, 7149 PackageParser.ActivityIntentInfo filter) { 7150 out.print(prefix); out.print( 7151 Integer.toHexString(System.identityHashCode(filter.activity))); 7152 out.print(' '); 7153 filter.activity.printComponentShortName(out); 7154 out.print(" filter "); 7155 out.println(Integer.toHexString(System.identityHashCode(filter))); 7156 } 7157 7158// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7159// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7160// final List<ResolveInfo> retList = Lists.newArrayList(); 7161// while (i.hasNext()) { 7162// final ResolveInfo resolveInfo = i.next(); 7163// if (isEnabledLP(resolveInfo.activityInfo)) { 7164// retList.add(resolveInfo); 7165// } 7166// } 7167// return retList; 7168// } 7169 7170 // Keys are String (activity class name), values are Activity. 7171 private final HashMap<ComponentName, PackageParser.Activity> mActivities 7172 = new HashMap<ComponentName, PackageParser.Activity>(); 7173 private int mFlags; 7174 } 7175 7176 private final class ServiceIntentResolver 7177 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 7178 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7179 boolean defaultOnly, int userId) { 7180 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7181 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7182 } 7183 7184 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7185 int userId) { 7186 if (!sUserManager.exists(userId)) return null; 7187 mFlags = flags; 7188 return super.queryIntent(intent, resolvedType, 7189 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7190 } 7191 7192 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7193 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 7194 if (!sUserManager.exists(userId)) return null; 7195 if (packageServices == null) { 7196 return null; 7197 } 7198 mFlags = flags; 7199 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7200 final int N = packageServices.size(); 7201 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 7202 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 7203 7204 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 7205 for (int i = 0; i < N; ++i) { 7206 intentFilters = packageServices.get(i).intents; 7207 if (intentFilters != null && intentFilters.size() > 0) { 7208 PackageParser.ServiceIntentInfo[] array = 7209 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 7210 intentFilters.toArray(array); 7211 listCut.add(array); 7212 } 7213 } 7214 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7215 } 7216 7217 public final void addService(PackageParser.Service s) { 7218 mServices.put(s.getComponentName(), s); 7219 if (DEBUG_SHOW_INFO) { 7220 Log.v(TAG, " " 7221 + (s.info.nonLocalizedLabel != null 7222 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7223 Log.v(TAG, " Class=" + s.info.name); 7224 } 7225 final int NI = s.intents.size(); 7226 int j; 7227 for (j=0; j<NI; j++) { 7228 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7229 if (DEBUG_SHOW_INFO) { 7230 Log.v(TAG, " IntentFilter:"); 7231 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7232 } 7233 if (!intent.debugCheck()) { 7234 Log.w(TAG, "==> For Service " + s.info.name); 7235 } 7236 addFilter(intent); 7237 } 7238 } 7239 7240 public final void removeService(PackageParser.Service s) { 7241 mServices.remove(s.getComponentName()); 7242 if (DEBUG_SHOW_INFO) { 7243 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 7244 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7245 Log.v(TAG, " Class=" + s.info.name); 7246 } 7247 final int NI = s.intents.size(); 7248 int j; 7249 for (j=0; j<NI; j++) { 7250 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7251 if (DEBUG_SHOW_INFO) { 7252 Log.v(TAG, " IntentFilter:"); 7253 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7254 } 7255 removeFilter(intent); 7256 } 7257 } 7258 7259 @Override 7260 protected boolean allowFilterResult( 7261 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 7262 ServiceInfo filterSi = filter.service.info; 7263 for (int i=dest.size()-1; i>=0; i--) { 7264 ServiceInfo destAi = dest.get(i).serviceInfo; 7265 if (destAi.name == filterSi.name 7266 && destAi.packageName == filterSi.packageName) { 7267 return false; 7268 } 7269 } 7270 return true; 7271 } 7272 7273 @Override 7274 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 7275 return new PackageParser.ServiceIntentInfo[size]; 7276 } 7277 7278 @Override 7279 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 7280 if (!sUserManager.exists(userId)) return true; 7281 PackageParser.Package p = filter.service.owner; 7282 if (p != null) { 7283 PackageSetting ps = (PackageSetting)p.mExtras; 7284 if (ps != null) { 7285 // System apps are never considered stopped for purposes of 7286 // filtering, because there may be no way for the user to 7287 // actually re-launch them. 7288 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7289 && ps.getStopped(userId); 7290 } 7291 } 7292 return false; 7293 } 7294 7295 @Override 7296 protected boolean isPackageForFilter(String packageName, 7297 PackageParser.ServiceIntentInfo info) { 7298 return packageName.equals(info.service.owner.packageName); 7299 } 7300 7301 @Override 7302 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 7303 int match, int userId) { 7304 if (!sUserManager.exists(userId)) return null; 7305 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 7306 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 7307 return null; 7308 } 7309 final PackageParser.Service service = info.service; 7310 if (mSafeMode && (service.info.applicationInfo.flags 7311 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7312 return null; 7313 } 7314 PackageSetting ps = (PackageSetting) service.owner.mExtras; 7315 if (ps == null) { 7316 return null; 7317 } 7318 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 7319 ps.readUserState(userId), userId); 7320 if (si == null) { 7321 return null; 7322 } 7323 final ResolveInfo res = new ResolveInfo(); 7324 res.serviceInfo = si; 7325 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7326 res.filter = filter; 7327 } 7328 res.priority = info.getPriority(); 7329 res.preferredOrder = service.owner.mPreferredOrder; 7330 //System.out.println("Result: " + res.activityInfo.className + 7331 // " = " + res.priority); 7332 res.match = match; 7333 res.isDefault = info.hasDefault; 7334 res.labelRes = info.labelRes; 7335 res.nonLocalizedLabel = info.nonLocalizedLabel; 7336 res.icon = info.icon; 7337 res.system = isSystemApp(res.serviceInfo.applicationInfo); 7338 return res; 7339 } 7340 7341 @Override 7342 protected void sortResults(List<ResolveInfo> results) { 7343 Collections.sort(results, mResolvePrioritySorter); 7344 } 7345 7346 @Override 7347 protected void dumpFilter(PrintWriter out, String prefix, 7348 PackageParser.ServiceIntentInfo filter) { 7349 out.print(prefix); out.print( 7350 Integer.toHexString(System.identityHashCode(filter.service))); 7351 out.print(' '); 7352 filter.service.printComponentShortName(out); 7353 out.print(" filter "); 7354 out.println(Integer.toHexString(System.identityHashCode(filter))); 7355 } 7356 7357// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7358// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7359// final List<ResolveInfo> retList = Lists.newArrayList(); 7360// while (i.hasNext()) { 7361// final ResolveInfo resolveInfo = (ResolveInfo) i; 7362// if (isEnabledLP(resolveInfo.serviceInfo)) { 7363// retList.add(resolveInfo); 7364// } 7365// } 7366// return retList; 7367// } 7368 7369 // Keys are String (activity class name), values are Activity. 7370 private final HashMap<ComponentName, PackageParser.Service> mServices 7371 = new HashMap<ComponentName, PackageParser.Service>(); 7372 private int mFlags; 7373 }; 7374 7375 private final class ProviderIntentResolver 7376 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 7377 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7378 boolean defaultOnly, int userId) { 7379 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7380 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7381 } 7382 7383 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7384 int userId) { 7385 if (!sUserManager.exists(userId)) 7386 return null; 7387 mFlags = flags; 7388 return super.queryIntent(intent, resolvedType, 7389 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7390 } 7391 7392 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7393 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 7394 if (!sUserManager.exists(userId)) 7395 return null; 7396 if (packageProviders == null) { 7397 return null; 7398 } 7399 mFlags = flags; 7400 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 7401 final int N = packageProviders.size(); 7402 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 7403 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 7404 7405 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 7406 for (int i = 0; i < N; ++i) { 7407 intentFilters = packageProviders.get(i).intents; 7408 if (intentFilters != null && intentFilters.size() > 0) { 7409 PackageParser.ProviderIntentInfo[] array = 7410 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 7411 intentFilters.toArray(array); 7412 listCut.add(array); 7413 } 7414 } 7415 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7416 } 7417 7418 public final void addProvider(PackageParser.Provider p) { 7419 if (mProviders.containsKey(p.getComponentName())) { 7420 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 7421 return; 7422 } 7423 7424 mProviders.put(p.getComponentName(), p); 7425 if (DEBUG_SHOW_INFO) { 7426 Log.v(TAG, " " 7427 + (p.info.nonLocalizedLabel != null 7428 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7429 Log.v(TAG, " Class=" + p.info.name); 7430 } 7431 final int NI = p.intents.size(); 7432 int j; 7433 for (j = 0; j < NI; j++) { 7434 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7435 if (DEBUG_SHOW_INFO) { 7436 Log.v(TAG, " IntentFilter:"); 7437 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7438 } 7439 if (!intent.debugCheck()) { 7440 Log.w(TAG, "==> For Provider " + p.info.name); 7441 } 7442 addFilter(intent); 7443 } 7444 } 7445 7446 public final void removeProvider(PackageParser.Provider p) { 7447 mProviders.remove(p.getComponentName()); 7448 if (DEBUG_SHOW_INFO) { 7449 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 7450 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7451 Log.v(TAG, " Class=" + p.info.name); 7452 } 7453 final int NI = p.intents.size(); 7454 int j; 7455 for (j = 0; j < NI; j++) { 7456 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7457 if (DEBUG_SHOW_INFO) { 7458 Log.v(TAG, " IntentFilter:"); 7459 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7460 } 7461 removeFilter(intent); 7462 } 7463 } 7464 7465 @Override 7466 protected boolean allowFilterResult( 7467 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 7468 ProviderInfo filterPi = filter.provider.info; 7469 for (int i = dest.size() - 1; i >= 0; i--) { 7470 ProviderInfo destPi = dest.get(i).providerInfo; 7471 if (destPi.name == filterPi.name 7472 && destPi.packageName == filterPi.packageName) { 7473 return false; 7474 } 7475 } 7476 return true; 7477 } 7478 7479 @Override 7480 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 7481 return new PackageParser.ProviderIntentInfo[size]; 7482 } 7483 7484 @Override 7485 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 7486 if (!sUserManager.exists(userId)) 7487 return true; 7488 PackageParser.Package p = filter.provider.owner; 7489 if (p != null) { 7490 PackageSetting ps = (PackageSetting) p.mExtras; 7491 if (ps != null) { 7492 // System apps are never considered stopped for purposes of 7493 // filtering, because there may be no way for the user to 7494 // actually re-launch them. 7495 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7496 && ps.getStopped(userId); 7497 } 7498 } 7499 return false; 7500 } 7501 7502 @Override 7503 protected boolean isPackageForFilter(String packageName, 7504 PackageParser.ProviderIntentInfo info) { 7505 return packageName.equals(info.provider.owner.packageName); 7506 } 7507 7508 @Override 7509 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 7510 int match, int userId) { 7511 if (!sUserManager.exists(userId)) 7512 return null; 7513 final PackageParser.ProviderIntentInfo info = filter; 7514 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 7515 return null; 7516 } 7517 final PackageParser.Provider provider = info.provider; 7518 if (mSafeMode && (provider.info.applicationInfo.flags 7519 & ApplicationInfo.FLAG_SYSTEM) == 0) { 7520 return null; 7521 } 7522 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 7523 if (ps == null) { 7524 return null; 7525 } 7526 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 7527 ps.readUserState(userId), userId); 7528 if (pi == null) { 7529 return null; 7530 } 7531 final ResolveInfo res = new ResolveInfo(); 7532 res.providerInfo = pi; 7533 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 7534 res.filter = filter; 7535 } 7536 res.priority = info.getPriority(); 7537 res.preferredOrder = provider.owner.mPreferredOrder; 7538 res.match = match; 7539 res.isDefault = info.hasDefault; 7540 res.labelRes = info.labelRes; 7541 res.nonLocalizedLabel = info.nonLocalizedLabel; 7542 res.icon = info.icon; 7543 res.system = isSystemApp(res.providerInfo.applicationInfo); 7544 return res; 7545 } 7546 7547 @Override 7548 protected void sortResults(List<ResolveInfo> results) { 7549 Collections.sort(results, mResolvePrioritySorter); 7550 } 7551 7552 @Override 7553 protected void dumpFilter(PrintWriter out, String prefix, 7554 PackageParser.ProviderIntentInfo filter) { 7555 out.print(prefix); 7556 out.print( 7557 Integer.toHexString(System.identityHashCode(filter.provider))); 7558 out.print(' '); 7559 filter.provider.printComponentShortName(out); 7560 out.print(" filter "); 7561 out.println(Integer.toHexString(System.identityHashCode(filter))); 7562 } 7563 7564 private final HashMap<ComponentName, PackageParser.Provider> mProviders 7565 = new HashMap<ComponentName, PackageParser.Provider>(); 7566 private int mFlags; 7567 }; 7568 7569 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 7570 new Comparator<ResolveInfo>() { 7571 public int compare(ResolveInfo r1, ResolveInfo r2) { 7572 int v1 = r1.priority; 7573 int v2 = r2.priority; 7574 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 7575 if (v1 != v2) { 7576 return (v1 > v2) ? -1 : 1; 7577 } 7578 v1 = r1.preferredOrder; 7579 v2 = r2.preferredOrder; 7580 if (v1 != v2) { 7581 return (v1 > v2) ? -1 : 1; 7582 } 7583 if (r1.isDefault != r2.isDefault) { 7584 return r1.isDefault ? -1 : 1; 7585 } 7586 v1 = r1.match; 7587 v2 = r2.match; 7588 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 7589 if (v1 != v2) { 7590 return (v1 > v2) ? -1 : 1; 7591 } 7592 if (r1.system != r2.system) { 7593 return r1.system ? -1 : 1; 7594 } 7595 return 0; 7596 } 7597 }; 7598 7599 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 7600 new Comparator<ProviderInfo>() { 7601 public int compare(ProviderInfo p1, ProviderInfo p2) { 7602 final int v1 = p1.initOrder; 7603 final int v2 = p2.initOrder; 7604 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 7605 } 7606 }; 7607 7608 static final void sendPackageBroadcast(String action, String pkg, 7609 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 7610 int[] userIds) { 7611 IActivityManager am = ActivityManagerNative.getDefault(); 7612 if (am != null) { 7613 try { 7614 if (userIds == null) { 7615 userIds = am.getRunningUserIds(); 7616 } 7617 for (int id : userIds) { 7618 final Intent intent = new Intent(action, 7619 pkg != null ? Uri.fromParts("package", pkg, null) : null); 7620 if (extras != null) { 7621 intent.putExtras(extras); 7622 } 7623 if (targetPkg != null) { 7624 intent.setPackage(targetPkg); 7625 } 7626 // Modify the UID when posting to other users 7627 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 7628 if (uid > 0 && UserHandle.getUserId(uid) != id) { 7629 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 7630 intent.putExtra(Intent.EXTRA_UID, uid); 7631 } 7632 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 7633 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 7634 if (DEBUG_BROADCASTS) { 7635 RuntimeException here = new RuntimeException("here"); 7636 here.fillInStackTrace(); 7637 Slog.d(TAG, "Sending to user " + id + ": " 7638 + intent.toShortString(false, true, false, false) 7639 + " " + intent.getExtras(), here); 7640 } 7641 am.broadcastIntent(null, intent, null, finishedReceiver, 7642 0, null, null, null, android.app.AppOpsManager.OP_NONE, 7643 finishedReceiver != null, false, id); 7644 } 7645 } catch (RemoteException ex) { 7646 } 7647 } 7648 } 7649 7650 /** 7651 * Check if the external storage media is available. This is true if there 7652 * is a mounted external storage medium or if the external storage is 7653 * emulated. 7654 */ 7655 private boolean isExternalMediaAvailable() { 7656 return mMediaMounted || Environment.isExternalStorageEmulated(); 7657 } 7658 7659 @Override 7660 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 7661 // writer 7662 synchronized (mPackages) { 7663 if (!isExternalMediaAvailable()) { 7664 // If the external storage is no longer mounted at this point, 7665 // the caller may not have been able to delete all of this 7666 // packages files and can not delete any more. Bail. 7667 return null; 7668 } 7669 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 7670 if (lastPackage != null) { 7671 pkgs.remove(lastPackage); 7672 } 7673 if (pkgs.size() > 0) { 7674 return pkgs.get(0); 7675 } 7676 } 7677 return null; 7678 } 7679 7680 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 7681 if (false) { 7682 RuntimeException here = new RuntimeException("here"); 7683 here.fillInStackTrace(); 7684 Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId 7685 + " andCode=" + andCode, here); 7686 } 7687 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, 7688 userId, andCode ? 1 : 0, packageName)); 7689 } 7690 7691 void startCleaningPackages() { 7692 // reader 7693 synchronized (mPackages) { 7694 if (!isExternalMediaAvailable()) { 7695 return; 7696 } 7697 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 7698 return; 7699 } 7700 } 7701 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 7702 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 7703 IActivityManager am = ActivityManagerNative.getDefault(); 7704 if (am != null) { 7705 try { 7706 am.startService(null, intent, null, UserHandle.USER_OWNER); 7707 } catch (RemoteException e) { 7708 } 7709 } 7710 } 7711 7712 @Override 7713 public void installPackage(String originPath, IPackageInstallObserver2 observer, 7714 int installFlags, String installerPackageName, VerificationParams verificationParams, 7715 String packageAbiOverride) { 7716 installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams, 7717 packageAbiOverride, UserHandle.getCallingUserId()); 7718 } 7719 7720 @Override 7721 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 7722 int installFlags, String installerPackageName, VerificationParams verificationParams, 7723 String packageAbiOverride, int userId) { 7724 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7725 null); 7726 if (UserHandle.getCallingUserId() != userId) { 7727 mContext.enforceCallingOrSelfPermission( 7728 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 7729 "installPackage " + userId); 7730 } 7731 7732 final File originFile = new File(originPath); 7733 final int uid = Binder.getCallingUid(); 7734 if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) { 7735 try { 7736 if (observer != null) { 7737 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 7738 } 7739 } catch (RemoteException re) { 7740 } 7741 return; 7742 } 7743 7744 UserHandle user; 7745 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 7746 user = UserHandle.ALL; 7747 } else { 7748 user = new UserHandle(userId); 7749 } 7750 7751 final int filteredInstallFlags; 7752 if (uid == Process.SHELL_UID || uid == 0) { 7753 if (DEBUG_INSTALL) { 7754 Slog.v(TAG, "Install from ADB"); 7755 } 7756 filteredInstallFlags = installFlags | PackageManager.INSTALL_FROM_ADB; 7757 } else { 7758 filteredInstallFlags = installFlags & ~PackageManager.INSTALL_FROM_ADB; 7759 } 7760 7761 verificationParams.setInstallerUid(uid); 7762 7763 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 7764 7765 final Message msg = mHandler.obtainMessage(INIT_COPY); 7766 msg.obj = new InstallParams(origin, observer, filteredInstallFlags, 7767 installerPackageName, verificationParams, user, packageAbiOverride); 7768 mHandler.sendMessage(msg); 7769 } 7770 7771 void installStage(String packageName, File stagedDir, String stagedCid, 7772 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 7773 String installerPackageName, int installerUid, UserHandle user) { 7774 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 7775 params.referrerUri, installerUid, null); 7776 7777 final OriginInfo origin; 7778 if (stagedDir != null) { 7779 origin = OriginInfo.fromStagedFile(stagedDir); 7780 } else { 7781 origin = OriginInfo.fromStagedContainer(stagedCid); 7782 } 7783 7784 final Message msg = mHandler.obtainMessage(INIT_COPY); 7785 msg.obj = new InstallParams(origin, observer, params.installFlags, 7786 installerPackageName, verifParams, user, params.abiOverride); 7787 mHandler.sendMessage(msg); 7788 } 7789 7790 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 7791 Bundle extras = new Bundle(1); 7792 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 7793 7794 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 7795 packageName, extras, null, null, new int[] {userId}); 7796 try { 7797 IActivityManager am = ActivityManagerNative.getDefault(); 7798 final boolean isSystem = 7799 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 7800 if (isSystem && am.isUserRunning(userId, false)) { 7801 // The just-installed/enabled app is bundled on the system, so presumed 7802 // to be able to run automatically without needing an explicit launch. 7803 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 7804 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 7805 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 7806 .setPackage(packageName); 7807 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 7808 android.app.AppOpsManager.OP_NONE, false, false, userId); 7809 } 7810 } catch (RemoteException e) { 7811 // shouldn't happen 7812 Slog.w(TAG, "Unable to bootstrap installed package", e); 7813 } 7814 } 7815 7816 @Override 7817 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 7818 int userId) { 7819 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7820 PackageSetting pkgSetting; 7821 final int uid = Binder.getCallingUid(); 7822 if (UserHandle.getUserId(uid) != userId) { 7823 mContext.enforceCallingOrSelfPermission( 7824 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 7825 "setApplicationHiddenSetting for user " + userId); 7826 } 7827 7828 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 7829 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 7830 return false; 7831 } 7832 7833 long callingId = Binder.clearCallingIdentity(); 7834 try { 7835 boolean sendAdded = false; 7836 boolean sendRemoved = false; 7837 // writer 7838 synchronized (mPackages) { 7839 pkgSetting = mSettings.mPackages.get(packageName); 7840 if (pkgSetting == null) { 7841 return false; 7842 } 7843 if (pkgSetting.getHidden(userId) != hidden) { 7844 pkgSetting.setHidden(hidden, userId); 7845 mSettings.writePackageRestrictionsLPr(userId); 7846 if (hidden) { 7847 sendRemoved = true; 7848 } else { 7849 sendAdded = true; 7850 } 7851 } 7852 } 7853 if (sendAdded) { 7854 sendPackageAddedForUser(packageName, pkgSetting, userId); 7855 return true; 7856 } 7857 if (sendRemoved) { 7858 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 7859 "hiding pkg"); 7860 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 7861 } 7862 } finally { 7863 Binder.restoreCallingIdentity(callingId); 7864 } 7865 return false; 7866 } 7867 7868 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 7869 int userId) { 7870 final PackageRemovedInfo info = new PackageRemovedInfo(); 7871 info.removedPackage = packageName; 7872 info.removedUsers = new int[] {userId}; 7873 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 7874 info.sendBroadcast(false, false, false); 7875 } 7876 7877 /** 7878 * Returns true if application is not found or there was an error. Otherwise it returns 7879 * the hidden state of the package for the given user. 7880 */ 7881 @Override 7882 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 7883 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7884 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 7885 "getApplicationHidden for user " + userId); 7886 PackageSetting pkgSetting; 7887 long callingId = Binder.clearCallingIdentity(); 7888 try { 7889 // writer 7890 synchronized (mPackages) { 7891 pkgSetting = mSettings.mPackages.get(packageName); 7892 if (pkgSetting == null) { 7893 return true; 7894 } 7895 return pkgSetting.getHidden(userId); 7896 } 7897 } finally { 7898 Binder.restoreCallingIdentity(callingId); 7899 } 7900 } 7901 7902 /** 7903 * @hide 7904 */ 7905 @Override 7906 public int installExistingPackageAsUser(String packageName, int userId) { 7907 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7908 null); 7909 PackageSetting pkgSetting; 7910 final int uid = Binder.getCallingUid(); 7911 enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId); 7912 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 7913 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 7914 } 7915 7916 long callingId = Binder.clearCallingIdentity(); 7917 try { 7918 boolean sendAdded = false; 7919 Bundle extras = new Bundle(1); 7920 7921 // writer 7922 synchronized (mPackages) { 7923 pkgSetting = mSettings.mPackages.get(packageName); 7924 if (pkgSetting == null) { 7925 return PackageManager.INSTALL_FAILED_INVALID_URI; 7926 } 7927 if (!pkgSetting.getInstalled(userId)) { 7928 pkgSetting.setInstalled(true, userId); 7929 pkgSetting.setHidden(false, userId); 7930 mSettings.writePackageRestrictionsLPr(userId); 7931 sendAdded = true; 7932 } 7933 } 7934 7935 if (sendAdded) { 7936 sendPackageAddedForUser(packageName, pkgSetting, userId); 7937 } 7938 } finally { 7939 Binder.restoreCallingIdentity(callingId); 7940 } 7941 7942 return PackageManager.INSTALL_SUCCEEDED; 7943 } 7944 7945 boolean isUserRestricted(int userId, String restrictionKey) { 7946 Bundle restrictions = sUserManager.getUserRestrictions(userId); 7947 if (restrictions.getBoolean(restrictionKey, false)) { 7948 Log.w(TAG, "User is restricted: " + restrictionKey); 7949 return true; 7950 } 7951 return false; 7952 } 7953 7954 @Override 7955 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 7956 mContext.enforceCallingOrSelfPermission( 7957 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7958 "Only package verification agents can verify applications"); 7959 7960 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7961 final PackageVerificationResponse response = new PackageVerificationResponse( 7962 verificationCode, Binder.getCallingUid()); 7963 msg.arg1 = id; 7964 msg.obj = response; 7965 mHandler.sendMessage(msg); 7966 } 7967 7968 @Override 7969 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 7970 long millisecondsToDelay) { 7971 mContext.enforceCallingOrSelfPermission( 7972 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7973 "Only package verification agents can extend verification timeouts"); 7974 7975 final PackageVerificationState state = mPendingVerification.get(id); 7976 final PackageVerificationResponse response = new PackageVerificationResponse( 7977 verificationCodeAtTimeout, Binder.getCallingUid()); 7978 7979 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 7980 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 7981 } 7982 if (millisecondsToDelay < 0) { 7983 millisecondsToDelay = 0; 7984 } 7985 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 7986 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 7987 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 7988 } 7989 7990 if ((state != null) && !state.timeoutExtended()) { 7991 state.extendTimeout(); 7992 7993 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7994 msg.arg1 = id; 7995 msg.obj = response; 7996 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 7997 } 7998 } 7999 8000 private void broadcastPackageVerified(int verificationId, Uri packageUri, 8001 int verificationCode, UserHandle user) { 8002 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 8003 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 8004 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8005 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8006 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 8007 8008 mContext.sendBroadcastAsUser(intent, user, 8009 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 8010 } 8011 8012 private ComponentName matchComponentForVerifier(String packageName, 8013 List<ResolveInfo> receivers) { 8014 ActivityInfo targetReceiver = null; 8015 8016 final int NR = receivers.size(); 8017 for (int i = 0; i < NR; i++) { 8018 final ResolveInfo info = receivers.get(i); 8019 if (info.activityInfo == null) { 8020 continue; 8021 } 8022 8023 if (packageName.equals(info.activityInfo.packageName)) { 8024 targetReceiver = info.activityInfo; 8025 break; 8026 } 8027 } 8028 8029 if (targetReceiver == null) { 8030 return null; 8031 } 8032 8033 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8034 } 8035 8036 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8037 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8038 if (pkgInfo.verifiers.length == 0) { 8039 return null; 8040 } 8041 8042 final int N = pkgInfo.verifiers.length; 8043 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8044 for (int i = 0; i < N; i++) { 8045 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8046 8047 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8048 receivers); 8049 if (comp == null) { 8050 continue; 8051 } 8052 8053 final int verifierUid = getUidForVerifier(verifierInfo); 8054 if (verifierUid == -1) { 8055 continue; 8056 } 8057 8058 if (DEBUG_VERIFY) { 8059 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8060 + " with the correct signature"); 8061 } 8062 sufficientVerifiers.add(comp); 8063 verificationState.addSufficientVerifier(verifierUid); 8064 } 8065 8066 return sufficientVerifiers; 8067 } 8068 8069 private int getUidForVerifier(VerifierInfo verifierInfo) { 8070 synchronized (mPackages) { 8071 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8072 if (pkg == null) { 8073 return -1; 8074 } else if (pkg.mSignatures.length != 1) { 8075 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8076 + " has more than one signature; ignoring"); 8077 return -1; 8078 } 8079 8080 /* 8081 * If the public key of the package's signature does not match 8082 * our expected public key, then this is a different package and 8083 * we should skip. 8084 */ 8085 8086 final byte[] expectedPublicKey; 8087 try { 8088 final Signature verifierSig = pkg.mSignatures[0]; 8089 final PublicKey publicKey = verifierSig.getPublicKey(); 8090 expectedPublicKey = publicKey.getEncoded(); 8091 } catch (CertificateException e) { 8092 return -1; 8093 } 8094 8095 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8096 8097 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8098 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8099 + " does not have the expected public key; ignoring"); 8100 return -1; 8101 } 8102 8103 return pkg.applicationInfo.uid; 8104 } 8105 } 8106 8107 @Override 8108 public void finishPackageInstall(int token) { 8109 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8110 8111 if (DEBUG_INSTALL) { 8112 Slog.v(TAG, "BM finishing package install for " + token); 8113 } 8114 8115 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8116 mHandler.sendMessage(msg); 8117 } 8118 8119 /** 8120 * Get the verification agent timeout. 8121 * 8122 * @return verification timeout in milliseconds 8123 */ 8124 private long getVerificationTimeout() { 8125 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8126 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8127 DEFAULT_VERIFICATION_TIMEOUT); 8128 } 8129 8130 /** 8131 * Get the default verification agent response code. 8132 * 8133 * @return default verification response code 8134 */ 8135 private int getDefaultVerificationResponse() { 8136 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8137 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8138 DEFAULT_VERIFICATION_RESPONSE); 8139 } 8140 8141 /** 8142 * Check whether or not package verification has been enabled. 8143 * 8144 * @return true if verification should be performed 8145 */ 8146 private boolean isVerificationEnabled(int userId, int installFlags) { 8147 if (!DEFAULT_VERIFY_ENABLE) { 8148 return false; 8149 } 8150 8151 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 8152 8153 // Check if installing from ADB 8154 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 8155 // Do not run verification in a test harness environment 8156 if (ActivityManager.isRunningInTestHarness()) { 8157 return false; 8158 } 8159 if (ensureVerifyAppsEnabled) { 8160 return true; 8161 } 8162 // Check if the developer does not want package verification for ADB installs 8163 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8164 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8165 return false; 8166 } 8167 } 8168 8169 if (ensureVerifyAppsEnabled) { 8170 return true; 8171 } 8172 8173 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8174 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8175 } 8176 8177 /** 8178 * Get the "allow unknown sources" setting. 8179 * 8180 * @return the current "allow unknown sources" setting 8181 */ 8182 private int getUnknownSourcesSettings() { 8183 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8184 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 8185 -1); 8186 } 8187 8188 @Override 8189 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 8190 final int uid = Binder.getCallingUid(); 8191 // writer 8192 synchronized (mPackages) { 8193 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 8194 if (targetPackageSetting == null) { 8195 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 8196 } 8197 8198 PackageSetting installerPackageSetting; 8199 if (installerPackageName != null) { 8200 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 8201 if (installerPackageSetting == null) { 8202 throw new IllegalArgumentException("Unknown installer package: " 8203 + installerPackageName); 8204 } 8205 } else { 8206 installerPackageSetting = null; 8207 } 8208 8209 Signature[] callerSignature; 8210 Object obj = mSettings.getUserIdLPr(uid); 8211 if (obj != null) { 8212 if (obj instanceof SharedUserSetting) { 8213 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 8214 } else if (obj instanceof PackageSetting) { 8215 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 8216 } else { 8217 throw new SecurityException("Bad object " + obj + " for uid " + uid); 8218 } 8219 } else { 8220 throw new SecurityException("Unknown calling uid " + uid); 8221 } 8222 8223 // Verify: can't set installerPackageName to a package that is 8224 // not signed with the same cert as the caller. 8225 if (installerPackageSetting != null) { 8226 if (compareSignatures(callerSignature, 8227 installerPackageSetting.signatures.mSignatures) 8228 != PackageManager.SIGNATURE_MATCH) { 8229 throw new SecurityException( 8230 "Caller does not have same cert as new installer package " 8231 + installerPackageName); 8232 } 8233 } 8234 8235 // Verify: if target already has an installer package, it must 8236 // be signed with the same cert as the caller. 8237 if (targetPackageSetting.installerPackageName != null) { 8238 PackageSetting setting = mSettings.mPackages.get( 8239 targetPackageSetting.installerPackageName); 8240 // If the currently set package isn't valid, then it's always 8241 // okay to change it. 8242 if (setting != null) { 8243 if (compareSignatures(callerSignature, 8244 setting.signatures.mSignatures) 8245 != PackageManager.SIGNATURE_MATCH) { 8246 throw new SecurityException( 8247 "Caller does not have same cert as old installer package " 8248 + targetPackageSetting.installerPackageName); 8249 } 8250 } 8251 } 8252 8253 // Okay! 8254 targetPackageSetting.installerPackageName = installerPackageName; 8255 scheduleWriteSettingsLocked(); 8256 } 8257 } 8258 8259 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 8260 // Queue up an async operation since the package installation may take a little while. 8261 mHandler.post(new Runnable() { 8262 public void run() { 8263 mHandler.removeCallbacks(this); 8264 // Result object to be returned 8265 PackageInstalledInfo res = new PackageInstalledInfo(); 8266 res.returnCode = currentStatus; 8267 res.uid = -1; 8268 res.pkg = null; 8269 res.removedInfo = new PackageRemovedInfo(); 8270 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 8271 args.doPreInstall(res.returnCode); 8272 synchronized (mInstallLock) { 8273 installPackageLI(args, res); 8274 } 8275 args.doPostInstall(res.returnCode, res.uid); 8276 } 8277 8278 // A restore should be performed at this point if (a) the install 8279 // succeeded, (b) the operation is not an update, and (c) the new 8280 // package has not opted out of backup participation. 8281 final boolean update = res.removedInfo.removedPackage != null; 8282 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 8283 boolean doRestore = !update 8284 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 8285 8286 // Set up the post-install work request bookkeeping. This will be used 8287 // and cleaned up by the post-install event handling regardless of whether 8288 // there's a restore pass performed. Token values are >= 1. 8289 int token; 8290 if (mNextInstallToken < 0) mNextInstallToken = 1; 8291 token = mNextInstallToken++; 8292 8293 PostInstallData data = new PostInstallData(args, res); 8294 mRunningInstalls.put(token, data); 8295 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 8296 8297 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 8298 // Pass responsibility to the Backup Manager. It will perform a 8299 // restore if appropriate, then pass responsibility back to the 8300 // Package Manager to run the post-install observer callbacks 8301 // and broadcasts. 8302 IBackupManager bm = IBackupManager.Stub.asInterface( 8303 ServiceManager.getService(Context.BACKUP_SERVICE)); 8304 if (bm != null) { 8305 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 8306 + " to BM for possible restore"); 8307 try { 8308 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 8309 } catch (RemoteException e) { 8310 // can't happen; the backup manager is local 8311 } catch (Exception e) { 8312 Slog.e(TAG, "Exception trying to enqueue restore", e); 8313 doRestore = false; 8314 } 8315 } else { 8316 Slog.e(TAG, "Backup Manager not found!"); 8317 doRestore = false; 8318 } 8319 } 8320 8321 if (!doRestore) { 8322 // No restore possible, or the Backup Manager was mysteriously not 8323 // available -- just fire the post-install work request directly. 8324 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 8325 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8326 mHandler.sendMessage(msg); 8327 } 8328 } 8329 }); 8330 } 8331 8332 private abstract class HandlerParams { 8333 private static final int MAX_RETRIES = 4; 8334 8335 /** 8336 * Number of times startCopy() has been attempted and had a non-fatal 8337 * error. 8338 */ 8339 private int mRetries = 0; 8340 8341 /** User handle for the user requesting the information or installation. */ 8342 private final UserHandle mUser; 8343 8344 HandlerParams(UserHandle user) { 8345 mUser = user; 8346 } 8347 8348 UserHandle getUser() { 8349 return mUser; 8350 } 8351 8352 final boolean startCopy() { 8353 boolean res; 8354 try { 8355 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 8356 8357 if (++mRetries > MAX_RETRIES) { 8358 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 8359 mHandler.sendEmptyMessage(MCS_GIVE_UP); 8360 handleServiceError(); 8361 return false; 8362 } else { 8363 handleStartCopy(); 8364 res = true; 8365 } 8366 } catch (RemoteException e) { 8367 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 8368 mHandler.sendEmptyMessage(MCS_RECONNECT); 8369 res = false; 8370 } 8371 handleReturnCode(); 8372 return res; 8373 } 8374 8375 final void serviceError() { 8376 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 8377 handleServiceError(); 8378 handleReturnCode(); 8379 } 8380 8381 abstract void handleStartCopy() throws RemoteException; 8382 abstract void handleServiceError(); 8383 abstract void handleReturnCode(); 8384 } 8385 8386 class MeasureParams extends HandlerParams { 8387 private final PackageStats mStats; 8388 private boolean mSuccess; 8389 8390 private final IPackageStatsObserver mObserver; 8391 8392 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 8393 super(new UserHandle(stats.userHandle)); 8394 mObserver = observer; 8395 mStats = stats; 8396 } 8397 8398 @Override 8399 public String toString() { 8400 return "MeasureParams{" 8401 + Integer.toHexString(System.identityHashCode(this)) 8402 + " " + mStats.packageName + "}"; 8403 } 8404 8405 @Override 8406 void handleStartCopy() throws RemoteException { 8407 synchronized (mInstallLock) { 8408 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 8409 } 8410 8411 if (mSuccess) { 8412 final boolean mounted; 8413 if (Environment.isExternalStorageEmulated()) { 8414 mounted = true; 8415 } else { 8416 final String status = Environment.getExternalStorageState(); 8417 mounted = (Environment.MEDIA_MOUNTED.equals(status) 8418 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 8419 } 8420 8421 if (mounted) { 8422 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 8423 8424 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 8425 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 8426 8427 mStats.externalDataSize = calculateDirectorySize(mContainerService, 8428 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 8429 8430 // Always subtract cache size, since it's a subdirectory 8431 mStats.externalDataSize -= mStats.externalCacheSize; 8432 8433 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 8434 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 8435 8436 mStats.externalObbSize = calculateDirectorySize(mContainerService, 8437 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 8438 } 8439 } 8440 } 8441 8442 @Override 8443 void handleReturnCode() { 8444 if (mObserver != null) { 8445 try { 8446 mObserver.onGetStatsCompleted(mStats, mSuccess); 8447 } catch (RemoteException e) { 8448 Slog.i(TAG, "Observer no longer exists."); 8449 } 8450 } 8451 } 8452 8453 @Override 8454 void handleServiceError() { 8455 Slog.e(TAG, "Could not measure application " + mStats.packageName 8456 + " external storage"); 8457 } 8458 } 8459 8460 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 8461 throws RemoteException { 8462 long result = 0; 8463 for (File path : paths) { 8464 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 8465 } 8466 return result; 8467 } 8468 8469 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 8470 for (File path : paths) { 8471 try { 8472 mcs.clearDirectory(path.getAbsolutePath()); 8473 } catch (RemoteException e) { 8474 } 8475 } 8476 } 8477 8478 static class OriginInfo { 8479 /** 8480 * Location where install is coming from, before it has been 8481 * copied/renamed into place. This could be a single monolithic APK 8482 * file, or a cluster directory. This location may be untrusted. 8483 */ 8484 final File file; 8485 final String cid; 8486 8487 /** 8488 * Flag indicating that {@link #file} or {@link #cid} has already been 8489 * staged, meaning downstream users don't need to defensively copy the 8490 * contents. 8491 */ 8492 final boolean staged; 8493 8494 /** 8495 * Flag indicating that {@link #file} or {@link #cid} is an already 8496 * installed app that is being moved. 8497 */ 8498 final boolean existing; 8499 8500 final String resolvedPath; 8501 final File resolvedFile; 8502 8503 static OriginInfo fromNothing() { 8504 return new OriginInfo(null, null, false, false); 8505 } 8506 8507 static OriginInfo fromUntrustedFile(File file) { 8508 return new OriginInfo(file, null, false, false); 8509 } 8510 8511 static OriginInfo fromExistingFile(File file) { 8512 return new OriginInfo(file, null, false, true); 8513 } 8514 8515 static OriginInfo fromStagedFile(File file) { 8516 return new OriginInfo(file, null, true, false); 8517 } 8518 8519 static OriginInfo fromStagedContainer(String cid) { 8520 return new OriginInfo(null, cid, true, false); 8521 } 8522 8523 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 8524 this.file = file; 8525 this.cid = cid; 8526 this.staged = staged; 8527 this.existing = existing; 8528 8529 if (cid != null) { 8530 resolvedPath = PackageHelper.getSdDir(cid); 8531 resolvedFile = new File(resolvedPath); 8532 } else if (file != null) { 8533 resolvedPath = file.getAbsolutePath(); 8534 resolvedFile = file; 8535 } else { 8536 resolvedPath = null; 8537 resolvedFile = null; 8538 } 8539 } 8540 } 8541 8542 class InstallParams extends HandlerParams { 8543 final OriginInfo origin; 8544 final IPackageInstallObserver2 observer; 8545 int installFlags; 8546 final String installerPackageName; 8547 final VerificationParams verificationParams; 8548 private InstallArgs mArgs; 8549 private int mRet; 8550 final String packageAbiOverride; 8551 8552 InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 8553 String installerPackageName, VerificationParams verificationParams, UserHandle user, 8554 String packageAbiOverride) { 8555 super(user); 8556 this.origin = origin; 8557 this.observer = observer; 8558 this.installFlags = installFlags; 8559 this.installerPackageName = installerPackageName; 8560 this.verificationParams = verificationParams; 8561 this.packageAbiOverride = packageAbiOverride; 8562 } 8563 8564 @Override 8565 public String toString() { 8566 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 8567 + " file=" + origin.file + " cid=" + origin.cid + "}"; 8568 } 8569 8570 public ManifestDigest getManifestDigest() { 8571 if (verificationParams == null) { 8572 return null; 8573 } 8574 return verificationParams.getManifestDigest(); 8575 } 8576 8577 private int installLocationPolicy(PackageInfoLite pkgLite) { 8578 String packageName = pkgLite.packageName; 8579 int installLocation = pkgLite.installLocation; 8580 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 8581 // reader 8582 synchronized (mPackages) { 8583 PackageParser.Package pkg = mPackages.get(packageName); 8584 if (pkg != null) { 8585 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 8586 // Check for downgrading. 8587 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 8588 if (pkgLite.versionCode < pkg.mVersionCode) { 8589 Slog.w(TAG, "Can't install update of " + packageName 8590 + " update version " + pkgLite.versionCode 8591 + " is older than installed version " 8592 + pkg.mVersionCode); 8593 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 8594 } 8595 } 8596 // Check for updated system application. 8597 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8598 if (onSd) { 8599 Slog.w(TAG, "Cannot install update to system app on sdcard"); 8600 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 8601 } 8602 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8603 } else { 8604 if (onSd) { 8605 // Install flag overrides everything. 8606 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8607 } 8608 // If current upgrade specifies particular preference 8609 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 8610 // Application explicitly specified internal. 8611 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8612 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 8613 // App explictly prefers external. Let policy decide 8614 } else { 8615 // Prefer previous location 8616 if (isExternal(pkg)) { 8617 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8618 } 8619 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8620 } 8621 } 8622 } else { 8623 // Invalid install. Return error code 8624 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 8625 } 8626 } 8627 } 8628 // All the special cases have been taken care of. 8629 // Return result based on recommended install location. 8630 if (onSd) { 8631 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8632 } 8633 return pkgLite.recommendedInstallLocation; 8634 } 8635 8636 /* 8637 * Invoke remote method to get package information and install 8638 * location values. Override install location based on default 8639 * policy if needed and then create install arguments based 8640 * on the install location. 8641 */ 8642 public void handleStartCopy() throws RemoteException { 8643 int ret = PackageManager.INSTALL_SUCCEEDED; 8644 8645 // If we're already staged, we've firmly committed to an install location 8646 if (origin.staged) { 8647 if (origin.file != null) { 8648 installFlags |= PackageManager.INSTALL_INTERNAL; 8649 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 8650 } else if (origin.cid != null) { 8651 installFlags |= PackageManager.INSTALL_EXTERNAL; 8652 installFlags &= ~PackageManager.INSTALL_INTERNAL; 8653 } else { 8654 throw new IllegalStateException("Invalid stage location"); 8655 } 8656 } 8657 8658 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 8659 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 8660 8661 PackageInfoLite pkgLite = null; 8662 8663 if (onInt && onSd) { 8664 // Check if both bits are set. 8665 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 8666 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8667 } else { 8668 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 8669 packageAbiOverride); 8670 8671 /* 8672 * If we have too little free space, try to free cache 8673 * before giving up. 8674 */ 8675 if (!origin.staged && pkgLite.recommendedInstallLocation 8676 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8677 // TODO: focus freeing disk space on the target device 8678 final StorageManager storage = StorageManager.from(mContext); 8679 final long lowThreshold = storage.getStorageLowBytes( 8680 Environment.getDataDirectory()); 8681 8682 final long sizeBytes = mContainerService.calculateInstalledSize( 8683 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 8684 8685 if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) { 8686 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 8687 installFlags, packageAbiOverride); 8688 } 8689 8690 /* 8691 * The cache free must have deleted the file we 8692 * downloaded to install. 8693 * 8694 * TODO: fix the "freeCache" call to not delete 8695 * the file we care about. 8696 */ 8697 if (pkgLite.recommendedInstallLocation 8698 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8699 pkgLite.recommendedInstallLocation 8700 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 8701 } 8702 } 8703 } 8704 8705 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8706 int loc = pkgLite.recommendedInstallLocation; 8707 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 8708 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8709 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 8710 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 8711 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8712 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8713 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 8714 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 8715 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8716 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 8717 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 8718 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 8719 } else { 8720 // Override with defaults if needed. 8721 loc = installLocationPolicy(pkgLite); 8722 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 8723 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 8724 } else if (!onSd && !onInt) { 8725 // Override install location with flags 8726 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 8727 // Set the flag to install on external media. 8728 installFlags |= PackageManager.INSTALL_EXTERNAL; 8729 installFlags &= ~PackageManager.INSTALL_INTERNAL; 8730 } else { 8731 // Make sure the flag for installing on external 8732 // media is unset 8733 installFlags |= PackageManager.INSTALL_INTERNAL; 8734 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 8735 } 8736 } 8737 } 8738 } 8739 8740 final InstallArgs args = createInstallArgs(this); 8741 mArgs = args; 8742 8743 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8744 /* 8745 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 8746 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 8747 */ 8748 int userIdentifier = getUser().getIdentifier(); 8749 if (userIdentifier == UserHandle.USER_ALL 8750 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 8751 userIdentifier = UserHandle.USER_OWNER; 8752 } 8753 8754 /* 8755 * Determine if we have any installed package verifiers. If we 8756 * do, then we'll defer to them to verify the packages. 8757 */ 8758 final int requiredUid = mRequiredVerifierPackage == null ? -1 8759 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 8760 if (!origin.existing && requiredUid != -1 8761 && isVerificationEnabled(userIdentifier, installFlags)) { 8762 final Intent verification = new Intent( 8763 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 8764 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 8765 PACKAGE_MIME_TYPE); 8766 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8767 8768 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 8769 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 8770 0 /* TODO: Which userId? */); 8771 8772 if (DEBUG_VERIFY) { 8773 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 8774 + verification.toString() + " with " + pkgLite.verifiers.length 8775 + " optional verifiers"); 8776 } 8777 8778 final int verificationId = mPendingVerificationToken++; 8779 8780 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8781 8782 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 8783 installerPackageName); 8784 8785 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 8786 installFlags); 8787 8788 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 8789 pkgLite.packageName); 8790 8791 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 8792 pkgLite.versionCode); 8793 8794 if (verificationParams != null) { 8795 if (verificationParams.getVerificationURI() != null) { 8796 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 8797 verificationParams.getVerificationURI()); 8798 } 8799 if (verificationParams.getOriginatingURI() != null) { 8800 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 8801 verificationParams.getOriginatingURI()); 8802 } 8803 if (verificationParams.getReferrer() != null) { 8804 verification.putExtra(Intent.EXTRA_REFERRER, 8805 verificationParams.getReferrer()); 8806 } 8807 if (verificationParams.getOriginatingUid() >= 0) { 8808 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 8809 verificationParams.getOriginatingUid()); 8810 } 8811 if (verificationParams.getInstallerUid() >= 0) { 8812 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 8813 verificationParams.getInstallerUid()); 8814 } 8815 } 8816 8817 final PackageVerificationState verificationState = new PackageVerificationState( 8818 requiredUid, args); 8819 8820 mPendingVerification.append(verificationId, verificationState); 8821 8822 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 8823 receivers, verificationState); 8824 8825 /* 8826 * If any sufficient verifiers were listed in the package 8827 * manifest, attempt to ask them. 8828 */ 8829 if (sufficientVerifiers != null) { 8830 final int N = sufficientVerifiers.size(); 8831 if (N == 0) { 8832 Slog.i(TAG, "Additional verifiers required, but none installed."); 8833 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 8834 } else { 8835 for (int i = 0; i < N; i++) { 8836 final ComponentName verifierComponent = sufficientVerifiers.get(i); 8837 8838 final Intent sufficientIntent = new Intent(verification); 8839 sufficientIntent.setComponent(verifierComponent); 8840 8841 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 8842 } 8843 } 8844 } 8845 8846 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 8847 mRequiredVerifierPackage, receivers); 8848 if (ret == PackageManager.INSTALL_SUCCEEDED 8849 && mRequiredVerifierPackage != null) { 8850 /* 8851 * Send the intent to the required verification agent, 8852 * but only start the verification timeout after the 8853 * target BroadcastReceivers have run. 8854 */ 8855 verification.setComponent(requiredVerifierComponent); 8856 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 8857 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8858 new BroadcastReceiver() { 8859 @Override 8860 public void onReceive(Context context, Intent intent) { 8861 final Message msg = mHandler 8862 .obtainMessage(CHECK_PENDING_VERIFICATION); 8863 msg.arg1 = verificationId; 8864 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 8865 } 8866 }, null, 0, null, null); 8867 8868 /* 8869 * We don't want the copy to proceed until verification 8870 * succeeds, so null out this field. 8871 */ 8872 mArgs = null; 8873 } 8874 } else { 8875 /* 8876 * No package verification is enabled, so immediately start 8877 * the remote call to initiate copy using temporary file. 8878 */ 8879 ret = args.copyApk(mContainerService, true); 8880 } 8881 } 8882 8883 mRet = ret; 8884 } 8885 8886 @Override 8887 void handleReturnCode() { 8888 // If mArgs is null, then MCS couldn't be reached. When it 8889 // reconnects, it will try again to install. At that point, this 8890 // will succeed. 8891 if (mArgs != null) { 8892 processPendingInstall(mArgs, mRet); 8893 } 8894 } 8895 8896 @Override 8897 void handleServiceError() { 8898 mArgs = createInstallArgs(this); 8899 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8900 } 8901 8902 public boolean isForwardLocked() { 8903 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8904 } 8905 } 8906 8907 /** 8908 * Used during creation of InstallArgs 8909 * 8910 * @param installFlags package installation flags 8911 * @return true if should be installed on external storage 8912 */ 8913 private static boolean installOnSd(int installFlags) { 8914 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 8915 return false; 8916 } 8917 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 8918 return true; 8919 } 8920 return false; 8921 } 8922 8923 /** 8924 * Used during creation of InstallArgs 8925 * 8926 * @param installFlags package installation flags 8927 * @return true if should be installed as forward locked 8928 */ 8929 private static boolean installForwardLocked(int installFlags) { 8930 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8931 } 8932 8933 private InstallArgs createInstallArgs(InstallParams params) { 8934 if (installOnSd(params.installFlags) || params.isForwardLocked()) { 8935 return new AsecInstallArgs(params); 8936 } else { 8937 return new FileInstallArgs(params); 8938 } 8939 } 8940 8941 /** 8942 * Create args that describe an existing installed package. Typically used 8943 * when cleaning up old installs, or used as a move source. 8944 */ 8945 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 8946 String resourcePath, String nativeLibraryRoot, String[] instructionSets) { 8947 final boolean isInAsec; 8948 if (installOnSd(installFlags)) { 8949 /* Apps on SD card are always in ASEC containers. */ 8950 isInAsec = true; 8951 } else if (installForwardLocked(installFlags) 8952 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 8953 /* 8954 * Forward-locked apps are only in ASEC containers if they're the 8955 * new style 8956 */ 8957 isInAsec = true; 8958 } else { 8959 isInAsec = false; 8960 } 8961 8962 if (isInAsec) { 8963 return new AsecInstallArgs(codePath, instructionSets, 8964 installOnSd(installFlags), installForwardLocked(installFlags)); 8965 } else { 8966 return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot, 8967 instructionSets); 8968 } 8969 } 8970 8971 static abstract class InstallArgs { 8972 /** @see InstallParams#origin */ 8973 final OriginInfo origin; 8974 8975 final IPackageInstallObserver2 observer; 8976 // Always refers to PackageManager flags only 8977 final int installFlags; 8978 final String installerPackageName; 8979 final ManifestDigest manifestDigest; 8980 final UserHandle user; 8981 final String abiOverride; 8982 8983 // The list of instruction sets supported by this app. This is currently 8984 // only used during the rmdex() phase to clean up resources. We can get rid of this 8985 // if we move dex files under the common app path. 8986 /* nullable */ String[] instructionSets; 8987 8988 InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 8989 String installerPackageName, ManifestDigest manifestDigest, UserHandle user, 8990 String[] instructionSets, String abiOverride) { 8991 this.origin = origin; 8992 this.installFlags = installFlags; 8993 this.observer = observer; 8994 this.installerPackageName = installerPackageName; 8995 this.manifestDigest = manifestDigest; 8996 this.user = user; 8997 this.instructionSets = instructionSets; 8998 this.abiOverride = abiOverride; 8999 } 9000 9001 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 9002 abstract int doPreInstall(int status); 9003 9004 /** 9005 * Rename package into final resting place. All paths on the given 9006 * scanned package should be updated to reflect the rename. 9007 */ 9008 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 9009 abstract int doPostInstall(int status, int uid); 9010 9011 /** @see PackageSettingBase#codePathString */ 9012 abstract String getCodePath(); 9013 /** @see PackageSettingBase#resourcePathString */ 9014 abstract String getResourcePath(); 9015 abstract String getLegacyNativeLibraryPath(); 9016 9017 // Need installer lock especially for dex file removal. 9018 abstract void cleanUpResourcesLI(); 9019 abstract boolean doPostDeleteLI(boolean delete); 9020 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9021 9022 /** 9023 * Called before the source arguments are copied. This is used mostly 9024 * for MoveParams when it needs to read the source file to put it in the 9025 * destination. 9026 */ 9027 int doPreCopy() { 9028 return PackageManager.INSTALL_SUCCEEDED; 9029 } 9030 9031 /** 9032 * Called after the source arguments are copied. This is used mostly for 9033 * MoveParams when it needs to read the source file to put it in the 9034 * destination. 9035 * 9036 * @return 9037 */ 9038 int doPostCopy(int uid) { 9039 return PackageManager.INSTALL_SUCCEEDED; 9040 } 9041 9042 protected boolean isFwdLocked() { 9043 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9044 } 9045 9046 protected boolean isExternal() { 9047 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9048 } 9049 9050 UserHandle getUser() { 9051 return user; 9052 } 9053 } 9054 9055 /** 9056 * Logic to handle installation of non-ASEC applications, including copying 9057 * and renaming logic. 9058 */ 9059 class FileInstallArgs extends InstallArgs { 9060 private File codeFile; 9061 private File resourceFile; 9062 private File legacyNativeLibraryPath; 9063 9064 // Example topology: 9065 // /data/app/com.example/base.apk 9066 // /data/app/com.example/split_foo.apk 9067 // /data/app/com.example/lib/arm/libfoo.so 9068 // /data/app/com.example/lib/arm64/libfoo.so 9069 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 9070 9071 /** New install */ 9072 FileInstallArgs(InstallParams params) { 9073 super(params.origin, params.observer, params.installFlags, 9074 params.installerPackageName, params.getManifestDigest(), params.getUser(), 9075 null /* instruction sets */, params.packageAbiOverride); 9076 if (isFwdLocked()) { 9077 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 9078 } 9079 } 9080 9081 /** Existing install */ 9082 FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath, 9083 String[] instructionSets) { 9084 super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null); 9085 this.codeFile = (codePath != null) ? new File(codePath) : null; 9086 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 9087 this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ? 9088 new File(legacyNativeLibraryPath) : null; 9089 } 9090 9091 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9092 final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(), 9093 isFwdLocked(), abiOverride); 9094 9095 final StorageManager storage = StorageManager.from(mContext); 9096 return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory())); 9097 } 9098 9099 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9100 if (origin.staged) { 9101 Slog.d(TAG, origin.file + " already staged; skipping copy"); 9102 codeFile = origin.file; 9103 resourceFile = origin.file; 9104 return PackageManager.INSTALL_SUCCEEDED; 9105 } 9106 9107 try { 9108 final File tempDir = mInstallerService.allocateInternalStageDirLegacy(); 9109 codeFile = tempDir; 9110 resourceFile = tempDir; 9111 } catch (IOException e) { 9112 Slog.w(TAG, "Failed to create copy file: " + e); 9113 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9114 } 9115 9116 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 9117 @Override 9118 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 9119 if (!FileUtils.isValidExtFilename(name)) { 9120 throw new IllegalArgumentException("Invalid filename: " + name); 9121 } 9122 try { 9123 final File file = new File(codeFile, name); 9124 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 9125 O_RDWR | O_CREAT, 0644); 9126 Os.chmod(file.getAbsolutePath(), 0644); 9127 return new ParcelFileDescriptor(fd); 9128 } catch (ErrnoException e) { 9129 throw new RemoteException("Failed to open: " + e.getMessage()); 9130 } 9131 } 9132 }; 9133 9134 int ret = PackageManager.INSTALL_SUCCEEDED; 9135 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 9136 if (ret != PackageManager.INSTALL_SUCCEEDED) { 9137 Slog.e(TAG, "Failed to copy package"); 9138 return ret; 9139 } 9140 9141 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 9142 NativeLibraryHelper.Handle handle = null; 9143 try { 9144 handle = NativeLibraryHelper.Handle.create(codeFile); 9145 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 9146 abiOverride); 9147 } catch (IOException e) { 9148 Slog.e(TAG, "Copying native libraries failed", e); 9149 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9150 } finally { 9151 IoUtils.closeQuietly(handle); 9152 } 9153 9154 return ret; 9155 } 9156 9157 int doPreInstall(int status) { 9158 if (status != PackageManager.INSTALL_SUCCEEDED) { 9159 cleanUp(); 9160 } 9161 return status; 9162 } 9163 9164 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9165 if (status != PackageManager.INSTALL_SUCCEEDED) { 9166 cleanUp(); 9167 return false; 9168 } else { 9169 final File beforeCodeFile = codeFile; 9170 final File afterCodeFile = getNextCodePath(pkg.packageName); 9171 9172 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 9173 try { 9174 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 9175 } catch (ErrnoException e) { 9176 Slog.d(TAG, "Failed to rename", e); 9177 return false; 9178 } 9179 9180 if (!SELinux.restoreconRecursive(afterCodeFile)) { 9181 Slog.d(TAG, "Failed to restorecon"); 9182 return false; 9183 } 9184 9185 // Reflect the rename internally 9186 codeFile = afterCodeFile; 9187 resourceFile = afterCodeFile; 9188 9189 // Reflect the rename in scanned details 9190 pkg.codePath = afterCodeFile.getAbsolutePath(); 9191 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9192 pkg.baseCodePath); 9193 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9194 pkg.splitCodePaths); 9195 9196 // Reflect the rename in app info 9197 pkg.applicationInfo.setCodePath(pkg.codePath); 9198 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9199 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9200 pkg.applicationInfo.setResourcePath(pkg.codePath); 9201 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9202 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9203 9204 return true; 9205 } 9206 } 9207 9208 int doPostInstall(int status, int uid) { 9209 if (status != PackageManager.INSTALL_SUCCEEDED) { 9210 cleanUp(); 9211 } 9212 return status; 9213 } 9214 9215 @Override 9216 String getCodePath() { 9217 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 9218 } 9219 9220 @Override 9221 String getResourcePath() { 9222 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 9223 } 9224 9225 @Override 9226 String getLegacyNativeLibraryPath() { 9227 return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null; 9228 } 9229 9230 private boolean cleanUp() { 9231 if (codeFile == null || !codeFile.exists()) { 9232 return false; 9233 } 9234 9235 if (codeFile.isDirectory()) { 9236 FileUtils.deleteContents(codeFile); 9237 } 9238 codeFile.delete(); 9239 9240 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 9241 resourceFile.delete(); 9242 } 9243 9244 if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) { 9245 if (!FileUtils.deleteContents(legacyNativeLibraryPath)) { 9246 Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath); 9247 } 9248 legacyNativeLibraryPath.delete(); 9249 } 9250 9251 return true; 9252 } 9253 9254 void cleanUpResourcesLI() { 9255 // Try enumerating all code paths before deleting 9256 List<String> allCodePaths = Collections.EMPTY_LIST; 9257 if (codeFile != null && codeFile.exists()) { 9258 try { 9259 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9260 allCodePaths = pkg.getAllCodePaths(); 9261 } catch (PackageParserException e) { 9262 // Ignored; we tried our best 9263 } 9264 } 9265 9266 cleanUp(); 9267 9268 if (!allCodePaths.isEmpty()) { 9269 if (instructionSets == null) { 9270 throw new IllegalStateException("instructionSet == null"); 9271 } 9272 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9273 for (String codePath : allCodePaths) { 9274 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9275 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9276 if (retCode < 0) { 9277 Slog.w(TAG, "Couldn't remove dex file for package: " 9278 + " at location " + codePath + ", retcode=" + retCode); 9279 // we don't consider this to be a failure of the core package deletion 9280 } 9281 } 9282 } 9283 } 9284 } 9285 9286 boolean doPostDeleteLI(boolean delete) { 9287 // XXX err, shouldn't we respect the delete flag? 9288 cleanUpResourcesLI(); 9289 return true; 9290 } 9291 } 9292 9293 private boolean isAsecExternal(String cid) { 9294 final String asecPath = PackageHelper.getSdFilesystem(cid); 9295 return !asecPath.startsWith(mAsecInternalPath); 9296 } 9297 9298 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 9299 PackageManagerException { 9300 if (copyRet < 0) { 9301 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 9302 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 9303 throw new PackageManagerException(copyRet, message); 9304 } 9305 } 9306 } 9307 9308 /** 9309 * Extract the MountService "container ID" from the full code path of an 9310 * .apk. 9311 */ 9312 static String cidFromCodePath(String fullCodePath) { 9313 int eidx = fullCodePath.lastIndexOf("/"); 9314 String subStr1 = fullCodePath.substring(0, eidx); 9315 int sidx = subStr1.lastIndexOf("/"); 9316 return subStr1.substring(sidx+1, eidx); 9317 } 9318 9319 /** 9320 * Logic to handle installation of ASEC applications, including copying and 9321 * renaming logic. 9322 */ 9323 class AsecInstallArgs extends InstallArgs { 9324 static final String RES_FILE_NAME = "pkg.apk"; 9325 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 9326 9327 String cid; 9328 String packagePath; 9329 String resourcePath; 9330 String legacyNativeLibraryDir; 9331 9332 /** New install */ 9333 AsecInstallArgs(InstallParams params) { 9334 super(params.origin, params.observer, params.installFlags, 9335 params.installerPackageName, params.getManifestDigest(), 9336 params.getUser(), null /* instruction sets */, 9337 params.packageAbiOverride); 9338 } 9339 9340 /** Existing install */ 9341 AsecInstallArgs(String fullCodePath, String[] instructionSets, 9342 boolean isExternal, boolean isForwardLocked) { 9343 super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0) 9344 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9345 instructionSets, null); 9346 // Hackily pretend we're still looking at a full code path 9347 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 9348 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 9349 } 9350 9351 // Extract cid from fullCodePath 9352 int eidx = fullCodePath.lastIndexOf("/"); 9353 String subStr1 = fullCodePath.substring(0, eidx); 9354 int sidx = subStr1.lastIndexOf("/"); 9355 cid = subStr1.substring(sidx+1, eidx); 9356 setMountPath(subStr1); 9357 } 9358 9359 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 9360 super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 9361 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9362 instructionSets, null); 9363 this.cid = cid; 9364 setMountPath(PackageHelper.getSdDir(cid)); 9365 } 9366 9367 void createCopyFile() { 9368 cid = mInstallerService.allocateExternalStageCidLegacy(); 9369 } 9370 9371 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9372 final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(), 9373 abiOverride); 9374 9375 final File target; 9376 if (isExternal()) { 9377 target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory(); 9378 } else { 9379 target = Environment.getDataDirectory(); 9380 } 9381 9382 final StorageManager storage = StorageManager.from(mContext); 9383 return (sizeBytes <= storage.getStorageBytesUntilLow(target)); 9384 } 9385 9386 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9387 if (origin.staged) { 9388 Slog.d(TAG, origin.cid + " already staged; skipping copy"); 9389 cid = origin.cid; 9390 setMountPath(PackageHelper.getSdDir(cid)); 9391 return PackageManager.INSTALL_SUCCEEDED; 9392 } 9393 9394 if (temp) { 9395 createCopyFile(); 9396 } else { 9397 /* 9398 * Pre-emptively destroy the container since it's destroyed if 9399 * copying fails due to it existing anyway. 9400 */ 9401 PackageHelper.destroySdDir(cid); 9402 } 9403 9404 final String newMountPath = imcs.copyPackageToContainer( 9405 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(), 9406 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 9407 9408 if (newMountPath != null) { 9409 setMountPath(newMountPath); 9410 return PackageManager.INSTALL_SUCCEEDED; 9411 } else { 9412 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9413 } 9414 } 9415 9416 @Override 9417 String getCodePath() { 9418 return packagePath; 9419 } 9420 9421 @Override 9422 String getResourcePath() { 9423 return resourcePath; 9424 } 9425 9426 @Override 9427 String getLegacyNativeLibraryPath() { 9428 return legacyNativeLibraryDir; 9429 } 9430 9431 int doPreInstall(int status) { 9432 if (status != PackageManager.INSTALL_SUCCEEDED) { 9433 // Destroy container 9434 PackageHelper.destroySdDir(cid); 9435 } else { 9436 boolean mounted = PackageHelper.isContainerMounted(cid); 9437 if (!mounted) { 9438 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 9439 Process.SYSTEM_UID); 9440 if (newMountPath != null) { 9441 setMountPath(newMountPath); 9442 } else { 9443 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9444 } 9445 } 9446 } 9447 return status; 9448 } 9449 9450 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9451 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 9452 String newMountPath = null; 9453 if (PackageHelper.isContainerMounted(cid)) { 9454 // Unmount the container 9455 if (!PackageHelper.unMountSdDir(cid)) { 9456 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9457 return false; 9458 } 9459 } 9460 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9461 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9462 " which might be stale. Will try to clean up."); 9463 // Clean up the stale container and proceed to recreate. 9464 if (!PackageHelper.destroySdDir(newCacheId)) { 9465 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9466 return false; 9467 } 9468 // Successfully cleaned up stale container. Try to rename again. 9469 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9470 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9471 + " inspite of cleaning it up."); 9472 return false; 9473 } 9474 } 9475 if (!PackageHelper.isContainerMounted(newCacheId)) { 9476 Slog.w(TAG, "Mounting container " + newCacheId); 9477 newMountPath = PackageHelper.mountSdDir(newCacheId, 9478 getEncryptKey(), Process.SYSTEM_UID); 9479 } else { 9480 newMountPath = PackageHelper.getSdDir(newCacheId); 9481 } 9482 if (newMountPath == null) { 9483 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9484 return false; 9485 } 9486 Log.i(TAG, "Succesfully renamed " + cid + 9487 " to " + newCacheId + 9488 " at new path: " + newMountPath); 9489 cid = newCacheId; 9490 9491 final File beforeCodeFile = new File(packagePath); 9492 setMountPath(newMountPath); 9493 final File afterCodeFile = new File(packagePath); 9494 9495 // Reflect the rename in scanned details 9496 pkg.codePath = afterCodeFile.getAbsolutePath(); 9497 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9498 pkg.baseCodePath); 9499 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9500 pkg.splitCodePaths); 9501 9502 // Reflect the rename in app info 9503 pkg.applicationInfo.setCodePath(pkg.codePath); 9504 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9505 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9506 pkg.applicationInfo.setResourcePath(pkg.codePath); 9507 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9508 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9509 9510 return true; 9511 } 9512 9513 private void setMountPath(String mountPath) { 9514 final File mountFile = new File(mountPath); 9515 9516 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 9517 if (monolithicFile.exists()) { 9518 packagePath = monolithicFile.getAbsolutePath(); 9519 if (isFwdLocked()) { 9520 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 9521 } else { 9522 resourcePath = packagePath; 9523 } 9524 } else { 9525 packagePath = mountFile.getAbsolutePath(); 9526 resourcePath = packagePath; 9527 } 9528 9529 legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath(); 9530 } 9531 9532 int doPostInstall(int status, int uid) { 9533 if (status != PackageManager.INSTALL_SUCCEEDED) { 9534 cleanUp(); 9535 } else { 9536 final int groupOwner; 9537 final String protectedFile; 9538 if (isFwdLocked()) { 9539 groupOwner = UserHandle.getSharedAppGid(uid); 9540 protectedFile = RES_FILE_NAME; 9541 } else { 9542 groupOwner = -1; 9543 protectedFile = null; 9544 } 9545 9546 if (uid < Process.FIRST_APPLICATION_UID 9547 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9548 Slog.e(TAG, "Failed to finalize " + cid); 9549 PackageHelper.destroySdDir(cid); 9550 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9551 } 9552 9553 boolean mounted = PackageHelper.isContainerMounted(cid); 9554 if (!mounted) { 9555 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9556 } 9557 } 9558 return status; 9559 } 9560 9561 private void cleanUp() { 9562 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9563 9564 // Destroy secure container 9565 PackageHelper.destroySdDir(cid); 9566 } 9567 9568 private List<String> getAllCodePaths() { 9569 final File codeFile = new File(getCodePath()); 9570 if (codeFile != null && codeFile.exists()) { 9571 try { 9572 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9573 return pkg.getAllCodePaths(); 9574 } catch (PackageParserException e) { 9575 // Ignored; we tried our best 9576 } 9577 } 9578 return Collections.EMPTY_LIST; 9579 } 9580 9581 void cleanUpResourcesLI() { 9582 // Enumerate all code paths before deleting 9583 cleanUpResourcesLI(getAllCodePaths()); 9584 } 9585 9586 private void cleanUpResourcesLI(List<String> allCodePaths) { 9587 cleanUp(); 9588 9589 if (!allCodePaths.isEmpty()) { 9590 if (instructionSets == null) { 9591 throw new IllegalStateException("instructionSet == null"); 9592 } 9593 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9594 for (String codePath : allCodePaths) { 9595 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9596 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9597 if (retCode < 0) { 9598 Slog.w(TAG, "Couldn't remove dex file for package: " 9599 + " at location " + codePath + ", retcode=" + retCode); 9600 // we don't consider this to be a failure of the core package deletion 9601 } 9602 } 9603 } 9604 } 9605 } 9606 9607 boolean matchContainer(String app) { 9608 if (cid.startsWith(app)) { 9609 return true; 9610 } 9611 return false; 9612 } 9613 9614 String getPackageName() { 9615 return getAsecPackageName(cid); 9616 } 9617 9618 boolean doPostDeleteLI(boolean delete) { 9619 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 9620 final List<String> allCodePaths = getAllCodePaths(); 9621 boolean mounted = PackageHelper.isContainerMounted(cid); 9622 if (mounted) { 9623 // Unmount first 9624 if (PackageHelper.unMountSdDir(cid)) { 9625 mounted = false; 9626 } 9627 } 9628 if (!mounted && delete) { 9629 cleanUpResourcesLI(allCodePaths); 9630 } 9631 return !mounted; 9632 } 9633 9634 @Override 9635 int doPreCopy() { 9636 if (isFwdLocked()) { 9637 if (!PackageHelper.fixSdPermissions(cid, 9638 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 9639 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9640 } 9641 } 9642 9643 return PackageManager.INSTALL_SUCCEEDED; 9644 } 9645 9646 @Override 9647 int doPostCopy(int uid) { 9648 if (isFwdLocked()) { 9649 if (uid < Process.FIRST_APPLICATION_UID 9650 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 9651 RES_FILE_NAME)) { 9652 Slog.e(TAG, "Failed to finalize " + cid); 9653 PackageHelper.destroySdDir(cid); 9654 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9655 } 9656 } 9657 9658 return PackageManager.INSTALL_SUCCEEDED; 9659 } 9660 } 9661 9662 static String getAsecPackageName(String packageCid) { 9663 int idx = packageCid.lastIndexOf("-"); 9664 if (idx == -1) { 9665 return packageCid; 9666 } 9667 return packageCid.substring(0, idx); 9668 } 9669 9670 // Utility method used to create code paths based on package name and available index. 9671 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 9672 String idxStr = ""; 9673 int idx = 1; 9674 // Fall back to default value of idx=1 if prefix is not 9675 // part of oldCodePath 9676 if (oldCodePath != null) { 9677 String subStr = oldCodePath; 9678 // Drop the suffix right away 9679 if (suffix != null && subStr.endsWith(suffix)) { 9680 subStr = subStr.substring(0, subStr.length() - suffix.length()); 9681 } 9682 // If oldCodePath already contains prefix find out the 9683 // ending index to either increment or decrement. 9684 int sidx = subStr.lastIndexOf(prefix); 9685 if (sidx != -1) { 9686 subStr = subStr.substring(sidx + prefix.length()); 9687 if (subStr != null) { 9688 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 9689 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 9690 } 9691 try { 9692 idx = Integer.parseInt(subStr); 9693 if (idx <= 1) { 9694 idx++; 9695 } else { 9696 idx--; 9697 } 9698 } catch(NumberFormatException e) { 9699 } 9700 } 9701 } 9702 } 9703 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 9704 return prefix + idxStr; 9705 } 9706 9707 private File getNextCodePath(String packageName) { 9708 int suffix = 1; 9709 File result; 9710 do { 9711 result = new File(mAppInstallDir, packageName + "-" + suffix); 9712 suffix++; 9713 } while (result.exists()); 9714 return result; 9715 } 9716 9717 // Utility method used to ignore ADD/REMOVE events 9718 // by directory observer. 9719 private static boolean ignoreCodePath(String fullPathStr) { 9720 String apkName = deriveCodePathName(fullPathStr); 9721 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 9722 if (idx != -1 && ((idx+1) < apkName.length())) { 9723 // Make sure the package ends with a numeral 9724 String version = apkName.substring(idx+1); 9725 try { 9726 Integer.parseInt(version); 9727 return true; 9728 } catch (NumberFormatException e) {} 9729 } 9730 return false; 9731 } 9732 9733 // Utility method that returns the relative package path with respect 9734 // to the installation directory. Like say for /data/data/com.test-1.apk 9735 // string com.test-1 is returned. 9736 static String deriveCodePathName(String codePath) { 9737 if (codePath == null) { 9738 return null; 9739 } 9740 final File codeFile = new File(codePath); 9741 final String name = codeFile.getName(); 9742 if (codeFile.isDirectory()) { 9743 return name; 9744 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 9745 final int lastDot = name.lastIndexOf('.'); 9746 return name.substring(0, lastDot); 9747 } else { 9748 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 9749 return null; 9750 } 9751 } 9752 9753 class PackageInstalledInfo { 9754 String name; 9755 int uid; 9756 // The set of users that originally had this package installed. 9757 int[] origUsers; 9758 // The set of users that now have this package installed. 9759 int[] newUsers; 9760 PackageParser.Package pkg; 9761 int returnCode; 9762 String returnMsg; 9763 PackageRemovedInfo removedInfo; 9764 9765 public void setError(int code, String msg) { 9766 returnCode = code; 9767 returnMsg = msg; 9768 Slog.w(TAG, msg); 9769 } 9770 9771 public void setError(String msg, PackageParserException e) { 9772 returnCode = e.error; 9773 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9774 Slog.w(TAG, msg, e); 9775 } 9776 9777 public void setError(String msg, PackageManagerException e) { 9778 returnCode = e.error; 9779 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 9780 Slog.w(TAG, msg, e); 9781 } 9782 9783 // In some error cases we want to convey more info back to the observer 9784 String origPackage; 9785 String origPermission; 9786 } 9787 9788 /* 9789 * Install a non-existing package. 9790 */ 9791 private void installNewPackageLI(PackageParser.Package pkg, 9792 int parseFlags, int scanFlags, UserHandle user, 9793 String installerPackageName, PackageInstalledInfo res) { 9794 // Remember this for later, in case we need to rollback this install 9795 String pkgName = pkg.packageName; 9796 9797 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 9798 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 9799 synchronized(mPackages) { 9800 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 9801 // A package with the same name is already installed, though 9802 // it has been renamed to an older name. The package we 9803 // are trying to install should be installed as an update to 9804 // the existing one, but that has not been requested, so bail. 9805 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9806 + " without first uninstalling package running as " 9807 + mSettings.mRenamedPackages.get(pkgName)); 9808 return; 9809 } 9810 if (mPackages.containsKey(pkgName)) { 9811 // Don't allow installation over an existing package with the same name. 9812 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 9813 + " without first uninstalling."); 9814 return; 9815 } 9816 } 9817 9818 try { 9819 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 9820 System.currentTimeMillis(), user); 9821 9822 updateSettingsLI(newPackage, installerPackageName, null, null, res); 9823 // delete the partially installed application. the data directory will have to be 9824 // restored if it was already existing 9825 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9826 // remove package from internal structures. Note that we want deletePackageX to 9827 // delete the package data and cache directories that it created in 9828 // scanPackageLocked, unless those directories existed before we even tried to 9829 // install. 9830 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 9831 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 9832 res.removedInfo, true); 9833 } 9834 9835 } catch (PackageManagerException e) { 9836 res.setError("Package couldn't be installed in " + pkg.codePath, e); 9837 } 9838 } 9839 9840 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 9841 // Upgrade keysets are being used. Determine if new package has a superset of the 9842 // required keys. 9843 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 9844 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9845 for (int i = 0; i < upgradeKeySets.length; i++) { 9846 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 9847 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 9848 return true; 9849 } 9850 } 9851 return false; 9852 } 9853 9854 private void replacePackageLI(PackageParser.Package pkg, 9855 int parseFlags, int scanFlags, UserHandle user, 9856 String installerPackageName, PackageInstalledInfo res) { 9857 PackageParser.Package oldPackage; 9858 String pkgName = pkg.packageName; 9859 int[] allUsers; 9860 boolean[] perUserInstalled; 9861 9862 // First find the old package info and check signatures 9863 synchronized(mPackages) { 9864 oldPackage = mPackages.get(pkgName); 9865 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 9866 PackageSetting ps = mSettings.mPackages.get(pkgName); 9867 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 9868 // default to original signature matching 9869 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 9870 != PackageManager.SIGNATURE_MATCH) { 9871 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9872 "New package has a different signature: " + pkgName); 9873 return; 9874 } 9875 } else { 9876 if(!checkUpgradeKeySetLP(ps, pkg)) { 9877 res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9878 "New package not signed by keys specified by upgrade-keysets: " 9879 + pkgName); 9880 return; 9881 } 9882 } 9883 9884 // In case of rollback, remember per-user/profile install state 9885 allUsers = sUserManager.getUserIds(); 9886 perUserInstalled = new boolean[allUsers.length]; 9887 for (int i = 0; i < allUsers.length; i++) { 9888 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 9889 } 9890 } 9891 9892 boolean sysPkg = (isSystemApp(oldPackage)); 9893 if (sysPkg) { 9894 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 9895 user, allUsers, perUserInstalled, installerPackageName, res); 9896 } else { 9897 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 9898 user, allUsers, perUserInstalled, installerPackageName, res); 9899 } 9900 } 9901 9902 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 9903 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 9904 int[] allUsers, boolean[] perUserInstalled, 9905 String installerPackageName, PackageInstalledInfo res) { 9906 String pkgName = deletedPackage.packageName; 9907 boolean deletedPkg = true; 9908 boolean updatedSettings = false; 9909 9910 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 9911 + deletedPackage); 9912 long origUpdateTime; 9913 if (pkg.mExtras != null) { 9914 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 9915 } else { 9916 origUpdateTime = 0; 9917 } 9918 9919 // First delete the existing package while retaining the data directory 9920 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 9921 res.removedInfo, true)) { 9922 // If the existing package wasn't successfully deleted 9923 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 9924 deletedPkg = false; 9925 } else { 9926 // Successfully deleted the old package; proceed with replace. 9927 9928 // If deleted package lived in a container, give users a chance to 9929 // relinquish resources before killing. 9930 if (isForwardLocked(deletedPackage) || isExternal(deletedPackage)) { 9931 if (DEBUG_INSTALL) { 9932 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 9933 } 9934 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 9935 final ArrayList<String> pkgList = new ArrayList<String>(1); 9936 pkgList.add(deletedPackage.applicationInfo.packageName); 9937 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 9938 } 9939 9940 deleteCodeCacheDirsLI(pkgName); 9941 try { 9942 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 9943 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 9944 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 9945 updatedSettings = true; 9946 } catch (PackageManagerException e) { 9947 res.setError("Package couldn't be installed in " + pkg.codePath, e); 9948 } 9949 } 9950 9951 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9952 // remove package from internal structures. Note that we want deletePackageX to 9953 // delete the package data and cache directories that it created in 9954 // scanPackageLocked, unless those directories existed before we even tried to 9955 // install. 9956 if(updatedSettings) { 9957 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 9958 deletePackageLI( 9959 pkgName, null, true, allUsers, perUserInstalled, 9960 PackageManager.DELETE_KEEP_DATA, 9961 res.removedInfo, true); 9962 } 9963 // Since we failed to install the new package we need to restore the old 9964 // package that we deleted. 9965 if (deletedPkg) { 9966 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 9967 File restoreFile = new File(deletedPackage.codePath); 9968 // Parse old package 9969 boolean oldOnSd = isExternal(deletedPackage); 9970 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 9971 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) | 9972 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 9973 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 9974 try { 9975 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 9976 } catch (PackageManagerException e) { 9977 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 9978 + e.getMessage()); 9979 return; 9980 } 9981 // Restore of old package succeeded. Update permissions. 9982 // writer 9983 synchronized (mPackages) { 9984 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 9985 UPDATE_PERMISSIONS_ALL); 9986 // can downgrade to reader 9987 mSettings.writeLPr(); 9988 } 9989 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 9990 } 9991 } 9992 } 9993 9994 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 9995 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 9996 int[] allUsers, boolean[] perUserInstalled, 9997 String installerPackageName, PackageInstalledInfo res) { 9998 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 9999 + ", old=" + deletedPackage); 10000 boolean updatedSettings = false; 10001 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 10002 if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) { 10003 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10004 } 10005 String packageName = deletedPackage.packageName; 10006 if (packageName == null) { 10007 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10008 "Attempt to delete null packageName."); 10009 return; 10010 } 10011 PackageParser.Package oldPkg; 10012 PackageSetting oldPkgSetting; 10013 // reader 10014 synchronized (mPackages) { 10015 oldPkg = mPackages.get(packageName); 10016 oldPkgSetting = mSettings.mPackages.get(packageName); 10017 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 10018 (oldPkgSetting == null)) { 10019 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10020 "Couldn't find package:" + packageName + " information"); 10021 return; 10022 } 10023 } 10024 10025 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 10026 10027 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10028 res.removedInfo.removedPackage = packageName; 10029 // Remove existing system package 10030 removePackageLI(oldPkgSetting, true); 10031 // writer 10032 synchronized (mPackages) { 10033 if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) { 10034 // We didn't need to disable the .apk as a current system package, 10035 // which means we are replacing another update that is already 10036 // installed. We need to make sure to delete the older one's .apk. 10037 res.removedInfo.args = createInstallArgsForExisting(0, 10038 deletedPackage.applicationInfo.getCodePath(), 10039 deletedPackage.applicationInfo.getResourcePath(), 10040 deletedPackage.applicationInfo.nativeLibraryRootDir, 10041 getAppDexInstructionSets(deletedPackage.applicationInfo)); 10042 } else { 10043 res.removedInfo.args = null; 10044 } 10045 } 10046 10047 // Successfully disabled the old package. Now proceed with re-installation 10048 deleteCodeCacheDirsLI(packageName); 10049 10050 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10051 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10052 10053 PackageParser.Package newPackage = null; 10054 try { 10055 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 10056 if (newPackage.mExtras != null) { 10057 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 10058 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10059 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10060 10061 // is the update attempting to change shared user? that isn't going to work... 10062 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10063 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 10064 "Forbidding shared user change from " + oldPkgSetting.sharedUser 10065 + " to " + newPkgSetting.sharedUser); 10066 updatedSettings = true; 10067 } 10068 } 10069 10070 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10071 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10072 updatedSettings = true; 10073 } 10074 10075 } catch (PackageManagerException e) { 10076 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10077 } 10078 10079 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10080 // Re installation failed. Restore old information 10081 // Remove new pkg information 10082 if (newPackage != null) { 10083 removeInstalledPackageLI(newPackage, true); 10084 } 10085 // Add back the old system package 10086 try { 10087 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 10088 } catch (PackageManagerException e) { 10089 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 10090 } 10091 // Restore the old system information in Settings 10092 synchronized(mPackages) { 10093 if (updatedSettings) { 10094 mSettings.enableSystemPackageLPw(packageName); 10095 mSettings.setInstallerPackageName(packageName, 10096 oldPkgSetting.installerPackageName); 10097 } 10098 mSettings.writeLPr(); 10099 } 10100 } 10101 } 10102 10103 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10104 int[] allUsers, boolean[] perUserInstalled, 10105 PackageInstalledInfo res) { 10106 String pkgName = newPackage.packageName; 10107 synchronized (mPackages) { 10108 //write settings. the installStatus will be incomplete at this stage. 10109 //note that the new package setting would have already been 10110 //added to mPackages. It hasn't been persisted yet. 10111 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10112 mSettings.writeLPr(); 10113 } 10114 10115 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10116 10117 synchronized (mPackages) { 10118 updatePermissionsLPw(newPackage.packageName, newPackage, 10119 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10120 ? UPDATE_PERMISSIONS_ALL : 0)); 10121 // For system-bundled packages, we assume that installing an upgraded version 10122 // of the package implies that the user actually wants to run that new code, 10123 // so we enable the package. 10124 if (isSystemApp(newPackage)) { 10125 // NB: implicit assumption that system package upgrades apply to all users 10126 if (DEBUG_INSTALL) { 10127 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10128 } 10129 PackageSetting ps = mSettings.mPackages.get(pkgName); 10130 if (ps != null) { 10131 if (res.origUsers != null) { 10132 for (int userHandle : res.origUsers) { 10133 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10134 userHandle, installerPackageName); 10135 } 10136 } 10137 // Also convey the prior install/uninstall state 10138 if (allUsers != null && perUserInstalled != null) { 10139 for (int i = 0; i < allUsers.length; i++) { 10140 if (DEBUG_INSTALL) { 10141 Slog.d(TAG, " user " + allUsers[i] 10142 + " => " + perUserInstalled[i]); 10143 } 10144 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10145 } 10146 // these install state changes will be persisted in the 10147 // upcoming call to mSettings.writeLPr(). 10148 } 10149 } 10150 } 10151 res.name = pkgName; 10152 res.uid = newPackage.applicationInfo.uid; 10153 res.pkg = newPackage; 10154 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10155 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10156 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10157 //to update install status 10158 mSettings.writeLPr(); 10159 } 10160 } 10161 10162 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 10163 final int installFlags = args.installFlags; 10164 String installerPackageName = args.installerPackageName; 10165 File tmpPackageFile = new File(args.getCodePath()); 10166 boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10167 boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0); 10168 boolean replace = false; 10169 final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE; 10170 // Result object to be returned 10171 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10172 10173 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10174 // Retrieve PackageSettings and parse package 10175 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10176 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10177 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 10178 PackageParser pp = new PackageParser(); 10179 pp.setSeparateProcesses(mSeparateProcesses); 10180 pp.setDisplayMetrics(mMetrics); 10181 10182 final PackageParser.Package pkg; 10183 try { 10184 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 10185 } catch (PackageParserException e) { 10186 res.setError("Failed parse during installPackageLI", e); 10187 return; 10188 } 10189 10190 // Mark that we have an install time CPU ABI override. 10191 pkg.cpuAbiOverride = args.abiOverride; 10192 10193 String pkgName = res.name = pkg.packageName; 10194 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 10195 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 10196 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 10197 return; 10198 } 10199 } 10200 10201 try { 10202 pp.collectCertificates(pkg, parseFlags); 10203 pp.collectManifestDigest(pkg); 10204 } catch (PackageParserException e) { 10205 res.setError("Failed collect during installPackageLI", e); 10206 return; 10207 } 10208 10209 /* If the installer passed in a manifest digest, compare it now. */ 10210 if (args.manifestDigest != null) { 10211 if (DEBUG_INSTALL) { 10212 final String parsedManifest = pkg.manifestDigest == null ? "null" 10213 : pkg.manifestDigest.toString(); 10214 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 10215 + parsedManifest); 10216 } 10217 10218 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 10219 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 10220 return; 10221 } 10222 } else if (DEBUG_INSTALL) { 10223 final String parsedManifest = pkg.manifestDigest == null 10224 ? "null" : pkg.manifestDigest.toString(); 10225 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 10226 } 10227 10228 // Get rid of all references to package scan path via parser. 10229 pp = null; 10230 String oldCodePath = null; 10231 boolean systemApp = false; 10232 synchronized (mPackages) { 10233 // Check whether the newly-scanned package wants to define an already-defined perm 10234 int N = pkg.permissions.size(); 10235 for (int i = N-1; i >= 0; i--) { 10236 PackageParser.Permission perm = pkg.permissions.get(i); 10237 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 10238 if (bp != null) { 10239 // If the defining package is signed with our cert, it's okay. This 10240 // also includes the "updating the same package" case, of course. 10241 if (compareSignatures(bp.packageSetting.signatures.mSignatures, 10242 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 10243 // If the owning package is the system itself, we log but allow 10244 // install to proceed; we fail the install on all other permission 10245 // redefinitions. 10246 if (!bp.sourcePackage.equals("android")) { 10247 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 10248 + pkg.packageName + " attempting to redeclare permission " 10249 + perm.info.name + " already owned by " + bp.sourcePackage); 10250 res.origPermission = perm.info.name; 10251 res.origPackage = bp.sourcePackage; 10252 return; 10253 } else { 10254 Slog.w(TAG, "Package " + pkg.packageName 10255 + " attempting to redeclare system permission " 10256 + perm.info.name + "; ignoring new declaration"); 10257 pkg.permissions.remove(i); 10258 } 10259 } 10260 } 10261 } 10262 10263 // Check if installing already existing package 10264 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10265 String oldName = mSettings.mRenamedPackages.get(pkgName); 10266 if (pkg.mOriginalPackages != null 10267 && pkg.mOriginalPackages.contains(oldName) 10268 && mPackages.containsKey(oldName)) { 10269 // This package is derived from an original package, 10270 // and this device has been updating from that original 10271 // name. We must continue using the original name, so 10272 // rename the new package here. 10273 pkg.setPackageName(oldName); 10274 pkgName = pkg.packageName; 10275 replace = true; 10276 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 10277 + oldName + " pkgName=" + pkgName); 10278 } else if (mPackages.containsKey(pkgName)) { 10279 // This package, under its official name, already exists 10280 // on the device; we should replace it. 10281 replace = true; 10282 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 10283 } 10284 } 10285 PackageSetting ps = mSettings.mPackages.get(pkgName); 10286 if (ps != null) { 10287 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 10288 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 10289 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 10290 systemApp = (ps.pkg.applicationInfo.flags & 10291 ApplicationInfo.FLAG_SYSTEM) != 0; 10292 } 10293 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10294 } 10295 } 10296 10297 if (systemApp && onSd) { 10298 // Disable updates to system apps on sdcard 10299 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 10300 "Cannot install updates to system apps on sdcard"); 10301 return; 10302 } 10303 10304 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 10305 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 10306 return; 10307 } 10308 10309 if (replace) { 10310 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 10311 installerPackageName, res); 10312 } else { 10313 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 10314 args.user, installerPackageName, res); 10315 } 10316 synchronized (mPackages) { 10317 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10318 if (ps != null) { 10319 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10320 } 10321 } 10322 } 10323 10324 private static boolean isForwardLocked(PackageParser.Package pkg) { 10325 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10326 } 10327 10328 private static boolean isForwardLocked(ApplicationInfo info) { 10329 return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10330 } 10331 10332 private boolean isForwardLocked(PackageSetting ps) { 10333 return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10334 } 10335 10336 private static boolean isMultiArch(PackageSetting ps) { 10337 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10338 } 10339 10340 private static boolean isMultiArch(ApplicationInfo info) { 10341 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10342 } 10343 10344 private static boolean isExternal(PackageParser.Package pkg) { 10345 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10346 } 10347 10348 private static boolean isExternal(PackageSetting ps) { 10349 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10350 } 10351 10352 private static boolean isExternal(ApplicationInfo info) { 10353 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10354 } 10355 10356 private static boolean isSystemApp(PackageParser.Package pkg) { 10357 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10358 } 10359 10360 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 10361 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0; 10362 } 10363 10364 private static boolean isSystemApp(ApplicationInfo info) { 10365 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10366 } 10367 10368 private static boolean isSystemApp(PackageSetting ps) { 10369 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 10370 } 10371 10372 private static boolean isUpdatedSystemApp(PackageSetting ps) { 10373 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10374 } 10375 10376 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 10377 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10378 } 10379 10380 private static boolean isUpdatedSystemApp(ApplicationInfo info) { 10381 return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10382 } 10383 10384 private int packageFlagsToInstallFlags(PackageSetting ps) { 10385 int installFlags = 0; 10386 if (isExternal(ps)) { 10387 installFlags |= PackageManager.INSTALL_EXTERNAL; 10388 } 10389 if (isForwardLocked(ps)) { 10390 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 10391 } 10392 return installFlags; 10393 } 10394 10395 private void deleteTempPackageFiles() { 10396 final FilenameFilter filter = new FilenameFilter() { 10397 public boolean accept(File dir, String name) { 10398 return name.startsWith("vmdl") && name.endsWith(".tmp"); 10399 } 10400 }; 10401 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 10402 file.delete(); 10403 } 10404 } 10405 10406 @Override 10407 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 10408 int flags) { 10409 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 10410 flags); 10411 } 10412 10413 @Override 10414 public void deletePackage(final String packageName, 10415 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 10416 mContext.enforceCallingOrSelfPermission( 10417 android.Manifest.permission.DELETE_PACKAGES, null); 10418 final int uid = Binder.getCallingUid(); 10419 if (UserHandle.getUserId(uid) != userId) { 10420 mContext.enforceCallingPermission( 10421 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 10422 "deletePackage for user " + userId); 10423 } 10424 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 10425 try { 10426 observer.onPackageDeleted(packageName, 10427 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 10428 } catch (RemoteException re) { 10429 } 10430 return; 10431 } 10432 10433 boolean uninstallBlocked = false; 10434 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 10435 int[] users = sUserManager.getUserIds(); 10436 for (int i = 0; i < users.length; ++i) { 10437 if (getBlockUninstallForUser(packageName, users[i])) { 10438 uninstallBlocked = true; 10439 break; 10440 } 10441 } 10442 } else { 10443 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 10444 } 10445 if (uninstallBlocked) { 10446 try { 10447 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 10448 null); 10449 } catch (RemoteException re) { 10450 } 10451 return; 10452 } 10453 10454 if (DEBUG_REMOVE) { 10455 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 10456 } 10457 // Queue up an async operation since the package deletion may take a little while. 10458 mHandler.post(new Runnable() { 10459 public void run() { 10460 mHandler.removeCallbacks(this); 10461 final int returnCode = deletePackageX(packageName, userId, flags); 10462 if (observer != null) { 10463 try { 10464 observer.onPackageDeleted(packageName, returnCode, null); 10465 } catch (RemoteException e) { 10466 Log.i(TAG, "Observer no longer exists."); 10467 } //end catch 10468 } //end if 10469 } //end run 10470 }); 10471 } 10472 10473 private boolean isPackageDeviceAdmin(String packageName, int userId) { 10474 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 10475 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 10476 try { 10477 if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId) 10478 || dpm.isDeviceOwner(packageName))) { 10479 return true; 10480 } 10481 } catch (RemoteException e) { 10482 } 10483 return false; 10484 } 10485 10486 /** 10487 * This method is an internal method that could be get invoked either 10488 * to delete an installed package or to clean up a failed installation. 10489 * After deleting an installed package, a broadcast is sent to notify any 10490 * listeners that the package has been installed. For cleaning up a failed 10491 * installation, the broadcast is not necessary since the package's 10492 * installation wouldn't have sent the initial broadcast either 10493 * The key steps in deleting a package are 10494 * deleting the package information in internal structures like mPackages, 10495 * deleting the packages base directories through installd 10496 * updating mSettings to reflect current status 10497 * persisting settings for later use 10498 * sending a broadcast if necessary 10499 */ 10500 private int deletePackageX(String packageName, int userId, int flags) { 10501 final PackageRemovedInfo info = new PackageRemovedInfo(); 10502 final boolean res; 10503 10504 if (isPackageDeviceAdmin(packageName, userId)) { 10505 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 10506 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 10507 } 10508 10509 boolean removedForAllUsers = false; 10510 boolean systemUpdate = false; 10511 10512 // for the uninstall-updates case and restricted profiles, remember the per- 10513 // userhandle installed state 10514 int[] allUsers; 10515 boolean[] perUserInstalled; 10516 synchronized (mPackages) { 10517 PackageSetting ps = mSettings.mPackages.get(packageName); 10518 allUsers = sUserManager.getUserIds(); 10519 perUserInstalled = new boolean[allUsers.length]; 10520 for (int i = 0; i < allUsers.length; i++) { 10521 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10522 } 10523 } 10524 10525 synchronized (mInstallLock) { 10526 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 10527 res = deletePackageLI(packageName, 10528 (flags & PackageManager.DELETE_ALL_USERS) != 0 10529 ? UserHandle.ALL : new UserHandle(userId), 10530 true, allUsers, perUserInstalled, 10531 flags | REMOVE_CHATTY, info, true); 10532 systemUpdate = info.isRemovedPackageSystemUpdate; 10533 if (res && !systemUpdate && mPackages.get(packageName) == null) { 10534 removedForAllUsers = true; 10535 } 10536 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 10537 + " removedForAllUsers=" + removedForAllUsers); 10538 } 10539 10540 if (res) { 10541 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 10542 10543 // If the removed package was a system update, the old system package 10544 // was re-enabled; we need to broadcast this information 10545 if (systemUpdate) { 10546 Bundle extras = new Bundle(1); 10547 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 10548 ? info.removedAppId : info.uid); 10549 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10550 10551 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 10552 extras, null, null, null); 10553 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 10554 extras, null, null, null); 10555 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 10556 null, packageName, null, null); 10557 } 10558 } 10559 // Force a gc here. 10560 Runtime.getRuntime().gc(); 10561 // Delete the resources here after sending the broadcast to let 10562 // other processes clean up before deleting resources. 10563 if (info.args != null) { 10564 synchronized (mInstallLock) { 10565 info.args.doPostDeleteLI(true); 10566 } 10567 } 10568 10569 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10570 } 10571 10572 static class PackageRemovedInfo { 10573 String removedPackage; 10574 int uid = -1; 10575 int removedAppId = -1; 10576 int[] removedUsers = null; 10577 boolean isRemovedPackageSystemUpdate = false; 10578 // Clean up resources deleted packages. 10579 InstallArgs args = null; 10580 10581 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 10582 Bundle extras = new Bundle(1); 10583 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 10584 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 10585 if (replacing) { 10586 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10587 } 10588 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 10589 if (removedPackage != null) { 10590 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 10591 extras, null, null, removedUsers); 10592 if (fullRemove && !replacing) { 10593 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 10594 extras, null, null, removedUsers); 10595 } 10596 } 10597 if (removedAppId >= 0) { 10598 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 10599 removedUsers); 10600 } 10601 } 10602 } 10603 10604 /* 10605 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 10606 * flag is not set, the data directory is removed as well. 10607 * make sure this flag is set for partially installed apps. If not its meaningless to 10608 * delete a partially installed application. 10609 */ 10610 private void removePackageDataLI(PackageSetting ps, 10611 int[] allUserHandles, boolean[] perUserInstalled, 10612 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 10613 String packageName = ps.name; 10614 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 10615 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 10616 // Retrieve object to delete permissions for shared user later on 10617 final PackageSetting deletedPs; 10618 // reader 10619 synchronized (mPackages) { 10620 deletedPs = mSettings.mPackages.get(packageName); 10621 if (outInfo != null) { 10622 outInfo.removedPackage = packageName; 10623 outInfo.removedUsers = deletedPs != null 10624 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 10625 : null; 10626 } 10627 } 10628 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10629 removeDataDirsLI(packageName); 10630 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 10631 } 10632 // writer 10633 synchronized (mPackages) { 10634 if (deletedPs != null) { 10635 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10636 if (outInfo != null) { 10637 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 10638 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 10639 } 10640 if (deletedPs != null) { 10641 updatePermissionsLPw(deletedPs.name, null, 0); 10642 if (deletedPs.sharedUser != null) { 10643 // remove permissions associated with package 10644 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 10645 } 10646 } 10647 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 10648 } 10649 // make sure to preserve per-user disabled state if this removal was just 10650 // a downgrade of a system app to the factory package 10651 if (allUserHandles != null && perUserInstalled != null) { 10652 if (DEBUG_REMOVE) { 10653 Slog.d(TAG, "Propagating install state across downgrade"); 10654 } 10655 for (int i = 0; i < allUserHandles.length; i++) { 10656 if (DEBUG_REMOVE) { 10657 Slog.d(TAG, " user " + allUserHandles[i] 10658 + " => " + perUserInstalled[i]); 10659 } 10660 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10661 } 10662 } 10663 } 10664 // can downgrade to reader 10665 if (writeSettings) { 10666 // Save settings now 10667 mSettings.writeLPr(); 10668 } 10669 } 10670 if (outInfo != null) { 10671 // A user ID was deleted here. Go through all users and remove it 10672 // from KeyStore. 10673 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 10674 } 10675 } 10676 10677 static boolean locationIsPrivileged(File path) { 10678 try { 10679 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 10680 .getCanonicalPath(); 10681 return path.getCanonicalPath().startsWith(privilegedAppDir); 10682 } catch (IOException e) { 10683 Slog.e(TAG, "Unable to access code path " + path); 10684 } 10685 return false; 10686 } 10687 10688 /* 10689 * Tries to delete system package. 10690 */ 10691 private boolean deleteSystemPackageLI(PackageSetting newPs, 10692 int[] allUserHandles, boolean[] perUserInstalled, 10693 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 10694 final boolean applyUserRestrictions 10695 = (allUserHandles != null) && (perUserInstalled != null); 10696 PackageSetting disabledPs = null; 10697 // Confirm if the system package has been updated 10698 // An updated system app can be deleted. This will also have to restore 10699 // the system pkg from system partition 10700 // reader 10701 synchronized (mPackages) { 10702 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 10703 } 10704 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 10705 + " disabledPs=" + disabledPs); 10706 if (disabledPs == null) { 10707 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 10708 return false; 10709 } else if (DEBUG_REMOVE) { 10710 Slog.d(TAG, "Deleting system pkg from data partition"); 10711 } 10712 if (DEBUG_REMOVE) { 10713 if (applyUserRestrictions) { 10714 Slog.d(TAG, "Remembering install states:"); 10715 for (int i = 0; i < allUserHandles.length; i++) { 10716 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 10717 } 10718 } 10719 } 10720 // Delete the updated package 10721 outInfo.isRemovedPackageSystemUpdate = true; 10722 if (disabledPs.versionCode < newPs.versionCode) { 10723 // Delete data for downgrades 10724 flags &= ~PackageManager.DELETE_KEEP_DATA; 10725 } else { 10726 // Preserve data by setting flag 10727 flags |= PackageManager.DELETE_KEEP_DATA; 10728 } 10729 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 10730 allUserHandles, perUserInstalled, outInfo, writeSettings); 10731 if (!ret) { 10732 return false; 10733 } 10734 // writer 10735 synchronized (mPackages) { 10736 // Reinstate the old system package 10737 mSettings.enableSystemPackageLPw(newPs.name); 10738 // Remove any native libraries from the upgraded package. 10739 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 10740 } 10741 // Install the system package 10742 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 10743 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 10744 if (locationIsPrivileged(disabledPs.codePath)) { 10745 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10746 } 10747 10748 final PackageParser.Package newPkg; 10749 try { 10750 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 10751 } catch (PackageManagerException e) { 10752 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 10753 return false; 10754 } 10755 10756 // writer 10757 synchronized (mPackages) { 10758 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 10759 updatePermissionsLPw(newPkg.packageName, newPkg, 10760 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 10761 if (applyUserRestrictions) { 10762 if (DEBUG_REMOVE) { 10763 Slog.d(TAG, "Propagating install state across reinstall"); 10764 } 10765 for (int i = 0; i < allUserHandles.length; i++) { 10766 if (DEBUG_REMOVE) { 10767 Slog.d(TAG, " user " + allUserHandles[i] 10768 + " => " + perUserInstalled[i]); 10769 } 10770 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10771 } 10772 // Regardless of writeSettings we need to ensure that this restriction 10773 // state propagation is persisted 10774 mSettings.writeAllUsersPackageRestrictionsLPr(); 10775 } 10776 // can downgrade to reader here 10777 if (writeSettings) { 10778 mSettings.writeLPr(); 10779 } 10780 } 10781 return true; 10782 } 10783 10784 private boolean deleteInstalledPackageLI(PackageSetting ps, 10785 boolean deleteCodeAndResources, int flags, 10786 int[] allUserHandles, boolean[] perUserInstalled, 10787 PackageRemovedInfo outInfo, boolean writeSettings) { 10788 if (outInfo != null) { 10789 outInfo.uid = ps.appId; 10790 } 10791 10792 // Delete package data from internal structures and also remove data if flag is set 10793 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 10794 10795 // Delete application code and resources 10796 if (deleteCodeAndResources && (outInfo != null)) { 10797 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 10798 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 10799 getAppDexInstructionSets(ps)); 10800 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 10801 } 10802 return true; 10803 } 10804 10805 @Override 10806 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 10807 int userId) { 10808 mContext.enforceCallingOrSelfPermission( 10809 android.Manifest.permission.DELETE_PACKAGES, null); 10810 synchronized (mPackages) { 10811 PackageSetting ps = mSettings.mPackages.get(packageName); 10812 if (ps == null) { 10813 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 10814 return false; 10815 } 10816 if (!ps.getInstalled(userId)) { 10817 // Can't block uninstall for an app that is not installed or enabled. 10818 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 10819 return false; 10820 } 10821 ps.setBlockUninstall(blockUninstall, userId); 10822 mSettings.writePackageRestrictionsLPr(userId); 10823 } 10824 return true; 10825 } 10826 10827 @Override 10828 public boolean getBlockUninstallForUser(String packageName, int userId) { 10829 synchronized (mPackages) { 10830 PackageSetting ps = mSettings.mPackages.get(packageName); 10831 if (ps == null) { 10832 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 10833 return false; 10834 } 10835 return ps.getBlockUninstall(userId); 10836 } 10837 } 10838 10839 /* 10840 * This method handles package deletion in general 10841 */ 10842 private boolean deletePackageLI(String packageName, UserHandle user, 10843 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 10844 int flags, PackageRemovedInfo outInfo, 10845 boolean writeSettings) { 10846 if (packageName == null) { 10847 Slog.w(TAG, "Attempt to delete null packageName."); 10848 return false; 10849 } 10850 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 10851 PackageSetting ps; 10852 boolean dataOnly = false; 10853 int removeUser = -1; 10854 int appId = -1; 10855 synchronized (mPackages) { 10856 ps = mSettings.mPackages.get(packageName); 10857 if (ps == null) { 10858 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 10859 return false; 10860 } 10861 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 10862 && user.getIdentifier() != UserHandle.USER_ALL) { 10863 // The caller is asking that the package only be deleted for a single 10864 // user. To do this, we just mark its uninstalled state and delete 10865 // its data. If this is a system app, we only allow this to happen if 10866 // they have set the special DELETE_SYSTEM_APP which requests different 10867 // semantics than normal for uninstalling system apps. 10868 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 10869 ps.setUserState(user.getIdentifier(), 10870 COMPONENT_ENABLED_STATE_DEFAULT, 10871 false, //installed 10872 true, //stopped 10873 true, //notLaunched 10874 false, //hidden 10875 null, null, null, 10876 false // blockUninstall 10877 ); 10878 if (!isSystemApp(ps)) { 10879 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 10880 // Other user still have this package installed, so all 10881 // we need to do is clear this user's data and save that 10882 // it is uninstalled. 10883 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 10884 removeUser = user.getIdentifier(); 10885 appId = ps.appId; 10886 mSettings.writePackageRestrictionsLPr(removeUser); 10887 } else { 10888 // We need to set it back to 'installed' so the uninstall 10889 // broadcasts will be sent correctly. 10890 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 10891 ps.setInstalled(true, user.getIdentifier()); 10892 } 10893 } else { 10894 // This is a system app, so we assume that the 10895 // other users still have this package installed, so all 10896 // we need to do is clear this user's data and save that 10897 // it is uninstalled. 10898 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 10899 removeUser = user.getIdentifier(); 10900 appId = ps.appId; 10901 mSettings.writePackageRestrictionsLPr(removeUser); 10902 } 10903 } 10904 } 10905 10906 if (removeUser >= 0) { 10907 // From above, we determined that we are deleting this only 10908 // for a single user. Continue the work here. 10909 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 10910 if (outInfo != null) { 10911 outInfo.removedPackage = packageName; 10912 outInfo.removedAppId = appId; 10913 outInfo.removedUsers = new int[] {removeUser}; 10914 } 10915 mInstaller.clearUserData(packageName, removeUser); 10916 removeKeystoreDataIfNeeded(removeUser, appId); 10917 schedulePackageCleaning(packageName, removeUser, false); 10918 return true; 10919 } 10920 10921 if (dataOnly) { 10922 // Delete application data first 10923 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 10924 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 10925 return true; 10926 } 10927 10928 boolean ret = false; 10929 if (isSystemApp(ps)) { 10930 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 10931 // When an updated system application is deleted we delete the existing resources as well and 10932 // fall back to existing code in system partition 10933 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 10934 flags, outInfo, writeSettings); 10935 } else { 10936 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 10937 // Kill application pre-emptively especially for apps on sd. 10938 killApplication(packageName, ps.appId, "uninstall pkg"); 10939 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 10940 allUserHandles, perUserInstalled, 10941 outInfo, writeSettings); 10942 } 10943 10944 return ret; 10945 } 10946 10947 private final class ClearStorageConnection implements ServiceConnection { 10948 IMediaContainerService mContainerService; 10949 10950 @Override 10951 public void onServiceConnected(ComponentName name, IBinder service) { 10952 synchronized (this) { 10953 mContainerService = IMediaContainerService.Stub.asInterface(service); 10954 notifyAll(); 10955 } 10956 } 10957 10958 @Override 10959 public void onServiceDisconnected(ComponentName name) { 10960 } 10961 } 10962 10963 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 10964 final boolean mounted; 10965 if (Environment.isExternalStorageEmulated()) { 10966 mounted = true; 10967 } else { 10968 final String status = Environment.getExternalStorageState(); 10969 10970 mounted = status.equals(Environment.MEDIA_MOUNTED) 10971 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 10972 } 10973 10974 if (!mounted) { 10975 return; 10976 } 10977 10978 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 10979 int[] users; 10980 if (userId == UserHandle.USER_ALL) { 10981 users = sUserManager.getUserIds(); 10982 } else { 10983 users = new int[] { userId }; 10984 } 10985 final ClearStorageConnection conn = new ClearStorageConnection(); 10986 if (mContext.bindServiceAsUser( 10987 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 10988 try { 10989 for (int curUser : users) { 10990 long timeout = SystemClock.uptimeMillis() + 5000; 10991 synchronized (conn) { 10992 long now = SystemClock.uptimeMillis(); 10993 while (conn.mContainerService == null && now < timeout) { 10994 try { 10995 conn.wait(timeout - now); 10996 } catch (InterruptedException e) { 10997 } 10998 } 10999 } 11000 if (conn.mContainerService == null) { 11001 return; 11002 } 11003 11004 final UserEnvironment userEnv = new UserEnvironment(curUser); 11005 clearDirectory(conn.mContainerService, 11006 userEnv.buildExternalStorageAppCacheDirs(packageName)); 11007 if (allData) { 11008 clearDirectory(conn.mContainerService, 11009 userEnv.buildExternalStorageAppDataDirs(packageName)); 11010 clearDirectory(conn.mContainerService, 11011 userEnv.buildExternalStorageAppMediaDirs(packageName)); 11012 } 11013 } 11014 } finally { 11015 mContext.unbindService(conn); 11016 } 11017 } 11018 } 11019 11020 @Override 11021 public void clearApplicationUserData(final String packageName, 11022 final IPackageDataObserver observer, final int userId) { 11023 mContext.enforceCallingOrSelfPermission( 11024 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 11025 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data"); 11026 // Queue up an async operation since the package deletion may take a little while. 11027 mHandler.post(new Runnable() { 11028 public void run() { 11029 mHandler.removeCallbacks(this); 11030 final boolean succeeded; 11031 synchronized (mInstallLock) { 11032 succeeded = clearApplicationUserDataLI(packageName, userId); 11033 } 11034 clearExternalStorageDataSync(packageName, userId, true); 11035 if (succeeded) { 11036 // invoke DeviceStorageMonitor's update method to clear any notifications 11037 DeviceStorageMonitorInternal 11038 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 11039 if (dsm != null) { 11040 dsm.checkMemory(); 11041 } 11042 } 11043 if(observer != null) { 11044 try { 11045 observer.onRemoveCompleted(packageName, succeeded); 11046 } catch (RemoteException e) { 11047 Log.i(TAG, "Observer no longer exists."); 11048 } 11049 } //end if observer 11050 } //end run 11051 }); 11052 } 11053 11054 private boolean clearApplicationUserDataLI(String packageName, int userId) { 11055 if (packageName == null) { 11056 Slog.w(TAG, "Attempt to delete null packageName."); 11057 return false; 11058 } 11059 PackageParser.Package pkg; 11060 boolean dataOnly = false; 11061 final int appId; 11062 synchronized (mPackages) { 11063 pkg = mPackages.get(packageName); 11064 if (pkg == null) { 11065 dataOnly = true; 11066 PackageSetting ps = mSettings.mPackages.get(packageName); 11067 if ((ps == null) || (ps.pkg == null)) { 11068 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11069 return false; 11070 } 11071 pkg = ps.pkg; 11072 } 11073 if (!dataOnly) { 11074 // need to check this only for fully installed applications 11075 if (pkg == null) { 11076 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11077 return false; 11078 } 11079 final ApplicationInfo applicationInfo = pkg.applicationInfo; 11080 if (applicationInfo == null) { 11081 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11082 return false; 11083 } 11084 } 11085 if (pkg != null && pkg.applicationInfo != null) { 11086 appId = pkg.applicationInfo.uid; 11087 } else { 11088 appId = -1; 11089 } 11090 } 11091 int retCode = mInstaller.clearUserData(packageName, userId); 11092 if (retCode < 0) { 11093 Slog.w(TAG, "Couldn't remove cache files for package: " 11094 + packageName); 11095 return false; 11096 } 11097 removeKeystoreDataIfNeeded(userId, appId); 11098 11099 // Create a native library symlink only if we have native libraries 11100 // and if the native libraries are 32 bit libraries. We do not provide 11101 // this symlink for 64 bit libraries. 11102 if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null && 11103 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 11104 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 11105 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 11106 Slog.w(TAG, "Failed linking native library dir"); 11107 return false; 11108 } 11109 } 11110 11111 return true; 11112 } 11113 11114 /** 11115 * Remove entries from the keystore daemon. Will only remove it if the 11116 * {@code appId} is valid. 11117 */ 11118 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 11119 if (appId < 0) { 11120 return; 11121 } 11122 11123 final KeyStore keyStore = KeyStore.getInstance(); 11124 if (keyStore != null) { 11125 if (userId == UserHandle.USER_ALL) { 11126 for (final int individual : sUserManager.getUserIds()) { 11127 keyStore.clearUid(UserHandle.getUid(individual, appId)); 11128 } 11129 } else { 11130 keyStore.clearUid(UserHandle.getUid(userId, appId)); 11131 } 11132 } else { 11133 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 11134 } 11135 } 11136 11137 @Override 11138 public void deleteApplicationCacheFiles(final String packageName, 11139 final IPackageDataObserver observer) { 11140 mContext.enforceCallingOrSelfPermission( 11141 android.Manifest.permission.DELETE_CACHE_FILES, null); 11142 // Queue up an async operation since the package deletion may take a little while. 11143 final int userId = UserHandle.getCallingUserId(); 11144 mHandler.post(new Runnable() { 11145 public void run() { 11146 mHandler.removeCallbacks(this); 11147 final boolean succeded; 11148 synchronized (mInstallLock) { 11149 succeded = deleteApplicationCacheFilesLI(packageName, userId); 11150 } 11151 clearExternalStorageDataSync(packageName, userId, false); 11152 if(observer != null) { 11153 try { 11154 observer.onRemoveCompleted(packageName, succeded); 11155 } catch (RemoteException e) { 11156 Log.i(TAG, "Observer no longer exists."); 11157 } 11158 } //end if observer 11159 } //end run 11160 }); 11161 } 11162 11163 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 11164 if (packageName == null) { 11165 Slog.w(TAG, "Attempt to delete null packageName."); 11166 return false; 11167 } 11168 PackageParser.Package p; 11169 synchronized (mPackages) { 11170 p = mPackages.get(packageName); 11171 } 11172 if (p == null) { 11173 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11174 return false; 11175 } 11176 final ApplicationInfo applicationInfo = p.applicationInfo; 11177 if (applicationInfo == null) { 11178 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11179 return false; 11180 } 11181 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 11182 if (retCode < 0) { 11183 Slog.w(TAG, "Couldn't remove cache files for package: " 11184 + packageName + " u" + userId); 11185 return false; 11186 } 11187 return true; 11188 } 11189 11190 @Override 11191 public void getPackageSizeInfo(final String packageName, int userHandle, 11192 final IPackageStatsObserver observer) { 11193 mContext.enforceCallingOrSelfPermission( 11194 android.Manifest.permission.GET_PACKAGE_SIZE, null); 11195 if (packageName == null) { 11196 throw new IllegalArgumentException("Attempt to get size of null packageName"); 11197 } 11198 11199 PackageStats stats = new PackageStats(packageName, userHandle); 11200 11201 /* 11202 * Queue up an async operation since the package measurement may take a 11203 * little while. 11204 */ 11205 Message msg = mHandler.obtainMessage(INIT_COPY); 11206 msg.obj = new MeasureParams(stats, observer); 11207 mHandler.sendMessage(msg); 11208 } 11209 11210 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 11211 PackageStats pStats) { 11212 if (packageName == null) { 11213 Slog.w(TAG, "Attempt to get size of null packageName."); 11214 return false; 11215 } 11216 PackageParser.Package p; 11217 boolean dataOnly = false; 11218 String libDirRoot = null; 11219 String asecPath = null; 11220 PackageSetting ps = null; 11221 synchronized (mPackages) { 11222 p = mPackages.get(packageName); 11223 ps = mSettings.mPackages.get(packageName); 11224 if(p == null) { 11225 dataOnly = true; 11226 if((ps == null) || (ps.pkg == null)) { 11227 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11228 return false; 11229 } 11230 p = ps.pkg; 11231 } 11232 if (ps != null) { 11233 libDirRoot = ps.legacyNativeLibraryPathString; 11234 } 11235 if (p != null && (isExternal(p) || isForwardLocked(p))) { 11236 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 11237 if (secureContainerId != null) { 11238 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 11239 } 11240 } 11241 } 11242 String publicSrcDir = null; 11243 if(!dataOnly) { 11244 final ApplicationInfo applicationInfo = p.applicationInfo; 11245 if (applicationInfo == null) { 11246 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11247 return false; 11248 } 11249 if (isForwardLocked(p)) { 11250 publicSrcDir = applicationInfo.getBaseResourcePath(); 11251 } 11252 } 11253 // TODO: extend to measure size of split APKs 11254 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 11255 // not just the first level. 11256 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 11257 // just the primary. 11258 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 11259 int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot, 11260 publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 11261 if (res < 0) { 11262 return false; 11263 } 11264 11265 // Fix-up for forward-locked applications in ASEC containers. 11266 if (!isExternal(p)) { 11267 pStats.codeSize += pStats.externalCodeSize; 11268 pStats.externalCodeSize = 0L; 11269 } 11270 11271 return true; 11272 } 11273 11274 11275 @Override 11276 public void addPackageToPreferred(String packageName) { 11277 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 11278 } 11279 11280 @Override 11281 public void removePackageFromPreferred(String packageName) { 11282 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 11283 } 11284 11285 @Override 11286 public List<PackageInfo> getPreferredPackages(int flags) { 11287 return new ArrayList<PackageInfo>(); 11288 } 11289 11290 private int getUidTargetSdkVersionLockedLPr(int uid) { 11291 Object obj = mSettings.getUserIdLPr(uid); 11292 if (obj instanceof SharedUserSetting) { 11293 final SharedUserSetting sus = (SharedUserSetting) obj; 11294 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 11295 final Iterator<PackageSetting> it = sus.packages.iterator(); 11296 while (it.hasNext()) { 11297 final PackageSetting ps = it.next(); 11298 if (ps.pkg != null) { 11299 int v = ps.pkg.applicationInfo.targetSdkVersion; 11300 if (v < vers) vers = v; 11301 } 11302 } 11303 return vers; 11304 } else if (obj instanceof PackageSetting) { 11305 final PackageSetting ps = (PackageSetting) obj; 11306 if (ps.pkg != null) { 11307 return ps.pkg.applicationInfo.targetSdkVersion; 11308 } 11309 } 11310 return Build.VERSION_CODES.CUR_DEVELOPMENT; 11311 } 11312 11313 @Override 11314 public void addPreferredActivity(IntentFilter filter, int match, 11315 ComponentName[] set, ComponentName activity, int userId) { 11316 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11317 "Adding preferred"); 11318 } 11319 11320 private void addPreferredActivityInternal(IntentFilter filter, int match, 11321 ComponentName[] set, ComponentName activity, boolean always, int userId, 11322 String opname) { 11323 // writer 11324 int callingUid = Binder.getCallingUid(); 11325 enforceCrossUserPermission(callingUid, userId, true, "add preferred activity"); 11326 if (filter.countActions() == 0) { 11327 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11328 return; 11329 } 11330 synchronized (mPackages) { 11331 if (mContext.checkCallingOrSelfPermission( 11332 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11333 != PackageManager.PERMISSION_GRANTED) { 11334 if (getUidTargetSdkVersionLockedLPr(callingUid) 11335 < Build.VERSION_CODES.FROYO) { 11336 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 11337 + callingUid); 11338 return; 11339 } 11340 mContext.enforceCallingOrSelfPermission( 11341 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11342 } 11343 11344 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 11345 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 11346 + userId + ":"); 11347 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11348 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 11349 mSettings.writePackageRestrictionsLPr(userId); 11350 } 11351 } 11352 11353 @Override 11354 public void replacePreferredActivity(IntentFilter filter, int match, 11355 ComponentName[] set, ComponentName activity, int userId) { 11356 if (filter.countActions() != 1) { 11357 throw new IllegalArgumentException( 11358 "replacePreferredActivity expects filter to have only 1 action."); 11359 } 11360 if (filter.countDataAuthorities() != 0 11361 || filter.countDataPaths() != 0 11362 || filter.countDataSchemes() > 1 11363 || filter.countDataTypes() != 0) { 11364 throw new IllegalArgumentException( 11365 "replacePreferredActivity expects filter to have no data authorities, " + 11366 "paths, or types; and at most one scheme."); 11367 } 11368 11369 final int callingUid = Binder.getCallingUid(); 11370 enforceCrossUserPermission(callingUid, userId, true, "replace preferred activity"); 11371 synchronized (mPackages) { 11372 if (mContext.checkCallingOrSelfPermission( 11373 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11374 != PackageManager.PERMISSION_GRANTED) { 11375 if (getUidTargetSdkVersionLockedLPr(callingUid) 11376 < Build.VERSION_CODES.FROYO) { 11377 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 11378 + Binder.getCallingUid()); 11379 return; 11380 } 11381 mContext.enforceCallingOrSelfPermission( 11382 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11383 } 11384 11385 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11386 if (pir != null) { 11387 // Get all of the existing entries that exactly match this filter. 11388 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 11389 if (existing != null && existing.size() == 1) { 11390 PreferredActivity cur = existing.get(0); 11391 if (DEBUG_PREFERRED) { 11392 Slog.i(TAG, "Checking replace of preferred:"); 11393 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11394 if (!cur.mPref.mAlways) { 11395 Slog.i(TAG, " -- CUR; not mAlways!"); 11396 } else { 11397 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 11398 Slog.i(TAG, " -- CUR: mSet=" 11399 + Arrays.toString(cur.mPref.mSetComponents)); 11400 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 11401 Slog.i(TAG, " -- NEW: mMatch=" 11402 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 11403 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 11404 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 11405 } 11406 } 11407 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 11408 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 11409 && cur.mPref.sameSet(set)) { 11410 if (DEBUG_PREFERRED) { 11411 Slog.i(TAG, "Replacing with same preferred activity " 11412 + cur.mPref.mShortComponent + " for user " 11413 + userId + ":"); 11414 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11415 } else { 11416 Slog.i(TAG, "Replacing with same preferred activity " 11417 + cur.mPref.mShortComponent + " for user " 11418 + userId); 11419 } 11420 return; 11421 } 11422 } 11423 11424 if (existing != null) { 11425 if (DEBUG_PREFERRED) { 11426 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 11427 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11428 } 11429 for (int i = 0; i < existing.size(); i++) { 11430 PreferredActivity pa = existing.get(i); 11431 if (DEBUG_PREFERRED) { 11432 Slog.i(TAG, "Removing existing preferred activity " 11433 + pa.mPref.mComponent + ":"); 11434 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 11435 } 11436 pir.removeFilter(pa); 11437 } 11438 } 11439 } 11440 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11441 "Replacing preferred"); 11442 } 11443 } 11444 11445 @Override 11446 public void clearPackagePreferredActivities(String packageName) { 11447 final int uid = Binder.getCallingUid(); 11448 // writer 11449 synchronized (mPackages) { 11450 PackageParser.Package pkg = mPackages.get(packageName); 11451 if (pkg == null || pkg.applicationInfo.uid != uid) { 11452 if (mContext.checkCallingOrSelfPermission( 11453 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11454 != PackageManager.PERMISSION_GRANTED) { 11455 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11456 < Build.VERSION_CODES.FROYO) { 11457 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 11458 + Binder.getCallingUid()); 11459 return; 11460 } 11461 mContext.enforceCallingOrSelfPermission( 11462 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11463 } 11464 } 11465 11466 int user = UserHandle.getCallingUserId(); 11467 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 11468 mSettings.writePackageRestrictionsLPr(user); 11469 scheduleWriteSettingsLocked(); 11470 } 11471 } 11472 } 11473 11474 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 11475 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 11476 ArrayList<PreferredActivity> removed = null; 11477 boolean changed = false; 11478 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11479 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 11480 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11481 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 11482 continue; 11483 } 11484 Iterator<PreferredActivity> it = pir.filterIterator(); 11485 while (it.hasNext()) { 11486 PreferredActivity pa = it.next(); 11487 // Mark entry for removal only if it matches the package name 11488 // and the entry is of type "always". 11489 if (packageName == null || 11490 (pa.mPref.mComponent.getPackageName().equals(packageName) 11491 && pa.mPref.mAlways)) { 11492 if (removed == null) { 11493 removed = new ArrayList<PreferredActivity>(); 11494 } 11495 removed.add(pa); 11496 } 11497 } 11498 if (removed != null) { 11499 for (int j=0; j<removed.size(); j++) { 11500 PreferredActivity pa = removed.get(j); 11501 pir.removeFilter(pa); 11502 } 11503 changed = true; 11504 } 11505 } 11506 return changed; 11507 } 11508 11509 @Override 11510 public void resetPreferredActivities(int userId) { 11511 mContext.enforceCallingOrSelfPermission( 11512 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11513 // writer 11514 synchronized (mPackages) { 11515 int user = UserHandle.getCallingUserId(); 11516 clearPackagePreferredActivitiesLPw(null, user); 11517 mSettings.readDefaultPreferredAppsLPw(this, user); 11518 mSettings.writePackageRestrictionsLPr(user); 11519 scheduleWriteSettingsLocked(); 11520 } 11521 } 11522 11523 @Override 11524 public int getPreferredActivities(List<IntentFilter> outFilters, 11525 List<ComponentName> outActivities, String packageName) { 11526 11527 int num = 0; 11528 final int userId = UserHandle.getCallingUserId(); 11529 // reader 11530 synchronized (mPackages) { 11531 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11532 if (pir != null) { 11533 final Iterator<PreferredActivity> it = pir.filterIterator(); 11534 while (it.hasNext()) { 11535 final PreferredActivity pa = it.next(); 11536 if (packageName == null 11537 || (pa.mPref.mComponent.getPackageName().equals(packageName) 11538 && pa.mPref.mAlways)) { 11539 if (outFilters != null) { 11540 outFilters.add(new IntentFilter(pa)); 11541 } 11542 if (outActivities != null) { 11543 outActivities.add(pa.mPref.mComponent); 11544 } 11545 } 11546 } 11547 } 11548 } 11549 11550 return num; 11551 } 11552 11553 @Override 11554 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 11555 int userId) { 11556 int callingUid = Binder.getCallingUid(); 11557 if (callingUid != Process.SYSTEM_UID) { 11558 throw new SecurityException( 11559 "addPersistentPreferredActivity can only be run by the system"); 11560 } 11561 if (filter.countActions() == 0) { 11562 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11563 return; 11564 } 11565 synchronized (mPackages) { 11566 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 11567 " :"); 11568 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11569 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 11570 new PersistentPreferredActivity(filter, activity)); 11571 mSettings.writePackageRestrictionsLPr(userId); 11572 } 11573 } 11574 11575 @Override 11576 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 11577 int callingUid = Binder.getCallingUid(); 11578 if (callingUid != Process.SYSTEM_UID) { 11579 throw new SecurityException( 11580 "clearPackagePersistentPreferredActivities can only be run by the system"); 11581 } 11582 ArrayList<PersistentPreferredActivity> removed = null; 11583 boolean changed = false; 11584 synchronized (mPackages) { 11585 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 11586 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 11587 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 11588 .valueAt(i); 11589 if (userId != thisUserId) { 11590 continue; 11591 } 11592 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 11593 while (it.hasNext()) { 11594 PersistentPreferredActivity ppa = it.next(); 11595 // Mark entry for removal only if it matches the package name. 11596 if (ppa.mComponent.getPackageName().equals(packageName)) { 11597 if (removed == null) { 11598 removed = new ArrayList<PersistentPreferredActivity>(); 11599 } 11600 removed.add(ppa); 11601 } 11602 } 11603 if (removed != null) { 11604 for (int j=0; j<removed.size(); j++) { 11605 PersistentPreferredActivity ppa = removed.get(j); 11606 ppir.removeFilter(ppa); 11607 } 11608 changed = true; 11609 } 11610 } 11611 11612 if (changed) { 11613 mSettings.writePackageRestrictionsLPr(userId); 11614 } 11615 } 11616 } 11617 11618 @Override 11619 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 11620 int ownerUserId, int sourceUserId, int targetUserId, int flags) { 11621 mContext.enforceCallingOrSelfPermission( 11622 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11623 int callingUid = Binder.getCallingUid(); 11624 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11625 if (intentFilter.countActions() == 0) { 11626 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 11627 return; 11628 } 11629 synchronized (mPackages) { 11630 CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter, 11631 ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags); 11632 mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter); 11633 mSettings.writePackageRestrictionsLPr(sourceUserId); 11634 } 11635 } 11636 11637 @Override 11638 public void addCrossProfileIntentsForPackage(String packageName, 11639 int sourceUserId, int targetUserId) { 11640 mContext.enforceCallingOrSelfPermission( 11641 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11642 mSettings.addCrossProfilePackage(packageName, sourceUserId, targetUserId); 11643 mSettings.writePackageRestrictionsLPr(sourceUserId); 11644 } 11645 11646 @Override 11647 public void removeCrossProfileIntentsForPackage(String packageName, 11648 int sourceUserId, int targetUserId) { 11649 mContext.enforceCallingOrSelfPermission( 11650 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11651 mSettings.removeCrossProfilePackage(packageName, sourceUserId, targetUserId); 11652 mSettings.writePackageRestrictionsLPr(sourceUserId); 11653 } 11654 11655 @Override 11656 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage, 11657 int ownerUserId) { 11658 mContext.enforceCallingOrSelfPermission( 11659 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 11660 int callingUid = Binder.getCallingUid(); 11661 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 11662 int callingUserId = UserHandle.getUserId(callingUid); 11663 synchronized (mPackages) { 11664 CrossProfileIntentResolver resolver = 11665 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 11666 HashSet<CrossProfileIntentFilter> set = 11667 new HashSet<CrossProfileIntentFilter>(resolver.filterSet()); 11668 for (CrossProfileIntentFilter filter : set) { 11669 if (filter.getOwnerPackage().equals(ownerPackage) 11670 && filter.getOwnerUserId() == callingUserId) { 11671 resolver.removeFilter(filter); 11672 } 11673 } 11674 mSettings.writePackageRestrictionsLPr(sourceUserId); 11675 } 11676 } 11677 11678 // Enforcing that callingUid is owning pkg on userId 11679 private void enforceOwnerRights(String pkg, int userId, int callingUid) { 11680 // The system owns everything. 11681 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 11682 return; 11683 } 11684 int callingUserId = UserHandle.getUserId(callingUid); 11685 if (callingUserId != userId) { 11686 throw new SecurityException("calling uid " + callingUid 11687 + " pretends to own " + pkg + " on user " + userId + " but belongs to user " 11688 + callingUserId); 11689 } 11690 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 11691 if (pi == null) { 11692 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 11693 + callingUserId); 11694 } 11695 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 11696 throw new SecurityException("Calling uid " + callingUid 11697 + " does not own package " + pkg); 11698 } 11699 } 11700 11701 @Override 11702 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 11703 Intent intent = new Intent(Intent.ACTION_MAIN); 11704 intent.addCategory(Intent.CATEGORY_HOME); 11705 11706 final int callingUserId = UserHandle.getCallingUserId(); 11707 List<ResolveInfo> list = queryIntentActivities(intent, null, 11708 PackageManager.GET_META_DATA, callingUserId); 11709 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 11710 true, false, false, callingUserId); 11711 11712 allHomeCandidates.clear(); 11713 if (list != null) { 11714 for (ResolveInfo ri : list) { 11715 allHomeCandidates.add(ri); 11716 } 11717 } 11718 return (preferred == null || preferred.activityInfo == null) 11719 ? null 11720 : new ComponentName(preferred.activityInfo.packageName, 11721 preferred.activityInfo.name); 11722 } 11723 11724 /** 11725 * Check if calling UID is the current home app. This handles both the case 11726 * where the user has selected a specific home app, and where there is only 11727 * one home app. 11728 */ 11729 public boolean checkCallerIsHomeApp() { 11730 final Intent intent = new Intent(Intent.ACTION_MAIN); 11731 intent.addCategory(Intent.CATEGORY_HOME); 11732 11733 final int callingUid = Binder.getCallingUid(); 11734 final int callingUserId = UserHandle.getCallingUserId(); 11735 final List<ResolveInfo> allHomes = queryIntentActivities(intent, null, 0, callingUserId); 11736 final ResolveInfo preferredHome = findPreferredActivity(intent, null, 0, allHomes, 0, true, 11737 false, false, callingUserId); 11738 11739 if (preferredHome != null) { 11740 if (callingUid == preferredHome.activityInfo.applicationInfo.uid) { 11741 return true; 11742 } 11743 } else { 11744 for (ResolveInfo info : allHomes) { 11745 if (callingUid == info.activityInfo.applicationInfo.uid) { 11746 return true; 11747 } 11748 } 11749 } 11750 11751 return false; 11752 } 11753 11754 /** 11755 * Enforce that calling UID is the current home app. This handles both the 11756 * case where the user has selected a specific home app, and where there is 11757 * only one home app. 11758 */ 11759 public void enforceCallerIsHomeApp() { 11760 if (!checkCallerIsHomeApp()) { 11761 throw new SecurityException("Caller is not currently selected home app"); 11762 } 11763 } 11764 11765 @Override 11766 public void setApplicationEnabledSetting(String appPackageName, 11767 int newState, int flags, int userId, String callingPackage) { 11768 if (!sUserManager.exists(userId)) return; 11769 if (callingPackage == null) { 11770 callingPackage = Integer.toString(Binder.getCallingUid()); 11771 } 11772 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 11773 } 11774 11775 @Override 11776 public void setComponentEnabledSetting(ComponentName componentName, 11777 int newState, int flags, int userId) { 11778 if (!sUserManager.exists(userId)) return; 11779 setEnabledSetting(componentName.getPackageName(), 11780 componentName.getClassName(), newState, flags, userId, null); 11781 } 11782 11783 private void setEnabledSetting(final String packageName, String className, int newState, 11784 final int flags, int userId, String callingPackage) { 11785 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 11786 || newState == COMPONENT_ENABLED_STATE_ENABLED 11787 || newState == COMPONENT_ENABLED_STATE_DISABLED 11788 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 11789 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 11790 throw new IllegalArgumentException("Invalid new component state: " 11791 + newState); 11792 } 11793 PackageSetting pkgSetting; 11794 final int uid = Binder.getCallingUid(); 11795 final int permission = mContext.checkCallingOrSelfPermission( 11796 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11797 enforceCrossUserPermission(uid, userId, false, "set enabled"); 11798 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11799 boolean sendNow = false; 11800 boolean isApp = (className == null); 11801 String componentName = isApp ? packageName : className; 11802 int packageUid = -1; 11803 ArrayList<String> components; 11804 11805 // writer 11806 synchronized (mPackages) { 11807 pkgSetting = mSettings.mPackages.get(packageName); 11808 if (pkgSetting == null) { 11809 if (className == null) { 11810 throw new IllegalArgumentException( 11811 "Unknown package: " + packageName); 11812 } 11813 throw new IllegalArgumentException( 11814 "Unknown component: " + packageName 11815 + "/" + className); 11816 } 11817 // Allow root and verify that userId is not being specified by a different user 11818 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 11819 throw new SecurityException( 11820 "Permission Denial: attempt to change component state from pid=" 11821 + Binder.getCallingPid() 11822 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 11823 } 11824 if (className == null) { 11825 // We're dealing with an application/package level state change 11826 if (pkgSetting.getEnabled(userId) == newState) { 11827 // Nothing to do 11828 return; 11829 } 11830 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 11831 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 11832 // Don't care about who enables an app. 11833 callingPackage = null; 11834 } 11835 pkgSetting.setEnabled(newState, userId, callingPackage); 11836 // pkgSetting.pkg.mSetEnabled = newState; 11837 } else { 11838 // We're dealing with a component level state change 11839 // First, verify that this is a valid class name. 11840 PackageParser.Package pkg = pkgSetting.pkg; 11841 if (pkg == null || !pkg.hasComponentClassName(className)) { 11842 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 11843 throw new IllegalArgumentException("Component class " + className 11844 + " does not exist in " + packageName); 11845 } else { 11846 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 11847 + className + " does not exist in " + packageName); 11848 } 11849 } 11850 switch (newState) { 11851 case COMPONENT_ENABLED_STATE_ENABLED: 11852 if (!pkgSetting.enableComponentLPw(className, userId)) { 11853 return; 11854 } 11855 break; 11856 case COMPONENT_ENABLED_STATE_DISABLED: 11857 if (!pkgSetting.disableComponentLPw(className, userId)) { 11858 return; 11859 } 11860 break; 11861 case COMPONENT_ENABLED_STATE_DEFAULT: 11862 if (!pkgSetting.restoreComponentLPw(className, userId)) { 11863 return; 11864 } 11865 break; 11866 default: 11867 Slog.e(TAG, "Invalid new component state: " + newState); 11868 return; 11869 } 11870 } 11871 mSettings.writePackageRestrictionsLPr(userId); 11872 components = mPendingBroadcasts.get(userId, packageName); 11873 final boolean newPackage = components == null; 11874 if (newPackage) { 11875 components = new ArrayList<String>(); 11876 } 11877 if (!components.contains(componentName)) { 11878 components.add(componentName); 11879 } 11880 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 11881 sendNow = true; 11882 // Purge entry from pending broadcast list if another one exists already 11883 // since we are sending one right away. 11884 mPendingBroadcasts.remove(userId, packageName); 11885 } else { 11886 if (newPackage) { 11887 mPendingBroadcasts.put(userId, packageName, components); 11888 } 11889 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 11890 // Schedule a message 11891 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 11892 } 11893 } 11894 } 11895 11896 long callingId = Binder.clearCallingIdentity(); 11897 try { 11898 if (sendNow) { 11899 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 11900 sendPackageChangedBroadcast(packageName, 11901 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 11902 } 11903 } finally { 11904 Binder.restoreCallingIdentity(callingId); 11905 } 11906 } 11907 11908 private void sendPackageChangedBroadcast(String packageName, 11909 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 11910 if (DEBUG_INSTALL) 11911 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 11912 + componentNames); 11913 Bundle extras = new Bundle(4); 11914 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 11915 String nameList[] = new String[componentNames.size()]; 11916 componentNames.toArray(nameList); 11917 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 11918 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 11919 extras.putInt(Intent.EXTRA_UID, packageUid); 11920 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 11921 new int[] {UserHandle.getUserId(packageUid)}); 11922 } 11923 11924 @Override 11925 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 11926 if (!sUserManager.exists(userId)) return; 11927 final int uid = Binder.getCallingUid(); 11928 final int permission = mContext.checkCallingOrSelfPermission( 11929 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11930 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11931 enforceCrossUserPermission(uid, userId, true, "stop package"); 11932 // writer 11933 synchronized (mPackages) { 11934 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 11935 uid, userId)) { 11936 scheduleWritePackageRestrictionsLocked(userId); 11937 } 11938 } 11939 } 11940 11941 @Override 11942 public String getInstallerPackageName(String packageName) { 11943 // reader 11944 synchronized (mPackages) { 11945 return mSettings.getInstallerPackageNameLPr(packageName); 11946 } 11947 } 11948 11949 @Override 11950 public int getApplicationEnabledSetting(String packageName, int userId) { 11951 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11952 int uid = Binder.getCallingUid(); 11953 enforceCrossUserPermission(uid, userId, false, "get enabled"); 11954 // reader 11955 synchronized (mPackages) { 11956 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 11957 } 11958 } 11959 11960 @Override 11961 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 11962 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11963 int uid = Binder.getCallingUid(); 11964 enforceCrossUserPermission(uid, userId, false, "get component enabled"); 11965 // reader 11966 synchronized (mPackages) { 11967 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 11968 } 11969 } 11970 11971 @Override 11972 public void enterSafeMode() { 11973 enforceSystemOrRoot("Only the system can request entering safe mode"); 11974 11975 if (!mSystemReady) { 11976 mSafeMode = true; 11977 } 11978 } 11979 11980 @Override 11981 public void systemReady() { 11982 mSystemReady = true; 11983 11984 // Read the compatibilty setting when the system is ready. 11985 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 11986 mContext.getContentResolver(), 11987 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 11988 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 11989 if (DEBUG_SETTINGS) { 11990 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 11991 } 11992 11993 synchronized (mPackages) { 11994 // Verify that all of the preferred activity components actually 11995 // exist. It is possible for applications to be updated and at 11996 // that point remove a previously declared activity component that 11997 // had been set as a preferred activity. We try to clean this up 11998 // the next time we encounter that preferred activity, but it is 11999 // possible for the user flow to never be able to return to that 12000 // situation so here we do a sanity check to make sure we haven't 12001 // left any junk around. 12002 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 12003 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12004 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12005 removed.clear(); 12006 for (PreferredActivity pa : pir.filterSet()) { 12007 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 12008 removed.add(pa); 12009 } 12010 } 12011 if (removed.size() > 0) { 12012 for (int r=0; r<removed.size(); r++) { 12013 PreferredActivity pa = removed.get(r); 12014 Slog.w(TAG, "Removing dangling preferred activity: " 12015 + pa.mPref.mComponent); 12016 pir.removeFilter(pa); 12017 } 12018 mSettings.writePackageRestrictionsLPr( 12019 mSettings.mPreferredActivities.keyAt(i)); 12020 } 12021 } 12022 } 12023 sUserManager.systemReady(); 12024 } 12025 12026 @Override 12027 public boolean isSafeMode() { 12028 return mSafeMode; 12029 } 12030 12031 @Override 12032 public boolean hasSystemUidErrors() { 12033 return mHasSystemUidErrors; 12034 } 12035 12036 static String arrayToString(int[] array) { 12037 StringBuffer buf = new StringBuffer(128); 12038 buf.append('['); 12039 if (array != null) { 12040 for (int i=0; i<array.length; i++) { 12041 if (i > 0) buf.append(", "); 12042 buf.append(array[i]); 12043 } 12044 } 12045 buf.append(']'); 12046 return buf.toString(); 12047 } 12048 12049 static class DumpState { 12050 public static final int DUMP_LIBS = 1 << 0; 12051 public static final int DUMP_FEATURES = 1 << 1; 12052 public static final int DUMP_RESOLVERS = 1 << 2; 12053 public static final int DUMP_PERMISSIONS = 1 << 3; 12054 public static final int DUMP_PACKAGES = 1 << 4; 12055 public static final int DUMP_SHARED_USERS = 1 << 5; 12056 public static final int DUMP_MESSAGES = 1 << 6; 12057 public static final int DUMP_PROVIDERS = 1 << 7; 12058 public static final int DUMP_VERIFIERS = 1 << 8; 12059 public static final int DUMP_PREFERRED = 1 << 9; 12060 public static final int DUMP_PREFERRED_XML = 1 << 10; 12061 public static final int DUMP_KEYSETS = 1 << 11; 12062 public static final int DUMP_VERSION = 1 << 12; 12063 public static final int DUMP_INSTALLS = 1 << 13; 12064 12065 public static final int OPTION_SHOW_FILTERS = 1 << 0; 12066 12067 private int mTypes; 12068 12069 private int mOptions; 12070 12071 private boolean mTitlePrinted; 12072 12073 private SharedUserSetting mSharedUser; 12074 12075 public boolean isDumping(int type) { 12076 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 12077 return true; 12078 } 12079 12080 return (mTypes & type) != 0; 12081 } 12082 12083 public void setDump(int type) { 12084 mTypes |= type; 12085 } 12086 12087 public boolean isOptionEnabled(int option) { 12088 return (mOptions & option) != 0; 12089 } 12090 12091 public void setOptionEnabled(int option) { 12092 mOptions |= option; 12093 } 12094 12095 public boolean onTitlePrinted() { 12096 final boolean printed = mTitlePrinted; 12097 mTitlePrinted = true; 12098 return printed; 12099 } 12100 12101 public boolean getTitlePrinted() { 12102 return mTitlePrinted; 12103 } 12104 12105 public void setTitlePrinted(boolean enabled) { 12106 mTitlePrinted = enabled; 12107 } 12108 12109 public SharedUserSetting getSharedUser() { 12110 return mSharedUser; 12111 } 12112 12113 public void setSharedUser(SharedUserSetting user) { 12114 mSharedUser = user; 12115 } 12116 } 12117 12118 @Override 12119 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 12120 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 12121 != PackageManager.PERMISSION_GRANTED) { 12122 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 12123 + Binder.getCallingPid() 12124 + ", uid=" + Binder.getCallingUid() 12125 + " without permission " 12126 + android.Manifest.permission.DUMP); 12127 return; 12128 } 12129 12130 DumpState dumpState = new DumpState(); 12131 boolean fullPreferred = false; 12132 boolean checkin = false; 12133 12134 String packageName = null; 12135 12136 int opti = 0; 12137 while (opti < args.length) { 12138 String opt = args[opti]; 12139 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 12140 break; 12141 } 12142 opti++; 12143 if ("-a".equals(opt)) { 12144 // Right now we only know how to print all. 12145 } else if ("-h".equals(opt)) { 12146 pw.println("Package manager dump options:"); 12147 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 12148 pw.println(" --checkin: dump for a checkin"); 12149 pw.println(" -f: print details of intent filters"); 12150 pw.println(" -h: print this help"); 12151 pw.println(" cmd may be one of:"); 12152 pw.println(" l[ibraries]: list known shared libraries"); 12153 pw.println(" f[ibraries]: list device features"); 12154 pw.println(" k[eysets]: print known keysets"); 12155 pw.println(" r[esolvers]: dump intent resolvers"); 12156 pw.println(" perm[issions]: dump permissions"); 12157 pw.println(" pref[erred]: print preferred package settings"); 12158 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 12159 pw.println(" prov[iders]: dump content providers"); 12160 pw.println(" p[ackages]: dump installed packages"); 12161 pw.println(" s[hared-users]: dump shared user IDs"); 12162 pw.println(" m[essages]: print collected runtime messages"); 12163 pw.println(" v[erifiers]: print package verifier info"); 12164 pw.println(" version: print database version info"); 12165 pw.println(" write: write current settings now"); 12166 pw.println(" <package.name>: info about given package"); 12167 pw.println(" installs: details about install sessions"); 12168 return; 12169 } else if ("--checkin".equals(opt)) { 12170 checkin = true; 12171 } else if ("-f".equals(opt)) { 12172 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12173 } else { 12174 pw.println("Unknown argument: " + opt + "; use -h for help"); 12175 } 12176 } 12177 12178 // Is the caller requesting to dump a particular piece of data? 12179 if (opti < args.length) { 12180 String cmd = args[opti]; 12181 opti++; 12182 // Is this a package name? 12183 if ("android".equals(cmd) || cmd.contains(".")) { 12184 packageName = cmd; 12185 // When dumping a single package, we always dump all of its 12186 // filter information since the amount of data will be reasonable. 12187 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12188 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 12189 dumpState.setDump(DumpState.DUMP_LIBS); 12190 } else if ("f".equals(cmd) || "features".equals(cmd)) { 12191 dumpState.setDump(DumpState.DUMP_FEATURES); 12192 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 12193 dumpState.setDump(DumpState.DUMP_RESOLVERS); 12194 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 12195 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 12196 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 12197 dumpState.setDump(DumpState.DUMP_PREFERRED); 12198 } else if ("preferred-xml".equals(cmd)) { 12199 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 12200 if (opti < args.length && "--full".equals(args[opti])) { 12201 fullPreferred = true; 12202 opti++; 12203 } 12204 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 12205 dumpState.setDump(DumpState.DUMP_PACKAGES); 12206 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 12207 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 12208 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 12209 dumpState.setDump(DumpState.DUMP_PROVIDERS); 12210 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 12211 dumpState.setDump(DumpState.DUMP_MESSAGES); 12212 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 12213 dumpState.setDump(DumpState.DUMP_VERIFIERS); 12214 } else if ("version".equals(cmd)) { 12215 dumpState.setDump(DumpState.DUMP_VERSION); 12216 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 12217 dumpState.setDump(DumpState.DUMP_KEYSETS); 12218 } else if ("write".equals(cmd)) { 12219 synchronized (mPackages) { 12220 mSettings.writeLPr(); 12221 pw.println("Settings written."); 12222 return; 12223 } 12224 } else if ("installs".equals(cmd)) { 12225 dumpState.setDump(DumpState.DUMP_INSTALLS); 12226 } 12227 } 12228 12229 if (checkin) { 12230 pw.println("vers,1"); 12231 } 12232 12233 // reader 12234 synchronized (mPackages) { 12235 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 12236 if (!checkin) { 12237 if (dumpState.onTitlePrinted()) 12238 pw.println(); 12239 pw.println("Database versions:"); 12240 pw.print(" SDK Version:"); 12241 pw.print(" internal="); 12242 pw.print(mSettings.mInternalSdkPlatform); 12243 pw.print(" external="); 12244 pw.println(mSettings.mExternalSdkPlatform); 12245 pw.print(" DB Version:"); 12246 pw.print(" internal="); 12247 pw.print(mSettings.mInternalDatabaseVersion); 12248 pw.print(" external="); 12249 pw.println(mSettings.mExternalDatabaseVersion); 12250 } 12251 } 12252 12253 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 12254 if (!checkin) { 12255 if (dumpState.onTitlePrinted()) 12256 pw.println(); 12257 pw.println("Verifiers:"); 12258 pw.print(" Required: "); 12259 pw.print(mRequiredVerifierPackage); 12260 pw.print(" (uid="); 12261 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 12262 pw.println(")"); 12263 } else if (mRequiredVerifierPackage != null) { 12264 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 12265 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 12266 } 12267 } 12268 12269 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 12270 boolean printedHeader = false; 12271 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 12272 while (it.hasNext()) { 12273 String name = it.next(); 12274 SharedLibraryEntry ent = mSharedLibraries.get(name); 12275 if (!checkin) { 12276 if (!printedHeader) { 12277 if (dumpState.onTitlePrinted()) 12278 pw.println(); 12279 pw.println("Libraries:"); 12280 printedHeader = true; 12281 } 12282 pw.print(" "); 12283 } else { 12284 pw.print("lib,"); 12285 } 12286 pw.print(name); 12287 if (!checkin) { 12288 pw.print(" -> "); 12289 } 12290 if (ent.path != null) { 12291 if (!checkin) { 12292 pw.print("(jar) "); 12293 pw.print(ent.path); 12294 } else { 12295 pw.print(",jar,"); 12296 pw.print(ent.path); 12297 } 12298 } else { 12299 if (!checkin) { 12300 pw.print("(apk) "); 12301 pw.print(ent.apk); 12302 } else { 12303 pw.print(",apk,"); 12304 pw.print(ent.apk); 12305 } 12306 } 12307 pw.println(); 12308 } 12309 } 12310 12311 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 12312 if (dumpState.onTitlePrinted()) 12313 pw.println(); 12314 if (!checkin) { 12315 pw.println("Features:"); 12316 } 12317 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 12318 while (it.hasNext()) { 12319 String name = it.next(); 12320 if (!checkin) { 12321 pw.print(" "); 12322 } else { 12323 pw.print("feat,"); 12324 } 12325 pw.println(name); 12326 } 12327 } 12328 12329 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 12330 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 12331 : "Activity Resolver Table:", " ", packageName, 12332 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12333 dumpState.setTitlePrinted(true); 12334 } 12335 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 12336 : "Receiver Resolver Table:", " ", packageName, 12337 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12338 dumpState.setTitlePrinted(true); 12339 } 12340 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 12341 : "Service Resolver Table:", " ", packageName, 12342 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12343 dumpState.setTitlePrinted(true); 12344 } 12345 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 12346 : "Provider Resolver Table:", " ", packageName, 12347 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 12348 dumpState.setTitlePrinted(true); 12349 } 12350 } 12351 12352 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 12353 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12354 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12355 int user = mSettings.mPreferredActivities.keyAt(i); 12356 if (pir.dump(pw, 12357 dumpState.getTitlePrinted() 12358 ? "\nPreferred Activities User " + user + ":" 12359 : "Preferred Activities User " + user + ":", " ", 12360 packageName, true)) { 12361 dumpState.setTitlePrinted(true); 12362 } 12363 } 12364 } 12365 12366 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 12367 pw.flush(); 12368 FileOutputStream fout = new FileOutputStream(fd); 12369 BufferedOutputStream str = new BufferedOutputStream(fout); 12370 XmlSerializer serializer = new FastXmlSerializer(); 12371 try { 12372 serializer.setOutput(str, "utf-8"); 12373 serializer.startDocument(null, true); 12374 serializer.setFeature( 12375 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 12376 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 12377 serializer.endDocument(); 12378 serializer.flush(); 12379 } catch (IllegalArgumentException e) { 12380 pw.println("Failed writing: " + e); 12381 } catch (IllegalStateException e) { 12382 pw.println("Failed writing: " + e); 12383 } catch (IOException e) { 12384 pw.println("Failed writing: " + e); 12385 } 12386 } 12387 12388 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 12389 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 12390 if (packageName == null) { 12391 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 12392 if (iperm == 0) { 12393 if (dumpState.onTitlePrinted()) 12394 pw.println(); 12395 pw.println("AppOp Permissions:"); 12396 } 12397 pw.print(" AppOp Permission "); 12398 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 12399 pw.println(":"); 12400 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 12401 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 12402 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 12403 } 12404 } 12405 } 12406 } 12407 12408 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 12409 boolean printedSomething = false; 12410 for (PackageParser.Provider p : mProviders.mProviders.values()) { 12411 if (packageName != null && !packageName.equals(p.info.packageName)) { 12412 continue; 12413 } 12414 if (!printedSomething) { 12415 if (dumpState.onTitlePrinted()) 12416 pw.println(); 12417 pw.println("Registered ContentProviders:"); 12418 printedSomething = true; 12419 } 12420 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 12421 pw.print(" "); pw.println(p.toString()); 12422 } 12423 printedSomething = false; 12424 for (Map.Entry<String, PackageParser.Provider> entry : 12425 mProvidersByAuthority.entrySet()) { 12426 PackageParser.Provider p = entry.getValue(); 12427 if (packageName != null && !packageName.equals(p.info.packageName)) { 12428 continue; 12429 } 12430 if (!printedSomething) { 12431 if (dumpState.onTitlePrinted()) 12432 pw.println(); 12433 pw.println("ContentProvider Authorities:"); 12434 printedSomething = true; 12435 } 12436 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 12437 pw.print(" "); pw.println(p.toString()); 12438 if (p.info != null && p.info.applicationInfo != null) { 12439 final String appInfo = p.info.applicationInfo.toString(); 12440 pw.print(" applicationInfo="); pw.println(appInfo); 12441 } 12442 } 12443 } 12444 12445 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 12446 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 12447 } 12448 12449 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 12450 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 12451 } 12452 12453 if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 12454 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState); 12455 } 12456 12457 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS)) { 12458 if (dumpState.onTitlePrinted()) pw.println(); 12459 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 12460 } 12461 12462 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 12463 if (dumpState.onTitlePrinted()) pw.println(); 12464 mSettings.dumpReadMessagesLPr(pw, dumpState); 12465 12466 pw.println(); 12467 pw.println("Package warning messages:"); 12468 final File fname = getSettingsProblemFile(); 12469 FileInputStream in = null; 12470 try { 12471 in = new FileInputStream(fname); 12472 final int avail = in.available(); 12473 final byte[] data = new byte[avail]; 12474 in.read(data); 12475 pw.print(new String(data)); 12476 } catch (FileNotFoundException e) { 12477 } catch (IOException e) { 12478 } finally { 12479 if (in != null) { 12480 try { 12481 in.close(); 12482 } catch (IOException e) { 12483 } 12484 } 12485 } 12486 } 12487 } 12488 } 12489 12490 // ------- apps on sdcard specific code ------- 12491 static final boolean DEBUG_SD_INSTALL = false; 12492 12493 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 12494 12495 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 12496 12497 private boolean mMediaMounted = false; 12498 12499 static String getEncryptKey() { 12500 try { 12501 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 12502 SD_ENCRYPTION_KEYSTORE_NAME); 12503 if (sdEncKey == null) { 12504 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 12505 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 12506 if (sdEncKey == null) { 12507 Slog.e(TAG, "Failed to create encryption keys"); 12508 return null; 12509 } 12510 } 12511 return sdEncKey; 12512 } catch (NoSuchAlgorithmException nsae) { 12513 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 12514 return null; 12515 } catch (IOException ioe) { 12516 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 12517 return null; 12518 } 12519 } 12520 12521 /* 12522 * Update media status on PackageManager. 12523 */ 12524 @Override 12525 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 12526 int callingUid = Binder.getCallingUid(); 12527 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 12528 throw new SecurityException("Media status can only be updated by the system"); 12529 } 12530 // reader; this apparently protects mMediaMounted, but should probably 12531 // be a different lock in that case. 12532 synchronized (mPackages) { 12533 Log.i(TAG, "Updating external media status from " 12534 + (mMediaMounted ? "mounted" : "unmounted") + " to " 12535 + (mediaStatus ? "mounted" : "unmounted")); 12536 if (DEBUG_SD_INSTALL) 12537 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 12538 + ", mMediaMounted=" + mMediaMounted); 12539 if (mediaStatus == mMediaMounted) { 12540 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 12541 : 0, -1); 12542 mHandler.sendMessage(msg); 12543 return; 12544 } 12545 mMediaMounted = mediaStatus; 12546 } 12547 // Queue up an async operation since the package installation may take a 12548 // little while. 12549 mHandler.post(new Runnable() { 12550 public void run() { 12551 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 12552 } 12553 }); 12554 } 12555 12556 /** 12557 * Called by MountService when the initial ASECs to scan are available. 12558 * Should block until all the ASEC containers are finished being scanned. 12559 */ 12560 public void scanAvailableAsecs() { 12561 updateExternalMediaStatusInner(true, false, false); 12562 if (mShouldRestoreconData) { 12563 SELinuxMMAC.setRestoreconDone(); 12564 mShouldRestoreconData = false; 12565 } 12566 } 12567 12568 /* 12569 * Collect information of applications on external media, map them against 12570 * existing containers and update information based on current mount status. 12571 * Please note that we always have to report status if reportStatus has been 12572 * set to true especially when unloading packages. 12573 */ 12574 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 12575 boolean externalStorage) { 12576 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 12577 int[] uidArr = EmptyArray.INT; 12578 12579 final String[] list = PackageHelper.getSecureContainerList(); 12580 if (ArrayUtils.isEmpty(list)) { 12581 Log.i(TAG, "No secure containers found"); 12582 } else { 12583 // Process list of secure containers and categorize them 12584 // as active or stale based on their package internal state. 12585 12586 // reader 12587 synchronized (mPackages) { 12588 for (String cid : list) { 12589 // Leave stages untouched for now; installer service owns them 12590 if (PackageInstallerService.isStageName(cid)) continue; 12591 12592 if (DEBUG_SD_INSTALL) 12593 Log.i(TAG, "Processing container " + cid); 12594 String pkgName = getAsecPackageName(cid); 12595 if (pkgName == null) { 12596 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 12597 continue; 12598 } 12599 if (DEBUG_SD_INSTALL) 12600 Log.i(TAG, "Looking for pkg : " + pkgName); 12601 12602 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12603 if (ps == null) { 12604 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 12605 continue; 12606 } 12607 12608 /* 12609 * Skip packages that are not external if we're unmounting 12610 * external storage. 12611 */ 12612 if (externalStorage && !isMounted && !isExternal(ps)) { 12613 continue; 12614 } 12615 12616 final AsecInstallArgs args = new AsecInstallArgs(cid, 12617 getAppDexInstructionSets(ps), isForwardLocked(ps)); 12618 // The package status is changed only if the code path 12619 // matches between settings and the container id. 12620 if (ps.codePathString != null 12621 && ps.codePathString.startsWith(args.getCodePath())) { 12622 if (DEBUG_SD_INSTALL) { 12623 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 12624 + " at code path: " + ps.codePathString); 12625 } 12626 12627 // We do have a valid package installed on sdcard 12628 processCids.put(args, ps.codePathString); 12629 final int uid = ps.appId; 12630 if (uid != -1) { 12631 uidArr = ArrayUtils.appendInt(uidArr, uid); 12632 } 12633 } else { 12634 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 12635 + ps.codePathString); 12636 } 12637 } 12638 } 12639 12640 Arrays.sort(uidArr); 12641 } 12642 12643 // Process packages with valid entries. 12644 if (isMounted) { 12645 if (DEBUG_SD_INSTALL) 12646 Log.i(TAG, "Loading packages"); 12647 loadMediaPackages(processCids, uidArr); 12648 startCleaningPackages(); 12649 mInstallerService.onSecureContainersAvailable(); 12650 } else { 12651 if (DEBUG_SD_INSTALL) 12652 Log.i(TAG, "Unloading packages"); 12653 unloadMediaPackages(processCids, uidArr, reportStatus); 12654 } 12655 } 12656 12657 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 12658 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 12659 int size = pkgList.size(); 12660 if (size > 0) { 12661 // Send broadcasts here 12662 Bundle extras = new Bundle(); 12663 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 12664 .toArray(new String[size])); 12665 if (uidArr != null) { 12666 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 12667 } 12668 if (replacing) { 12669 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 12670 } 12671 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 12672 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 12673 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 12674 } 12675 } 12676 12677 /* 12678 * Look at potentially valid container ids from processCids If package 12679 * information doesn't match the one on record or package scanning fails, 12680 * the cid is added to list of removeCids. We currently don't delete stale 12681 * containers. 12682 */ 12683 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 12684 ArrayList<String> pkgList = new ArrayList<String>(); 12685 Set<AsecInstallArgs> keys = processCids.keySet(); 12686 12687 for (AsecInstallArgs args : keys) { 12688 String codePath = processCids.get(args); 12689 if (DEBUG_SD_INSTALL) 12690 Log.i(TAG, "Loading container : " + args.cid); 12691 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 12692 try { 12693 // Make sure there are no container errors first. 12694 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 12695 Slog.e(TAG, "Failed to mount cid : " + args.cid 12696 + " when installing from sdcard"); 12697 continue; 12698 } 12699 // Check code path here. 12700 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 12701 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 12702 + " does not match one in settings " + codePath); 12703 continue; 12704 } 12705 // Parse package 12706 int parseFlags = mDefParseFlags; 12707 if (args.isExternal()) { 12708 parseFlags |= PackageParser.PARSE_ON_SDCARD; 12709 } 12710 if (args.isFwdLocked()) { 12711 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 12712 } 12713 12714 synchronized (mInstallLock) { 12715 PackageParser.Package pkg = null; 12716 try { 12717 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 12718 } catch (PackageManagerException e) { 12719 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 12720 } 12721 // Scan the package 12722 if (pkg != null) { 12723 /* 12724 * TODO why is the lock being held? doPostInstall is 12725 * called in other places without the lock. This needs 12726 * to be straightened out. 12727 */ 12728 // writer 12729 synchronized (mPackages) { 12730 retCode = PackageManager.INSTALL_SUCCEEDED; 12731 pkgList.add(pkg.packageName); 12732 // Post process args 12733 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 12734 pkg.applicationInfo.uid); 12735 } 12736 } else { 12737 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 12738 } 12739 } 12740 12741 } finally { 12742 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 12743 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 12744 } 12745 } 12746 } 12747 // writer 12748 synchronized (mPackages) { 12749 // If the platform SDK has changed since the last time we booted, 12750 // we need to re-grant app permission to catch any new ones that 12751 // appear. This is really a hack, and means that apps can in some 12752 // cases get permissions that the user didn't initially explicitly 12753 // allow... it would be nice to have some better way to handle 12754 // this situation. 12755 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 12756 if (regrantPermissions) 12757 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 12758 + mSdkVersion + "; regranting permissions for external storage"); 12759 mSettings.mExternalSdkPlatform = mSdkVersion; 12760 12761 // Make sure group IDs have been assigned, and any permission 12762 // changes in other apps are accounted for 12763 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 12764 | (regrantPermissions 12765 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 12766 : 0)); 12767 12768 mSettings.updateExternalDatabaseVersion(); 12769 12770 // can downgrade to reader 12771 // Persist settings 12772 mSettings.writeLPr(); 12773 } 12774 // Send a broadcast to let everyone know we are done processing 12775 if (pkgList.size() > 0) { 12776 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12777 } 12778 } 12779 12780 /* 12781 * Utility method to unload a list of specified containers 12782 */ 12783 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 12784 // Just unmount all valid containers. 12785 for (AsecInstallArgs arg : cidArgs) { 12786 synchronized (mInstallLock) { 12787 arg.doPostDeleteLI(false); 12788 } 12789 } 12790 } 12791 12792 /* 12793 * Unload packages mounted on external media. This involves deleting package 12794 * data from internal structures, sending broadcasts about diabled packages, 12795 * gc'ing to free up references, unmounting all secure containers 12796 * corresponding to packages on external media, and posting a 12797 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 12798 * that we always have to post this message if status has been requested no 12799 * matter what. 12800 */ 12801 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 12802 final boolean reportStatus) { 12803 if (DEBUG_SD_INSTALL) 12804 Log.i(TAG, "unloading media packages"); 12805 ArrayList<String> pkgList = new ArrayList<String>(); 12806 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 12807 final Set<AsecInstallArgs> keys = processCids.keySet(); 12808 for (AsecInstallArgs args : keys) { 12809 String pkgName = args.getPackageName(); 12810 if (DEBUG_SD_INSTALL) 12811 Log.i(TAG, "Trying to unload pkg : " + pkgName); 12812 // Delete package internally 12813 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 12814 synchronized (mInstallLock) { 12815 boolean res = deletePackageLI(pkgName, null, false, null, null, 12816 PackageManager.DELETE_KEEP_DATA, outInfo, false); 12817 if (res) { 12818 pkgList.add(pkgName); 12819 } else { 12820 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 12821 failedList.add(args); 12822 } 12823 } 12824 } 12825 12826 // reader 12827 synchronized (mPackages) { 12828 // We didn't update the settings after removing each package; 12829 // write them now for all packages. 12830 mSettings.writeLPr(); 12831 } 12832 12833 // We have to absolutely send UPDATED_MEDIA_STATUS only 12834 // after confirming that all the receivers processed the ordered 12835 // broadcast when packages get disabled, force a gc to clean things up. 12836 // and unload all the containers. 12837 if (pkgList.size() > 0) { 12838 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 12839 new IIntentReceiver.Stub() { 12840 public void performReceive(Intent intent, int resultCode, String data, 12841 Bundle extras, boolean ordered, boolean sticky, 12842 int sendingUser) throws RemoteException { 12843 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 12844 reportStatus ? 1 : 0, 1, keys); 12845 mHandler.sendMessage(msg); 12846 } 12847 }); 12848 } else { 12849 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 12850 keys); 12851 mHandler.sendMessage(msg); 12852 } 12853 } 12854 12855 /** Binder call */ 12856 @Override 12857 public void movePackage(final String packageName, final IPackageMoveObserver observer, 12858 final int flags) { 12859 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 12860 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 12861 int returnCode = PackageManager.MOVE_SUCCEEDED; 12862 int currInstallFlags = 0; 12863 int newInstallFlags = 0; 12864 12865 File codeFile = null; 12866 String installerPackageName = null; 12867 String packageAbiOverride = null; 12868 12869 // reader 12870 synchronized (mPackages) { 12871 final PackageParser.Package pkg = mPackages.get(packageName); 12872 final PackageSetting ps = mSettings.mPackages.get(packageName); 12873 if (pkg == null || ps == null) { 12874 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12875 } else { 12876 // Disable moving fwd locked apps and system packages 12877 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 12878 Slog.w(TAG, "Cannot move system application"); 12879 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 12880 } else if (pkg.mOperationPending) { 12881 Slog.w(TAG, "Attempt to move package which has pending operations"); 12882 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 12883 } else { 12884 // Find install location first 12885 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 12886 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 12887 Slog.w(TAG, "Ambigous flags specified for move location."); 12888 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12889 } else { 12890 newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 12891 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 12892 currInstallFlags = isExternal(pkg) 12893 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 12894 12895 if (newInstallFlags == currInstallFlags) { 12896 Slog.w(TAG, "No move required. Trying to move to same location"); 12897 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12898 } else { 12899 if (isForwardLocked(pkg)) { 12900 currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12901 newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12902 } 12903 } 12904 } 12905 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12906 pkg.mOperationPending = true; 12907 } 12908 } 12909 12910 codeFile = new File(pkg.codePath); 12911 installerPackageName = ps.installerPackageName; 12912 packageAbiOverride = ps.cpuAbiOverrideString; 12913 } 12914 } 12915 12916 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 12917 try { 12918 observer.packageMoved(packageName, returnCode); 12919 } catch (RemoteException ignored) { 12920 } 12921 return; 12922 } 12923 12924 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 12925 @Override 12926 public void onUserActionRequired(Intent intent) throws RemoteException { 12927 throw new IllegalStateException(); 12928 } 12929 12930 @Override 12931 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 12932 Bundle extras) throws RemoteException { 12933 Slog.d(TAG, "Install result for move: " 12934 + PackageManager.installStatusToString(returnCode, msg)); 12935 12936 // We usually have a new package now after the install, but if 12937 // we failed we need to clear the pending flag on the original 12938 // package object. 12939 synchronized (mPackages) { 12940 final PackageParser.Package pkg = mPackages.get(packageName); 12941 if (pkg != null) { 12942 pkg.mOperationPending = false; 12943 } 12944 } 12945 12946 final int status = PackageManager.installStatusToPublicStatus(returnCode); 12947 switch (status) { 12948 case PackageInstaller.STATUS_SUCCESS: 12949 observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED); 12950 break; 12951 case PackageInstaller.STATUS_FAILURE_STORAGE: 12952 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 12953 break; 12954 default: 12955 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR); 12956 break; 12957 } 12958 } 12959 }; 12960 12961 // Treat a move like reinstalling an existing app, which ensures that we 12962 // process everythign uniformly, like unpacking native libraries. 12963 newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 12964 12965 final Message msg = mHandler.obtainMessage(INIT_COPY); 12966 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 12967 msg.obj = new InstallParams(origin, installObserver, newInstallFlags, 12968 installerPackageName, null, user, packageAbiOverride); 12969 mHandler.sendMessage(msg); 12970 } 12971 12972 @Override 12973 public boolean setInstallLocation(int loc) { 12974 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 12975 null); 12976 if (getInstallLocation() == loc) { 12977 return true; 12978 } 12979 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 12980 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 12981 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 12982 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 12983 return true; 12984 } 12985 return false; 12986 } 12987 12988 @Override 12989 public int getInstallLocation() { 12990 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12991 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 12992 PackageHelper.APP_INSTALL_AUTO); 12993 } 12994 12995 /** Called by UserManagerService */ 12996 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 12997 mDirtyUsers.remove(userHandle); 12998 mSettings.removeUserLPw(userHandle); 12999 mPendingBroadcasts.remove(userHandle); 13000 if (mInstaller != null) { 13001 // Technically, we shouldn't be doing this with the package lock 13002 // held. However, this is very rare, and there is already so much 13003 // other disk I/O going on, that we'll let it slide for now. 13004 mInstaller.removeUserDataDirs(userHandle); 13005 } 13006 mUserNeedsBadging.delete(userHandle); 13007 removeUnusedPackagesLILPw(userManager, userHandle); 13008 } 13009 13010 /** 13011 * We're removing userHandle and would like to remove any downloaded packages 13012 * that are no longer in use by any other user. 13013 * @param userHandle the user being removed 13014 */ 13015 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 13016 final boolean DEBUG_CLEAN_APKS = false; 13017 int [] users = userManager.getUserIdsLPr(); 13018 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 13019 while (psit.hasNext()) { 13020 PackageSetting ps = psit.next(); 13021 if (ps.pkg == null) { 13022 continue; 13023 } 13024 final String packageName = ps.pkg.packageName; 13025 // Skip over if system app 13026 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 13027 continue; 13028 } 13029 if (DEBUG_CLEAN_APKS) { 13030 Slog.i(TAG, "Checking package " + packageName); 13031 } 13032 boolean keep = false; 13033 for (int i = 0; i < users.length; i++) { 13034 if (users[i] != userHandle && ps.getInstalled(users[i])) { 13035 keep = true; 13036 if (DEBUG_CLEAN_APKS) { 13037 Slog.i(TAG, " Keeping package " + packageName + " for user " 13038 + users[i]); 13039 } 13040 break; 13041 } 13042 } 13043 if (!keep) { 13044 if (DEBUG_CLEAN_APKS) { 13045 Slog.i(TAG, " Removing package " + packageName); 13046 } 13047 mHandler.post(new Runnable() { 13048 public void run() { 13049 deletePackageX(packageName, userHandle, 0); 13050 } //end run 13051 }); 13052 } 13053 } 13054 } 13055 13056 /** Called by UserManagerService */ 13057 void createNewUserLILPw(int userHandle, File path) { 13058 if (mInstaller != null) { 13059 mInstaller.createUserConfig(userHandle); 13060 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 13061 } 13062 } 13063 13064 @Override 13065 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 13066 mContext.enforceCallingOrSelfPermission( 13067 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13068 "Only package verification agents can read the verifier device identity"); 13069 13070 synchronized (mPackages) { 13071 return mSettings.getVerifierDeviceIdentityLPw(); 13072 } 13073 } 13074 13075 @Override 13076 public void setPermissionEnforced(String permission, boolean enforced) { 13077 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 13078 if (READ_EXTERNAL_STORAGE.equals(permission)) { 13079 synchronized (mPackages) { 13080 if (mSettings.mReadExternalStorageEnforced == null 13081 || mSettings.mReadExternalStorageEnforced != enforced) { 13082 mSettings.mReadExternalStorageEnforced = enforced; 13083 mSettings.writeLPr(); 13084 } 13085 } 13086 // kill any non-foreground processes so we restart them and 13087 // grant/revoke the GID. 13088 final IActivityManager am = ActivityManagerNative.getDefault(); 13089 if (am != null) { 13090 final long token = Binder.clearCallingIdentity(); 13091 try { 13092 am.killProcessesBelowForeground("setPermissionEnforcement"); 13093 } catch (RemoteException e) { 13094 } finally { 13095 Binder.restoreCallingIdentity(token); 13096 } 13097 } 13098 } else { 13099 throw new IllegalArgumentException("No selective enforcement for " + permission); 13100 } 13101 } 13102 13103 @Override 13104 @Deprecated 13105 public boolean isPermissionEnforced(String permission) { 13106 return true; 13107 } 13108 13109 @Override 13110 public boolean isStorageLow() { 13111 final long token = Binder.clearCallingIdentity(); 13112 try { 13113 final DeviceStorageMonitorInternal 13114 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13115 if (dsm != null) { 13116 return dsm.isMemoryLow(); 13117 } else { 13118 return false; 13119 } 13120 } finally { 13121 Binder.restoreCallingIdentity(token); 13122 } 13123 } 13124 13125 @Override 13126 public IPackageInstaller getPackageInstaller() { 13127 return mInstallerService; 13128 } 13129 13130 private boolean userNeedsBadging(int userId) { 13131 int index = mUserNeedsBadging.indexOfKey(userId); 13132 if (index < 0) { 13133 final UserInfo userInfo; 13134 final long token = Binder.clearCallingIdentity(); 13135 try { 13136 userInfo = sUserManager.getUserInfo(userId); 13137 } finally { 13138 Binder.restoreCallingIdentity(token); 13139 } 13140 final boolean b; 13141 if (userInfo != null && userInfo.isManagedProfile()) { 13142 b = true; 13143 } else { 13144 b = false; 13145 } 13146 mUserNeedsBadging.put(userId, b); 13147 return b; 13148 } 13149 return mUserNeedsBadging.valueAt(index); 13150 } 13151 13152 @Override 13153 public KeySet getKeySetByAlias(String packageName, String alias) { 13154 if (packageName == null || alias == null) { 13155 return null; 13156 } 13157 synchronized(mPackages) { 13158 final PackageParser.Package pkg = mPackages.get(packageName); 13159 if (pkg == null) { 13160 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13161 throw new IllegalArgumentException("Unknown package: " + packageName); 13162 } 13163 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13164 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 13165 } 13166 } 13167 13168 @Override 13169 public KeySet getSigningKeySet(String packageName) { 13170 if (packageName == null) { 13171 return null; 13172 } 13173 synchronized(mPackages) { 13174 final PackageParser.Package pkg = mPackages.get(packageName); 13175 if (pkg == null) { 13176 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13177 throw new IllegalArgumentException("Unknown package: " + packageName); 13178 } 13179 if (pkg.applicationInfo.uid != Binder.getCallingUid() 13180 && Process.SYSTEM_UID != Binder.getCallingUid()) { 13181 throw new SecurityException("May not access signing KeySet of other apps."); 13182 } 13183 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13184 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 13185 } 13186 } 13187 13188 @Override 13189 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 13190 if (packageName == null || ks == null) { 13191 return false; 13192 } 13193 synchronized(mPackages) { 13194 final PackageParser.Package pkg = mPackages.get(packageName); 13195 if (pkg == null) { 13196 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13197 throw new IllegalArgumentException("Unknown package: " + packageName); 13198 } 13199 IBinder ksh = ks.getToken(); 13200 if (ksh instanceof KeySetHandle) { 13201 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13202 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 13203 } 13204 return false; 13205 } 13206 } 13207 13208 @Override 13209 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 13210 if (packageName == null || ks == null) { 13211 return false; 13212 } 13213 synchronized(mPackages) { 13214 final PackageParser.Package pkg = mPackages.get(packageName); 13215 if (pkg == null) { 13216 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13217 throw new IllegalArgumentException("Unknown package: " + packageName); 13218 } 13219 IBinder ksh = ks.getToken(); 13220 if (ksh instanceof KeySetHandle) { 13221 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13222 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 13223 } 13224 return false; 13225 } 13226 } 13227} 13228