PackageManagerService.java revision 05ecfd308d983755bc7cab39ba99a37c321f176b
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_FAILED_VERSION_DOWNGRADE; 45import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 46import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 47import static android.content.pm.PackageParser.isApkFile; 48import static android.os.Process.PACKAGE_INFO_GID; 49import static android.os.Process.SYSTEM_UID; 50import static android.system.OsConstants.O_CREAT; 51import static android.system.OsConstants.O_RDWR; 52import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 53import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER; 54import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 55import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 56import static com.android.internal.util.ArrayUtils.appendInt; 57import static com.android.internal.util.ArrayUtils.removeInt; 58 59import android.util.ArrayMap; 60 61import com.android.internal.R; 62import com.android.internal.app.IMediaContainerService; 63import com.android.internal.app.ResolverActivity; 64import com.android.internal.content.NativeLibraryHelper; 65import com.android.internal.content.PackageHelper; 66import com.android.internal.os.IParcelFileDescriptorFactory; 67import com.android.internal.util.ArrayUtils; 68import com.android.internal.util.FastPrintWriter; 69import com.android.internal.util.FastXmlSerializer; 70import com.android.internal.util.IndentingPrintWriter; 71import com.android.server.EventLogTags; 72import com.android.server.IntentResolver; 73import com.android.server.LocalServices; 74import com.android.server.ServiceThread; 75import com.android.server.SystemConfig; 76import com.android.server.Watchdog; 77import com.android.server.pm.Settings.DatabaseVersion; 78import com.android.server.storage.DeviceStorageMonitorInternal; 79 80import org.xmlpull.v1.XmlSerializer; 81 82import android.app.ActivityManager; 83import android.app.ActivityManagerNative; 84import android.app.AppGlobals; 85import android.app.IActivityManager; 86import android.app.admin.IDevicePolicyManager; 87import android.app.backup.IBackupManager; 88import android.app.usage.UsageStats; 89import android.app.usage.UsageStatsManager; 90import android.content.BroadcastReceiver; 91import android.content.ComponentName; 92import android.content.Context; 93import android.content.IIntentReceiver; 94import android.content.Intent; 95import android.content.IntentFilter; 96import android.content.IntentSender; 97import android.content.IntentSender.SendIntentException; 98import android.content.ServiceConnection; 99import android.content.pm.ActivityInfo; 100import android.content.pm.ApplicationInfo; 101import android.content.pm.FeatureInfo; 102import android.content.pm.IPackageDataObserver; 103import android.content.pm.IPackageDeleteObserver; 104import android.content.pm.IPackageDeleteObserver2; 105import android.content.pm.IPackageInstallObserver2; 106import android.content.pm.IPackageInstaller; 107import android.content.pm.IPackageManager; 108import android.content.pm.IPackageMoveObserver; 109import android.content.pm.IPackageStatsObserver; 110import android.content.pm.InstrumentationInfo; 111import android.content.pm.KeySet; 112import android.content.pm.ManifestDigest; 113import android.content.pm.PackageCleanItem; 114import android.content.pm.PackageInfo; 115import android.content.pm.PackageInfoLite; 116import android.content.pm.PackageInstaller; 117import android.content.pm.PackageManager; 118import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 119import android.content.pm.PackageParser.ActivityIntentInfo; 120import android.content.pm.PackageParser.PackageLite; 121import android.content.pm.PackageParser.PackageParserException; 122import android.content.pm.PackageParser; 123import android.content.pm.PackageStats; 124import android.content.pm.PackageUserState; 125import android.content.pm.ParceledListSlice; 126import android.content.pm.PermissionGroupInfo; 127import android.content.pm.PermissionInfo; 128import android.content.pm.ProviderInfo; 129import android.content.pm.ResolveInfo; 130import android.content.pm.ServiceInfo; 131import android.content.pm.Signature; 132import android.content.pm.UserInfo; 133import android.content.pm.VerificationParams; 134import android.content.pm.VerifierDeviceIdentity; 135import android.content.pm.VerifierInfo; 136import android.content.res.Resources; 137import android.hardware.display.DisplayManager; 138import android.net.Uri; 139import android.os.Binder; 140import android.os.Build; 141import android.os.Bundle; 142import android.os.Environment; 143import android.os.Environment.UserEnvironment; 144import android.os.storage.IMountService; 145import android.os.storage.StorageManager; 146import android.os.Debug; 147import android.os.FileUtils; 148import android.os.Handler; 149import android.os.IBinder; 150import android.os.Looper; 151import android.os.Message; 152import android.os.Parcel; 153import android.os.ParcelFileDescriptor; 154import android.os.Process; 155import android.os.RemoteException; 156import android.os.SELinux; 157import android.os.ServiceManager; 158import android.os.SystemClock; 159import android.os.SystemProperties; 160import android.os.UserHandle; 161import android.os.UserManager; 162import android.security.KeyStore; 163import android.security.SystemKeyStore; 164import android.system.ErrnoException; 165import android.system.Os; 166import android.system.StructStat; 167import android.text.TextUtils; 168import android.text.format.DateUtils; 169import android.util.ArraySet; 170import android.util.AtomicFile; 171import android.util.DisplayMetrics; 172import android.util.EventLog; 173import android.util.ExceptionUtils; 174import android.util.Log; 175import android.util.LogPrinter; 176import android.util.PrintStreamPrinter; 177import android.util.Slog; 178import android.util.SparseArray; 179import android.util.SparseBooleanArray; 180import android.view.Display; 181 182import java.io.BufferedInputStream; 183import java.io.BufferedOutputStream; 184import java.io.BufferedReader; 185import java.io.File; 186import java.io.FileDescriptor; 187import java.io.FileInputStream; 188import java.io.FileNotFoundException; 189import java.io.FileOutputStream; 190import java.io.FileReader; 191import java.io.FilenameFilter; 192import java.io.IOException; 193import java.io.InputStream; 194import java.io.PrintWriter; 195import java.nio.charset.StandardCharsets; 196import java.security.NoSuchAlgorithmException; 197import java.security.PublicKey; 198import java.security.cert.CertificateEncodingException; 199import java.security.cert.CertificateException; 200import java.text.SimpleDateFormat; 201import java.util.ArrayList; 202import java.util.Arrays; 203import java.util.Collection; 204import java.util.Collections; 205import java.util.Comparator; 206import java.util.Date; 207import java.util.Iterator; 208import java.util.List; 209import java.util.Map; 210import java.util.Objects; 211import java.util.Set; 212import java.util.concurrent.atomic.AtomicBoolean; 213import java.util.concurrent.atomic.AtomicLong; 214 215import dalvik.system.DexFile; 216import dalvik.system.StaleDexCacheError; 217import dalvik.system.VMRuntime; 218 219import libcore.io.IoUtils; 220import libcore.util.EmptyArray; 221 222/** 223 * Keep track of all those .apks everywhere. 224 * 225 * This is very central to the platform's security; please run the unit 226 * tests whenever making modifications here: 227 * 228mmm frameworks/base/tests/AndroidTests 229adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 230adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 231 * 232 * {@hide} 233 */ 234public class PackageManagerService extends IPackageManager.Stub { 235 static final String TAG = "PackageManager"; 236 static final boolean DEBUG_SETTINGS = false; 237 static final boolean DEBUG_PREFERRED = false; 238 static final boolean DEBUG_UPGRADE = false; 239 private static final boolean DEBUG_INSTALL = false; 240 private static final boolean DEBUG_REMOVE = false; 241 private static final boolean DEBUG_BROADCASTS = false; 242 private static final boolean DEBUG_SHOW_INFO = false; 243 private static final boolean DEBUG_PACKAGE_INFO = false; 244 private static final boolean DEBUG_INTENT_MATCHING = false; 245 private static final boolean DEBUG_PACKAGE_SCANNING = false; 246 private static final boolean DEBUG_VERIFY = false; 247 private static final boolean DEBUG_DEXOPT = false; 248 private static final boolean DEBUG_ABI_SELECTION = false; 249 250 private static final int RADIO_UID = Process.PHONE_UID; 251 private static final int LOG_UID = Process.LOG_UID; 252 private static final int NFC_UID = Process.NFC_UID; 253 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 254 private static final int SHELL_UID = Process.SHELL_UID; 255 256 // Cap the size of permission trees that 3rd party apps can define 257 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 258 259 // Suffix used during package installation when copying/moving 260 // package apks to install directory. 261 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 262 263 static final int SCAN_NO_DEX = 1<<1; 264 static final int SCAN_FORCE_DEX = 1<<2; 265 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 266 static final int SCAN_NEW_INSTALL = 1<<4; 267 static final int SCAN_NO_PATHS = 1<<5; 268 static final int SCAN_UPDATE_TIME = 1<<6; 269 static final int SCAN_DEFER_DEX = 1<<7; 270 static final int SCAN_BOOTING = 1<<8; 271 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 272 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 273 static final int SCAN_REPLACING = 1<<11; 274 275 static final int REMOVE_CHATTY = 1<<16; 276 277 /** 278 * Timeout (in milliseconds) after which the watchdog should declare that 279 * our handler thread is wedged. The usual default for such things is one 280 * minute but we sometimes do very lengthy I/O operations on this thread, 281 * such as installing multi-gigabyte applications, so ours needs to be longer. 282 */ 283 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 284 285 /** 286 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 287 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 288 * settings entry if available, otherwise we use the hardcoded default. If it's been 289 * more than this long since the last fstrim, we force one during the boot sequence. 290 * 291 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 292 * one gets run at the next available charging+idle time. This final mandatory 293 * no-fstrim check kicks in only of the other scheduling criteria is never met. 294 */ 295 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 296 297 /** 298 * Whether verification is enabled by default. 299 */ 300 private static final boolean DEFAULT_VERIFY_ENABLE = true; 301 302 /** 303 * The default maximum time to wait for the verification agent to return in 304 * milliseconds. 305 */ 306 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 307 308 /** 309 * The default response for package verification timeout. 310 * 311 * This can be either PackageManager.VERIFICATION_ALLOW or 312 * PackageManager.VERIFICATION_REJECT. 313 */ 314 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 315 316 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 317 318 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 319 DEFAULT_CONTAINER_PACKAGE, 320 "com.android.defcontainer.DefaultContainerService"); 321 322 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 323 324 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 325 326 private static String sPreferredInstructionSet; 327 328 final ServiceThread mHandlerThread; 329 330 private static final String IDMAP_PREFIX = "/data/resource-cache/"; 331 private static final String IDMAP_SUFFIX = "@idmap"; 332 333 final PackageHandler mHandler; 334 335 /** 336 * Messages for {@link #mHandler} that need to wait for system ready before 337 * being dispatched. 338 */ 339 private ArrayList<Message> mPostSystemReadyMessages; 340 341 final int mSdkVersion = Build.VERSION.SDK_INT; 342 343 final Context mContext; 344 final boolean mFactoryTest; 345 final boolean mOnlyCore; 346 final boolean mLazyDexOpt; 347 final long mDexOptLRUThresholdInMills; 348 final DisplayMetrics mMetrics; 349 final int mDefParseFlags; 350 final String[] mSeparateProcesses; 351 final boolean mIsUpgrade; 352 353 // This is where all application persistent data goes. 354 final File mAppDataDir; 355 356 // This is where all application persistent data goes for secondary users. 357 final File mUserAppDataDir; 358 359 /** The location for ASEC container files on internal storage. */ 360 final String mAsecInternalPath; 361 362 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 363 // LOCK HELD. Can be called with mInstallLock held. 364 final Installer mInstaller; 365 366 /** Directory where installed third-party apps stored */ 367 final File mAppInstallDir; 368 369 /** 370 * Directory to which applications installed internally have their 371 * 32 bit native libraries copied. 372 */ 373 private File mAppLib32InstallDir; 374 375 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 376 // apps. 377 final File mDrmAppPrivateInstallDir; 378 379 // ---------------------------------------------------------------- 380 381 // Lock for state used when installing and doing other long running 382 // operations. Methods that must be called with this lock held have 383 // the suffix "LI". 384 final Object mInstallLock = new Object(); 385 386 // ---------------------------------------------------------------- 387 388 // Keys are String (package name), values are Package. This also serves 389 // as the lock for the global state. Methods that must be called with 390 // this lock held have the prefix "LP". 391 final ArrayMap<String, PackageParser.Package> mPackages = 392 new ArrayMap<String, PackageParser.Package>(); 393 394 // Tracks available target package names -> overlay package paths. 395 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 396 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 397 398 final Settings mSettings; 399 boolean mRestoredSettings; 400 401 // System configuration read by SystemConfig. 402 final int[] mGlobalGids; 403 final SparseArray<ArraySet<String>> mSystemPermissions; 404 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 405 406 // If mac_permissions.xml was found for seinfo labeling. 407 boolean mFoundPolicyFile; 408 409 // If a recursive restorecon of /data/data/<pkg> is needed. 410 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 411 412 public static final class SharedLibraryEntry { 413 public final String path; 414 public final String apk; 415 416 SharedLibraryEntry(String _path, String _apk) { 417 path = _path; 418 apk = _apk; 419 } 420 } 421 422 // Currently known shared libraries. 423 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 424 new ArrayMap<String, SharedLibraryEntry>(); 425 426 // All available activities, for your resolving pleasure. 427 final ActivityIntentResolver mActivities = 428 new ActivityIntentResolver(); 429 430 // All available receivers, for your resolving pleasure. 431 final ActivityIntentResolver mReceivers = 432 new ActivityIntentResolver(); 433 434 // All available services, for your resolving pleasure. 435 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 436 437 // All available providers, for your resolving pleasure. 438 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 439 440 // Mapping from provider base names (first directory in content URI codePath) 441 // to the provider information. 442 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 443 new ArrayMap<String, PackageParser.Provider>(); 444 445 // Mapping from instrumentation class names to info about them. 446 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 447 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 448 449 // Mapping from permission names to info about them. 450 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 451 new ArrayMap<String, PackageParser.PermissionGroup>(); 452 453 // Packages whose data we have transfered into another package, thus 454 // should no longer exist. 455 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 456 457 // Broadcast actions that are only available to the system. 458 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 459 460 /** List of packages waiting for verification. */ 461 final SparseArray<PackageVerificationState> mPendingVerification 462 = new SparseArray<PackageVerificationState>(); 463 464 /** Set of packages associated with each app op permission. */ 465 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 466 467 final PackageInstallerService mInstallerService; 468 469 ArraySet<PackageParser.Package> mDeferredDexOpt = null; 470 471 // Cache of users who need badging. 472 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 473 474 /** Token for keys in mPendingVerification. */ 475 private int mPendingVerificationToken = 0; 476 477 volatile boolean mSystemReady; 478 volatile boolean mSafeMode; 479 volatile boolean mHasSystemUidErrors; 480 481 ApplicationInfo mAndroidApplication; 482 final ActivityInfo mResolveActivity = new ActivityInfo(); 483 final ResolveInfo mResolveInfo = new ResolveInfo(); 484 ComponentName mResolveComponentName; 485 PackageParser.Package mPlatformPackage; 486 ComponentName mCustomResolverComponentName; 487 488 boolean mResolverReplaced = false; 489 490 // Set of pending broadcasts for aggregating enable/disable of components. 491 static class PendingPackageBroadcasts { 492 // for each user id, a map of <package name -> components within that package> 493 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 494 495 public PendingPackageBroadcasts() { 496 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 497 } 498 499 public ArrayList<String> get(int userId, String packageName) { 500 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 501 return packages.get(packageName); 502 } 503 504 public void put(int userId, String packageName, ArrayList<String> components) { 505 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 506 packages.put(packageName, components); 507 } 508 509 public void remove(int userId, String packageName) { 510 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 511 if (packages != null) { 512 packages.remove(packageName); 513 } 514 } 515 516 public void remove(int userId) { 517 mUidMap.remove(userId); 518 } 519 520 public int userIdCount() { 521 return mUidMap.size(); 522 } 523 524 public int userIdAt(int n) { 525 return mUidMap.keyAt(n); 526 } 527 528 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 529 return mUidMap.get(userId); 530 } 531 532 public int size() { 533 // total number of pending broadcast entries across all userIds 534 int num = 0; 535 for (int i = 0; i< mUidMap.size(); i++) { 536 num += mUidMap.valueAt(i).size(); 537 } 538 return num; 539 } 540 541 public void clear() { 542 mUidMap.clear(); 543 } 544 545 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 546 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 547 if (map == null) { 548 map = new ArrayMap<String, ArrayList<String>>(); 549 mUidMap.put(userId, map); 550 } 551 return map; 552 } 553 } 554 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 555 556 // Service Connection to remote media container service to copy 557 // package uri's from external media onto secure containers 558 // or internal storage. 559 private IMediaContainerService mContainerService = null; 560 561 static final int SEND_PENDING_BROADCAST = 1; 562 static final int MCS_BOUND = 3; 563 static final int END_COPY = 4; 564 static final int INIT_COPY = 5; 565 static final int MCS_UNBIND = 6; 566 static final int START_CLEANING_PACKAGE = 7; 567 static final int FIND_INSTALL_LOC = 8; 568 static final int POST_INSTALL = 9; 569 static final int MCS_RECONNECT = 10; 570 static final int MCS_GIVE_UP = 11; 571 static final int UPDATED_MEDIA_STATUS = 12; 572 static final int WRITE_SETTINGS = 13; 573 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 574 static final int PACKAGE_VERIFIED = 15; 575 static final int CHECK_PENDING_VERIFICATION = 16; 576 577 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 578 579 // Delay time in millisecs 580 static final int BROADCAST_DELAY = 10 * 1000; 581 582 static UserManagerService sUserManager; 583 584 // Stores a list of users whose package restrictions file needs to be updated 585 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 586 587 final private DefaultContainerConnection mDefContainerConn = 588 new DefaultContainerConnection(); 589 class DefaultContainerConnection implements ServiceConnection { 590 public void onServiceConnected(ComponentName name, IBinder service) { 591 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 592 IMediaContainerService imcs = 593 IMediaContainerService.Stub.asInterface(service); 594 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 595 } 596 597 public void onServiceDisconnected(ComponentName name) { 598 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 599 } 600 }; 601 602 // Recordkeeping of restore-after-install operations that are currently in flight 603 // between the Package Manager and the Backup Manager 604 class PostInstallData { 605 public InstallArgs args; 606 public PackageInstalledInfo res; 607 608 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 609 args = _a; 610 res = _r; 611 } 612 }; 613 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 614 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 615 616 private final String mRequiredVerifierPackage; 617 618 private final PackageUsage mPackageUsage = new PackageUsage(); 619 620 private class PackageUsage { 621 private static final int WRITE_INTERVAL 622 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 623 624 private final Object mFileLock = new Object(); 625 private final AtomicLong mLastWritten = new AtomicLong(0); 626 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 627 628 private boolean mIsHistoricalPackageUsageAvailable = true; 629 630 boolean isHistoricalPackageUsageAvailable() { 631 return mIsHistoricalPackageUsageAvailable; 632 } 633 634 void write(boolean force) { 635 if (force) { 636 writeInternal(); 637 return; 638 } 639 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 640 && !DEBUG_DEXOPT) { 641 return; 642 } 643 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 644 new Thread("PackageUsage_DiskWriter") { 645 @Override 646 public void run() { 647 try { 648 writeInternal(); 649 } finally { 650 mBackgroundWriteRunning.set(false); 651 } 652 } 653 }.start(); 654 } 655 } 656 657 private void writeInternal() { 658 synchronized (mPackages) { 659 synchronized (mFileLock) { 660 AtomicFile file = getFile(); 661 FileOutputStream f = null; 662 try { 663 f = file.startWrite(); 664 BufferedOutputStream out = new BufferedOutputStream(f); 665 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 666 StringBuilder sb = new StringBuilder(); 667 for (PackageParser.Package pkg : mPackages.values()) { 668 if (pkg.mLastPackageUsageTimeInMills == 0) { 669 continue; 670 } 671 sb.setLength(0); 672 sb.append(pkg.packageName); 673 sb.append(' '); 674 sb.append((long)pkg.mLastPackageUsageTimeInMills); 675 sb.append('\n'); 676 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 677 } 678 out.flush(); 679 file.finishWrite(f); 680 } catch (IOException e) { 681 if (f != null) { 682 file.failWrite(f); 683 } 684 Log.e(TAG, "Failed to write package usage times", e); 685 } 686 } 687 } 688 mLastWritten.set(SystemClock.elapsedRealtime()); 689 } 690 691 void readLP() { 692 synchronized (mFileLock) { 693 AtomicFile file = getFile(); 694 BufferedInputStream in = null; 695 try { 696 in = new BufferedInputStream(file.openRead()); 697 StringBuffer sb = new StringBuffer(); 698 while (true) { 699 String packageName = readToken(in, sb, ' '); 700 if (packageName == null) { 701 break; 702 } 703 String timeInMillisString = readToken(in, sb, '\n'); 704 if (timeInMillisString == null) { 705 throw new IOException("Failed to find last usage time for package " 706 + packageName); 707 } 708 PackageParser.Package pkg = mPackages.get(packageName); 709 if (pkg == null) { 710 continue; 711 } 712 long timeInMillis; 713 try { 714 timeInMillis = Long.parseLong(timeInMillisString.toString()); 715 } catch (NumberFormatException e) { 716 throw new IOException("Failed to parse " + timeInMillisString 717 + " as a long.", e); 718 } 719 pkg.mLastPackageUsageTimeInMills = timeInMillis; 720 } 721 } catch (FileNotFoundException expected) { 722 mIsHistoricalPackageUsageAvailable = false; 723 } catch (IOException e) { 724 Log.w(TAG, "Failed to read package usage times", e); 725 } finally { 726 IoUtils.closeQuietly(in); 727 } 728 } 729 mLastWritten.set(SystemClock.elapsedRealtime()); 730 } 731 732 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 733 throws IOException { 734 sb.setLength(0); 735 while (true) { 736 int ch = in.read(); 737 if (ch == -1) { 738 if (sb.length() == 0) { 739 return null; 740 } 741 throw new IOException("Unexpected EOF"); 742 } 743 if (ch == endOfToken) { 744 return sb.toString(); 745 } 746 sb.append((char)ch); 747 } 748 } 749 750 private AtomicFile getFile() { 751 File dataDir = Environment.getDataDirectory(); 752 File systemDir = new File(dataDir, "system"); 753 File fname = new File(systemDir, "package-usage.list"); 754 return new AtomicFile(fname); 755 } 756 } 757 758 class PackageHandler extends Handler { 759 private boolean mBound = false; 760 final ArrayList<HandlerParams> mPendingInstalls = 761 new ArrayList<HandlerParams>(); 762 763 private boolean connectToService() { 764 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 765 " DefaultContainerService"); 766 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 767 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 768 if (mContext.bindServiceAsUser(service, mDefContainerConn, 769 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 770 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 771 mBound = true; 772 return true; 773 } 774 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 775 return false; 776 } 777 778 private void disconnectService() { 779 mContainerService = null; 780 mBound = false; 781 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 782 mContext.unbindService(mDefContainerConn); 783 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 784 } 785 786 PackageHandler(Looper looper) { 787 super(looper); 788 } 789 790 public void handleMessage(Message msg) { 791 try { 792 doHandleMessage(msg); 793 } finally { 794 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 795 } 796 } 797 798 void doHandleMessage(Message msg) { 799 switch (msg.what) { 800 case INIT_COPY: { 801 HandlerParams params = (HandlerParams) msg.obj; 802 int idx = mPendingInstalls.size(); 803 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 804 // If a bind was already initiated we dont really 805 // need to do anything. The pending install 806 // will be processed later on. 807 if (!mBound) { 808 // If this is the only one pending we might 809 // have to bind to the service again. 810 if (!connectToService()) { 811 Slog.e(TAG, "Failed to bind to media container service"); 812 params.serviceError(); 813 return; 814 } else { 815 // Once we bind to the service, the first 816 // pending request will be processed. 817 mPendingInstalls.add(idx, params); 818 } 819 } else { 820 mPendingInstalls.add(idx, params); 821 // Already bound to the service. Just make 822 // sure we trigger off processing the first request. 823 if (idx == 0) { 824 mHandler.sendEmptyMessage(MCS_BOUND); 825 } 826 } 827 break; 828 } 829 case MCS_BOUND: { 830 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 831 if (msg.obj != null) { 832 mContainerService = (IMediaContainerService) msg.obj; 833 } 834 if (mContainerService == null) { 835 // Something seriously wrong. Bail out 836 Slog.e(TAG, "Cannot bind to media container service"); 837 for (HandlerParams params : mPendingInstalls) { 838 // Indicate service bind error 839 params.serviceError(); 840 } 841 mPendingInstalls.clear(); 842 } else if (mPendingInstalls.size() > 0) { 843 HandlerParams params = mPendingInstalls.get(0); 844 if (params != null) { 845 if (params.startCopy()) { 846 // We are done... look for more work or to 847 // go idle. 848 if (DEBUG_SD_INSTALL) Log.i(TAG, 849 "Checking for more work or unbind..."); 850 // Delete pending install 851 if (mPendingInstalls.size() > 0) { 852 mPendingInstalls.remove(0); 853 } 854 if (mPendingInstalls.size() == 0) { 855 if (mBound) { 856 if (DEBUG_SD_INSTALL) Log.i(TAG, 857 "Posting delayed MCS_UNBIND"); 858 removeMessages(MCS_UNBIND); 859 Message ubmsg = obtainMessage(MCS_UNBIND); 860 // Unbind after a little delay, to avoid 861 // continual thrashing. 862 sendMessageDelayed(ubmsg, 10000); 863 } 864 } else { 865 // There are more pending requests in queue. 866 // Just post MCS_BOUND message to trigger processing 867 // of next pending install. 868 if (DEBUG_SD_INSTALL) Log.i(TAG, 869 "Posting MCS_BOUND for next work"); 870 mHandler.sendEmptyMessage(MCS_BOUND); 871 } 872 } 873 } 874 } else { 875 // Should never happen ideally. 876 Slog.w(TAG, "Empty queue"); 877 } 878 break; 879 } 880 case MCS_RECONNECT: { 881 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 882 if (mPendingInstalls.size() > 0) { 883 if (mBound) { 884 disconnectService(); 885 } 886 if (!connectToService()) { 887 Slog.e(TAG, "Failed to bind to media container service"); 888 for (HandlerParams params : mPendingInstalls) { 889 // Indicate service bind error 890 params.serviceError(); 891 } 892 mPendingInstalls.clear(); 893 } 894 } 895 break; 896 } 897 case MCS_UNBIND: { 898 // If there is no actual work left, then time to unbind. 899 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 900 901 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 902 if (mBound) { 903 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 904 905 disconnectService(); 906 } 907 } else if (mPendingInstalls.size() > 0) { 908 // There are more pending requests in queue. 909 // Just post MCS_BOUND message to trigger processing 910 // of next pending install. 911 mHandler.sendEmptyMessage(MCS_BOUND); 912 } 913 914 break; 915 } 916 case MCS_GIVE_UP: { 917 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 918 mPendingInstalls.remove(0); 919 break; 920 } 921 case SEND_PENDING_BROADCAST: { 922 String packages[]; 923 ArrayList<String> components[]; 924 int size = 0; 925 int uids[]; 926 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 927 synchronized (mPackages) { 928 if (mPendingBroadcasts == null) { 929 return; 930 } 931 size = mPendingBroadcasts.size(); 932 if (size <= 0) { 933 // Nothing to be done. Just return 934 return; 935 } 936 packages = new String[size]; 937 components = new ArrayList[size]; 938 uids = new int[size]; 939 int i = 0; // filling out the above arrays 940 941 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 942 int packageUserId = mPendingBroadcasts.userIdAt(n); 943 Iterator<Map.Entry<String, ArrayList<String>>> it 944 = mPendingBroadcasts.packagesForUserId(packageUserId) 945 .entrySet().iterator(); 946 while (it.hasNext() && i < size) { 947 Map.Entry<String, ArrayList<String>> ent = it.next(); 948 packages[i] = ent.getKey(); 949 components[i] = ent.getValue(); 950 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 951 uids[i] = (ps != null) 952 ? UserHandle.getUid(packageUserId, ps.appId) 953 : -1; 954 i++; 955 } 956 } 957 size = i; 958 mPendingBroadcasts.clear(); 959 } 960 // Send broadcasts 961 for (int i = 0; i < size; i++) { 962 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 963 } 964 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 965 break; 966 } 967 case START_CLEANING_PACKAGE: { 968 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 969 final String packageName = (String)msg.obj; 970 final int userId = msg.arg1; 971 final boolean andCode = msg.arg2 != 0; 972 synchronized (mPackages) { 973 if (userId == UserHandle.USER_ALL) { 974 int[] users = sUserManager.getUserIds(); 975 for (int user : users) { 976 mSettings.addPackageToCleanLPw( 977 new PackageCleanItem(user, packageName, andCode)); 978 } 979 } else { 980 mSettings.addPackageToCleanLPw( 981 new PackageCleanItem(userId, packageName, andCode)); 982 } 983 } 984 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 985 startCleaningPackages(); 986 } break; 987 case POST_INSTALL: { 988 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 989 PostInstallData data = mRunningInstalls.get(msg.arg1); 990 mRunningInstalls.delete(msg.arg1); 991 boolean deleteOld = false; 992 993 if (data != null) { 994 InstallArgs args = data.args; 995 PackageInstalledInfo res = data.res; 996 997 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 998 res.removedInfo.sendBroadcast(false, true, false); 999 Bundle extras = new Bundle(1); 1000 extras.putInt(Intent.EXTRA_UID, res.uid); 1001 // Determine the set of users who are adding this 1002 // package for the first time vs. those who are seeing 1003 // an update. 1004 int[] firstUsers; 1005 int[] updateUsers = new int[0]; 1006 if (res.origUsers == null || res.origUsers.length == 0) { 1007 firstUsers = res.newUsers; 1008 } else { 1009 firstUsers = new int[0]; 1010 for (int i=0; i<res.newUsers.length; i++) { 1011 int user = res.newUsers[i]; 1012 boolean isNew = true; 1013 for (int j=0; j<res.origUsers.length; j++) { 1014 if (res.origUsers[j] == user) { 1015 isNew = false; 1016 break; 1017 } 1018 } 1019 if (isNew) { 1020 int[] newFirst = new int[firstUsers.length+1]; 1021 System.arraycopy(firstUsers, 0, newFirst, 0, 1022 firstUsers.length); 1023 newFirst[firstUsers.length] = user; 1024 firstUsers = newFirst; 1025 } else { 1026 int[] newUpdate = new int[updateUsers.length+1]; 1027 System.arraycopy(updateUsers, 0, newUpdate, 0, 1028 updateUsers.length); 1029 newUpdate[updateUsers.length] = user; 1030 updateUsers = newUpdate; 1031 } 1032 } 1033 } 1034 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1035 res.pkg.applicationInfo.packageName, 1036 extras, null, null, firstUsers); 1037 final boolean update = res.removedInfo.removedPackage != null; 1038 if (update) { 1039 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1040 } 1041 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1042 res.pkg.applicationInfo.packageName, 1043 extras, null, null, updateUsers); 1044 if (update) { 1045 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1046 res.pkg.applicationInfo.packageName, 1047 extras, null, null, updateUsers); 1048 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1049 null, null, 1050 res.pkg.applicationInfo.packageName, null, updateUsers); 1051 1052 // treat asec-hosted packages like removable media on upgrade 1053 if (isForwardLocked(res.pkg) || isExternal(res.pkg)) { 1054 if (DEBUG_INSTALL) { 1055 Slog.i(TAG, "upgrading pkg " + res.pkg 1056 + " is ASEC-hosted -> AVAILABLE"); 1057 } 1058 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1059 ArrayList<String> pkgList = new ArrayList<String>(1); 1060 pkgList.add(res.pkg.applicationInfo.packageName); 1061 sendResourcesChangedBroadcast(true, true, 1062 pkgList,uidArray, null); 1063 } 1064 } 1065 if (res.removedInfo.args != null) { 1066 // Remove the replaced package's older resources safely now 1067 deleteOld = true; 1068 } 1069 1070 // Log current value of "unknown sources" setting 1071 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1072 getUnknownSourcesSettings()); 1073 } 1074 // Force a gc to clear up things 1075 Runtime.getRuntime().gc(); 1076 // We delete after a gc for applications on sdcard. 1077 if (deleteOld) { 1078 synchronized (mInstallLock) { 1079 res.removedInfo.args.doPostDeleteLI(true); 1080 } 1081 } 1082 if (args.observer != null) { 1083 try { 1084 Bundle extras = extrasForInstallResult(res); 1085 args.observer.onPackageInstalled(res.name, res.returnCode, 1086 res.returnMsg, extras); 1087 } catch (RemoteException e) { 1088 Slog.i(TAG, "Observer no longer exists."); 1089 } 1090 } 1091 } else { 1092 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1093 } 1094 } break; 1095 case UPDATED_MEDIA_STATUS: { 1096 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1097 boolean reportStatus = msg.arg1 == 1; 1098 boolean doGc = msg.arg2 == 1; 1099 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1100 if (doGc) { 1101 // Force a gc to clear up stale containers. 1102 Runtime.getRuntime().gc(); 1103 } 1104 if (msg.obj != null) { 1105 @SuppressWarnings("unchecked") 1106 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1107 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1108 // Unload containers 1109 unloadAllContainers(args); 1110 } 1111 if (reportStatus) { 1112 try { 1113 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1114 PackageHelper.getMountService().finishMediaUpdate(); 1115 } catch (RemoteException e) { 1116 Log.e(TAG, "MountService not running?"); 1117 } 1118 } 1119 } break; 1120 case WRITE_SETTINGS: { 1121 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1122 synchronized (mPackages) { 1123 removeMessages(WRITE_SETTINGS); 1124 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1125 mSettings.writeLPr(); 1126 mDirtyUsers.clear(); 1127 } 1128 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1129 } break; 1130 case WRITE_PACKAGE_RESTRICTIONS: { 1131 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1132 synchronized (mPackages) { 1133 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1134 for (int userId : mDirtyUsers) { 1135 mSettings.writePackageRestrictionsLPr(userId); 1136 } 1137 mDirtyUsers.clear(); 1138 } 1139 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1140 } break; 1141 case CHECK_PENDING_VERIFICATION: { 1142 final int verificationId = msg.arg1; 1143 final PackageVerificationState state = mPendingVerification.get(verificationId); 1144 1145 if ((state != null) && !state.timeoutExtended()) { 1146 final InstallArgs args = state.getInstallArgs(); 1147 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1148 1149 Slog.i(TAG, "Verification timed out for " + originUri); 1150 mPendingVerification.remove(verificationId); 1151 1152 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1153 1154 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1155 Slog.i(TAG, "Continuing with installation of " + originUri); 1156 state.setVerifierResponse(Binder.getCallingUid(), 1157 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1158 broadcastPackageVerified(verificationId, originUri, 1159 PackageManager.VERIFICATION_ALLOW, 1160 state.getInstallArgs().getUser()); 1161 try { 1162 ret = args.copyApk(mContainerService, true); 1163 } catch (RemoteException e) { 1164 Slog.e(TAG, "Could not contact the ContainerService"); 1165 } 1166 } else { 1167 broadcastPackageVerified(verificationId, originUri, 1168 PackageManager.VERIFICATION_REJECT, 1169 state.getInstallArgs().getUser()); 1170 } 1171 1172 processPendingInstall(args, ret); 1173 mHandler.sendEmptyMessage(MCS_UNBIND); 1174 } 1175 break; 1176 } 1177 case PACKAGE_VERIFIED: { 1178 final int verificationId = msg.arg1; 1179 1180 final PackageVerificationState state = mPendingVerification.get(verificationId); 1181 if (state == null) { 1182 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1183 break; 1184 } 1185 1186 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1187 1188 state.setVerifierResponse(response.callerUid, response.code); 1189 1190 if (state.isVerificationComplete()) { 1191 mPendingVerification.remove(verificationId); 1192 1193 final InstallArgs args = state.getInstallArgs(); 1194 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1195 1196 int ret; 1197 if (state.isInstallAllowed()) { 1198 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1199 broadcastPackageVerified(verificationId, originUri, 1200 response.code, state.getInstallArgs().getUser()); 1201 try { 1202 ret = args.copyApk(mContainerService, true); 1203 } catch (RemoteException e) { 1204 Slog.e(TAG, "Could not contact the ContainerService"); 1205 } 1206 } else { 1207 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1208 } 1209 1210 processPendingInstall(args, ret); 1211 1212 mHandler.sendEmptyMessage(MCS_UNBIND); 1213 } 1214 1215 break; 1216 } 1217 } 1218 } 1219 } 1220 1221 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1222 Bundle extras = null; 1223 switch (res.returnCode) { 1224 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1225 extras = new Bundle(); 1226 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1227 res.origPermission); 1228 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1229 res.origPackage); 1230 break; 1231 } 1232 } 1233 return extras; 1234 } 1235 1236 void scheduleWriteSettingsLocked() { 1237 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1238 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1239 } 1240 } 1241 1242 void scheduleWritePackageRestrictionsLocked(int userId) { 1243 if (!sUserManager.exists(userId)) return; 1244 mDirtyUsers.add(userId); 1245 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1246 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1247 } 1248 } 1249 1250 public static final PackageManagerService main(Context context, Installer installer, 1251 boolean factoryTest, boolean onlyCore) { 1252 PackageManagerService m = new PackageManagerService(context, installer, 1253 factoryTest, onlyCore); 1254 ServiceManager.addService("package", m); 1255 return m; 1256 } 1257 1258 static String[] splitString(String str, char sep) { 1259 int count = 1; 1260 int i = 0; 1261 while ((i=str.indexOf(sep, i)) >= 0) { 1262 count++; 1263 i++; 1264 } 1265 1266 String[] res = new String[count]; 1267 i=0; 1268 count = 0; 1269 int lastI=0; 1270 while ((i=str.indexOf(sep, i)) >= 0) { 1271 res[count] = str.substring(lastI, i); 1272 count++; 1273 i++; 1274 lastI = i; 1275 } 1276 res[count] = str.substring(lastI, str.length()); 1277 return res; 1278 } 1279 1280 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1281 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1282 Context.DISPLAY_SERVICE); 1283 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1284 } 1285 1286 public PackageManagerService(Context context, Installer installer, 1287 boolean factoryTest, boolean onlyCore) { 1288 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1289 SystemClock.uptimeMillis()); 1290 1291 if (mSdkVersion <= 0) { 1292 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1293 } 1294 1295 mContext = context; 1296 mFactoryTest = factoryTest; 1297 mOnlyCore = onlyCore; 1298 mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type")); 1299 mMetrics = new DisplayMetrics(); 1300 mSettings = new Settings(context); 1301 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1302 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1303 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1304 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1305 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1306 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1307 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1308 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1309 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1310 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1311 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1312 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1313 1314 // TODO: add a property to control this? 1315 long dexOptLRUThresholdInMinutes; 1316 if (mLazyDexOpt) { 1317 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 1318 } else { 1319 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 1320 } 1321 mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 1322 1323 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1324 if (separateProcesses != null && separateProcesses.length() > 0) { 1325 if ("*".equals(separateProcesses)) { 1326 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1327 mSeparateProcesses = null; 1328 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1329 } else { 1330 mDefParseFlags = 0; 1331 mSeparateProcesses = separateProcesses.split(","); 1332 Slog.w(TAG, "Running with debug.separate_processes: " 1333 + separateProcesses); 1334 } 1335 } else { 1336 mDefParseFlags = 0; 1337 mSeparateProcesses = null; 1338 } 1339 1340 mInstaller = installer; 1341 1342 getDefaultDisplayMetrics(context, mMetrics); 1343 1344 SystemConfig systemConfig = SystemConfig.getInstance(); 1345 mGlobalGids = systemConfig.getGlobalGids(); 1346 mSystemPermissions = systemConfig.getSystemPermissions(); 1347 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1348 1349 synchronized (mInstallLock) { 1350 // writer 1351 synchronized (mPackages) { 1352 mHandlerThread = new ServiceThread(TAG, 1353 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1354 mHandlerThread.start(); 1355 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1356 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1357 1358 File dataDir = Environment.getDataDirectory(); 1359 mAppDataDir = new File(dataDir, "data"); 1360 mAppInstallDir = new File(dataDir, "app"); 1361 mAppLib32InstallDir = new File(dataDir, "app-lib"); 1362 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1363 mUserAppDataDir = new File(dataDir, "user"); 1364 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1365 1366 sUserManager = new UserManagerService(context, this, 1367 mInstallLock, mPackages); 1368 1369 // Propagate permission configuration in to package manager. 1370 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 1371 = systemConfig.getPermissions(); 1372 for (int i=0; i<permConfig.size(); i++) { 1373 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 1374 BasePermission bp = mSettings.mPermissions.get(perm.name); 1375 if (bp == null) { 1376 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 1377 mSettings.mPermissions.put(perm.name, bp); 1378 } 1379 if (perm.gids != null) { 1380 bp.gids = appendInts(bp.gids, perm.gids); 1381 } 1382 } 1383 1384 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 1385 for (int i=0; i<libConfig.size(); i++) { 1386 mSharedLibraries.put(libConfig.keyAt(i), 1387 new SharedLibraryEntry(libConfig.valueAt(i), null)); 1388 } 1389 1390 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1391 1392 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1393 mSdkVersion, mOnlyCore); 1394 1395 String customResolverActivity = Resources.getSystem().getString( 1396 R.string.config_customResolverActivity); 1397 if (TextUtils.isEmpty(customResolverActivity)) { 1398 customResolverActivity = null; 1399 } else { 1400 mCustomResolverComponentName = ComponentName.unflattenFromString( 1401 customResolverActivity); 1402 } 1403 1404 long startTime = SystemClock.uptimeMillis(); 1405 1406 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1407 startTime); 1408 1409 // Set flag to monitor and not change apk file paths when 1410 // scanning install directories. 1411 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1412 1413 final ArraySet<String> alreadyDexOpted = new ArraySet<String>(); 1414 1415 /** 1416 * Add everything in the in the boot class path to the 1417 * list of process files because dexopt will have been run 1418 * if necessary during zygote startup. 1419 */ 1420 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 1421 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 1422 1423 if (bootClassPath != null) { 1424 String[] bootClassPathElements = splitString(bootClassPath, ':'); 1425 for (String element : bootClassPathElements) { 1426 alreadyDexOpted.add(element); 1427 } 1428 } else { 1429 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1430 } 1431 1432 if (systemServerClassPath != null) { 1433 String[] systemServerClassPathElements = splitString(systemServerClassPath, ':'); 1434 for (String element : systemServerClassPathElements) { 1435 alreadyDexOpted.add(element); 1436 } 1437 } else { 1438 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 1439 } 1440 1441 final List<String> allInstructionSets = getAllInstructionSets(); 1442 final String[] dexCodeInstructionSets = 1443 getDexCodeInstructionSets(allInstructionSets.toArray(new String[allInstructionSets.size()])); 1444 1445 /** 1446 * Ensure all external libraries have had dexopt run on them. 1447 */ 1448 if (mSharedLibraries.size() > 0) { 1449 // NOTE: For now, we're compiling these system "shared libraries" 1450 // (and framework jars) into all available architectures. It's possible 1451 // to compile them only when we come across an app that uses them (there's 1452 // already logic for that in scanPackageLI) but that adds some complexity. 1453 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1454 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1455 final String lib = libEntry.path; 1456 if (lib == null) { 1457 continue; 1458 } 1459 1460 try { 1461 byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null, 1462 dexCodeInstructionSet, 1463 false); 1464 if (dexoptRequired != DexFile.UP_TO_DATE) { 1465 alreadyDexOpted.add(lib); 1466 1467 // The list of "shared libraries" we have at this point is 1468 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1469 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1470 } else { 1471 mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1472 } 1473 } 1474 } catch (FileNotFoundException e) { 1475 Slog.w(TAG, "Library not found: " + lib); 1476 } catch (IOException e) { 1477 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1478 + e.getMessage()); 1479 } 1480 } 1481 } 1482 } 1483 1484 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1485 1486 // Gross hack for now: we know this file doesn't contain any 1487 // code, so don't dexopt it to avoid the resulting log spew. 1488 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1489 1490 // Gross hack for now: we know this file is only part of 1491 // the boot class path for art, so don't dexopt it to 1492 // avoid the resulting log spew. 1493 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1494 1495 /** 1496 * And there are a number of commands implemented in Java, which 1497 * we currently need to do the dexopt on so that they can be 1498 * run from a non-root shell. 1499 */ 1500 String[] frameworkFiles = frameworkDir.list(); 1501 if (frameworkFiles != null) { 1502 // TODO: We could compile these only for the most preferred ABI. We should 1503 // first double check that the dex files for these commands are not referenced 1504 // by other system apps. 1505 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 1506 for (int i=0; i<frameworkFiles.length; i++) { 1507 File libPath = new File(frameworkDir, frameworkFiles[i]); 1508 String path = libPath.getPath(); 1509 // Skip the file if we already did it. 1510 if (alreadyDexOpted.contains(path)) { 1511 continue; 1512 } 1513 // Skip the file if it is not a type we want to dexopt. 1514 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1515 continue; 1516 } 1517 try { 1518 byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null, 1519 dexCodeInstructionSet, 1520 false); 1521 if (dexoptRequired == DexFile.DEXOPT_NEEDED) { 1522 mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1523 } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) { 1524 mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet); 1525 } 1526 } catch (FileNotFoundException e) { 1527 Slog.w(TAG, "Jar not found: " + path); 1528 } catch (IOException e) { 1529 Slog.w(TAG, "Exception reading jar: " + path, e); 1530 } 1531 } 1532 } 1533 } 1534 1535 // Collect vendor overlay packages. 1536 // (Do this before scanning any apps.) 1537 // For security and version matching reason, only consider 1538 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1539 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1540 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1541 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 1542 1543 // Find base frameworks (resource packages without code). 1544 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1545 | PackageParser.PARSE_IS_SYSTEM_DIR 1546 | PackageParser.PARSE_IS_PRIVILEGED, 1547 scanFlags | SCAN_NO_DEX, 0); 1548 1549 // Collected privileged system packages. 1550 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1551 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1552 | PackageParser.PARSE_IS_SYSTEM_DIR 1553 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 1554 1555 // Collect ordinary system packages. 1556 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1557 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1558 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1559 1560 // Collect all vendor packages. 1561 File vendorAppDir = new File("/vendor/app"); 1562 try { 1563 vendorAppDir = vendorAppDir.getCanonicalFile(); 1564 } catch (IOException e) { 1565 // failed to look up canonical path, continue with original one 1566 } 1567 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1568 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1569 1570 // Collect all OEM packages. 1571 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 1572 scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 1573 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 1574 1575 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1576 mInstaller.moveFiles(); 1577 1578 // Prune any system packages that no longer exist. 1579 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1580 final ArrayMap<String, File> expectingBetter = new ArrayMap<>(); 1581 if (!mOnlyCore) { 1582 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1583 while (psit.hasNext()) { 1584 PackageSetting ps = psit.next(); 1585 1586 /* 1587 * If this is not a system app, it can't be a 1588 * disable system app. 1589 */ 1590 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1591 continue; 1592 } 1593 1594 /* 1595 * If the package is scanned, it's not erased. 1596 */ 1597 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1598 if (scannedPkg != null) { 1599 /* 1600 * If the system app is both scanned and in the 1601 * disabled packages list, then it must have been 1602 * added via OTA. Remove it from the currently 1603 * scanned package so the previously user-installed 1604 * application can be scanned. 1605 */ 1606 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1607 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 1608 + ps.name + "; removing system app. Last known codePath=" 1609 + ps.codePathString + ", installStatus=" + ps.installStatus 1610 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 1611 + scannedPkg.mVersionCode); 1612 removePackageLI(ps, true); 1613 expectingBetter.put(ps.name, ps.codePath); 1614 } 1615 1616 continue; 1617 } 1618 1619 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1620 psit.remove(); 1621 logCriticalInfo(Log.WARN, "System package " + ps.name 1622 + " no longer exists; wiping its data"); 1623 removeDataDirsLI(ps.name); 1624 } else { 1625 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1626 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1627 possiblyDeletedUpdatedSystemApps.add(ps.name); 1628 } 1629 } 1630 } 1631 } 1632 1633 //look for any incomplete package installations 1634 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1635 //clean up list 1636 for(int i = 0; i < deletePkgsList.size(); i++) { 1637 //clean up here 1638 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1639 } 1640 //delete tmp files 1641 deleteTempPackageFiles(); 1642 1643 // Remove any shared userIDs that have no associated packages 1644 mSettings.pruneSharedUsersLPw(); 1645 1646 if (!mOnlyCore) { 1647 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 1648 SystemClock.uptimeMillis()); 1649 scanDirLI(mAppInstallDir, 0, scanFlags, 0); 1650 1651 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 1652 scanFlags, 0); 1653 1654 /** 1655 * Remove disable package settings for any updated system 1656 * apps that were removed via an OTA. If they're not a 1657 * previously-updated app, remove them completely. 1658 * Otherwise, just revoke their system-level permissions. 1659 */ 1660 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 1661 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 1662 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 1663 1664 String msg; 1665 if (deletedPkg == null) { 1666 msg = "Updated system package " + deletedAppName 1667 + " no longer exists; wiping its data"; 1668 removeDataDirsLI(deletedAppName); 1669 } else { 1670 msg = "Updated system app + " + deletedAppName 1671 + " no longer present; removing system privileges for " 1672 + deletedAppName; 1673 1674 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 1675 1676 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 1677 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 1678 } 1679 logCriticalInfo(Log.WARN, msg); 1680 } 1681 1682 /** 1683 * Make sure all system apps that we expected to appear on 1684 * the userdata partition actually showed up. If they never 1685 * appeared, crawl back and revive the system version. 1686 */ 1687 for (int i = 0; i < expectingBetter.size(); i++) { 1688 final String packageName = expectingBetter.keyAt(i); 1689 if (!mPackages.containsKey(packageName)) { 1690 final File scanFile = expectingBetter.valueAt(i); 1691 1692 logCriticalInfo(Log.WARN, "Expected better " + packageName 1693 + " but never showed up; reverting to system"); 1694 1695 final int reparseFlags; 1696 if (FileUtils.contains(privilegedAppDir, scanFile)) { 1697 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1698 | PackageParser.PARSE_IS_SYSTEM_DIR 1699 | PackageParser.PARSE_IS_PRIVILEGED; 1700 } else if (FileUtils.contains(systemAppDir, scanFile)) { 1701 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1702 | PackageParser.PARSE_IS_SYSTEM_DIR; 1703 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 1704 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1705 | PackageParser.PARSE_IS_SYSTEM_DIR; 1706 } else if (FileUtils.contains(oemAppDir, scanFile)) { 1707 reparseFlags = PackageParser.PARSE_IS_SYSTEM 1708 | PackageParser.PARSE_IS_SYSTEM_DIR; 1709 } else { 1710 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 1711 continue; 1712 } 1713 1714 mSettings.enableSystemPackageLPw(packageName); 1715 1716 try { 1717 scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null); 1718 } catch (PackageManagerException e) { 1719 Slog.e(TAG, "Failed to parse original system package: " 1720 + e.getMessage()); 1721 } 1722 } 1723 } 1724 } 1725 1726 // Now that we know all of the shared libraries, update all clients to have 1727 // the correct library paths. 1728 updateAllSharedLibrariesLPw(); 1729 1730 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 1731 // NOTE: We ignore potential failures here during a system scan (like 1732 // the rest of the commands above) because there's precious little we 1733 // can do about it. A settings error is reported, though. 1734 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 1735 false /* force dexopt */, false /* defer dexopt */); 1736 } 1737 1738 // Now that we know all the packages we are keeping, 1739 // read and update their last usage times. 1740 mPackageUsage.readLP(); 1741 1742 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 1743 SystemClock.uptimeMillis()); 1744 Slog.i(TAG, "Time to scan packages: " 1745 + ((SystemClock.uptimeMillis()-startTime)/1000f) 1746 + " seconds"); 1747 1748 // If the platform SDK has changed since the last time we booted, 1749 // we need to re-grant app permission to catch any new ones that 1750 // appear. This is really a hack, and means that apps can in some 1751 // cases get permissions that the user didn't initially explicitly 1752 // allow... it would be nice to have some better way to handle 1753 // this situation. 1754 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 1755 != mSdkVersion; 1756 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 1757 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 1758 + "; regranting permissions for internal storage"); 1759 mSettings.mInternalSdkPlatform = mSdkVersion; 1760 1761 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 1762 | (regrantPermissions 1763 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 1764 : 0)); 1765 1766 // If this is the first boot, and it is a normal boot, then 1767 // we need to initialize the default preferred apps. 1768 if (!mRestoredSettings && !onlyCore) { 1769 mSettings.readDefaultPreferredAppsLPw(this, 0); 1770 } 1771 1772 // If this is first boot after an OTA, and a normal boot, then 1773 // we need to clear code cache directories. 1774 mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint); 1775 if (mIsUpgrade && !onlyCore) { 1776 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 1777 for (String pkgName : mSettings.mPackages.keySet()) { 1778 deleteCodeCacheDirsLI(pkgName); 1779 } 1780 mSettings.mFingerprint = Build.FINGERPRINT; 1781 } 1782 1783 // All the changes are done during package scanning. 1784 mSettings.updateInternalDatabaseVersion(); 1785 1786 // can downgrade to reader 1787 mSettings.writeLPr(); 1788 1789 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 1790 SystemClock.uptimeMillis()); 1791 1792 1793 mRequiredVerifierPackage = getRequiredVerifierLPr(); 1794 } // synchronized (mPackages) 1795 } // synchronized (mInstallLock) 1796 1797 mInstallerService = new PackageInstallerService(context, this, mAppInstallDir); 1798 1799 // Now after opening every single application zip, make sure they 1800 // are all flushed. Not really needed, but keeps things nice and 1801 // tidy. 1802 Runtime.getRuntime().gc(); 1803 } 1804 1805 @Override 1806 public boolean isFirstBoot() { 1807 return !mRestoredSettings; 1808 } 1809 1810 @Override 1811 public boolean isOnlyCoreApps() { 1812 return mOnlyCore; 1813 } 1814 1815 @Override 1816 public boolean isUpgrade() { 1817 return mIsUpgrade; 1818 } 1819 1820 private String getRequiredVerifierLPr() { 1821 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 1822 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 1823 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 1824 1825 String requiredVerifier = null; 1826 1827 final int N = receivers.size(); 1828 for (int i = 0; i < N; i++) { 1829 final ResolveInfo info = receivers.get(i); 1830 1831 if (info.activityInfo == null) { 1832 continue; 1833 } 1834 1835 final String packageName = info.activityInfo.packageName; 1836 1837 final PackageSetting ps = mSettings.mPackages.get(packageName); 1838 if (ps == null) { 1839 continue; 1840 } 1841 1842 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1843 if (!gp.grantedPermissions 1844 .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) { 1845 continue; 1846 } 1847 1848 if (requiredVerifier != null) { 1849 throw new RuntimeException("There can be only one required verifier"); 1850 } 1851 1852 requiredVerifier = packageName; 1853 } 1854 1855 return requiredVerifier; 1856 } 1857 1858 @Override 1859 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 1860 throws RemoteException { 1861 try { 1862 return super.onTransact(code, data, reply, flags); 1863 } catch (RuntimeException e) { 1864 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 1865 Slog.wtf(TAG, "Package Manager Crash", e); 1866 } 1867 throw e; 1868 } 1869 } 1870 1871 void cleanupInstallFailedPackage(PackageSetting ps) { 1872 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name); 1873 1874 removeDataDirsLI(ps.name); 1875 if (ps.codePath != null) { 1876 if (ps.codePath.isDirectory()) { 1877 FileUtils.deleteContents(ps.codePath); 1878 } 1879 ps.codePath.delete(); 1880 } 1881 if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) { 1882 if (ps.resourcePath.isDirectory()) { 1883 FileUtils.deleteContents(ps.resourcePath); 1884 } 1885 ps.resourcePath.delete(); 1886 } 1887 mSettings.removePackageLPw(ps.name); 1888 } 1889 1890 static int[] appendInts(int[] cur, int[] add) { 1891 if (add == null) return cur; 1892 if (cur == null) return add; 1893 final int N = add.length; 1894 for (int i=0; i<N; i++) { 1895 cur = appendInt(cur, add[i]); 1896 } 1897 return cur; 1898 } 1899 1900 static int[] removeInts(int[] cur, int[] rem) { 1901 if (rem == null) return cur; 1902 if (cur == null) return cur; 1903 final int N = rem.length; 1904 for (int i=0; i<N; i++) { 1905 cur = removeInt(cur, rem[i]); 1906 } 1907 return cur; 1908 } 1909 1910 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 1911 if (!sUserManager.exists(userId)) return null; 1912 final PackageSetting ps = (PackageSetting) p.mExtras; 1913 if (ps == null) { 1914 return null; 1915 } 1916 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1917 final PackageUserState state = ps.readUserState(userId); 1918 return PackageParser.generatePackageInfo(p, gp.gids, flags, 1919 ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions, 1920 state, userId); 1921 } 1922 1923 @Override 1924 public boolean isPackageAvailable(String packageName, int userId) { 1925 if (!sUserManager.exists(userId)) return false; 1926 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available"); 1927 synchronized (mPackages) { 1928 PackageParser.Package p = mPackages.get(packageName); 1929 if (p != null) { 1930 final PackageSetting ps = (PackageSetting) p.mExtras; 1931 if (ps != null) { 1932 final PackageUserState state = ps.readUserState(userId); 1933 if (state != null) { 1934 return PackageParser.isAvailable(state); 1935 } 1936 } 1937 } 1938 } 1939 return false; 1940 } 1941 1942 @Override 1943 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 1944 if (!sUserManager.exists(userId)) return null; 1945 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info"); 1946 // reader 1947 synchronized (mPackages) { 1948 PackageParser.Package p = mPackages.get(packageName); 1949 if (DEBUG_PACKAGE_INFO) 1950 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 1951 if (p != null) { 1952 return generatePackageInfo(p, flags, userId); 1953 } 1954 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 1955 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 1956 } 1957 } 1958 return null; 1959 } 1960 1961 @Override 1962 public String[] currentToCanonicalPackageNames(String[] names) { 1963 String[] out = new String[names.length]; 1964 // reader 1965 synchronized (mPackages) { 1966 for (int i=names.length-1; i>=0; i--) { 1967 PackageSetting ps = mSettings.mPackages.get(names[i]); 1968 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 1969 } 1970 } 1971 return out; 1972 } 1973 1974 @Override 1975 public String[] canonicalToCurrentPackageNames(String[] names) { 1976 String[] out = new String[names.length]; 1977 // reader 1978 synchronized (mPackages) { 1979 for (int i=names.length-1; i>=0; i--) { 1980 String cur = mSettings.mRenamedPackages.get(names[i]); 1981 out[i] = cur != null ? cur : names[i]; 1982 } 1983 } 1984 return out; 1985 } 1986 1987 @Override 1988 public int getPackageUid(String packageName, int userId) { 1989 if (!sUserManager.exists(userId)) return -1; 1990 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid"); 1991 // reader 1992 synchronized (mPackages) { 1993 PackageParser.Package p = mPackages.get(packageName); 1994 if(p != null) { 1995 return UserHandle.getUid(userId, p.applicationInfo.uid); 1996 } 1997 PackageSetting ps = mSettings.mPackages.get(packageName); 1998 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 1999 return -1; 2000 } 2001 p = ps.pkg; 2002 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2003 } 2004 } 2005 2006 @Override 2007 public int[] getPackageGids(String packageName) { 2008 // reader 2009 synchronized (mPackages) { 2010 PackageParser.Package p = mPackages.get(packageName); 2011 if (DEBUG_PACKAGE_INFO) 2012 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2013 if (p != null) { 2014 final PackageSetting ps = (PackageSetting)p.mExtras; 2015 return ps.getGids(); 2016 } 2017 } 2018 // stupid thing to indicate an error. 2019 return new int[0]; 2020 } 2021 2022 static final PermissionInfo generatePermissionInfo( 2023 BasePermission bp, int flags) { 2024 if (bp.perm != null) { 2025 return PackageParser.generatePermissionInfo(bp.perm, flags); 2026 } 2027 PermissionInfo pi = new PermissionInfo(); 2028 pi.name = bp.name; 2029 pi.packageName = bp.sourcePackage; 2030 pi.nonLocalizedLabel = bp.name; 2031 pi.protectionLevel = bp.protectionLevel; 2032 return pi; 2033 } 2034 2035 @Override 2036 public PermissionInfo getPermissionInfo(String name, int flags) { 2037 // reader 2038 synchronized (mPackages) { 2039 final BasePermission p = mSettings.mPermissions.get(name); 2040 if (p != null) { 2041 return generatePermissionInfo(p, flags); 2042 } 2043 return null; 2044 } 2045 } 2046 2047 @Override 2048 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2049 // reader 2050 synchronized (mPackages) { 2051 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2052 for (BasePermission p : mSettings.mPermissions.values()) { 2053 if (group == null) { 2054 if (p.perm == null || p.perm.info.group == null) { 2055 out.add(generatePermissionInfo(p, flags)); 2056 } 2057 } else { 2058 if (p.perm != null && group.equals(p.perm.info.group)) { 2059 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2060 } 2061 } 2062 } 2063 2064 if (out.size() > 0) { 2065 return out; 2066 } 2067 return mPermissionGroups.containsKey(group) ? out : null; 2068 } 2069 } 2070 2071 @Override 2072 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2073 // reader 2074 synchronized (mPackages) { 2075 return PackageParser.generatePermissionGroupInfo( 2076 mPermissionGroups.get(name), flags); 2077 } 2078 } 2079 2080 @Override 2081 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2082 // reader 2083 synchronized (mPackages) { 2084 final int N = mPermissionGroups.size(); 2085 ArrayList<PermissionGroupInfo> out 2086 = new ArrayList<PermissionGroupInfo>(N); 2087 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2088 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2089 } 2090 return out; 2091 } 2092 } 2093 2094 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2095 int userId) { 2096 if (!sUserManager.exists(userId)) return null; 2097 PackageSetting ps = mSettings.mPackages.get(packageName); 2098 if (ps != null) { 2099 if (ps.pkg == null) { 2100 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2101 flags, userId); 2102 if (pInfo != null) { 2103 return pInfo.applicationInfo; 2104 } 2105 return null; 2106 } 2107 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2108 ps.readUserState(userId), userId); 2109 } 2110 return null; 2111 } 2112 2113 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2114 int userId) { 2115 if (!sUserManager.exists(userId)) return null; 2116 PackageSetting ps = mSettings.mPackages.get(packageName); 2117 if (ps != null) { 2118 PackageParser.Package pkg = ps.pkg; 2119 if (pkg == null) { 2120 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2121 return null; 2122 } 2123 // Only data remains, so we aren't worried about code paths 2124 pkg = new PackageParser.Package(packageName); 2125 pkg.applicationInfo.packageName = packageName; 2126 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2127 pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags; 2128 pkg.applicationInfo.dataDir = 2129 getDataPathForPackage(packageName, 0).getPath(); 2130 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2131 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2132 } 2133 return generatePackageInfo(pkg, flags, userId); 2134 } 2135 return null; 2136 } 2137 2138 @Override 2139 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2140 if (!sUserManager.exists(userId)) return null; 2141 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2142 // writer 2143 synchronized (mPackages) { 2144 PackageParser.Package p = mPackages.get(packageName); 2145 if (DEBUG_PACKAGE_INFO) Log.v( 2146 TAG, "getApplicationInfo " + packageName 2147 + ": " + p); 2148 if (p != null) { 2149 PackageSetting ps = mSettings.mPackages.get(packageName); 2150 if (ps == null) return null; 2151 // Note: isEnabledLP() does not apply here - always return info 2152 return PackageParser.generateApplicationInfo( 2153 p, flags, ps.readUserState(userId), userId); 2154 } 2155 if ("android".equals(packageName)||"system".equals(packageName)) { 2156 return mAndroidApplication; 2157 } 2158 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2159 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2160 } 2161 } 2162 return null; 2163 } 2164 2165 2166 @Override 2167 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2168 mContext.enforceCallingOrSelfPermission( 2169 android.Manifest.permission.CLEAR_APP_CACHE, null); 2170 // Queue up an async operation since clearing cache may take a little while. 2171 mHandler.post(new Runnable() { 2172 public void run() { 2173 mHandler.removeCallbacks(this); 2174 int retCode = -1; 2175 synchronized (mInstallLock) { 2176 retCode = mInstaller.freeCache(freeStorageSize); 2177 if (retCode < 0) { 2178 Slog.w(TAG, "Couldn't clear application caches"); 2179 } 2180 } 2181 if (observer != null) { 2182 try { 2183 observer.onRemoveCompleted(null, (retCode >= 0)); 2184 } catch (RemoteException e) { 2185 Slog.w(TAG, "RemoveException when invoking call back"); 2186 } 2187 } 2188 } 2189 }); 2190 } 2191 2192 @Override 2193 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2194 mContext.enforceCallingOrSelfPermission( 2195 android.Manifest.permission.CLEAR_APP_CACHE, null); 2196 // Queue up an async operation since clearing cache may take a little while. 2197 mHandler.post(new Runnable() { 2198 public void run() { 2199 mHandler.removeCallbacks(this); 2200 int retCode = -1; 2201 synchronized (mInstallLock) { 2202 retCode = mInstaller.freeCache(freeStorageSize); 2203 if (retCode < 0) { 2204 Slog.w(TAG, "Couldn't clear application caches"); 2205 } 2206 } 2207 if(pi != null) { 2208 try { 2209 // Callback via pending intent 2210 int code = (retCode >= 0) ? 1 : 0; 2211 pi.sendIntent(null, code, null, 2212 null, null); 2213 } catch (SendIntentException e1) { 2214 Slog.i(TAG, "Failed to send pending intent"); 2215 } 2216 } 2217 } 2218 }); 2219 } 2220 2221 void freeStorage(long freeStorageSize) throws IOException { 2222 synchronized (mInstallLock) { 2223 if (mInstaller.freeCache(freeStorageSize) < 0) { 2224 throw new IOException("Failed to free enough space"); 2225 } 2226 } 2227 } 2228 2229 @Override 2230 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2231 if (!sUserManager.exists(userId)) return null; 2232 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2233 synchronized (mPackages) { 2234 PackageParser.Activity a = mActivities.mActivities.get(component); 2235 2236 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2237 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2238 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2239 if (ps == null) return null; 2240 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2241 userId); 2242 } 2243 if (mResolveComponentName.equals(component)) { 2244 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2245 new PackageUserState(), userId); 2246 } 2247 } 2248 return null; 2249 } 2250 2251 @Override 2252 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2253 String resolvedType) { 2254 synchronized (mPackages) { 2255 PackageParser.Activity a = mActivities.mActivities.get(component); 2256 if (a == null) { 2257 return false; 2258 } 2259 for (int i=0; i<a.intents.size(); i++) { 2260 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2261 intent.getData(), intent.getCategories(), TAG) >= 0) { 2262 return true; 2263 } 2264 } 2265 return false; 2266 } 2267 } 2268 2269 @Override 2270 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2271 if (!sUserManager.exists(userId)) return null; 2272 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2273 synchronized (mPackages) { 2274 PackageParser.Activity a = mReceivers.mActivities.get(component); 2275 if (DEBUG_PACKAGE_INFO) Log.v( 2276 TAG, "getReceiverInfo " + component + ": " + a); 2277 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2278 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2279 if (ps == null) return null; 2280 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2281 userId); 2282 } 2283 } 2284 return null; 2285 } 2286 2287 @Override 2288 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2289 if (!sUserManager.exists(userId)) return null; 2290 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2291 synchronized (mPackages) { 2292 PackageParser.Service s = mServices.mServices.get(component); 2293 if (DEBUG_PACKAGE_INFO) Log.v( 2294 TAG, "getServiceInfo " + component + ": " + s); 2295 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2296 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2297 if (ps == null) return null; 2298 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2299 userId); 2300 } 2301 } 2302 return null; 2303 } 2304 2305 @Override 2306 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2307 if (!sUserManager.exists(userId)) return null; 2308 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2309 synchronized (mPackages) { 2310 PackageParser.Provider p = mProviders.mProviders.get(component); 2311 if (DEBUG_PACKAGE_INFO) Log.v( 2312 TAG, "getProviderInfo " + component + ": " + p); 2313 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2314 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2315 if (ps == null) return null; 2316 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2317 userId); 2318 } 2319 } 2320 return null; 2321 } 2322 2323 @Override 2324 public String[] getSystemSharedLibraryNames() { 2325 Set<String> libSet; 2326 synchronized (mPackages) { 2327 libSet = mSharedLibraries.keySet(); 2328 int size = libSet.size(); 2329 if (size > 0) { 2330 String[] libs = new String[size]; 2331 libSet.toArray(libs); 2332 return libs; 2333 } 2334 } 2335 return null; 2336 } 2337 2338 @Override 2339 public FeatureInfo[] getSystemAvailableFeatures() { 2340 Collection<FeatureInfo> featSet; 2341 synchronized (mPackages) { 2342 featSet = mAvailableFeatures.values(); 2343 int size = featSet.size(); 2344 if (size > 0) { 2345 FeatureInfo[] features = new FeatureInfo[size+1]; 2346 featSet.toArray(features); 2347 FeatureInfo fi = new FeatureInfo(); 2348 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2349 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2350 features[size] = fi; 2351 return features; 2352 } 2353 } 2354 return null; 2355 } 2356 2357 @Override 2358 public boolean hasSystemFeature(String name) { 2359 synchronized (mPackages) { 2360 return mAvailableFeatures.containsKey(name); 2361 } 2362 } 2363 2364 private void checkValidCaller(int uid, int userId) { 2365 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2366 return; 2367 2368 throw new SecurityException("Caller uid=" + uid 2369 + " is not privileged to communicate with user=" + userId); 2370 } 2371 2372 @Override 2373 public int checkPermission(String permName, String pkgName) { 2374 synchronized (mPackages) { 2375 PackageParser.Package p = mPackages.get(pkgName); 2376 if (p != null && p.mExtras != null) { 2377 PackageSetting ps = (PackageSetting)p.mExtras; 2378 if (ps.sharedUser != null) { 2379 if (ps.sharedUser.grantedPermissions.contains(permName)) { 2380 return PackageManager.PERMISSION_GRANTED; 2381 } 2382 } else if (ps.grantedPermissions.contains(permName)) { 2383 return PackageManager.PERMISSION_GRANTED; 2384 } 2385 } 2386 } 2387 return PackageManager.PERMISSION_DENIED; 2388 } 2389 2390 @Override 2391 public int checkUidPermission(String permName, int uid) { 2392 synchronized (mPackages) { 2393 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2394 if (obj != null) { 2395 GrantedPermissions gp = (GrantedPermissions)obj; 2396 if (gp.grantedPermissions.contains(permName)) { 2397 return PackageManager.PERMISSION_GRANTED; 2398 } 2399 } else { 2400 ArraySet<String> perms = mSystemPermissions.get(uid); 2401 if (perms != null && perms.contains(permName)) { 2402 return PackageManager.PERMISSION_GRANTED; 2403 } 2404 } 2405 } 2406 return PackageManager.PERMISSION_DENIED; 2407 } 2408 2409 /** 2410 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2411 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2412 * @param checkShell TODO(yamasani): 2413 * @param message the message to log on security exception 2414 */ 2415 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2416 boolean checkShell, String message) { 2417 if (userId < 0) { 2418 throw new IllegalArgumentException("Invalid userId " + userId); 2419 } 2420 if (checkShell) { 2421 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 2422 } 2423 if (userId == UserHandle.getUserId(callingUid)) return; 2424 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2425 if (requireFullPermission) { 2426 mContext.enforceCallingOrSelfPermission( 2427 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2428 } else { 2429 try { 2430 mContext.enforceCallingOrSelfPermission( 2431 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2432 } catch (SecurityException se) { 2433 mContext.enforceCallingOrSelfPermission( 2434 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2435 } 2436 } 2437 } 2438 } 2439 2440 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 2441 if (callingUid == Process.SHELL_UID) { 2442 if (userHandle >= 0 2443 && sUserManager.hasUserRestriction(restriction, userHandle)) { 2444 throw new SecurityException("Shell does not have permission to access user " 2445 + userHandle); 2446 } else if (userHandle < 0) { 2447 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 2448 + Debug.getCallers(3)); 2449 } 2450 } 2451 } 2452 2453 private BasePermission findPermissionTreeLP(String permName) { 2454 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2455 if (permName.startsWith(bp.name) && 2456 permName.length() > bp.name.length() && 2457 permName.charAt(bp.name.length()) == '.') { 2458 return bp; 2459 } 2460 } 2461 return null; 2462 } 2463 2464 private BasePermission checkPermissionTreeLP(String permName) { 2465 if (permName != null) { 2466 BasePermission bp = findPermissionTreeLP(permName); 2467 if (bp != null) { 2468 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2469 return bp; 2470 } 2471 throw new SecurityException("Calling uid " 2472 + Binder.getCallingUid() 2473 + " is not allowed to add to permission tree " 2474 + bp.name + " owned by uid " + bp.uid); 2475 } 2476 } 2477 throw new SecurityException("No permission tree found for " + permName); 2478 } 2479 2480 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2481 if (s1 == null) { 2482 return s2 == null; 2483 } 2484 if (s2 == null) { 2485 return false; 2486 } 2487 if (s1.getClass() != s2.getClass()) { 2488 return false; 2489 } 2490 return s1.equals(s2); 2491 } 2492 2493 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2494 if (pi1.icon != pi2.icon) return false; 2495 if (pi1.logo != pi2.logo) return false; 2496 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2497 if (!compareStrings(pi1.name, pi2.name)) return false; 2498 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2499 // We'll take care of setting this one. 2500 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2501 // These are not currently stored in settings. 2502 //if (!compareStrings(pi1.group, pi2.group)) return false; 2503 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2504 //if (pi1.labelRes != pi2.labelRes) return false; 2505 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2506 return true; 2507 } 2508 2509 int permissionInfoFootprint(PermissionInfo info) { 2510 int size = info.name.length(); 2511 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2512 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2513 return size; 2514 } 2515 2516 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2517 int size = 0; 2518 for (BasePermission perm : mSettings.mPermissions.values()) { 2519 if (perm.uid == tree.uid) { 2520 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2521 } 2522 } 2523 return size; 2524 } 2525 2526 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2527 // We calculate the max size of permissions defined by this uid and throw 2528 // if that plus the size of 'info' would exceed our stated maximum. 2529 if (tree.uid != Process.SYSTEM_UID) { 2530 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2531 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2532 throw new SecurityException("Permission tree size cap exceeded"); 2533 } 2534 } 2535 } 2536 2537 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2538 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2539 throw new SecurityException("Label must be specified in permission"); 2540 } 2541 BasePermission tree = checkPermissionTreeLP(info.name); 2542 BasePermission bp = mSettings.mPermissions.get(info.name); 2543 boolean added = bp == null; 2544 boolean changed = true; 2545 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2546 if (added) { 2547 enforcePermissionCapLocked(info, tree); 2548 bp = new BasePermission(info.name, tree.sourcePackage, 2549 BasePermission.TYPE_DYNAMIC); 2550 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2551 throw new SecurityException( 2552 "Not allowed to modify non-dynamic permission " 2553 + info.name); 2554 } else { 2555 if (bp.protectionLevel == fixedLevel 2556 && bp.perm.owner.equals(tree.perm.owner) 2557 && bp.uid == tree.uid 2558 && comparePermissionInfos(bp.perm.info, info)) { 2559 changed = false; 2560 } 2561 } 2562 bp.protectionLevel = fixedLevel; 2563 info = new PermissionInfo(info); 2564 info.protectionLevel = fixedLevel; 2565 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 2566 bp.perm.info.packageName = tree.perm.info.packageName; 2567 bp.uid = tree.uid; 2568 if (added) { 2569 mSettings.mPermissions.put(info.name, bp); 2570 } 2571 if (changed) { 2572 if (!async) { 2573 mSettings.writeLPr(); 2574 } else { 2575 scheduleWriteSettingsLocked(); 2576 } 2577 } 2578 return added; 2579 } 2580 2581 @Override 2582 public boolean addPermission(PermissionInfo info) { 2583 synchronized (mPackages) { 2584 return addPermissionLocked(info, false); 2585 } 2586 } 2587 2588 @Override 2589 public boolean addPermissionAsync(PermissionInfo info) { 2590 synchronized (mPackages) { 2591 return addPermissionLocked(info, true); 2592 } 2593 } 2594 2595 @Override 2596 public void removePermission(String name) { 2597 synchronized (mPackages) { 2598 checkPermissionTreeLP(name); 2599 BasePermission bp = mSettings.mPermissions.get(name); 2600 if (bp != null) { 2601 if (bp.type != BasePermission.TYPE_DYNAMIC) { 2602 throw new SecurityException( 2603 "Not allowed to modify non-dynamic permission " 2604 + name); 2605 } 2606 mSettings.mPermissions.remove(name); 2607 mSettings.writeLPr(); 2608 } 2609 } 2610 } 2611 2612 private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) { 2613 int index = pkg.requestedPermissions.indexOf(bp.name); 2614 if (index == -1) { 2615 throw new SecurityException("Package " + pkg.packageName 2616 + " has not requested permission " + bp.name); 2617 } 2618 boolean isNormal = 2619 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2620 == PermissionInfo.PROTECTION_NORMAL); 2621 boolean isDangerous = 2622 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2623 == PermissionInfo.PROTECTION_DANGEROUS); 2624 boolean isDevelopment = 2625 ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0); 2626 2627 if (!isNormal && !isDangerous && !isDevelopment) { 2628 throw new SecurityException("Permission " + bp.name 2629 + " is not a changeable permission type"); 2630 } 2631 2632 if (isNormal || isDangerous) { 2633 if (pkg.requestedPermissionsRequired.get(index)) { 2634 throw new SecurityException("Can't change " + bp.name 2635 + ". It is required by the application"); 2636 } 2637 } 2638 } 2639 2640 @Override 2641 public void grantPermission(String packageName, String permissionName) { 2642 mContext.enforceCallingOrSelfPermission( 2643 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2644 synchronized (mPackages) { 2645 final PackageParser.Package pkg = mPackages.get(packageName); 2646 if (pkg == null) { 2647 throw new IllegalArgumentException("Unknown package: " + packageName); 2648 } 2649 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2650 if (bp == null) { 2651 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2652 } 2653 2654 checkGrantRevokePermissions(pkg, bp); 2655 2656 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2657 if (ps == null) { 2658 return; 2659 } 2660 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2661 if (gp.grantedPermissions.add(permissionName)) { 2662 if (ps.haveGids) { 2663 gp.gids = appendInts(gp.gids, bp.gids); 2664 } 2665 mSettings.writeLPr(); 2666 } 2667 } 2668 } 2669 2670 @Override 2671 public void revokePermission(String packageName, String permissionName) { 2672 int changedAppId = -1; 2673 2674 synchronized (mPackages) { 2675 final PackageParser.Package pkg = mPackages.get(packageName); 2676 if (pkg == null) { 2677 throw new IllegalArgumentException("Unknown package: " + packageName); 2678 } 2679 if (pkg.applicationInfo.uid != Binder.getCallingUid()) { 2680 mContext.enforceCallingOrSelfPermission( 2681 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2682 } 2683 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2684 if (bp == null) { 2685 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2686 } 2687 2688 checkGrantRevokePermissions(pkg, bp); 2689 2690 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2691 if (ps == null) { 2692 return; 2693 } 2694 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2695 if (gp.grantedPermissions.remove(permissionName)) { 2696 gp.grantedPermissions.remove(permissionName); 2697 if (ps.haveGids) { 2698 gp.gids = removeInts(gp.gids, bp.gids); 2699 } 2700 mSettings.writeLPr(); 2701 changedAppId = ps.appId; 2702 } 2703 } 2704 2705 if (changedAppId >= 0) { 2706 // We changed the perm on someone, kill its processes. 2707 IActivityManager am = ActivityManagerNative.getDefault(); 2708 if (am != null) { 2709 final int callingUserId = UserHandle.getCallingUserId(); 2710 final long ident = Binder.clearCallingIdentity(); 2711 try { 2712 //XXX we should only revoke for the calling user's app permissions, 2713 // but for now we impact all users. 2714 //am.killUid(UserHandle.getUid(callingUserId, changedAppId), 2715 // "revoke " + permissionName); 2716 int[] users = sUserManager.getUserIds(); 2717 for (int user : users) { 2718 am.killUid(UserHandle.getUid(user, changedAppId), 2719 "revoke " + permissionName); 2720 } 2721 } catch (RemoteException e) { 2722 } finally { 2723 Binder.restoreCallingIdentity(ident); 2724 } 2725 } 2726 } 2727 } 2728 2729 @Override 2730 public boolean isProtectedBroadcast(String actionName) { 2731 synchronized (mPackages) { 2732 return mProtectedBroadcasts.contains(actionName); 2733 } 2734 } 2735 2736 @Override 2737 public int checkSignatures(String pkg1, String pkg2) { 2738 synchronized (mPackages) { 2739 final PackageParser.Package p1 = mPackages.get(pkg1); 2740 final PackageParser.Package p2 = mPackages.get(pkg2); 2741 if (p1 == null || p1.mExtras == null 2742 || p2 == null || p2.mExtras == null) { 2743 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2744 } 2745 return compareSignatures(p1.mSignatures, p2.mSignatures); 2746 } 2747 } 2748 2749 @Override 2750 public int checkUidSignatures(int uid1, int uid2) { 2751 // Map to base uids. 2752 uid1 = UserHandle.getAppId(uid1); 2753 uid2 = UserHandle.getAppId(uid2); 2754 // reader 2755 synchronized (mPackages) { 2756 Signature[] s1; 2757 Signature[] s2; 2758 Object obj = mSettings.getUserIdLPr(uid1); 2759 if (obj != null) { 2760 if (obj instanceof SharedUserSetting) { 2761 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 2762 } else if (obj instanceof PackageSetting) { 2763 s1 = ((PackageSetting)obj).signatures.mSignatures; 2764 } else { 2765 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2766 } 2767 } else { 2768 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2769 } 2770 obj = mSettings.getUserIdLPr(uid2); 2771 if (obj != null) { 2772 if (obj instanceof SharedUserSetting) { 2773 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 2774 } else if (obj instanceof PackageSetting) { 2775 s2 = ((PackageSetting)obj).signatures.mSignatures; 2776 } else { 2777 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2778 } 2779 } else { 2780 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2781 } 2782 return compareSignatures(s1, s2); 2783 } 2784 } 2785 2786 /** 2787 * Compares two sets of signatures. Returns: 2788 * <br /> 2789 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 2790 * <br /> 2791 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 2792 * <br /> 2793 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 2794 * <br /> 2795 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 2796 * <br /> 2797 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 2798 */ 2799 static int compareSignatures(Signature[] s1, Signature[] s2) { 2800 if (s1 == null) { 2801 return s2 == null 2802 ? PackageManager.SIGNATURE_NEITHER_SIGNED 2803 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 2804 } 2805 2806 if (s2 == null) { 2807 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 2808 } 2809 2810 if (s1.length != s2.length) { 2811 return PackageManager.SIGNATURE_NO_MATCH; 2812 } 2813 2814 // Since both signature sets are of size 1, we can compare without HashSets. 2815 if (s1.length == 1) { 2816 return s1[0].equals(s2[0]) ? 2817 PackageManager.SIGNATURE_MATCH : 2818 PackageManager.SIGNATURE_NO_MATCH; 2819 } 2820 2821 ArraySet<Signature> set1 = new ArraySet<Signature>(); 2822 for (Signature sig : s1) { 2823 set1.add(sig); 2824 } 2825 ArraySet<Signature> set2 = new ArraySet<Signature>(); 2826 for (Signature sig : s2) { 2827 set2.add(sig); 2828 } 2829 // Make sure s2 contains all signatures in s1. 2830 if (set1.equals(set2)) { 2831 return PackageManager.SIGNATURE_MATCH; 2832 } 2833 return PackageManager.SIGNATURE_NO_MATCH; 2834 } 2835 2836 /** 2837 * If the database version for this type of package (internal storage or 2838 * external storage) is less than the version where package signatures 2839 * were updated, return true. 2840 */ 2841 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2842 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 2843 DatabaseVersion.SIGNATURE_END_ENTITY)) 2844 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 2845 DatabaseVersion.SIGNATURE_END_ENTITY)); 2846 } 2847 2848 /** 2849 * Used for backward compatibility to make sure any packages with 2850 * certificate chains get upgraded to the new style. {@code existingSigs} 2851 * will be in the old format (since they were stored on disk from before the 2852 * system upgrade) and {@code scannedSigs} will be in the newer format. 2853 */ 2854 private int compareSignaturesCompat(PackageSignatures existingSigs, 2855 PackageParser.Package scannedPkg) { 2856 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 2857 return PackageManager.SIGNATURE_NO_MATCH; 2858 } 2859 2860 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 2861 for (Signature sig : existingSigs.mSignatures) { 2862 existingSet.add(sig); 2863 } 2864 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 2865 for (Signature sig : scannedPkg.mSignatures) { 2866 try { 2867 Signature[] chainSignatures = sig.getChainSignatures(); 2868 for (Signature chainSig : chainSignatures) { 2869 scannedCompatSet.add(chainSig); 2870 } 2871 } catch (CertificateEncodingException e) { 2872 scannedCompatSet.add(sig); 2873 } 2874 } 2875 /* 2876 * Make sure the expanded scanned set contains all signatures in the 2877 * existing one. 2878 */ 2879 if (scannedCompatSet.equals(existingSet)) { 2880 // Migrate the old signatures to the new scheme. 2881 existingSigs.assignSignatures(scannedPkg.mSignatures); 2882 // The new KeySets will be re-added later in the scanning process. 2883 synchronized (mPackages) { 2884 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 2885 } 2886 return PackageManager.SIGNATURE_MATCH; 2887 } 2888 return PackageManager.SIGNATURE_NO_MATCH; 2889 } 2890 2891 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2892 if (isExternal(scannedPkg)) { 2893 return mSettings.isExternalDatabaseVersionOlderThan( 2894 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 2895 } else { 2896 return mSettings.isInternalDatabaseVersionOlderThan( 2897 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 2898 } 2899 } 2900 2901 private int compareSignaturesRecover(PackageSignatures existingSigs, 2902 PackageParser.Package scannedPkg) { 2903 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 2904 return PackageManager.SIGNATURE_NO_MATCH; 2905 } 2906 2907 String msg = null; 2908 try { 2909 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 2910 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 2911 + scannedPkg.packageName); 2912 return PackageManager.SIGNATURE_MATCH; 2913 } 2914 } catch (CertificateException e) { 2915 msg = e.getMessage(); 2916 } 2917 2918 logCriticalInfo(Log.INFO, 2919 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 2920 return PackageManager.SIGNATURE_NO_MATCH; 2921 } 2922 2923 @Override 2924 public String[] getPackagesForUid(int uid) { 2925 uid = UserHandle.getAppId(uid); 2926 // reader 2927 synchronized (mPackages) { 2928 Object obj = mSettings.getUserIdLPr(uid); 2929 if (obj instanceof SharedUserSetting) { 2930 final SharedUserSetting sus = (SharedUserSetting) obj; 2931 final int N = sus.packages.size(); 2932 final String[] res = new String[N]; 2933 final Iterator<PackageSetting> it = sus.packages.iterator(); 2934 int i = 0; 2935 while (it.hasNext()) { 2936 res[i++] = it.next().name; 2937 } 2938 return res; 2939 } else if (obj instanceof PackageSetting) { 2940 final PackageSetting ps = (PackageSetting) obj; 2941 return new String[] { ps.name }; 2942 } 2943 } 2944 return null; 2945 } 2946 2947 @Override 2948 public String getNameForUid(int uid) { 2949 // reader 2950 synchronized (mPackages) { 2951 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2952 if (obj instanceof SharedUserSetting) { 2953 final SharedUserSetting sus = (SharedUserSetting) obj; 2954 return sus.name + ":" + sus.userId; 2955 } else if (obj instanceof PackageSetting) { 2956 final PackageSetting ps = (PackageSetting) obj; 2957 return ps.name; 2958 } 2959 } 2960 return null; 2961 } 2962 2963 @Override 2964 public int getUidForSharedUser(String sharedUserName) { 2965 if(sharedUserName == null) { 2966 return -1; 2967 } 2968 // reader 2969 synchronized (mPackages) { 2970 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 2971 if (suid == null) { 2972 return -1; 2973 } 2974 return suid.userId; 2975 } 2976 } 2977 2978 @Override 2979 public int getFlagsForUid(int uid) { 2980 synchronized (mPackages) { 2981 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2982 if (obj instanceof SharedUserSetting) { 2983 final SharedUserSetting sus = (SharedUserSetting) obj; 2984 return sus.pkgFlags; 2985 } else if (obj instanceof PackageSetting) { 2986 final PackageSetting ps = (PackageSetting) obj; 2987 return ps.pkgFlags; 2988 } 2989 } 2990 return 0; 2991 } 2992 2993 @Override 2994 public int getPrivateFlagsForUid(int uid) { 2995 synchronized (mPackages) { 2996 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2997 if (obj instanceof SharedUserSetting) { 2998 final SharedUserSetting sus = (SharedUserSetting) obj; 2999 return sus.pkgPrivateFlags; 3000 } else if (obj instanceof PackageSetting) { 3001 final PackageSetting ps = (PackageSetting) obj; 3002 return ps.pkgPrivateFlags; 3003 } 3004 } 3005 return 0; 3006 } 3007 3008 @Override 3009 public boolean isUidPrivileged(int uid) { 3010 uid = UserHandle.getAppId(uid); 3011 // reader 3012 synchronized (mPackages) { 3013 Object obj = mSettings.getUserIdLPr(uid); 3014 if (obj instanceof SharedUserSetting) { 3015 final SharedUserSetting sus = (SharedUserSetting) obj; 3016 final Iterator<PackageSetting> it = sus.packages.iterator(); 3017 while (it.hasNext()) { 3018 if (it.next().isPrivileged()) { 3019 return true; 3020 } 3021 } 3022 } else if (obj instanceof PackageSetting) { 3023 final PackageSetting ps = (PackageSetting) obj; 3024 return ps.isPrivileged(); 3025 } 3026 } 3027 return false; 3028 } 3029 3030 @Override 3031 public String[] getAppOpPermissionPackages(String permissionName) { 3032 synchronized (mPackages) { 3033 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 3034 if (pkgs == null) { 3035 return null; 3036 } 3037 return pkgs.toArray(new String[pkgs.size()]); 3038 } 3039 } 3040 3041 @Override 3042 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 3043 int flags, int userId) { 3044 if (!sUserManager.exists(userId)) return null; 3045 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 3046 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3047 return chooseBestActivity(intent, resolvedType, flags, query, userId); 3048 } 3049 3050 @Override 3051 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 3052 IntentFilter filter, int match, ComponentName activity) { 3053 final int userId = UserHandle.getCallingUserId(); 3054 if (DEBUG_PREFERRED) { 3055 Log.v(TAG, "setLastChosenActivity intent=" + intent 3056 + " resolvedType=" + resolvedType 3057 + " flags=" + flags 3058 + " filter=" + filter 3059 + " match=" + match 3060 + " activity=" + activity); 3061 filter.dump(new PrintStreamPrinter(System.out), " "); 3062 } 3063 intent.setComponent(null); 3064 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3065 // Find any earlier preferred or last chosen entries and nuke them 3066 findPreferredActivity(intent, resolvedType, 3067 flags, query, 0, false, true, false, userId); 3068 // Add the new activity as the last chosen for this filter 3069 addPreferredActivityInternal(filter, match, null, activity, false, userId, 3070 "Setting last chosen"); 3071 } 3072 3073 @Override 3074 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 3075 final int userId = UserHandle.getCallingUserId(); 3076 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 3077 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3078 return findPreferredActivity(intent, resolvedType, flags, query, 0, 3079 false, false, false, userId); 3080 } 3081 3082 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 3083 int flags, List<ResolveInfo> query, int userId) { 3084 if (query != null) { 3085 final int N = query.size(); 3086 if (N == 1) { 3087 return query.get(0); 3088 } else if (N > 1) { 3089 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 3090 // If there is more than one activity with the same priority, 3091 // then let the user decide between them. 3092 ResolveInfo r0 = query.get(0); 3093 ResolveInfo r1 = query.get(1); 3094 if (DEBUG_INTENT_MATCHING || debug) { 3095 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 3096 + r1.activityInfo.name + "=" + r1.priority); 3097 } 3098 // If the first activity has a higher priority, or a different 3099 // default, then it is always desireable to pick it. 3100 if (r0.priority != r1.priority 3101 || r0.preferredOrder != r1.preferredOrder 3102 || r0.isDefault != r1.isDefault) { 3103 return query.get(0); 3104 } 3105 // If we have saved a preference for a preferred activity for 3106 // this Intent, use that. 3107 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 3108 flags, query, r0.priority, true, false, debug, userId); 3109 if (ri != null) { 3110 return ri; 3111 } 3112 if (userId != 0) { 3113 ri = new ResolveInfo(mResolveInfo); 3114 ri.activityInfo = new ActivityInfo(ri.activityInfo); 3115 ri.activityInfo.applicationInfo = new ApplicationInfo( 3116 ri.activityInfo.applicationInfo); 3117 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 3118 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 3119 return ri; 3120 } 3121 return mResolveInfo; 3122 } 3123 } 3124 return null; 3125 } 3126 3127 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3128 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3129 final int N = query.size(); 3130 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3131 .get(userId); 3132 // Get the list of persistent preferred activities that handle the intent 3133 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3134 List<PersistentPreferredActivity> pprefs = ppir != null 3135 ? ppir.queryIntent(intent, resolvedType, 3136 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3137 : null; 3138 if (pprefs != null && pprefs.size() > 0) { 3139 final int M = pprefs.size(); 3140 for (int i=0; i<M; i++) { 3141 final PersistentPreferredActivity ppa = pprefs.get(i); 3142 if (DEBUG_PREFERRED || debug) { 3143 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3144 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3145 + "\n component=" + ppa.mComponent); 3146 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3147 } 3148 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3149 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3150 if (DEBUG_PREFERRED || debug) { 3151 Slog.v(TAG, "Found persistent preferred activity:"); 3152 if (ai != null) { 3153 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3154 } else { 3155 Slog.v(TAG, " null"); 3156 } 3157 } 3158 if (ai == null) { 3159 // This previously registered persistent preferred activity 3160 // component is no longer known. Ignore it and do NOT remove it. 3161 continue; 3162 } 3163 for (int j=0; j<N; j++) { 3164 final ResolveInfo ri = query.get(j); 3165 if (!ri.activityInfo.applicationInfo.packageName 3166 .equals(ai.applicationInfo.packageName)) { 3167 continue; 3168 } 3169 if (!ri.activityInfo.name.equals(ai.name)) { 3170 continue; 3171 } 3172 // Found a persistent preference that can handle the intent. 3173 if (DEBUG_PREFERRED || debug) { 3174 Slog.v(TAG, "Returning persistent preferred activity: " + 3175 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3176 } 3177 return ri; 3178 } 3179 } 3180 } 3181 return null; 3182 } 3183 3184 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3185 List<ResolveInfo> query, int priority, boolean always, 3186 boolean removeMatches, boolean debug, int userId) { 3187 if (!sUserManager.exists(userId)) return null; 3188 // writer 3189 synchronized (mPackages) { 3190 if (intent.getSelector() != null) { 3191 intent = intent.getSelector(); 3192 } 3193 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3194 3195 // Try to find a matching persistent preferred activity. 3196 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3197 debug, userId); 3198 3199 // If a persistent preferred activity matched, use it. 3200 if (pri != null) { 3201 return pri; 3202 } 3203 3204 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3205 // Get the list of preferred activities that handle the intent 3206 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3207 List<PreferredActivity> prefs = pir != null 3208 ? pir.queryIntent(intent, resolvedType, 3209 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3210 : null; 3211 if (prefs != null && prefs.size() > 0) { 3212 boolean changed = false; 3213 try { 3214 // First figure out how good the original match set is. 3215 // We will only allow preferred activities that came 3216 // from the same match quality. 3217 int match = 0; 3218 3219 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3220 3221 final int N = query.size(); 3222 for (int j=0; j<N; j++) { 3223 final ResolveInfo ri = query.get(j); 3224 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3225 + ": 0x" + Integer.toHexString(match)); 3226 if (ri.match > match) { 3227 match = ri.match; 3228 } 3229 } 3230 3231 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3232 + Integer.toHexString(match)); 3233 3234 match &= IntentFilter.MATCH_CATEGORY_MASK; 3235 final int M = prefs.size(); 3236 for (int i=0; i<M; i++) { 3237 final PreferredActivity pa = prefs.get(i); 3238 if (DEBUG_PREFERRED || debug) { 3239 Slog.v(TAG, "Checking PreferredActivity ds=" 3240 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3241 + "\n component=" + pa.mPref.mComponent); 3242 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3243 } 3244 if (pa.mPref.mMatch != match) { 3245 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3246 + Integer.toHexString(pa.mPref.mMatch)); 3247 continue; 3248 } 3249 // If it's not an "always" type preferred activity and that's what we're 3250 // looking for, skip it. 3251 if (always && !pa.mPref.mAlways) { 3252 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3253 continue; 3254 } 3255 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3256 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3257 if (DEBUG_PREFERRED || debug) { 3258 Slog.v(TAG, "Found preferred activity:"); 3259 if (ai != null) { 3260 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3261 } else { 3262 Slog.v(TAG, " null"); 3263 } 3264 } 3265 if (ai == null) { 3266 // This previously registered preferred activity 3267 // component is no longer known. Most likely an update 3268 // to the app was installed and in the new version this 3269 // component no longer exists. Clean it up by removing 3270 // it from the preferred activities list, and skip it. 3271 Slog.w(TAG, "Removing dangling preferred activity: " 3272 + pa.mPref.mComponent); 3273 pir.removeFilter(pa); 3274 changed = true; 3275 continue; 3276 } 3277 for (int j=0; j<N; j++) { 3278 final ResolveInfo ri = query.get(j); 3279 if (!ri.activityInfo.applicationInfo.packageName 3280 .equals(ai.applicationInfo.packageName)) { 3281 continue; 3282 } 3283 if (!ri.activityInfo.name.equals(ai.name)) { 3284 continue; 3285 } 3286 3287 if (removeMatches) { 3288 pir.removeFilter(pa); 3289 changed = true; 3290 if (DEBUG_PREFERRED) { 3291 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3292 } 3293 break; 3294 } 3295 3296 // Okay we found a previously set preferred or last chosen app. 3297 // If the result set is different from when this 3298 // was created, we need to clear it and re-ask the 3299 // user their preference, if we're looking for an "always" type entry. 3300 if (always && !pa.mPref.sameSet(query)) { 3301 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3302 + intent + " type " + resolvedType); 3303 if (DEBUG_PREFERRED) { 3304 Slog.v(TAG, "Removing preferred activity since set changed " 3305 + pa.mPref.mComponent); 3306 } 3307 pir.removeFilter(pa); 3308 // Re-add the filter as a "last chosen" entry (!always) 3309 PreferredActivity lastChosen = new PreferredActivity( 3310 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3311 pir.addFilter(lastChosen); 3312 changed = true; 3313 return null; 3314 } 3315 3316 // Yay! Either the set matched or we're looking for the last chosen 3317 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3318 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3319 return ri; 3320 } 3321 } 3322 } finally { 3323 if (changed) { 3324 if (DEBUG_PREFERRED) { 3325 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 3326 } 3327 scheduleWritePackageRestrictionsLocked(userId); 3328 } 3329 } 3330 } 3331 } 3332 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3333 return null; 3334 } 3335 3336 /* 3337 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3338 */ 3339 @Override 3340 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3341 int targetUserId) { 3342 mContext.enforceCallingOrSelfPermission( 3343 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3344 List<CrossProfileIntentFilter> matches = 3345 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3346 if (matches != null) { 3347 int size = matches.size(); 3348 for (int i = 0; i < size; i++) { 3349 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3350 } 3351 } 3352 return false; 3353 } 3354 3355 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3356 String resolvedType, int userId) { 3357 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3358 if (resolver != null) { 3359 return resolver.queryIntent(intent, resolvedType, false, userId); 3360 } 3361 return null; 3362 } 3363 3364 @Override 3365 public List<ResolveInfo> queryIntentActivities(Intent intent, 3366 String resolvedType, int flags, int userId) { 3367 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3368 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 3369 ComponentName comp = intent.getComponent(); 3370 if (comp == null) { 3371 if (intent.getSelector() != null) { 3372 intent = intent.getSelector(); 3373 comp = intent.getComponent(); 3374 } 3375 } 3376 3377 if (comp != null) { 3378 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3379 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3380 if (ai != null) { 3381 final ResolveInfo ri = new ResolveInfo(); 3382 ri.activityInfo = ai; 3383 list.add(ri); 3384 } 3385 return list; 3386 } 3387 3388 // reader 3389 synchronized (mPackages) { 3390 final String pkgName = intent.getPackage(); 3391 if (pkgName == null) { 3392 List<CrossProfileIntentFilter> matchingFilters = 3393 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3394 // Check for results that need to skip the current profile. 3395 ResolveInfo resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3396 resolvedType, flags, userId); 3397 if (resolveInfo != null) { 3398 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3399 result.add(resolveInfo); 3400 return filterIfNotPrimaryUser(result, userId); 3401 } 3402 // Check for cross profile results. 3403 resolveInfo = queryCrossProfileIntents( 3404 matchingFilters, intent, resolvedType, flags, userId); 3405 3406 // Check for results in the current profile. 3407 List<ResolveInfo> result = mActivities.queryIntent( 3408 intent, resolvedType, flags, userId); 3409 if (resolveInfo != null) { 3410 result.add(resolveInfo); 3411 Collections.sort(result, mResolvePrioritySorter); 3412 } 3413 return filterIfNotPrimaryUser(result, userId); 3414 } 3415 final PackageParser.Package pkg = mPackages.get(pkgName); 3416 if (pkg != null) { 3417 return filterIfNotPrimaryUser( 3418 mActivities.queryIntentForPackage( 3419 intent, resolvedType, flags, pkg.activities, userId), 3420 userId); 3421 } 3422 return new ArrayList<ResolveInfo>(); 3423 } 3424 } 3425 3426 /** 3427 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 3428 * 3429 * @return filtered list 3430 */ 3431 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 3432 if (userId == UserHandle.USER_OWNER) { 3433 return resolveInfos; 3434 } 3435 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 3436 ResolveInfo info = resolveInfos.get(i); 3437 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 3438 resolveInfos.remove(i); 3439 } 3440 } 3441 return resolveInfos; 3442 } 3443 3444 3445 private ResolveInfo querySkipCurrentProfileIntents( 3446 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3447 int flags, int sourceUserId) { 3448 if (matchingFilters != null) { 3449 int size = matchingFilters.size(); 3450 for (int i = 0; i < size; i ++) { 3451 CrossProfileIntentFilter filter = matchingFilters.get(i); 3452 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 3453 // Checking if there are activities in the target user that can handle the 3454 // intent. 3455 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3456 flags, sourceUserId); 3457 if (resolveInfo != null) { 3458 return resolveInfo; 3459 } 3460 } 3461 } 3462 } 3463 return null; 3464 } 3465 3466 // Return matching ResolveInfo if any for skip current profile intent filters. 3467 private ResolveInfo queryCrossProfileIntents( 3468 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3469 int flags, int sourceUserId) { 3470 if (matchingFilters != null) { 3471 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 3472 // match the same intent. For performance reasons, it is better not to 3473 // run queryIntent twice for the same userId 3474 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 3475 int size = matchingFilters.size(); 3476 for (int i = 0; i < size; i++) { 3477 CrossProfileIntentFilter filter = matchingFilters.get(i); 3478 int targetUserId = filter.getTargetUserId(); 3479 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 3480 && !alreadyTriedUserIds.get(targetUserId)) { 3481 // Checking if there are activities in the target user that can handle the 3482 // intent. 3483 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3484 flags, sourceUserId); 3485 if (resolveInfo != null) return resolveInfo; 3486 alreadyTriedUserIds.put(targetUserId, true); 3487 } 3488 } 3489 } 3490 return null; 3491 } 3492 3493 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 3494 String resolvedType, int flags, int sourceUserId) { 3495 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 3496 resolvedType, flags, filter.getTargetUserId()); 3497 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 3498 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 3499 } 3500 return null; 3501 } 3502 3503 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 3504 int sourceUserId, int targetUserId) { 3505 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 3506 String className; 3507 if (targetUserId == UserHandle.USER_OWNER) { 3508 className = FORWARD_INTENT_TO_USER_OWNER; 3509 } else { 3510 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 3511 } 3512 ComponentName forwardingActivityComponentName = new ComponentName( 3513 mAndroidApplication.packageName, className); 3514 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 3515 sourceUserId); 3516 if (targetUserId == UserHandle.USER_OWNER) { 3517 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 3518 forwardingResolveInfo.noResourceId = true; 3519 } 3520 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 3521 forwardingResolveInfo.priority = 0; 3522 forwardingResolveInfo.preferredOrder = 0; 3523 forwardingResolveInfo.match = 0; 3524 forwardingResolveInfo.isDefault = true; 3525 forwardingResolveInfo.filter = filter; 3526 forwardingResolveInfo.targetUserId = targetUserId; 3527 return forwardingResolveInfo; 3528 } 3529 3530 @Override 3531 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 3532 Intent[] specifics, String[] specificTypes, Intent intent, 3533 String resolvedType, int flags, int userId) { 3534 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3535 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 3536 false, "query intent activity options"); 3537 final String resultsAction = intent.getAction(); 3538 3539 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 3540 | PackageManager.GET_RESOLVED_FILTER, userId); 3541 3542 if (DEBUG_INTENT_MATCHING) { 3543 Log.v(TAG, "Query " + intent + ": " + results); 3544 } 3545 3546 int specificsPos = 0; 3547 int N; 3548 3549 // todo: note that the algorithm used here is O(N^2). This 3550 // isn't a problem in our current environment, but if we start running 3551 // into situations where we have more than 5 or 10 matches then this 3552 // should probably be changed to something smarter... 3553 3554 // First we go through and resolve each of the specific items 3555 // that were supplied, taking care of removing any corresponding 3556 // duplicate items in the generic resolve list. 3557 if (specifics != null) { 3558 for (int i=0; i<specifics.length; i++) { 3559 final Intent sintent = specifics[i]; 3560 if (sintent == null) { 3561 continue; 3562 } 3563 3564 if (DEBUG_INTENT_MATCHING) { 3565 Log.v(TAG, "Specific #" + i + ": " + sintent); 3566 } 3567 3568 String action = sintent.getAction(); 3569 if (resultsAction != null && resultsAction.equals(action)) { 3570 // If this action was explicitly requested, then don't 3571 // remove things that have it. 3572 action = null; 3573 } 3574 3575 ResolveInfo ri = null; 3576 ActivityInfo ai = null; 3577 3578 ComponentName comp = sintent.getComponent(); 3579 if (comp == null) { 3580 ri = resolveIntent( 3581 sintent, 3582 specificTypes != null ? specificTypes[i] : null, 3583 flags, userId); 3584 if (ri == null) { 3585 continue; 3586 } 3587 if (ri == mResolveInfo) { 3588 // ACK! Must do something better with this. 3589 } 3590 ai = ri.activityInfo; 3591 comp = new ComponentName(ai.applicationInfo.packageName, 3592 ai.name); 3593 } else { 3594 ai = getActivityInfo(comp, flags, userId); 3595 if (ai == null) { 3596 continue; 3597 } 3598 } 3599 3600 // Look for any generic query activities that are duplicates 3601 // of this specific one, and remove them from the results. 3602 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 3603 N = results.size(); 3604 int j; 3605 for (j=specificsPos; j<N; j++) { 3606 ResolveInfo sri = results.get(j); 3607 if ((sri.activityInfo.name.equals(comp.getClassName()) 3608 && sri.activityInfo.applicationInfo.packageName.equals( 3609 comp.getPackageName())) 3610 || (action != null && sri.filter.matchAction(action))) { 3611 results.remove(j); 3612 if (DEBUG_INTENT_MATCHING) Log.v( 3613 TAG, "Removing duplicate item from " + j 3614 + " due to specific " + specificsPos); 3615 if (ri == null) { 3616 ri = sri; 3617 } 3618 j--; 3619 N--; 3620 } 3621 } 3622 3623 // Add this specific item to its proper place. 3624 if (ri == null) { 3625 ri = new ResolveInfo(); 3626 ri.activityInfo = ai; 3627 } 3628 results.add(specificsPos, ri); 3629 ri.specificIndex = i; 3630 specificsPos++; 3631 } 3632 } 3633 3634 // Now we go through the remaining generic results and remove any 3635 // duplicate actions that are found here. 3636 N = results.size(); 3637 for (int i=specificsPos; i<N-1; i++) { 3638 final ResolveInfo rii = results.get(i); 3639 if (rii.filter == null) { 3640 continue; 3641 } 3642 3643 // Iterate over all of the actions of this result's intent 3644 // filter... typically this should be just one. 3645 final Iterator<String> it = rii.filter.actionsIterator(); 3646 if (it == null) { 3647 continue; 3648 } 3649 while (it.hasNext()) { 3650 final String action = it.next(); 3651 if (resultsAction != null && resultsAction.equals(action)) { 3652 // If this action was explicitly requested, then don't 3653 // remove things that have it. 3654 continue; 3655 } 3656 for (int j=i+1; j<N; j++) { 3657 final ResolveInfo rij = results.get(j); 3658 if (rij.filter != null && rij.filter.hasAction(action)) { 3659 results.remove(j); 3660 if (DEBUG_INTENT_MATCHING) Log.v( 3661 TAG, "Removing duplicate item from " + j 3662 + " due to action " + action + " at " + i); 3663 j--; 3664 N--; 3665 } 3666 } 3667 } 3668 3669 // If the caller didn't request filter information, drop it now 3670 // so we don't have to marshall/unmarshall it. 3671 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3672 rii.filter = null; 3673 } 3674 } 3675 3676 // Filter out the caller activity if so requested. 3677 if (caller != null) { 3678 N = results.size(); 3679 for (int i=0; i<N; i++) { 3680 ActivityInfo ainfo = results.get(i).activityInfo; 3681 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 3682 && caller.getClassName().equals(ainfo.name)) { 3683 results.remove(i); 3684 break; 3685 } 3686 } 3687 } 3688 3689 // If the caller didn't request filter information, 3690 // drop them now so we don't have to 3691 // marshall/unmarshall it. 3692 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3693 N = results.size(); 3694 for (int i=0; i<N; i++) { 3695 results.get(i).filter = null; 3696 } 3697 } 3698 3699 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 3700 return results; 3701 } 3702 3703 @Override 3704 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 3705 int userId) { 3706 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3707 ComponentName comp = intent.getComponent(); 3708 if (comp == null) { 3709 if (intent.getSelector() != null) { 3710 intent = intent.getSelector(); 3711 comp = intent.getComponent(); 3712 } 3713 } 3714 if (comp != null) { 3715 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3716 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 3717 if (ai != null) { 3718 ResolveInfo ri = new ResolveInfo(); 3719 ri.activityInfo = ai; 3720 list.add(ri); 3721 } 3722 return list; 3723 } 3724 3725 // reader 3726 synchronized (mPackages) { 3727 String pkgName = intent.getPackage(); 3728 if (pkgName == null) { 3729 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 3730 } 3731 final PackageParser.Package pkg = mPackages.get(pkgName); 3732 if (pkg != null) { 3733 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 3734 userId); 3735 } 3736 return null; 3737 } 3738 } 3739 3740 @Override 3741 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 3742 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 3743 if (!sUserManager.exists(userId)) return null; 3744 if (query != null) { 3745 if (query.size() >= 1) { 3746 // If there is more than one service with the same priority, 3747 // just arbitrarily pick the first one. 3748 return query.get(0); 3749 } 3750 } 3751 return null; 3752 } 3753 3754 @Override 3755 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 3756 int userId) { 3757 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3758 ComponentName comp = intent.getComponent(); 3759 if (comp == null) { 3760 if (intent.getSelector() != null) { 3761 intent = intent.getSelector(); 3762 comp = intent.getComponent(); 3763 } 3764 } 3765 if (comp != null) { 3766 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3767 final ServiceInfo si = getServiceInfo(comp, flags, userId); 3768 if (si != null) { 3769 final ResolveInfo ri = new ResolveInfo(); 3770 ri.serviceInfo = si; 3771 list.add(ri); 3772 } 3773 return list; 3774 } 3775 3776 // reader 3777 synchronized (mPackages) { 3778 String pkgName = intent.getPackage(); 3779 if (pkgName == null) { 3780 return mServices.queryIntent(intent, resolvedType, flags, userId); 3781 } 3782 final PackageParser.Package pkg = mPackages.get(pkgName); 3783 if (pkg != null) { 3784 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 3785 userId); 3786 } 3787 return null; 3788 } 3789 } 3790 3791 @Override 3792 public List<ResolveInfo> queryIntentContentProviders( 3793 Intent intent, String resolvedType, int flags, int userId) { 3794 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3795 ComponentName comp = intent.getComponent(); 3796 if (comp == null) { 3797 if (intent.getSelector() != null) { 3798 intent = intent.getSelector(); 3799 comp = intent.getComponent(); 3800 } 3801 } 3802 if (comp != null) { 3803 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3804 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 3805 if (pi != null) { 3806 final ResolveInfo ri = new ResolveInfo(); 3807 ri.providerInfo = pi; 3808 list.add(ri); 3809 } 3810 return list; 3811 } 3812 3813 // reader 3814 synchronized (mPackages) { 3815 String pkgName = intent.getPackage(); 3816 if (pkgName == null) { 3817 return mProviders.queryIntent(intent, resolvedType, flags, userId); 3818 } 3819 final PackageParser.Package pkg = mPackages.get(pkgName); 3820 if (pkg != null) { 3821 return mProviders.queryIntentForPackage( 3822 intent, resolvedType, flags, pkg.providers, userId); 3823 } 3824 return null; 3825 } 3826 } 3827 3828 @Override 3829 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 3830 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3831 3832 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 3833 3834 // writer 3835 synchronized (mPackages) { 3836 ArrayList<PackageInfo> list; 3837 if (listUninstalled) { 3838 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 3839 for (PackageSetting ps : mSettings.mPackages.values()) { 3840 PackageInfo pi; 3841 if (ps.pkg != null) { 3842 pi = generatePackageInfo(ps.pkg, flags, userId); 3843 } else { 3844 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3845 } 3846 if (pi != null) { 3847 list.add(pi); 3848 } 3849 } 3850 } else { 3851 list = new ArrayList<PackageInfo>(mPackages.size()); 3852 for (PackageParser.Package p : mPackages.values()) { 3853 PackageInfo pi = generatePackageInfo(p, flags, userId); 3854 if (pi != null) { 3855 list.add(pi); 3856 } 3857 } 3858 } 3859 3860 return new ParceledListSlice<PackageInfo>(list); 3861 } 3862 } 3863 3864 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 3865 String[] permissions, boolean[] tmp, int flags, int userId) { 3866 int numMatch = 0; 3867 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 3868 for (int i=0; i<permissions.length; i++) { 3869 if (gp.grantedPermissions.contains(permissions[i])) { 3870 tmp[i] = true; 3871 numMatch++; 3872 } else { 3873 tmp[i] = false; 3874 } 3875 } 3876 if (numMatch == 0) { 3877 return; 3878 } 3879 PackageInfo pi; 3880 if (ps.pkg != null) { 3881 pi = generatePackageInfo(ps.pkg, flags, userId); 3882 } else { 3883 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3884 } 3885 // The above might return null in cases of uninstalled apps or install-state 3886 // skew across users/profiles. 3887 if (pi != null) { 3888 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 3889 if (numMatch == permissions.length) { 3890 pi.requestedPermissions = permissions; 3891 } else { 3892 pi.requestedPermissions = new String[numMatch]; 3893 numMatch = 0; 3894 for (int i=0; i<permissions.length; i++) { 3895 if (tmp[i]) { 3896 pi.requestedPermissions[numMatch] = permissions[i]; 3897 numMatch++; 3898 } 3899 } 3900 } 3901 } 3902 list.add(pi); 3903 } 3904 } 3905 3906 @Override 3907 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 3908 String[] permissions, int flags, int userId) { 3909 if (!sUserManager.exists(userId)) return null; 3910 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3911 3912 // writer 3913 synchronized (mPackages) { 3914 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 3915 boolean[] tmpBools = new boolean[permissions.length]; 3916 if (listUninstalled) { 3917 for (PackageSetting ps : mSettings.mPackages.values()) { 3918 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 3919 } 3920 } else { 3921 for (PackageParser.Package pkg : mPackages.values()) { 3922 PackageSetting ps = (PackageSetting)pkg.mExtras; 3923 if (ps != null) { 3924 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 3925 userId); 3926 } 3927 } 3928 } 3929 3930 return new ParceledListSlice<PackageInfo>(list); 3931 } 3932 } 3933 3934 @Override 3935 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 3936 if (!sUserManager.exists(userId)) return null; 3937 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3938 3939 // writer 3940 synchronized (mPackages) { 3941 ArrayList<ApplicationInfo> list; 3942 if (listUninstalled) { 3943 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 3944 for (PackageSetting ps : mSettings.mPackages.values()) { 3945 ApplicationInfo ai; 3946 if (ps.pkg != null) { 3947 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3948 ps.readUserState(userId), userId); 3949 } else { 3950 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 3951 } 3952 if (ai != null) { 3953 list.add(ai); 3954 } 3955 } 3956 } else { 3957 list = new ArrayList<ApplicationInfo>(mPackages.size()); 3958 for (PackageParser.Package p : mPackages.values()) { 3959 if (p.mExtras != null) { 3960 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3961 ((PackageSetting)p.mExtras).readUserState(userId), userId); 3962 if (ai != null) { 3963 list.add(ai); 3964 } 3965 } 3966 } 3967 } 3968 3969 return new ParceledListSlice<ApplicationInfo>(list); 3970 } 3971 } 3972 3973 public List<ApplicationInfo> getPersistentApplications(int flags) { 3974 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 3975 3976 // reader 3977 synchronized (mPackages) { 3978 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 3979 final int userId = UserHandle.getCallingUserId(); 3980 while (i.hasNext()) { 3981 final PackageParser.Package p = i.next(); 3982 if (p.applicationInfo != null 3983 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 3984 && (!mSafeMode || isSystemApp(p))) { 3985 PackageSetting ps = mSettings.mPackages.get(p.packageName); 3986 if (ps != null) { 3987 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3988 ps.readUserState(userId), userId); 3989 if (ai != null) { 3990 finalList.add(ai); 3991 } 3992 } 3993 } 3994 } 3995 } 3996 3997 return finalList; 3998 } 3999 4000 @Override 4001 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 4002 if (!sUserManager.exists(userId)) return null; 4003 // reader 4004 synchronized (mPackages) { 4005 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 4006 PackageSetting ps = provider != null 4007 ? mSettings.mPackages.get(provider.owner.packageName) 4008 : null; 4009 return ps != null 4010 && mSettings.isEnabledLPr(provider.info, flags, userId) 4011 && (!mSafeMode || (provider.info.applicationInfo.flags 4012 &ApplicationInfo.FLAG_SYSTEM) != 0) 4013 ? PackageParser.generateProviderInfo(provider, flags, 4014 ps.readUserState(userId), userId) 4015 : null; 4016 } 4017 } 4018 4019 /** 4020 * @deprecated 4021 */ 4022 @Deprecated 4023 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 4024 // reader 4025 synchronized (mPackages) { 4026 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 4027 .entrySet().iterator(); 4028 final int userId = UserHandle.getCallingUserId(); 4029 while (i.hasNext()) { 4030 Map.Entry<String, PackageParser.Provider> entry = i.next(); 4031 PackageParser.Provider p = entry.getValue(); 4032 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4033 4034 if (ps != null && p.syncable 4035 && (!mSafeMode || (p.info.applicationInfo.flags 4036 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 4037 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 4038 ps.readUserState(userId), userId); 4039 if (info != null) { 4040 outNames.add(entry.getKey()); 4041 outInfo.add(info); 4042 } 4043 } 4044 } 4045 } 4046 } 4047 4048 @Override 4049 public List<ProviderInfo> queryContentProviders(String processName, 4050 int uid, int flags) { 4051 ArrayList<ProviderInfo> finalList = null; 4052 // reader 4053 synchronized (mPackages) { 4054 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 4055 final int userId = processName != null ? 4056 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 4057 while (i.hasNext()) { 4058 final PackageParser.Provider p = i.next(); 4059 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4060 if (ps != null && p.info.authority != null 4061 && (processName == null 4062 || (p.info.processName.equals(processName) 4063 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 4064 && mSettings.isEnabledLPr(p.info, flags, userId) 4065 && (!mSafeMode 4066 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 4067 if (finalList == null) { 4068 finalList = new ArrayList<ProviderInfo>(3); 4069 } 4070 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 4071 ps.readUserState(userId), userId); 4072 if (info != null) { 4073 finalList.add(info); 4074 } 4075 } 4076 } 4077 } 4078 4079 if (finalList != null) { 4080 Collections.sort(finalList, mProviderInitOrderSorter); 4081 } 4082 4083 return finalList; 4084 } 4085 4086 @Override 4087 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4088 int flags) { 4089 // reader 4090 synchronized (mPackages) { 4091 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4092 return PackageParser.generateInstrumentationInfo(i, flags); 4093 } 4094 } 4095 4096 @Override 4097 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4098 int flags) { 4099 ArrayList<InstrumentationInfo> finalList = 4100 new ArrayList<InstrumentationInfo>(); 4101 4102 // reader 4103 synchronized (mPackages) { 4104 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4105 while (i.hasNext()) { 4106 final PackageParser.Instrumentation p = i.next(); 4107 if (targetPackage == null 4108 || targetPackage.equals(p.info.targetPackage)) { 4109 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4110 flags); 4111 if (ii != null) { 4112 finalList.add(ii); 4113 } 4114 } 4115 } 4116 } 4117 4118 return finalList; 4119 } 4120 4121 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4122 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4123 if (overlays == null) { 4124 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4125 return; 4126 } 4127 for (PackageParser.Package opkg : overlays.values()) { 4128 // Not much to do if idmap fails: we already logged the error 4129 // and we certainly don't want to abort installation of pkg simply 4130 // because an overlay didn't fit properly. For these reasons, 4131 // ignore the return value of createIdmapForPackagePairLI. 4132 createIdmapForPackagePairLI(pkg, opkg); 4133 } 4134 } 4135 4136 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4137 PackageParser.Package opkg) { 4138 if (!opkg.mTrustedOverlay) { 4139 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4140 opkg.baseCodePath + ": overlay not trusted"); 4141 return false; 4142 } 4143 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4144 if (overlaySet == null) { 4145 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4146 opkg.baseCodePath + " but target package has no known overlays"); 4147 return false; 4148 } 4149 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4150 // TODO: generate idmap for split APKs 4151 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4152 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4153 + opkg.baseCodePath); 4154 return false; 4155 } 4156 PackageParser.Package[] overlayArray = 4157 overlaySet.values().toArray(new PackageParser.Package[0]); 4158 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4159 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4160 return p1.mOverlayPriority - p2.mOverlayPriority; 4161 } 4162 }; 4163 Arrays.sort(overlayArray, cmp); 4164 4165 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4166 int i = 0; 4167 for (PackageParser.Package p : overlayArray) { 4168 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4169 } 4170 return true; 4171 } 4172 4173 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 4174 final File[] files = dir.listFiles(); 4175 if (ArrayUtils.isEmpty(files)) { 4176 Log.d(TAG, "No files in app dir " + dir); 4177 return; 4178 } 4179 4180 if (DEBUG_PACKAGE_SCANNING) { 4181 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 4182 + " flags=0x" + Integer.toHexString(parseFlags)); 4183 } 4184 4185 for (File file : files) { 4186 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 4187 && !PackageInstallerService.isStageName(file.getName()); 4188 if (!isPackage) { 4189 // Ignore entries which are not packages 4190 continue; 4191 } 4192 try { 4193 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 4194 scanFlags, currentTime, null); 4195 } catch (PackageManagerException e) { 4196 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4197 4198 // Delete invalid userdata apps 4199 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4200 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4201 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 4202 if (file.isDirectory()) { 4203 FileUtils.deleteContents(file); 4204 } 4205 file.delete(); 4206 } 4207 } 4208 } 4209 } 4210 4211 private static File getSettingsProblemFile() { 4212 File dataDir = Environment.getDataDirectory(); 4213 File systemDir = new File(dataDir, "system"); 4214 File fname = new File(systemDir, "uiderrors.txt"); 4215 return fname; 4216 } 4217 4218 static void reportSettingsProblem(int priority, String msg) { 4219 logCriticalInfo(priority, msg); 4220 } 4221 4222 static void logCriticalInfo(int priority, String msg) { 4223 Slog.println(priority, TAG, msg); 4224 EventLogTags.writePmCriticalInfo(msg); 4225 try { 4226 File fname = getSettingsProblemFile(); 4227 FileOutputStream out = new FileOutputStream(fname, true); 4228 PrintWriter pw = new FastPrintWriter(out); 4229 SimpleDateFormat formatter = new SimpleDateFormat(); 4230 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4231 pw.println(dateString + ": " + msg); 4232 pw.close(); 4233 FileUtils.setPermissions( 4234 fname.toString(), 4235 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4236 -1, -1); 4237 } catch (java.io.IOException e) { 4238 } 4239 } 4240 4241 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 4242 PackageParser.Package pkg, File srcFile, int parseFlags) 4243 throws PackageManagerException { 4244 if (ps != null 4245 && ps.codePath.equals(srcFile) 4246 && ps.timeStamp == srcFile.lastModified() 4247 && !isCompatSignatureUpdateNeeded(pkg) 4248 && !isRecoverSignatureUpdateNeeded(pkg)) { 4249 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4250 if (ps.signatures.mSignatures != null 4251 && ps.signatures.mSignatures.length != 0 4252 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4253 // Optimization: reuse the existing cached certificates 4254 // if the package appears to be unchanged. 4255 pkg.mSignatures = ps.signatures.mSignatures; 4256 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4257 synchronized (mPackages) { 4258 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 4259 } 4260 return; 4261 } 4262 4263 Slog.w(TAG, "PackageSetting for " + ps.name 4264 + " is missing signatures. Collecting certs again to recover them."); 4265 } else { 4266 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4267 } 4268 4269 try { 4270 pp.collectCertificates(pkg, parseFlags); 4271 pp.collectManifestDigest(pkg); 4272 } catch (PackageParserException e) { 4273 throw PackageManagerException.from(e); 4274 } 4275 } 4276 4277 /* 4278 * Scan a package and return the newly parsed package. 4279 * Returns null in case of errors and the error code is stored in mLastScanError 4280 */ 4281 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 4282 long currentTime, UserHandle user) throws PackageManagerException { 4283 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4284 parseFlags |= mDefParseFlags; 4285 PackageParser pp = new PackageParser(); 4286 pp.setSeparateProcesses(mSeparateProcesses); 4287 pp.setOnlyCoreApps(mOnlyCore); 4288 pp.setDisplayMetrics(mMetrics); 4289 4290 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 4291 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4292 } 4293 4294 final PackageParser.Package pkg; 4295 try { 4296 pkg = pp.parsePackage(scanFile, parseFlags); 4297 } catch (PackageParserException e) { 4298 throw PackageManagerException.from(e); 4299 } 4300 4301 PackageSetting ps = null; 4302 PackageSetting updatedPkg; 4303 // reader 4304 synchronized (mPackages) { 4305 // Look to see if we already know about this package. 4306 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4307 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4308 // This package has been renamed to its original name. Let's 4309 // use that. 4310 ps = mSettings.peekPackageLPr(oldName); 4311 } 4312 // If there was no original package, see one for the real package name. 4313 if (ps == null) { 4314 ps = mSettings.peekPackageLPr(pkg.packageName); 4315 } 4316 // Check to see if this package could be hiding/updating a system 4317 // package. Must look for it either under the original or real 4318 // package name depending on our state. 4319 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4320 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4321 } 4322 boolean updatedPkgBetter = false; 4323 // First check if this is a system package that may involve an update 4324 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4325 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 4326 // it needs to drop FLAG_PRIVILEGED. 4327 if (locationIsPrivileged(scanFile)) { 4328 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 4329 } else { 4330 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 4331 } 4332 4333 if (ps != null && !ps.codePath.equals(scanFile)) { 4334 // The path has changed from what was last scanned... check the 4335 // version of the new path against what we have stored to determine 4336 // what to do. 4337 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4338 if (pkg.mVersionCode <= ps.versionCode) { 4339 // The system package has been updated and the code path does not match 4340 // Ignore entry. Skip it. 4341 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 4342 + " ignored: updated version " + ps.versionCode 4343 + " better than this " + pkg.mVersionCode); 4344 if (!updatedPkg.codePath.equals(scanFile)) { 4345 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4346 + ps.name + " changing from " + updatedPkg.codePathString 4347 + " to " + scanFile); 4348 updatedPkg.codePath = scanFile; 4349 updatedPkg.codePathString = scanFile.toString(); 4350 updatedPkg.resourcePath = scanFile; 4351 updatedPkg.resourcePathString = scanFile.toString(); 4352 } 4353 updatedPkg.pkg = pkg; 4354 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 4355 } else { 4356 // The current app on the system partition is better than 4357 // what we have updated to on the data partition; switch 4358 // back to the system partition version. 4359 // At this point, its safely assumed that package installation for 4360 // apps in system partition will go through. If not there won't be a working 4361 // version of the app 4362 // writer 4363 synchronized (mPackages) { 4364 // Just remove the loaded entries from package lists. 4365 mPackages.remove(ps.name); 4366 } 4367 4368 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 4369 + " reverting from " + ps.codePathString 4370 + ": new version " + pkg.mVersionCode 4371 + " better than installed " + ps.versionCode); 4372 4373 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4374 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4375 getAppDexInstructionSets(ps)); 4376 synchronized (mInstallLock) { 4377 args.cleanUpResourcesLI(); 4378 } 4379 synchronized (mPackages) { 4380 mSettings.enableSystemPackageLPw(ps.name); 4381 } 4382 updatedPkgBetter = true; 4383 } 4384 } 4385 } 4386 4387 if (updatedPkg != null) { 4388 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4389 // initially 4390 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4391 4392 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4393 // flag set initially 4394 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 4395 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4396 } 4397 } 4398 4399 // Verify certificates against what was last scanned 4400 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 4401 4402 /* 4403 * A new system app appeared, but we already had a non-system one of the 4404 * same name installed earlier. 4405 */ 4406 boolean shouldHideSystemApp = false; 4407 if (updatedPkg == null && ps != null 4408 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4409 /* 4410 * Check to make sure the signatures match first. If they don't, 4411 * wipe the installed application and its data. 4412 */ 4413 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4414 != PackageManager.SIGNATURE_MATCH) { 4415 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 4416 + " signatures don't match existing userdata copy; removing"); 4417 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4418 ps = null; 4419 } else { 4420 /* 4421 * If the newly-added system app is an older version than the 4422 * already installed version, hide it. It will be scanned later 4423 * and re-added like an update. 4424 */ 4425 if (pkg.mVersionCode <= ps.versionCode) { 4426 shouldHideSystemApp = true; 4427 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 4428 + " but new version " + pkg.mVersionCode + " better than installed " 4429 + ps.versionCode + "; hiding system"); 4430 } else { 4431 /* 4432 * The newly found system app is a newer version that the 4433 * one previously installed. Simply remove the 4434 * already-installed application and replace it with our own 4435 * while keeping the application data. 4436 */ 4437 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 4438 + " reverting from " + ps.codePathString + ": new version " 4439 + pkg.mVersionCode + " better than installed " + ps.versionCode); 4440 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4441 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4442 getAppDexInstructionSets(ps)); 4443 synchronized (mInstallLock) { 4444 args.cleanUpResourcesLI(); 4445 } 4446 } 4447 } 4448 } 4449 4450 // The apk is forward locked (not public) if its code and resources 4451 // are kept in different files. (except for app in either system or 4452 // vendor path). 4453 // TODO grab this value from PackageSettings 4454 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4455 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4456 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 4457 } 4458 } 4459 4460 // TODO: extend to support forward-locked splits 4461 String resourcePath = null; 4462 String baseResourcePath = null; 4463 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 4464 if (ps != null && ps.resourcePathString != null) { 4465 resourcePath = ps.resourcePathString; 4466 baseResourcePath = ps.resourcePathString; 4467 } else { 4468 // Should not happen at all. Just log an error. 4469 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 4470 } 4471 } else { 4472 resourcePath = pkg.codePath; 4473 baseResourcePath = pkg.baseCodePath; 4474 } 4475 4476 // Set application objects path explicitly. 4477 pkg.applicationInfo.setCodePath(pkg.codePath); 4478 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 4479 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 4480 pkg.applicationInfo.setResourcePath(resourcePath); 4481 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 4482 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 4483 4484 // Note that we invoke the following method only if we are about to unpack an application 4485 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 4486 | SCAN_UPDATE_SIGNATURE, currentTime, user); 4487 4488 /* 4489 * If the system app should be overridden by a previously installed 4490 * data, hide the system app now and let the /data/app scan pick it up 4491 * again. 4492 */ 4493 if (shouldHideSystemApp) { 4494 synchronized (mPackages) { 4495 /* 4496 * We have to grant systems permissions before we hide, because 4497 * grantPermissions will assume the package update is trying to 4498 * expand its permissions. 4499 */ 4500 grantPermissionsLPw(pkg, true, pkg.packageName); 4501 mSettings.disableSystemPackageLPw(pkg.packageName); 4502 } 4503 } 4504 4505 return scannedPkg; 4506 } 4507 4508 private static String fixProcessName(String defProcessName, 4509 String processName, int uid) { 4510 if (processName == null) { 4511 return defProcessName; 4512 } 4513 return processName; 4514 } 4515 4516 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 4517 throws PackageManagerException { 4518 if (pkgSetting.signatures.mSignatures != null) { 4519 // Already existing package. Make sure signatures match 4520 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 4521 == PackageManager.SIGNATURE_MATCH; 4522 if (!match) { 4523 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 4524 == PackageManager.SIGNATURE_MATCH; 4525 } 4526 if (!match) { 4527 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 4528 == PackageManager.SIGNATURE_MATCH; 4529 } 4530 if (!match) { 4531 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 4532 + pkg.packageName + " signatures do not match the " 4533 + "previously installed version; ignoring!"); 4534 } 4535 } 4536 4537 // Check for shared user signatures 4538 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 4539 // Already existing package. Make sure signatures match 4540 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4541 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 4542 if (!match) { 4543 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 4544 == PackageManager.SIGNATURE_MATCH; 4545 } 4546 if (!match) { 4547 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 4548 == PackageManager.SIGNATURE_MATCH; 4549 } 4550 if (!match) { 4551 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 4552 "Package " + pkg.packageName 4553 + " has no signatures that match those in shared user " 4554 + pkgSetting.sharedUser.name + "; ignoring!"); 4555 } 4556 } 4557 } 4558 4559 /** 4560 * Enforces that only the system UID or root's UID can call a method exposed 4561 * via Binder. 4562 * 4563 * @param message used as message if SecurityException is thrown 4564 * @throws SecurityException if the caller is not system or root 4565 */ 4566 private static final void enforceSystemOrRoot(String message) { 4567 final int uid = Binder.getCallingUid(); 4568 if (uid != Process.SYSTEM_UID && uid != 0) { 4569 throw new SecurityException(message); 4570 } 4571 } 4572 4573 @Override 4574 public void performBootDexOpt() { 4575 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4576 4577 // Before everything else, see whether we need to fstrim. 4578 try { 4579 IMountService ms = PackageHelper.getMountService(); 4580 if (ms != null) { 4581 final boolean isUpgrade = isUpgrade(); 4582 boolean doTrim = isUpgrade; 4583 if (doTrim) { 4584 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 4585 } else { 4586 final long interval = android.provider.Settings.Global.getLong( 4587 mContext.getContentResolver(), 4588 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 4589 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 4590 if (interval > 0) { 4591 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 4592 if (timeSinceLast > interval) { 4593 doTrim = true; 4594 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 4595 + "; running immediately"); 4596 } 4597 } 4598 } 4599 if (doTrim) { 4600 if (!isFirstBoot()) { 4601 try { 4602 ActivityManagerNative.getDefault().showBootMessage( 4603 mContext.getResources().getString( 4604 R.string.android_upgrading_fstrim), true); 4605 } catch (RemoteException e) { 4606 } 4607 } 4608 ms.runMaintenance(); 4609 } 4610 } else { 4611 Slog.e(TAG, "Mount service unavailable!"); 4612 } 4613 } catch (RemoteException e) { 4614 // Can't happen; MountService is local 4615 } 4616 4617 final ArraySet<PackageParser.Package> pkgs; 4618 synchronized (mPackages) { 4619 pkgs = mDeferredDexOpt; 4620 mDeferredDexOpt = null; 4621 } 4622 4623 if (pkgs != null) { 4624 // Sort apps by importance for dexopt ordering. Important apps are given more priority 4625 // in case the device runs out of space. 4626 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 4627 // Give priority to core apps. 4628 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4629 PackageParser.Package pkg = it.next(); 4630 if (pkg.coreApp) { 4631 if (DEBUG_DEXOPT) { 4632 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 4633 } 4634 sortedPkgs.add(pkg); 4635 it.remove(); 4636 } 4637 } 4638 // Give priority to system apps that listen for pre boot complete. 4639 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 4640 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 4641 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4642 PackageParser.Package pkg = it.next(); 4643 if (pkgNames.contains(pkg.packageName)) { 4644 if (DEBUG_DEXOPT) { 4645 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 4646 } 4647 sortedPkgs.add(pkg); 4648 it.remove(); 4649 } 4650 } 4651 // Give priority to system apps. 4652 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4653 PackageParser.Package pkg = it.next(); 4654 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 4655 if (DEBUG_DEXOPT) { 4656 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 4657 } 4658 sortedPkgs.add(pkg); 4659 it.remove(); 4660 } 4661 } 4662 // Give priority to updated system apps. 4663 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4664 PackageParser.Package pkg = it.next(); 4665 if (isUpdatedSystemApp(pkg)) { 4666 if (DEBUG_DEXOPT) { 4667 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 4668 } 4669 sortedPkgs.add(pkg); 4670 it.remove(); 4671 } 4672 } 4673 // Give priority to apps that listen for boot complete. 4674 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 4675 pkgNames = getPackageNamesForIntent(intent); 4676 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4677 PackageParser.Package pkg = it.next(); 4678 if (pkgNames.contains(pkg.packageName)) { 4679 if (DEBUG_DEXOPT) { 4680 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 4681 } 4682 sortedPkgs.add(pkg); 4683 it.remove(); 4684 } 4685 } 4686 // Filter out packages that aren't recently used. 4687 filterRecentlyUsedApps(pkgs); 4688 // Add all remaining apps. 4689 for (PackageParser.Package pkg : pkgs) { 4690 if (DEBUG_DEXOPT) { 4691 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 4692 } 4693 sortedPkgs.add(pkg); 4694 } 4695 4696 // If we want to be lazy, filter everything that wasn't recently used. 4697 if (mLazyDexOpt) { 4698 filterRecentlyUsedApps(sortedPkgs); 4699 } 4700 4701 int i = 0; 4702 int total = sortedPkgs.size(); 4703 File dataDir = Environment.getDataDirectory(); 4704 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 4705 if (lowThreshold == 0) { 4706 throw new IllegalStateException("Invalid low memory threshold"); 4707 } 4708 for (PackageParser.Package pkg : sortedPkgs) { 4709 long usableSpace = dataDir.getUsableSpace(); 4710 if (usableSpace < lowThreshold) { 4711 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 4712 break; 4713 } 4714 performBootDexOpt(pkg, ++i, total); 4715 } 4716 } 4717 } 4718 4719 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 4720 // Filter out packages that aren't recently used. 4721 // 4722 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 4723 // should do a full dexopt. 4724 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 4725 int total = pkgs.size(); 4726 int skipped = 0; 4727 long now = System.currentTimeMillis(); 4728 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 4729 PackageParser.Package pkg = i.next(); 4730 long then = pkg.mLastPackageUsageTimeInMills; 4731 if (then + mDexOptLRUThresholdInMills < now) { 4732 if (DEBUG_DEXOPT) { 4733 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 4734 ((then == 0) ? "never" : new Date(then))); 4735 } 4736 i.remove(); 4737 skipped++; 4738 } 4739 } 4740 if (DEBUG_DEXOPT) { 4741 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 4742 } 4743 } 4744 } 4745 4746 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 4747 List<ResolveInfo> ris = null; 4748 try { 4749 ris = AppGlobals.getPackageManager().queryIntentReceivers( 4750 intent, null, 0, UserHandle.USER_OWNER); 4751 } catch (RemoteException e) { 4752 } 4753 ArraySet<String> pkgNames = new ArraySet<String>(); 4754 if (ris != null) { 4755 for (ResolveInfo ri : ris) { 4756 pkgNames.add(ri.activityInfo.packageName); 4757 } 4758 } 4759 return pkgNames; 4760 } 4761 4762 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 4763 if (DEBUG_DEXOPT) { 4764 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 4765 } 4766 if (!isFirstBoot()) { 4767 try { 4768 ActivityManagerNative.getDefault().showBootMessage( 4769 mContext.getResources().getString(R.string.android_upgrading_apk, 4770 curr, total), true); 4771 } catch (RemoteException e) { 4772 } 4773 } 4774 PackageParser.Package p = pkg; 4775 synchronized (mInstallLock) { 4776 performDexOptLI(p, null /* instruction sets */, false /* force dex */, 4777 false /* defer */, true /* include dependencies */); 4778 } 4779 } 4780 4781 @Override 4782 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 4783 return performDexOpt(packageName, instructionSet, false); 4784 } 4785 4786 private static String getPrimaryInstructionSet(ApplicationInfo info) { 4787 if (info.primaryCpuAbi == null) { 4788 return getPreferredInstructionSet(); 4789 } 4790 4791 return VMRuntime.getInstructionSet(info.primaryCpuAbi); 4792 } 4793 4794 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 4795 boolean dexopt = mLazyDexOpt || backgroundDexopt; 4796 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 4797 if (!dexopt && !updateUsage) { 4798 // We aren't going to dexopt or update usage, so bail early. 4799 return false; 4800 } 4801 PackageParser.Package p; 4802 final String targetInstructionSet; 4803 synchronized (mPackages) { 4804 p = mPackages.get(packageName); 4805 if (p == null) { 4806 return false; 4807 } 4808 if (updateUsage) { 4809 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 4810 } 4811 mPackageUsage.write(false); 4812 if (!dexopt) { 4813 // We aren't going to dexopt, so bail early. 4814 return false; 4815 } 4816 4817 targetInstructionSet = instructionSet != null ? instructionSet : 4818 getPrimaryInstructionSet(p.applicationInfo); 4819 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 4820 return false; 4821 } 4822 } 4823 4824 synchronized (mInstallLock) { 4825 final String[] instructionSets = new String[] { targetInstructionSet }; 4826 return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */, 4827 true /* include dependencies */) == DEX_OPT_PERFORMED; 4828 } 4829 } 4830 4831 public ArraySet<String> getPackagesThatNeedDexOpt() { 4832 ArraySet<String> pkgs = null; 4833 synchronized (mPackages) { 4834 for (PackageParser.Package p : mPackages.values()) { 4835 if (DEBUG_DEXOPT) { 4836 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 4837 } 4838 if (!p.mDexOptPerformed.isEmpty()) { 4839 continue; 4840 } 4841 if (pkgs == null) { 4842 pkgs = new ArraySet<String>(); 4843 } 4844 pkgs.add(p.packageName); 4845 } 4846 } 4847 return pkgs; 4848 } 4849 4850 public void shutdown() { 4851 mPackageUsage.write(true); 4852 } 4853 4854 private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets, 4855 boolean forceDex, boolean defer, ArraySet<String> done) { 4856 for (int i=0; i<libs.size(); i++) { 4857 PackageParser.Package libPkg; 4858 String libName; 4859 synchronized (mPackages) { 4860 libName = libs.get(i); 4861 SharedLibraryEntry lib = mSharedLibraries.get(libName); 4862 if (lib != null && lib.apk != null) { 4863 libPkg = mPackages.get(lib.apk); 4864 } else { 4865 libPkg = null; 4866 } 4867 } 4868 if (libPkg != null && !done.contains(libName)) { 4869 performDexOptLI(libPkg, instructionSets, forceDex, defer, done); 4870 } 4871 } 4872 } 4873 4874 static final int DEX_OPT_SKIPPED = 0; 4875 static final int DEX_OPT_PERFORMED = 1; 4876 static final int DEX_OPT_DEFERRED = 2; 4877 static final int DEX_OPT_FAILED = -1; 4878 4879 private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets, 4880 boolean forceDex, boolean defer, ArraySet<String> done) { 4881 final String[] instructionSets = targetInstructionSets != null ? 4882 targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo); 4883 4884 if (done != null) { 4885 done.add(pkg.packageName); 4886 if (pkg.usesLibraries != null) { 4887 performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done); 4888 } 4889 if (pkg.usesOptionalLibraries != null) { 4890 performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done); 4891 } 4892 } 4893 4894 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) { 4895 return DEX_OPT_SKIPPED; 4896 } 4897 4898 final boolean vmSafeMode = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0; 4899 4900 final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly(); 4901 boolean performedDexOpt = false; 4902 // There are three basic cases here: 4903 // 1.) we need to dexopt, either because we are forced or it is needed 4904 // 2.) we are defering a needed dexopt 4905 // 3.) we are skipping an unneeded dexopt 4906 final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 4907 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 4908 if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) { 4909 continue; 4910 } 4911 4912 for (String path : paths) { 4913 try { 4914 // This will return DEXOPT_NEEDED if we either cannot find any odex file for this 4915 // patckage or the one we find does not match the image checksum (i.e. it was 4916 // compiled against an old image). It will return PATCHOAT_NEEDED if we can find a 4917 // odex file and it matches the checksum of the image but not its base address, 4918 // meaning we need to move it. 4919 final byte isDexOptNeeded = DexFile.isDexOptNeededInternal(path, 4920 pkg.packageName, dexCodeInstructionSet, defer); 4921 if (forceDex || (!defer && isDexOptNeeded == DexFile.DEXOPT_NEEDED)) { 4922 Log.i(TAG, "Running dexopt on: " + path + " pkg=" 4923 + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet 4924 + " vmSafeMode=" + vmSafeMode); 4925 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4926 final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg), 4927 pkg.packageName, dexCodeInstructionSet, vmSafeMode); 4928 4929 if (ret < 0) { 4930 // Don't bother running dexopt again if we failed, it will probably 4931 // just result in an error again. Also, don't bother dexopting for other 4932 // paths & ISAs. 4933 return DEX_OPT_FAILED; 4934 } 4935 4936 performedDexOpt = true; 4937 } else if (!defer && isDexOptNeeded == DexFile.PATCHOAT_NEEDED) { 4938 Log.i(TAG, "Running patchoat on: " + pkg.applicationInfo.packageName); 4939 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4940 final int ret = mInstaller.patchoat(path, sharedGid, !isForwardLocked(pkg), 4941 pkg.packageName, dexCodeInstructionSet); 4942 4943 if (ret < 0) { 4944 // Don't bother running patchoat again if we failed, it will probably 4945 // just result in an error again. Also, don't bother dexopting for other 4946 // paths & ISAs. 4947 return DEX_OPT_FAILED; 4948 } 4949 4950 performedDexOpt = true; 4951 } 4952 4953 // We're deciding to defer a needed dexopt. Don't bother dexopting for other 4954 // paths and instruction sets. We'll deal with them all together when we process 4955 // our list of deferred dexopts. 4956 if (defer && isDexOptNeeded != DexFile.UP_TO_DATE) { 4957 if (mDeferredDexOpt == null) { 4958 mDeferredDexOpt = new ArraySet<PackageParser.Package>(); 4959 } 4960 mDeferredDexOpt.add(pkg); 4961 return DEX_OPT_DEFERRED; 4962 } 4963 } catch (FileNotFoundException e) { 4964 Slog.w(TAG, "Apk not found for dexopt: " + path); 4965 return DEX_OPT_FAILED; 4966 } catch (IOException e) { 4967 Slog.w(TAG, "IOException reading apk: " + path, e); 4968 return DEX_OPT_FAILED; 4969 } catch (StaleDexCacheError e) { 4970 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e); 4971 return DEX_OPT_FAILED; 4972 } catch (Exception e) { 4973 Slog.w(TAG, "Exception when doing dexopt : ", e); 4974 return DEX_OPT_FAILED; 4975 } 4976 } 4977 4978 // At this point we haven't failed dexopt and we haven't deferred dexopt. We must 4979 // either have either succeeded dexopt, or have had isDexOptNeededInternal tell us 4980 // it isn't required. We therefore mark that this package doesn't need dexopt unless 4981 // it's forced. performedDexOpt will tell us whether we performed dex-opt or skipped 4982 // it. 4983 pkg.mDexOptPerformed.add(dexCodeInstructionSet); 4984 } 4985 4986 // If we've gotten here, we're sure that no error occurred and that we haven't 4987 // deferred dex-opt. We've either dex-opted one more paths or instruction sets or 4988 // we've skipped all of them because they are up to date. In both cases this 4989 // package doesn't need dexopt any longer. 4990 return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED; 4991 } 4992 4993 private static String[] getAppDexInstructionSets(ApplicationInfo info) { 4994 if (info.primaryCpuAbi != null) { 4995 if (info.secondaryCpuAbi != null) { 4996 return new String[] { 4997 VMRuntime.getInstructionSet(info.primaryCpuAbi), 4998 VMRuntime.getInstructionSet(info.secondaryCpuAbi) }; 4999 } else { 5000 return new String[] { 5001 VMRuntime.getInstructionSet(info.primaryCpuAbi) }; 5002 } 5003 } 5004 5005 return new String[] { getPreferredInstructionSet() }; 5006 } 5007 5008 private static String[] getAppDexInstructionSets(PackageSetting ps) { 5009 if (ps.primaryCpuAbiString != null) { 5010 if (ps.secondaryCpuAbiString != null) { 5011 return new String[] { 5012 VMRuntime.getInstructionSet(ps.primaryCpuAbiString), 5013 VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) }; 5014 } else { 5015 return new String[] { 5016 VMRuntime.getInstructionSet(ps.primaryCpuAbiString) }; 5017 } 5018 } 5019 5020 return new String[] { getPreferredInstructionSet() }; 5021 } 5022 5023 private static String getPreferredInstructionSet() { 5024 if (sPreferredInstructionSet == null) { 5025 sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]); 5026 } 5027 5028 return sPreferredInstructionSet; 5029 } 5030 5031 private static List<String> getAllInstructionSets() { 5032 final String[] allAbis = Build.SUPPORTED_ABIS; 5033 final List<String> allInstructionSets = new ArrayList<String>(allAbis.length); 5034 5035 for (String abi : allAbis) { 5036 final String instructionSet = VMRuntime.getInstructionSet(abi); 5037 if (!allInstructionSets.contains(instructionSet)) { 5038 allInstructionSets.add(instructionSet); 5039 } 5040 } 5041 5042 return allInstructionSets; 5043 } 5044 5045 /** 5046 * Returns the instruction set that should be used to compile dex code. In the presence of 5047 * a native bridge this might be different than the one shared libraries use. 5048 */ 5049 private static String getDexCodeInstructionSet(String sharedLibraryIsa) { 5050 String dexCodeIsa = SystemProperties.get("ro.dalvik.vm.isa." + sharedLibraryIsa); 5051 return (dexCodeIsa.isEmpty() ? sharedLibraryIsa : dexCodeIsa); 5052 } 5053 5054 private static String[] getDexCodeInstructionSets(String[] instructionSets) { 5055 ArraySet<String> dexCodeInstructionSets = new ArraySet<String>(instructionSets.length); 5056 for (String instructionSet : instructionSets) { 5057 dexCodeInstructionSets.add(getDexCodeInstructionSet(instructionSet)); 5058 } 5059 return dexCodeInstructionSets.toArray(new String[dexCodeInstructionSets.size()]); 5060 } 5061 5062 /** 5063 * Returns deduplicated list of supported instructions for dex code. 5064 */ 5065 public static String[] getAllDexCodeInstructionSets() { 5066 String[] supportedInstructionSets = new String[Build.SUPPORTED_ABIS.length]; 5067 for (int i = 0; i < supportedInstructionSets.length; i++) { 5068 String abi = Build.SUPPORTED_ABIS[i]; 5069 supportedInstructionSets[i] = VMRuntime.getInstructionSet(abi); 5070 } 5071 return getDexCodeInstructionSets(supportedInstructionSets); 5072 } 5073 5074 @Override 5075 public void forceDexOpt(String packageName) { 5076 enforceSystemOrRoot("forceDexOpt"); 5077 5078 PackageParser.Package pkg; 5079 synchronized (mPackages) { 5080 pkg = mPackages.get(packageName); 5081 if (pkg == null) { 5082 throw new IllegalArgumentException("Missing package: " + packageName); 5083 } 5084 } 5085 5086 synchronized (mInstallLock) { 5087 final String[] instructionSets = new String[] { 5088 getPrimaryInstructionSet(pkg.applicationInfo) }; 5089 final int res = performDexOptLI(pkg, instructionSets, true, false, true); 5090 if (res != DEX_OPT_PERFORMED) { 5091 throw new IllegalStateException("Failed to dexopt: " + res); 5092 } 5093 } 5094 } 5095 5096 private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets, 5097 boolean forceDex, boolean defer, boolean inclDependencies) { 5098 ArraySet<String> done; 5099 if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) { 5100 done = new ArraySet<String>(); 5101 done.add(pkg.packageName); 5102 } else { 5103 done = null; 5104 } 5105 return performDexOptLI(pkg, instructionSets, forceDex, defer, done); 5106 } 5107 5108 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 5109 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 5110 Slog.w(TAG, "Unable to update from " + oldPkg.name 5111 + " to " + newPkg.packageName 5112 + ": old package not in system partition"); 5113 return false; 5114 } else if (mPackages.get(oldPkg.name) != null) { 5115 Slog.w(TAG, "Unable to update from " + oldPkg.name 5116 + " to " + newPkg.packageName 5117 + ": old package still exists"); 5118 return false; 5119 } 5120 return true; 5121 } 5122 5123 File getDataPathForUser(int userId) { 5124 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId); 5125 } 5126 5127 private File getDataPathForPackage(String packageName, int userId) { 5128 /* 5129 * Until we fully support multiple users, return the directory we 5130 * previously would have. The PackageManagerTests will need to be 5131 * revised when this is changed back.. 5132 */ 5133 if (userId == 0) { 5134 return new File(mAppDataDir, packageName); 5135 } else { 5136 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 5137 + File.separator + packageName); 5138 } 5139 } 5140 5141 private int createDataDirsLI(String packageName, int uid, String seinfo) { 5142 int[] users = sUserManager.getUserIds(); 5143 int res = mInstaller.install(packageName, uid, uid, seinfo); 5144 if (res < 0) { 5145 return res; 5146 } 5147 for (int user : users) { 5148 if (user != 0) { 5149 res = mInstaller.createUserData(packageName, 5150 UserHandle.getUid(user, uid), user, seinfo); 5151 if (res < 0) { 5152 return res; 5153 } 5154 } 5155 } 5156 return res; 5157 } 5158 5159 private int removeDataDirsLI(String packageName) { 5160 int[] users = sUserManager.getUserIds(); 5161 int res = 0; 5162 for (int user : users) { 5163 int resInner = mInstaller.remove(packageName, user); 5164 if (resInner < 0) { 5165 res = resInner; 5166 } 5167 } 5168 5169 return res; 5170 } 5171 5172 private int deleteCodeCacheDirsLI(String packageName) { 5173 int[] users = sUserManager.getUserIds(); 5174 int res = 0; 5175 for (int user : users) { 5176 int resInner = mInstaller.deleteCodeCacheFiles(packageName, user); 5177 if (resInner < 0) { 5178 res = resInner; 5179 } 5180 } 5181 return res; 5182 } 5183 5184 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 5185 PackageParser.Package changingLib) { 5186 if (file.path != null) { 5187 usesLibraryFiles.add(file.path); 5188 return; 5189 } 5190 PackageParser.Package p = mPackages.get(file.apk); 5191 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 5192 // If we are doing this while in the middle of updating a library apk, 5193 // then we need to make sure to use that new apk for determining the 5194 // dependencies here. (We haven't yet finished committing the new apk 5195 // to the package manager state.) 5196 if (p == null || p.packageName.equals(changingLib.packageName)) { 5197 p = changingLib; 5198 } 5199 } 5200 if (p != null) { 5201 usesLibraryFiles.addAll(p.getAllCodePaths()); 5202 } 5203 } 5204 5205 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 5206 PackageParser.Package changingLib) throws PackageManagerException { 5207 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 5208 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 5209 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 5210 for (int i=0; i<N; i++) { 5211 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 5212 if (file == null) { 5213 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 5214 "Package " + pkg.packageName + " requires unavailable shared library " 5215 + pkg.usesLibraries.get(i) + "; failing!"); 5216 } 5217 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5218 } 5219 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 5220 for (int i=0; i<N; i++) { 5221 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 5222 if (file == null) { 5223 Slog.w(TAG, "Package " + pkg.packageName 5224 + " desires unavailable shared library " 5225 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 5226 } else { 5227 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5228 } 5229 } 5230 N = usesLibraryFiles.size(); 5231 if (N > 0) { 5232 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 5233 } else { 5234 pkg.usesLibraryFiles = null; 5235 } 5236 } 5237 } 5238 5239 private static boolean hasString(List<String> list, List<String> which) { 5240 if (list == null) { 5241 return false; 5242 } 5243 for (int i=list.size()-1; i>=0; i--) { 5244 for (int j=which.size()-1; j>=0; j--) { 5245 if (which.get(j).equals(list.get(i))) { 5246 return true; 5247 } 5248 } 5249 } 5250 return false; 5251 } 5252 5253 private void updateAllSharedLibrariesLPw() { 5254 for (PackageParser.Package pkg : mPackages.values()) { 5255 try { 5256 updateSharedLibrariesLPw(pkg, null); 5257 } catch (PackageManagerException e) { 5258 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5259 } 5260 } 5261 } 5262 5263 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 5264 PackageParser.Package changingPkg) { 5265 ArrayList<PackageParser.Package> res = null; 5266 for (PackageParser.Package pkg : mPackages.values()) { 5267 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 5268 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 5269 if (res == null) { 5270 res = new ArrayList<PackageParser.Package>(); 5271 } 5272 res.add(pkg); 5273 try { 5274 updateSharedLibrariesLPw(pkg, changingPkg); 5275 } catch (PackageManagerException e) { 5276 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5277 } 5278 } 5279 } 5280 return res; 5281 } 5282 5283 /** 5284 * Derive the value of the {@code cpuAbiOverride} based on the provided 5285 * value and an optional stored value from the package settings. 5286 */ 5287 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5288 String cpuAbiOverride = null; 5289 5290 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5291 cpuAbiOverride = null; 5292 } else if (abiOverride != null) { 5293 cpuAbiOverride = abiOverride; 5294 } else if (settings != null) { 5295 cpuAbiOverride = settings.cpuAbiOverrideString; 5296 } 5297 5298 return cpuAbiOverride; 5299 } 5300 5301 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5302 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5303 boolean success = false; 5304 try { 5305 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 5306 currentTime, user); 5307 success = true; 5308 return res; 5309 } finally { 5310 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5311 removeDataDirsLI(pkg.packageName); 5312 } 5313 } 5314 } 5315 5316 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 5317 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5318 final File scanFile = new File(pkg.codePath); 5319 if (pkg.applicationInfo.getCodePath() == null || 5320 pkg.applicationInfo.getResourcePath() == null) { 5321 // Bail out. The resource and code paths haven't been set. 5322 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5323 "Code and resource paths haven't been set correctly"); 5324 } 5325 5326 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5327 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5328 } else { 5329 // Only allow system apps to be flagged as core apps. 5330 pkg.coreApp = false; 5331 } 5332 5333 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5334 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 5335 } 5336 5337 if (mCustomResolverComponentName != null && 5338 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5339 setUpCustomResolverActivity(pkg); 5340 } 5341 5342 if (pkg.packageName.equals("android")) { 5343 synchronized (mPackages) { 5344 if (mAndroidApplication != null) { 5345 Slog.w(TAG, "*************************************************"); 5346 Slog.w(TAG, "Core android package being redefined. Skipping."); 5347 Slog.w(TAG, " file=" + scanFile); 5348 Slog.w(TAG, "*************************************************"); 5349 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5350 "Core android package being redefined. Skipping."); 5351 } 5352 5353 // Set up information for our fall-back user intent resolution activity. 5354 mPlatformPackage = pkg; 5355 pkg.mVersionCode = mSdkVersion; 5356 mAndroidApplication = pkg.applicationInfo; 5357 5358 if (!mResolverReplaced) { 5359 mResolveActivity.applicationInfo = mAndroidApplication; 5360 mResolveActivity.name = ResolverActivity.class.getName(); 5361 mResolveActivity.packageName = mAndroidApplication.packageName; 5362 mResolveActivity.processName = "system:ui"; 5363 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5364 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5365 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5366 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5367 mResolveActivity.exported = true; 5368 mResolveActivity.enabled = true; 5369 mResolveInfo.activityInfo = mResolveActivity; 5370 mResolveInfo.priority = 0; 5371 mResolveInfo.preferredOrder = 0; 5372 mResolveInfo.match = 0; 5373 mResolveComponentName = new ComponentName( 5374 mAndroidApplication.packageName, mResolveActivity.name); 5375 } 5376 } 5377 } 5378 5379 if (DEBUG_PACKAGE_SCANNING) { 5380 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5381 Log.d(TAG, "Scanning package " + pkg.packageName); 5382 } 5383 5384 if (mPackages.containsKey(pkg.packageName) 5385 || mSharedLibraries.containsKey(pkg.packageName)) { 5386 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5387 "Application package " + pkg.packageName 5388 + " already installed. Skipping duplicate."); 5389 } 5390 5391 // Initialize package source and resource directories 5392 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5393 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5394 5395 SharedUserSetting suid = null; 5396 PackageSetting pkgSetting = null; 5397 5398 if (!isSystemApp(pkg)) { 5399 // Only system apps can use these features. 5400 pkg.mOriginalPackages = null; 5401 pkg.mRealPackage = null; 5402 pkg.mAdoptPermissions = null; 5403 } 5404 5405 // writer 5406 synchronized (mPackages) { 5407 if (pkg.mSharedUserId != null) { 5408 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 5409 if (suid == null) { 5410 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5411 "Creating application package " + pkg.packageName 5412 + " for shared user failed"); 5413 } 5414 if (DEBUG_PACKAGE_SCANNING) { 5415 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5416 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5417 + "): packages=" + suid.packages); 5418 } 5419 } 5420 5421 // Check if we are renaming from an original package name. 5422 PackageSetting origPackage = null; 5423 String realName = null; 5424 if (pkg.mOriginalPackages != null) { 5425 // This package may need to be renamed to a previously 5426 // installed name. Let's check on that... 5427 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5428 if (pkg.mOriginalPackages.contains(renamed)) { 5429 // This package had originally been installed as the 5430 // original name, and we have already taken care of 5431 // transitioning to the new one. Just update the new 5432 // one to continue using the old name. 5433 realName = pkg.mRealPackage; 5434 if (!pkg.packageName.equals(renamed)) { 5435 // Callers into this function may have already taken 5436 // care of renaming the package; only do it here if 5437 // it is not already done. 5438 pkg.setPackageName(renamed); 5439 } 5440 5441 } else { 5442 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5443 if ((origPackage = mSettings.peekPackageLPr( 5444 pkg.mOriginalPackages.get(i))) != null) { 5445 // We do have the package already installed under its 5446 // original name... should we use it? 5447 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5448 // New package is not compatible with original. 5449 origPackage = null; 5450 continue; 5451 } else if (origPackage.sharedUser != null) { 5452 // Make sure uid is compatible between packages. 5453 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5454 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5455 + " to " + pkg.packageName + ": old uid " 5456 + origPackage.sharedUser.name 5457 + " differs from " + pkg.mSharedUserId); 5458 origPackage = null; 5459 continue; 5460 } 5461 } else { 5462 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5463 + pkg.packageName + " to old name " + origPackage.name); 5464 } 5465 break; 5466 } 5467 } 5468 } 5469 } 5470 5471 if (mTransferedPackages.contains(pkg.packageName)) { 5472 Slog.w(TAG, "Package " + pkg.packageName 5473 + " was transferred to another, but its .apk remains"); 5474 } 5475 5476 // Just create the setting, don't add it yet. For already existing packages 5477 // the PkgSetting exists already and doesn't have to be created. 5478 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5479 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 5480 pkg.applicationInfo.primaryCpuAbi, 5481 pkg.applicationInfo.secondaryCpuAbi, 5482 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 5483 user, false); 5484 if (pkgSetting == null) { 5485 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5486 "Creating application package " + pkg.packageName + " failed"); 5487 } 5488 5489 if (pkgSetting.origPackage != null) { 5490 // If we are first transitioning from an original package, 5491 // fix up the new package's name now. We need to do this after 5492 // looking up the package under its new name, so getPackageLP 5493 // can take care of fiddling things correctly. 5494 pkg.setPackageName(origPackage.name); 5495 5496 // File a report about this. 5497 String msg = "New package " + pkgSetting.realName 5498 + " renamed to replace old package " + pkgSetting.name; 5499 reportSettingsProblem(Log.WARN, msg); 5500 5501 // Make a note of it. 5502 mTransferedPackages.add(origPackage.name); 5503 5504 // No longer need to retain this. 5505 pkgSetting.origPackage = null; 5506 } 5507 5508 if (realName != null) { 5509 // Make a note of it. 5510 mTransferedPackages.add(pkg.packageName); 5511 } 5512 5513 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5514 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5515 } 5516 5517 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5518 // Check all shared libraries and map to their actual file path. 5519 // We only do this here for apps not on a system dir, because those 5520 // are the only ones that can fail an install due to this. We 5521 // will take care of the system apps by updating all of their 5522 // library paths after the scan is done. 5523 updateSharedLibrariesLPw(pkg, null); 5524 } 5525 5526 if (mFoundPolicyFile) { 5527 SELinuxMMAC.assignSeinfoValue(pkg); 5528 } 5529 5530 pkg.applicationInfo.uid = pkgSetting.appId; 5531 pkg.mExtras = pkgSetting; 5532 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5533 try { 5534 verifySignaturesLP(pkgSetting, pkg); 5535 // We just determined the app is signed correctly, so bring 5536 // over the latest parsed certs. 5537 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5538 } catch (PackageManagerException e) { 5539 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5540 throw e; 5541 } 5542 // The signature has changed, but this package is in the system 5543 // image... let's recover! 5544 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5545 // However... if this package is part of a shared user, but it 5546 // doesn't match the signature of the shared user, let's fail. 5547 // What this means is that you can't change the signatures 5548 // associated with an overall shared user, which doesn't seem all 5549 // that unreasonable. 5550 if (pkgSetting.sharedUser != null) { 5551 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5552 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5553 throw new PackageManagerException( 5554 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 5555 "Signature mismatch for shared user : " 5556 + pkgSetting.sharedUser); 5557 } 5558 } 5559 // File a report about this. 5560 String msg = "System package " + pkg.packageName 5561 + " signature changed; retaining data."; 5562 reportSettingsProblem(Log.WARN, msg); 5563 } 5564 } else { 5565 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 5566 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5567 + pkg.packageName + " upgrade keys do not match the " 5568 + "previously installed version"); 5569 } else { 5570 // We just determined the app is signed correctly, so bring 5571 // over the latest parsed certs. 5572 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5573 } 5574 } 5575 // Verify that this new package doesn't have any content providers 5576 // that conflict with existing packages. Only do this if the 5577 // package isn't already installed, since we don't want to break 5578 // things that are installed. 5579 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 5580 final int N = pkg.providers.size(); 5581 int i; 5582 for (i=0; i<N; i++) { 5583 PackageParser.Provider p = pkg.providers.get(i); 5584 if (p.info.authority != null) { 5585 String names[] = p.info.authority.split(";"); 5586 for (int j = 0; j < names.length; j++) { 5587 if (mProvidersByAuthority.containsKey(names[j])) { 5588 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5589 final String otherPackageName = 5590 ((other != null && other.getComponentName() != null) ? 5591 other.getComponentName().getPackageName() : "?"); 5592 throw new PackageManagerException( 5593 INSTALL_FAILED_CONFLICTING_PROVIDER, 5594 "Can't install because provider name " + names[j] 5595 + " (in package " + pkg.applicationInfo.packageName 5596 + ") is already used by " + otherPackageName); 5597 } 5598 } 5599 } 5600 } 5601 } 5602 5603 if (pkg.mAdoptPermissions != null) { 5604 // This package wants to adopt ownership of permissions from 5605 // another package. 5606 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 5607 final String origName = pkg.mAdoptPermissions.get(i); 5608 final PackageSetting orig = mSettings.peekPackageLPr(origName); 5609 if (orig != null) { 5610 if (verifyPackageUpdateLPr(orig, pkg)) { 5611 Slog.i(TAG, "Adopting permissions from " + origName + " to " 5612 + pkg.packageName); 5613 mSettings.transferPermissionsLPw(origName, pkg.packageName); 5614 } 5615 } 5616 } 5617 } 5618 } 5619 5620 final String pkgName = pkg.packageName; 5621 5622 final long scanFileTime = scanFile.lastModified(); 5623 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 5624 pkg.applicationInfo.processName = fixProcessName( 5625 pkg.applicationInfo.packageName, 5626 pkg.applicationInfo.processName, 5627 pkg.applicationInfo.uid); 5628 5629 File dataPath; 5630 if (mPlatformPackage == pkg) { 5631 // The system package is special. 5632 dataPath = new File(Environment.getDataDirectory(), "system"); 5633 5634 pkg.applicationInfo.dataDir = dataPath.getPath(); 5635 5636 } else { 5637 // This is a normal package, need to make its data directory. 5638 dataPath = getDataPathForPackage(pkg.packageName, 0); 5639 5640 boolean uidError = false; 5641 if (dataPath.exists()) { 5642 int currentUid = 0; 5643 try { 5644 StructStat stat = Os.stat(dataPath.getPath()); 5645 currentUid = stat.st_uid; 5646 } catch (ErrnoException e) { 5647 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 5648 } 5649 5650 // If we have mismatched owners for the data path, we have a problem. 5651 if (currentUid != pkg.applicationInfo.uid) { 5652 boolean recovered = false; 5653 if (currentUid == 0) { 5654 // The directory somehow became owned by root. Wow. 5655 // This is probably because the system was stopped while 5656 // installd was in the middle of messing with its libs 5657 // directory. Ask installd to fix that. 5658 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 5659 pkg.applicationInfo.uid); 5660 if (ret >= 0) { 5661 recovered = true; 5662 String msg = "Package " + pkg.packageName 5663 + " unexpectedly changed to uid 0; recovered to " + 5664 + pkg.applicationInfo.uid; 5665 reportSettingsProblem(Log.WARN, msg); 5666 } 5667 } 5668 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5669 || (scanFlags&SCAN_BOOTING) != 0)) { 5670 // If this is a system app, we can at least delete its 5671 // current data so the application will still work. 5672 int ret = removeDataDirsLI(pkgName); 5673 if (ret >= 0) { 5674 // TODO: Kill the processes first 5675 // Old data gone! 5676 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5677 ? "System package " : "Third party package "; 5678 String msg = prefix + pkg.packageName 5679 + " has changed from uid: " 5680 + currentUid + " to " 5681 + pkg.applicationInfo.uid + "; old data erased"; 5682 reportSettingsProblem(Log.WARN, msg); 5683 recovered = true; 5684 5685 // And now re-install the app. 5686 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5687 pkg.applicationInfo.seinfo); 5688 if (ret == -1) { 5689 // Ack should not happen! 5690 msg = prefix + pkg.packageName 5691 + " could not have data directory re-created after delete."; 5692 reportSettingsProblem(Log.WARN, msg); 5693 throw new PackageManagerException( 5694 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 5695 } 5696 } 5697 if (!recovered) { 5698 mHasSystemUidErrors = true; 5699 } 5700 } else if (!recovered) { 5701 // If we allow this install to proceed, we will be broken. 5702 // Abort, abort! 5703 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 5704 "scanPackageLI"); 5705 } 5706 if (!recovered) { 5707 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 5708 + pkg.applicationInfo.uid + "/fs_" 5709 + currentUid; 5710 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 5711 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 5712 String msg = "Package " + pkg.packageName 5713 + " has mismatched uid: " 5714 + currentUid + " on disk, " 5715 + pkg.applicationInfo.uid + " in settings"; 5716 // writer 5717 synchronized (mPackages) { 5718 mSettings.mReadMessages.append(msg); 5719 mSettings.mReadMessages.append('\n'); 5720 uidError = true; 5721 if (!pkgSetting.uidError) { 5722 reportSettingsProblem(Log.ERROR, msg); 5723 } 5724 } 5725 } 5726 } 5727 pkg.applicationInfo.dataDir = dataPath.getPath(); 5728 if (mShouldRestoreconData) { 5729 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 5730 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 5731 pkg.applicationInfo.uid); 5732 } 5733 } else { 5734 if (DEBUG_PACKAGE_SCANNING) { 5735 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5736 Log.v(TAG, "Want this data dir: " + dataPath); 5737 } 5738 //invoke installer to do the actual installation 5739 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5740 pkg.applicationInfo.seinfo); 5741 if (ret < 0) { 5742 // Error from installer 5743 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5744 "Unable to create data dirs [errorCode=" + ret + "]"); 5745 } 5746 5747 if (dataPath.exists()) { 5748 pkg.applicationInfo.dataDir = dataPath.getPath(); 5749 } else { 5750 Slog.w(TAG, "Unable to create data directory: " + dataPath); 5751 pkg.applicationInfo.dataDir = null; 5752 } 5753 } 5754 5755 pkgSetting.uidError = uidError; 5756 } 5757 5758 final String path = scanFile.getPath(); 5759 final String codePath = pkg.applicationInfo.getCodePath(); 5760 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 5761 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 5762 setBundledAppAbisAndRoots(pkg, pkgSetting); 5763 5764 // If we haven't found any native libraries for the app, check if it has 5765 // renderscript code. We'll need to force the app to 32 bit if it has 5766 // renderscript bitcode. 5767 if (pkg.applicationInfo.primaryCpuAbi == null 5768 && pkg.applicationInfo.secondaryCpuAbi == null 5769 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5770 NativeLibraryHelper.Handle handle = null; 5771 try { 5772 handle = NativeLibraryHelper.Handle.create(scanFile); 5773 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5774 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 5775 } 5776 } catch (IOException ioe) { 5777 Slog.w(TAG, "Error scanning system app : " + ioe); 5778 } finally { 5779 IoUtils.closeQuietly(handle); 5780 } 5781 } 5782 5783 setNativeLibraryPaths(pkg); 5784 } else { 5785 // TODO: We can probably be smarter about this stuff. For installed apps, 5786 // we can calculate this information at install time once and for all. For 5787 // system apps, we can probably assume that this information doesn't change 5788 // after the first boot scan. As things stand, we do lots of unnecessary work. 5789 5790 // Give ourselves some initial paths; we'll come back for another 5791 // pass once we've determined ABI below. 5792 setNativeLibraryPaths(pkg); 5793 5794 final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg); 5795 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 5796 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 5797 5798 NativeLibraryHelper.Handle handle = null; 5799 try { 5800 handle = NativeLibraryHelper.Handle.create(scanFile); 5801 // TODO(multiArch): This can be null for apps that didn't go through the 5802 // usual installation process. We can calculate it again, like we 5803 // do during install time. 5804 // 5805 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 5806 // unnecessary. 5807 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 5808 5809 // Null out the abis so that they can be recalculated. 5810 pkg.applicationInfo.primaryCpuAbi = null; 5811 pkg.applicationInfo.secondaryCpuAbi = null; 5812 if (isMultiArch(pkg.applicationInfo)) { 5813 // Warn if we've set an abiOverride for multi-lib packages.. 5814 // By definition, we need to copy both 32 and 64 bit libraries for 5815 // such packages. 5816 if (pkg.cpuAbiOverride != null 5817 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 5818 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 5819 } 5820 5821 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 5822 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 5823 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 5824 if (isAsec) { 5825 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 5826 } else { 5827 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5828 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 5829 useIsaSpecificSubdirs); 5830 } 5831 } 5832 5833 maybeThrowExceptionForMultiArchCopy( 5834 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 5835 5836 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5837 if (isAsec) { 5838 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 5839 } else { 5840 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5841 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 5842 useIsaSpecificSubdirs); 5843 } 5844 } 5845 5846 maybeThrowExceptionForMultiArchCopy( 5847 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 5848 5849 if (abi64 >= 0) { 5850 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 5851 } 5852 5853 if (abi32 >= 0) { 5854 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 5855 if (abi64 >= 0) { 5856 pkg.applicationInfo.secondaryCpuAbi = abi; 5857 } else { 5858 pkg.applicationInfo.primaryCpuAbi = abi; 5859 } 5860 } 5861 } else { 5862 String[] abiList = (cpuAbiOverride != null) ? 5863 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 5864 5865 // Enable gross and lame hacks for apps that are built with old 5866 // SDK tools. We must scan their APKs for renderscript bitcode and 5867 // not launch them if it's present. Don't bother checking on devices 5868 // that don't have 64 bit support. 5869 boolean needsRenderScriptOverride = false; 5870 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 5871 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5872 abiList = Build.SUPPORTED_32_BIT_ABIS; 5873 needsRenderScriptOverride = true; 5874 } 5875 5876 final int copyRet; 5877 if (isAsec) { 5878 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 5879 } else { 5880 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5881 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 5882 } 5883 5884 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5885 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5886 "Error unpackaging native libs for app, errorCode=" + copyRet); 5887 } 5888 5889 if (copyRet >= 0) { 5890 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 5891 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 5892 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 5893 } else if (needsRenderScriptOverride) { 5894 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 5895 } 5896 } 5897 } catch (IOException ioe) { 5898 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 5899 } finally { 5900 IoUtils.closeQuietly(handle); 5901 } 5902 5903 // Now that we've calculated the ABIs and determined if it's an internal app, 5904 // we will go ahead and populate the nativeLibraryPath. 5905 setNativeLibraryPaths(pkg); 5906 5907 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 5908 final int[] userIds = sUserManager.getUserIds(); 5909 synchronized (mInstallLock) { 5910 // Create a native library symlink only if we have native libraries 5911 // and if the native libraries are 32 bit libraries. We do not provide 5912 // this symlink for 64 bit libraries. 5913 if (pkg.applicationInfo.primaryCpuAbi != null && 5914 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 5915 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 5916 for (int userId : userIds) { 5917 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 5918 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5919 "Failed linking native library dir (user=" + userId + ")"); 5920 } 5921 } 5922 } 5923 } 5924 } 5925 5926 // This is a special case for the "system" package, where the ABI is 5927 // dictated by the zygote configuration (and init.rc). We should keep track 5928 // of this ABI so that we can deal with "normal" applications that run under 5929 // the same UID correctly. 5930 if (mPlatformPackage == pkg) { 5931 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 5932 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 5933 } 5934 5935 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 5936 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 5937 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 5938 // Copy the derived override back to the parsed package, so that we can 5939 // update the package settings accordingly. 5940 pkg.cpuAbiOverride = cpuAbiOverride; 5941 5942 if (DEBUG_ABI_SELECTION) { 5943 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 5944 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 5945 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 5946 } 5947 5948 // Push the derived path down into PackageSettings so we know what to 5949 // clean up at uninstall time. 5950 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 5951 5952 if (DEBUG_ABI_SELECTION) { 5953 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 5954 " primary=" + pkg.applicationInfo.primaryCpuAbi + 5955 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 5956 } 5957 5958 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 5959 // We don't do this here during boot because we can do it all 5960 // at once after scanning all existing packages. 5961 // 5962 // We also do this *before* we perform dexopt on this package, so that 5963 // we can avoid redundant dexopts, and also to make sure we've got the 5964 // code and package path correct. 5965 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 5966 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 5967 } 5968 5969 if ((scanFlags & SCAN_NO_DEX) == 0) { 5970 if (performDexOptLI(pkg, null /* instruction sets */, forceDex, 5971 (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) { 5972 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 5973 } 5974 } 5975 5976 if (mFactoryTest && pkg.requestedPermissions.contains( 5977 android.Manifest.permission.FACTORY_TEST)) { 5978 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 5979 } 5980 5981 ArrayList<PackageParser.Package> clientLibPkgs = null; 5982 5983 // writer 5984 synchronized (mPackages) { 5985 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5986 // Only system apps can add new shared libraries. 5987 if (pkg.libraryNames != null) { 5988 for (int i=0; i<pkg.libraryNames.size(); i++) { 5989 String name = pkg.libraryNames.get(i); 5990 boolean allowed = false; 5991 if (isUpdatedSystemApp(pkg)) { 5992 // New library entries can only be added through the 5993 // system image. This is important to get rid of a lot 5994 // of nasty edge cases: for example if we allowed a non- 5995 // system update of the app to add a library, then uninstalling 5996 // the update would make the library go away, and assumptions 5997 // we made such as through app install filtering would now 5998 // have allowed apps on the device which aren't compatible 5999 // with it. Better to just have the restriction here, be 6000 // conservative, and create many fewer cases that can negatively 6001 // impact the user experience. 6002 final PackageSetting sysPs = mSettings 6003 .getDisabledSystemPkgLPr(pkg.packageName); 6004 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 6005 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 6006 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 6007 allowed = true; 6008 allowed = true; 6009 break; 6010 } 6011 } 6012 } 6013 } else { 6014 allowed = true; 6015 } 6016 if (allowed) { 6017 if (!mSharedLibraries.containsKey(name)) { 6018 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 6019 } else if (!name.equals(pkg.packageName)) { 6020 Slog.w(TAG, "Package " + pkg.packageName + " library " 6021 + name + " already exists; skipping"); 6022 } 6023 } else { 6024 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 6025 + name + " that is not declared on system image; skipping"); 6026 } 6027 } 6028 if ((scanFlags&SCAN_BOOTING) == 0) { 6029 // If we are not booting, we need to update any applications 6030 // that are clients of our shared library. If we are booting, 6031 // this will all be done once the scan is complete. 6032 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 6033 } 6034 } 6035 } 6036 } 6037 6038 // We also need to dexopt any apps that are dependent on this library. Note that 6039 // if these fail, we should abort the install since installing the library will 6040 // result in some apps being broken. 6041 if (clientLibPkgs != null) { 6042 if ((scanFlags & SCAN_NO_DEX) == 0) { 6043 for (int i = 0; i < clientLibPkgs.size(); i++) { 6044 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6045 if (performDexOptLI(clientPkg, null /* instruction sets */, forceDex, 6046 (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) { 6047 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 6048 "scanPackageLI failed to dexopt clientLibPkgs"); 6049 } 6050 } 6051 } 6052 } 6053 6054 // Request the ActivityManager to kill the process(only for existing packages) 6055 // so that we do not end up in a confused state while the user is still using the older 6056 // version of the application while the new one gets installed. 6057 if ((scanFlags & SCAN_REPLACING) != 0) { 6058 killApplication(pkg.applicationInfo.packageName, 6059 pkg.applicationInfo.uid, "update pkg"); 6060 } 6061 6062 // Also need to kill any apps that are dependent on the library. 6063 if (clientLibPkgs != null) { 6064 for (int i=0; i<clientLibPkgs.size(); i++) { 6065 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6066 killApplication(clientPkg.applicationInfo.packageName, 6067 clientPkg.applicationInfo.uid, "update lib"); 6068 } 6069 } 6070 6071 // writer 6072 synchronized (mPackages) { 6073 // We don't expect installation to fail beyond this point 6074 6075 // Add the new setting to mSettings 6076 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 6077 // Add the new setting to mPackages 6078 mPackages.put(pkg.applicationInfo.packageName, pkg); 6079 // Make sure we don't accidentally delete its data. 6080 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 6081 while (iter.hasNext()) { 6082 PackageCleanItem item = iter.next(); 6083 if (pkgName.equals(item.packageName)) { 6084 iter.remove(); 6085 } 6086 } 6087 6088 // Take care of first install / last update times. 6089 if (currentTime != 0) { 6090 if (pkgSetting.firstInstallTime == 0) { 6091 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 6092 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 6093 pkgSetting.lastUpdateTime = currentTime; 6094 } 6095 } else if (pkgSetting.firstInstallTime == 0) { 6096 // We need *something*. Take time time stamp of the file. 6097 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 6098 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 6099 if (scanFileTime != pkgSetting.timeStamp) { 6100 // A package on the system image has changed; consider this 6101 // to be an update. 6102 pkgSetting.lastUpdateTime = scanFileTime; 6103 } 6104 } 6105 6106 // Add the package's KeySets to the global KeySetManagerService 6107 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6108 try { 6109 // Old KeySetData no longer valid. 6110 ksms.removeAppKeySetDataLPw(pkg.packageName); 6111 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 6112 if (pkg.mKeySetMapping != null) { 6113 for (Map.Entry<String, ArraySet<PublicKey>> entry : 6114 pkg.mKeySetMapping.entrySet()) { 6115 if (entry.getValue() != null) { 6116 ksms.addDefinedKeySetToPackageLPw(pkg.packageName, 6117 entry.getValue(), entry.getKey()); 6118 } 6119 } 6120 if (pkg.mUpgradeKeySets != null) { 6121 for (String upgradeAlias : pkg.mUpgradeKeySets) { 6122 ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias); 6123 } 6124 } 6125 } 6126 } catch (NullPointerException e) { 6127 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 6128 } catch (IllegalArgumentException e) { 6129 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 6130 } 6131 6132 int N = pkg.providers.size(); 6133 StringBuilder r = null; 6134 int i; 6135 for (i=0; i<N; i++) { 6136 PackageParser.Provider p = pkg.providers.get(i); 6137 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 6138 p.info.processName, pkg.applicationInfo.uid); 6139 mProviders.addProvider(p); 6140 p.syncable = p.info.isSyncable; 6141 if (p.info.authority != null) { 6142 String names[] = p.info.authority.split(";"); 6143 p.info.authority = null; 6144 for (int j = 0; j < names.length; j++) { 6145 if (j == 1 && p.syncable) { 6146 // We only want the first authority for a provider to possibly be 6147 // syncable, so if we already added this provider using a different 6148 // authority clear the syncable flag. We copy the provider before 6149 // changing it because the mProviders object contains a reference 6150 // to a provider that we don't want to change. 6151 // Only do this for the second authority since the resulting provider 6152 // object can be the same for all future authorities for this provider. 6153 p = new PackageParser.Provider(p); 6154 p.syncable = false; 6155 } 6156 if (!mProvidersByAuthority.containsKey(names[j])) { 6157 mProvidersByAuthority.put(names[j], p); 6158 if (p.info.authority == null) { 6159 p.info.authority = names[j]; 6160 } else { 6161 p.info.authority = p.info.authority + ";" + names[j]; 6162 } 6163 if (DEBUG_PACKAGE_SCANNING) { 6164 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6165 Log.d(TAG, "Registered content provider: " + names[j] 6166 + ", className = " + p.info.name + ", isSyncable = " 6167 + p.info.isSyncable); 6168 } 6169 } else { 6170 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6171 Slog.w(TAG, "Skipping provider name " + names[j] + 6172 " (in package " + pkg.applicationInfo.packageName + 6173 "): name already used by " 6174 + ((other != null && other.getComponentName() != null) 6175 ? other.getComponentName().getPackageName() : "?")); 6176 } 6177 } 6178 } 6179 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6180 if (r == null) { 6181 r = new StringBuilder(256); 6182 } else { 6183 r.append(' '); 6184 } 6185 r.append(p.info.name); 6186 } 6187 } 6188 if (r != null) { 6189 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 6190 } 6191 6192 N = pkg.services.size(); 6193 r = null; 6194 for (i=0; i<N; i++) { 6195 PackageParser.Service s = pkg.services.get(i); 6196 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 6197 s.info.processName, pkg.applicationInfo.uid); 6198 mServices.addService(s); 6199 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6200 if (r == null) { 6201 r = new StringBuilder(256); 6202 } else { 6203 r.append(' '); 6204 } 6205 r.append(s.info.name); 6206 } 6207 } 6208 if (r != null) { 6209 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 6210 } 6211 6212 N = pkg.receivers.size(); 6213 r = null; 6214 for (i=0; i<N; i++) { 6215 PackageParser.Activity a = pkg.receivers.get(i); 6216 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6217 a.info.processName, pkg.applicationInfo.uid); 6218 mReceivers.addActivity(a, "receiver"); 6219 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6220 if (r == null) { 6221 r = new StringBuilder(256); 6222 } else { 6223 r.append(' '); 6224 } 6225 r.append(a.info.name); 6226 } 6227 } 6228 if (r != null) { 6229 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 6230 } 6231 6232 N = pkg.activities.size(); 6233 r = null; 6234 for (i=0; i<N; i++) { 6235 PackageParser.Activity a = pkg.activities.get(i); 6236 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6237 a.info.processName, pkg.applicationInfo.uid); 6238 mActivities.addActivity(a, "activity"); 6239 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6240 if (r == null) { 6241 r = new StringBuilder(256); 6242 } else { 6243 r.append(' '); 6244 } 6245 r.append(a.info.name); 6246 } 6247 } 6248 if (r != null) { 6249 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 6250 } 6251 6252 N = pkg.permissionGroups.size(); 6253 r = null; 6254 for (i=0; i<N; i++) { 6255 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 6256 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 6257 if (cur == null) { 6258 mPermissionGroups.put(pg.info.name, pg); 6259 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6260 if (r == null) { 6261 r = new StringBuilder(256); 6262 } else { 6263 r.append(' '); 6264 } 6265 r.append(pg.info.name); 6266 } 6267 } else { 6268 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 6269 + pg.info.packageName + " ignored: original from " 6270 + cur.info.packageName); 6271 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6272 if (r == null) { 6273 r = new StringBuilder(256); 6274 } else { 6275 r.append(' '); 6276 } 6277 r.append("DUP:"); 6278 r.append(pg.info.name); 6279 } 6280 } 6281 } 6282 if (r != null) { 6283 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6284 } 6285 6286 N = pkg.permissions.size(); 6287 r = null; 6288 for (i=0; i<N; i++) { 6289 PackageParser.Permission p = pkg.permissions.get(i); 6290 ArrayMap<String, BasePermission> permissionMap = 6291 p.tree ? mSettings.mPermissionTrees 6292 : mSettings.mPermissions; 6293 p.group = mPermissionGroups.get(p.info.group); 6294 if (p.info.group == null || p.group != null) { 6295 BasePermission bp = permissionMap.get(p.info.name); 6296 6297 // Allow system apps to redefine non-system permissions 6298 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 6299 final boolean currentOwnerIsSystem = (bp.perm != null 6300 && isSystemApp(bp.perm.owner)); 6301 if (isSystemApp(p.owner)) { 6302 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 6303 // It's a built-in permission and no owner, take ownership now 6304 bp.packageSetting = pkgSetting; 6305 bp.perm = p; 6306 bp.uid = pkg.applicationInfo.uid; 6307 bp.sourcePackage = p.info.packageName; 6308 } else if (!currentOwnerIsSystem) { 6309 String msg = "New decl " + p.owner + " of permission " 6310 + p.info.name + " is system; overriding " + bp.sourcePackage; 6311 reportSettingsProblem(Log.WARN, msg); 6312 bp = null; 6313 } 6314 } 6315 } 6316 6317 if (bp == null) { 6318 bp = new BasePermission(p.info.name, p.info.packageName, 6319 BasePermission.TYPE_NORMAL); 6320 permissionMap.put(p.info.name, bp); 6321 } 6322 6323 if (bp.perm == null) { 6324 if (bp.sourcePackage == null 6325 || bp.sourcePackage.equals(p.info.packageName)) { 6326 BasePermission tree = findPermissionTreeLP(p.info.name); 6327 if (tree == null 6328 || tree.sourcePackage.equals(p.info.packageName)) { 6329 bp.packageSetting = pkgSetting; 6330 bp.perm = p; 6331 bp.uid = pkg.applicationInfo.uid; 6332 bp.sourcePackage = p.info.packageName; 6333 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6334 if (r == null) { 6335 r = new StringBuilder(256); 6336 } else { 6337 r.append(' '); 6338 } 6339 r.append(p.info.name); 6340 } 6341 } else { 6342 Slog.w(TAG, "Permission " + p.info.name + " from package " 6343 + p.info.packageName + " ignored: base tree " 6344 + tree.name + " is from package " 6345 + tree.sourcePackage); 6346 } 6347 } else { 6348 Slog.w(TAG, "Permission " + p.info.name + " from package " 6349 + p.info.packageName + " ignored: original from " 6350 + bp.sourcePackage); 6351 } 6352 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6353 if (r == null) { 6354 r = new StringBuilder(256); 6355 } else { 6356 r.append(' '); 6357 } 6358 r.append("DUP:"); 6359 r.append(p.info.name); 6360 } 6361 if (bp.perm == p) { 6362 bp.protectionLevel = p.info.protectionLevel; 6363 } 6364 } else { 6365 Slog.w(TAG, "Permission " + p.info.name + " from package " 6366 + p.info.packageName + " ignored: no group " 6367 + p.group); 6368 } 6369 } 6370 if (r != null) { 6371 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6372 } 6373 6374 N = pkg.instrumentation.size(); 6375 r = null; 6376 for (i=0; i<N; i++) { 6377 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6378 a.info.packageName = pkg.applicationInfo.packageName; 6379 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6380 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6381 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6382 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6383 a.info.dataDir = pkg.applicationInfo.dataDir; 6384 6385 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6386 // need other information about the application, like the ABI and what not ? 6387 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6388 mInstrumentation.put(a.getComponentName(), a); 6389 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6390 if (r == null) { 6391 r = new StringBuilder(256); 6392 } else { 6393 r.append(' '); 6394 } 6395 r.append(a.info.name); 6396 } 6397 } 6398 if (r != null) { 6399 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6400 } 6401 6402 if (pkg.protectedBroadcasts != null) { 6403 N = pkg.protectedBroadcasts.size(); 6404 for (i=0; i<N; i++) { 6405 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6406 } 6407 } 6408 6409 pkgSetting.setTimeStamp(scanFileTime); 6410 6411 // Create idmap files for pairs of (packages, overlay packages). 6412 // Note: "android", ie framework-res.apk, is handled by native layers. 6413 if (pkg.mOverlayTarget != null) { 6414 // This is an overlay package. 6415 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6416 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6417 mOverlays.put(pkg.mOverlayTarget, 6418 new ArrayMap<String, PackageParser.Package>()); 6419 } 6420 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6421 map.put(pkg.packageName, pkg); 6422 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6423 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6424 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6425 "scanPackageLI failed to createIdmap"); 6426 } 6427 } 6428 } else if (mOverlays.containsKey(pkg.packageName) && 6429 !pkg.packageName.equals("android")) { 6430 // This is a regular package, with one or more known overlay packages. 6431 createIdmapsForPackageLI(pkg); 6432 } 6433 } 6434 6435 return pkg; 6436 } 6437 6438 /** 6439 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6440 * i.e, so that all packages can be run inside a single process if required. 6441 * 6442 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6443 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6444 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6445 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6446 * updating a package that belongs to a shared user. 6447 * 6448 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6449 * adds unnecessary complexity. 6450 */ 6451 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6452 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6453 String requiredInstructionSet = null; 6454 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6455 requiredInstructionSet = VMRuntime.getInstructionSet( 6456 scannedPackage.applicationInfo.primaryCpuAbi); 6457 } 6458 6459 PackageSetting requirer = null; 6460 for (PackageSetting ps : packagesForUser) { 6461 // If packagesForUser contains scannedPackage, we skip it. This will happen 6462 // when scannedPackage is an update of an existing package. Without this check, 6463 // we will never be able to change the ABI of any package belonging to a shared 6464 // user, even if it's compatible with other packages. 6465 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6466 if (ps.primaryCpuAbiString == null) { 6467 continue; 6468 } 6469 6470 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6471 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6472 // We have a mismatch between instruction sets (say arm vs arm64) warn about 6473 // this but there's not much we can do. 6474 String errorMessage = "Instruction set mismatch, " 6475 + ((requirer == null) ? "[caller]" : requirer) 6476 + " requires " + requiredInstructionSet + " whereas " + ps 6477 + " requires " + instructionSet; 6478 Slog.w(TAG, errorMessage); 6479 } 6480 6481 if (requiredInstructionSet == null) { 6482 requiredInstructionSet = instructionSet; 6483 requirer = ps; 6484 } 6485 } 6486 } 6487 6488 if (requiredInstructionSet != null) { 6489 String adjustedAbi; 6490 if (requirer != null) { 6491 // requirer != null implies that either scannedPackage was null or that scannedPackage 6492 // did not require an ABI, in which case we have to adjust scannedPackage to match 6493 // the ABI of the set (which is the same as requirer's ABI) 6494 adjustedAbi = requirer.primaryCpuAbiString; 6495 if (scannedPackage != null) { 6496 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6497 } 6498 } else { 6499 // requirer == null implies that we're updating all ABIs in the set to 6500 // match scannedPackage. 6501 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6502 } 6503 6504 for (PackageSetting ps : packagesForUser) { 6505 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6506 if (ps.primaryCpuAbiString != null) { 6507 continue; 6508 } 6509 6510 ps.primaryCpuAbiString = adjustedAbi; 6511 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6512 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6513 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6514 6515 if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt, 6516 deferDexOpt, true) == DEX_OPT_FAILED) { 6517 ps.primaryCpuAbiString = null; 6518 ps.pkg.applicationInfo.primaryCpuAbi = null; 6519 return; 6520 } else { 6521 mInstaller.rmdex(ps.codePathString, 6522 getDexCodeInstructionSet(getPreferredInstructionSet())); 6523 } 6524 } 6525 } 6526 } 6527 } 6528 } 6529 6530 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6531 synchronized (mPackages) { 6532 mResolverReplaced = true; 6533 // Set up information for custom user intent resolution activity. 6534 mResolveActivity.applicationInfo = pkg.applicationInfo; 6535 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6536 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6537 mResolveActivity.processName = pkg.applicationInfo.packageName; 6538 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6539 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6540 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6541 mResolveActivity.theme = 0; 6542 mResolveActivity.exported = true; 6543 mResolveActivity.enabled = true; 6544 mResolveInfo.activityInfo = mResolveActivity; 6545 mResolveInfo.priority = 0; 6546 mResolveInfo.preferredOrder = 0; 6547 mResolveInfo.match = 0; 6548 mResolveComponentName = mCustomResolverComponentName; 6549 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6550 mResolveComponentName); 6551 } 6552 } 6553 6554 private static String calculateBundledApkRoot(final String codePathString) { 6555 final File codePath = new File(codePathString); 6556 final File codeRoot; 6557 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6558 codeRoot = Environment.getRootDirectory(); 6559 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6560 codeRoot = Environment.getOemDirectory(); 6561 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6562 codeRoot = Environment.getVendorDirectory(); 6563 } else { 6564 // Unrecognized code path; take its top real segment as the apk root: 6565 // e.g. /something/app/blah.apk => /something 6566 try { 6567 File f = codePath.getCanonicalFile(); 6568 File parent = f.getParentFile(); // non-null because codePath is a file 6569 File tmp; 6570 while ((tmp = parent.getParentFile()) != null) { 6571 f = parent; 6572 parent = tmp; 6573 } 6574 codeRoot = f; 6575 Slog.w(TAG, "Unrecognized code path " 6576 + codePath + " - using " + codeRoot); 6577 } catch (IOException e) { 6578 // Can't canonicalize the code path -- shenanigans? 6579 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6580 return Environment.getRootDirectory().getPath(); 6581 } 6582 } 6583 return codeRoot.getPath(); 6584 } 6585 6586 /** 6587 * Derive and set the location of native libraries for the given package, 6588 * which varies depending on where and how the package was installed. 6589 */ 6590 private void setNativeLibraryPaths(PackageParser.Package pkg) { 6591 final ApplicationInfo info = pkg.applicationInfo; 6592 final String codePath = pkg.codePath; 6593 final File codeFile = new File(codePath); 6594 final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info); 6595 final boolean asecApp = isForwardLocked(info) || isExternal(info); 6596 6597 info.nativeLibraryRootDir = null; 6598 info.nativeLibraryRootRequiresIsa = false; 6599 info.nativeLibraryDir = null; 6600 info.secondaryNativeLibraryDir = null; 6601 6602 if (isApkFile(codeFile)) { 6603 // Monolithic install 6604 if (bundledApp) { 6605 // If "/system/lib64/apkname" exists, assume that is the per-package 6606 // native library directory to use; otherwise use "/system/lib/apkname". 6607 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 6608 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 6609 getPrimaryInstructionSet(info)); 6610 6611 // This is a bundled system app so choose the path based on the ABI. 6612 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 6613 // is just the default path. 6614 final String apkName = deriveCodePathName(codePath); 6615 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 6616 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 6617 apkName).getAbsolutePath(); 6618 6619 if (info.secondaryCpuAbi != null) { 6620 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 6621 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 6622 secondaryLibDir, apkName).getAbsolutePath(); 6623 } 6624 } else if (asecApp) { 6625 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 6626 .getAbsolutePath(); 6627 } else { 6628 final String apkName = deriveCodePathName(codePath); 6629 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 6630 .getAbsolutePath(); 6631 } 6632 6633 info.nativeLibraryRootRequiresIsa = false; 6634 info.nativeLibraryDir = info.nativeLibraryRootDir; 6635 } else { 6636 // Cluster install 6637 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 6638 info.nativeLibraryRootRequiresIsa = true; 6639 6640 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 6641 getPrimaryInstructionSet(info)).getAbsolutePath(); 6642 6643 if (info.secondaryCpuAbi != null) { 6644 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 6645 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 6646 } 6647 } 6648 } 6649 6650 /** 6651 * Calculate the abis and roots for a bundled app. These can uniquely 6652 * be determined from the contents of the system partition, i.e whether 6653 * it contains 64 or 32 bit shared libraries etc. We do not validate any 6654 * of this information, and instead assume that the system was built 6655 * sensibly. 6656 */ 6657 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 6658 PackageSetting pkgSetting) { 6659 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 6660 6661 // If "/system/lib64/apkname" exists, assume that is the per-package 6662 // native library directory to use; otherwise use "/system/lib/apkname". 6663 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 6664 setBundledAppAbi(pkg, apkRoot, apkName); 6665 // pkgSetting might be null during rescan following uninstall of updates 6666 // to a bundled app, so accommodate that possibility. The settings in 6667 // that case will be established later from the parsed package. 6668 // 6669 // If the settings aren't null, sync them up with what we've just derived. 6670 // note that apkRoot isn't stored in the package settings. 6671 if (pkgSetting != null) { 6672 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6673 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6674 } 6675 } 6676 6677 /** 6678 * Deduces the ABI of a bundled app and sets the relevant fields on the 6679 * parsed pkg object. 6680 * 6681 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 6682 * under which system libraries are installed. 6683 * @param apkName the name of the installed package. 6684 */ 6685 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 6686 final File codeFile = new File(pkg.codePath); 6687 6688 final boolean has64BitLibs; 6689 final boolean has32BitLibs; 6690 if (isApkFile(codeFile)) { 6691 // Monolithic install 6692 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 6693 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 6694 } else { 6695 // Cluster install 6696 final File rootDir = new File(codeFile, LIB_DIR_NAME); 6697 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 6698 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 6699 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 6700 has64BitLibs = (new File(rootDir, isa)).exists(); 6701 } else { 6702 has64BitLibs = false; 6703 } 6704 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 6705 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 6706 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 6707 has32BitLibs = (new File(rootDir, isa)).exists(); 6708 } else { 6709 has32BitLibs = false; 6710 } 6711 } 6712 6713 if (has64BitLibs && !has32BitLibs) { 6714 // The package has 64 bit libs, but not 32 bit libs. Its primary 6715 // ABI should be 64 bit. We can safely assume here that the bundled 6716 // native libraries correspond to the most preferred ABI in the list. 6717 6718 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6719 pkg.applicationInfo.secondaryCpuAbi = null; 6720 } else if (has32BitLibs && !has64BitLibs) { 6721 // The package has 32 bit libs but not 64 bit libs. Its primary 6722 // ABI should be 32 bit. 6723 6724 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6725 pkg.applicationInfo.secondaryCpuAbi = null; 6726 } else if (has32BitLibs && has64BitLibs) { 6727 // The application has both 64 and 32 bit bundled libraries. We check 6728 // here that the app declares multiArch support, and warn if it doesn't. 6729 // 6730 // We will be lenient here and record both ABIs. The primary will be the 6731 // ABI that's higher on the list, i.e, a device that's configured to prefer 6732 // 64 bit apps will see a 64 bit primary ABI, 6733 6734 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 6735 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 6736 } 6737 6738 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 6739 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6740 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6741 } else { 6742 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6743 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6744 } 6745 } else { 6746 pkg.applicationInfo.primaryCpuAbi = null; 6747 pkg.applicationInfo.secondaryCpuAbi = null; 6748 } 6749 } 6750 6751 private void killApplication(String pkgName, int appId, String reason) { 6752 // Request the ActivityManager to kill the process(only for existing packages) 6753 // so that we do not end up in a confused state while the user is still using the older 6754 // version of the application while the new one gets installed. 6755 IActivityManager am = ActivityManagerNative.getDefault(); 6756 if (am != null) { 6757 try { 6758 am.killApplicationWithAppId(pkgName, appId, reason); 6759 } catch (RemoteException e) { 6760 } 6761 } 6762 } 6763 6764 void removePackageLI(PackageSetting ps, boolean chatty) { 6765 if (DEBUG_INSTALL) { 6766 if (chatty) 6767 Log.d(TAG, "Removing package " + ps.name); 6768 } 6769 6770 // writer 6771 synchronized (mPackages) { 6772 mPackages.remove(ps.name); 6773 final PackageParser.Package pkg = ps.pkg; 6774 if (pkg != null) { 6775 cleanPackageDataStructuresLILPw(pkg, chatty); 6776 } 6777 } 6778 } 6779 6780 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 6781 if (DEBUG_INSTALL) { 6782 if (chatty) 6783 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 6784 } 6785 6786 // writer 6787 synchronized (mPackages) { 6788 mPackages.remove(pkg.applicationInfo.packageName); 6789 cleanPackageDataStructuresLILPw(pkg, chatty); 6790 } 6791 } 6792 6793 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 6794 int N = pkg.providers.size(); 6795 StringBuilder r = null; 6796 int i; 6797 for (i=0; i<N; i++) { 6798 PackageParser.Provider p = pkg.providers.get(i); 6799 mProviders.removeProvider(p); 6800 if (p.info.authority == null) { 6801 6802 /* There was another ContentProvider with this authority when 6803 * this app was installed so this authority is null, 6804 * Ignore it as we don't have to unregister the provider. 6805 */ 6806 continue; 6807 } 6808 String names[] = p.info.authority.split(";"); 6809 for (int j = 0; j < names.length; j++) { 6810 if (mProvidersByAuthority.get(names[j]) == p) { 6811 mProvidersByAuthority.remove(names[j]); 6812 if (DEBUG_REMOVE) { 6813 if (chatty) 6814 Log.d(TAG, "Unregistered content provider: " + names[j] 6815 + ", className = " + p.info.name + ", isSyncable = " 6816 + p.info.isSyncable); 6817 } 6818 } 6819 } 6820 if (DEBUG_REMOVE && chatty) { 6821 if (r == null) { 6822 r = new StringBuilder(256); 6823 } else { 6824 r.append(' '); 6825 } 6826 r.append(p.info.name); 6827 } 6828 } 6829 if (r != null) { 6830 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 6831 } 6832 6833 N = pkg.services.size(); 6834 r = null; 6835 for (i=0; i<N; i++) { 6836 PackageParser.Service s = pkg.services.get(i); 6837 mServices.removeService(s); 6838 if (chatty) { 6839 if (r == null) { 6840 r = new StringBuilder(256); 6841 } else { 6842 r.append(' '); 6843 } 6844 r.append(s.info.name); 6845 } 6846 } 6847 if (r != null) { 6848 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 6849 } 6850 6851 N = pkg.receivers.size(); 6852 r = null; 6853 for (i=0; i<N; i++) { 6854 PackageParser.Activity a = pkg.receivers.get(i); 6855 mReceivers.removeActivity(a, "receiver"); 6856 if (DEBUG_REMOVE && chatty) { 6857 if (r == null) { 6858 r = new StringBuilder(256); 6859 } else { 6860 r.append(' '); 6861 } 6862 r.append(a.info.name); 6863 } 6864 } 6865 if (r != null) { 6866 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 6867 } 6868 6869 N = pkg.activities.size(); 6870 r = null; 6871 for (i=0; i<N; i++) { 6872 PackageParser.Activity a = pkg.activities.get(i); 6873 mActivities.removeActivity(a, "activity"); 6874 if (DEBUG_REMOVE && chatty) { 6875 if (r == null) { 6876 r = new StringBuilder(256); 6877 } else { 6878 r.append(' '); 6879 } 6880 r.append(a.info.name); 6881 } 6882 } 6883 if (r != null) { 6884 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 6885 } 6886 6887 N = pkg.permissions.size(); 6888 r = null; 6889 for (i=0; i<N; i++) { 6890 PackageParser.Permission p = pkg.permissions.get(i); 6891 BasePermission bp = mSettings.mPermissions.get(p.info.name); 6892 if (bp == null) { 6893 bp = mSettings.mPermissionTrees.get(p.info.name); 6894 } 6895 if (bp != null && bp.perm == p) { 6896 bp.perm = null; 6897 if (DEBUG_REMOVE && chatty) { 6898 if (r == null) { 6899 r = new StringBuilder(256); 6900 } else { 6901 r.append(' '); 6902 } 6903 r.append(p.info.name); 6904 } 6905 } 6906 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6907 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 6908 if (appOpPerms != null) { 6909 appOpPerms.remove(pkg.packageName); 6910 } 6911 } 6912 } 6913 if (r != null) { 6914 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6915 } 6916 6917 N = pkg.requestedPermissions.size(); 6918 r = null; 6919 for (i=0; i<N; i++) { 6920 String perm = pkg.requestedPermissions.get(i); 6921 BasePermission bp = mSettings.mPermissions.get(perm); 6922 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6923 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 6924 if (appOpPerms != null) { 6925 appOpPerms.remove(pkg.packageName); 6926 if (appOpPerms.isEmpty()) { 6927 mAppOpPermissionPackages.remove(perm); 6928 } 6929 } 6930 } 6931 } 6932 if (r != null) { 6933 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6934 } 6935 6936 N = pkg.instrumentation.size(); 6937 r = null; 6938 for (i=0; i<N; i++) { 6939 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6940 mInstrumentation.remove(a.getComponentName()); 6941 if (DEBUG_REMOVE && chatty) { 6942 if (r == null) { 6943 r = new StringBuilder(256); 6944 } else { 6945 r.append(' '); 6946 } 6947 r.append(a.info.name); 6948 } 6949 } 6950 if (r != null) { 6951 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 6952 } 6953 6954 r = null; 6955 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6956 // Only system apps can hold shared libraries. 6957 if (pkg.libraryNames != null) { 6958 for (i=0; i<pkg.libraryNames.size(); i++) { 6959 String name = pkg.libraryNames.get(i); 6960 SharedLibraryEntry cur = mSharedLibraries.get(name); 6961 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 6962 mSharedLibraries.remove(name); 6963 if (DEBUG_REMOVE && chatty) { 6964 if (r == null) { 6965 r = new StringBuilder(256); 6966 } else { 6967 r.append(' '); 6968 } 6969 r.append(name); 6970 } 6971 } 6972 } 6973 } 6974 } 6975 if (r != null) { 6976 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 6977 } 6978 } 6979 6980 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 6981 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 6982 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 6983 return true; 6984 } 6985 } 6986 return false; 6987 } 6988 6989 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 6990 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 6991 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 6992 6993 private void updatePermissionsLPw(String changingPkg, 6994 PackageParser.Package pkgInfo, int flags) { 6995 // Make sure there are no dangling permission trees. 6996 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 6997 while (it.hasNext()) { 6998 final BasePermission bp = it.next(); 6999 if (bp.packageSetting == null) { 7000 // We may not yet have parsed the package, so just see if 7001 // we still know about its settings. 7002 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7003 } 7004 if (bp.packageSetting == null) { 7005 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 7006 + " from package " + bp.sourcePackage); 7007 it.remove(); 7008 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7009 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7010 Slog.i(TAG, "Removing old permission tree: " + bp.name 7011 + " from package " + bp.sourcePackage); 7012 flags |= UPDATE_PERMISSIONS_ALL; 7013 it.remove(); 7014 } 7015 } 7016 } 7017 7018 // Make sure all dynamic permissions have been assigned to a package, 7019 // and make sure there are no dangling permissions. 7020 it = mSettings.mPermissions.values().iterator(); 7021 while (it.hasNext()) { 7022 final BasePermission bp = it.next(); 7023 if (bp.type == BasePermission.TYPE_DYNAMIC) { 7024 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 7025 + bp.name + " pkg=" + bp.sourcePackage 7026 + " info=" + bp.pendingInfo); 7027 if (bp.packageSetting == null && bp.pendingInfo != null) { 7028 final BasePermission tree = findPermissionTreeLP(bp.name); 7029 if (tree != null && tree.perm != null) { 7030 bp.packageSetting = tree.packageSetting; 7031 bp.perm = new PackageParser.Permission(tree.perm.owner, 7032 new PermissionInfo(bp.pendingInfo)); 7033 bp.perm.info.packageName = tree.perm.info.packageName; 7034 bp.perm.info.name = bp.name; 7035 bp.uid = tree.uid; 7036 } 7037 } 7038 } 7039 if (bp.packageSetting == null) { 7040 // We may not yet have parsed the package, so just see if 7041 // we still know about its settings. 7042 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7043 } 7044 if (bp.packageSetting == null) { 7045 Slog.w(TAG, "Removing dangling permission: " + bp.name 7046 + " from package " + bp.sourcePackage); 7047 it.remove(); 7048 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7049 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7050 Slog.i(TAG, "Removing old permission: " + bp.name 7051 + " from package " + bp.sourcePackage); 7052 flags |= UPDATE_PERMISSIONS_ALL; 7053 it.remove(); 7054 } 7055 } 7056 } 7057 7058 // Now update the permissions for all packages, in particular 7059 // replace the granted permissions of the system packages. 7060 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 7061 for (PackageParser.Package pkg : mPackages.values()) { 7062 if (pkg != pkgInfo) { 7063 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 7064 changingPkg); 7065 } 7066 } 7067 } 7068 7069 if (pkgInfo != null) { 7070 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 7071 } 7072 } 7073 7074 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 7075 String packageOfInterest) { 7076 final PackageSetting ps = (PackageSetting) pkg.mExtras; 7077 if (ps == null) { 7078 return; 7079 } 7080 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 7081 ArraySet<String> origPermissions = gp.grantedPermissions; 7082 boolean changedPermission = false; 7083 7084 if (replace) { 7085 ps.permissionsFixed = false; 7086 if (gp == ps) { 7087 origPermissions = new ArraySet<String>(gp.grantedPermissions); 7088 gp.grantedPermissions.clear(); 7089 gp.gids = mGlobalGids; 7090 } 7091 } 7092 7093 if (gp.gids == null) { 7094 gp.gids = mGlobalGids; 7095 } 7096 7097 final int N = pkg.requestedPermissions.size(); 7098 for (int i=0; i<N; i++) { 7099 final String name = pkg.requestedPermissions.get(i); 7100 final boolean required = pkg.requestedPermissionsRequired.get(i); 7101 final BasePermission bp = mSettings.mPermissions.get(name); 7102 if (DEBUG_INSTALL) { 7103 if (gp != ps) { 7104 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 7105 } 7106 } 7107 7108 if (bp == null || bp.packageSetting == null) { 7109 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7110 Slog.w(TAG, "Unknown permission " + name 7111 + " in package " + pkg.packageName); 7112 } 7113 continue; 7114 } 7115 7116 final String perm = bp.name; 7117 boolean allowed; 7118 boolean allowedSig = false; 7119 if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7120 // Keep track of app op permissions. 7121 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 7122 if (pkgs == null) { 7123 pkgs = new ArraySet<>(); 7124 mAppOpPermissionPackages.put(bp.name, pkgs); 7125 } 7126 pkgs.add(pkg.packageName); 7127 } 7128 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 7129 if (level == PermissionInfo.PROTECTION_NORMAL 7130 || level == PermissionInfo.PROTECTION_DANGEROUS) { 7131 // We grant a normal or dangerous permission if any of the following 7132 // are true: 7133 // 1) The permission is required 7134 // 2) The permission is optional, but was granted in the past 7135 // 3) The permission is optional, but was requested by an 7136 // app in /system (not /data) 7137 // 7138 // Otherwise, reject the permission. 7139 allowed = (required || origPermissions.contains(perm) 7140 || (isSystemApp(ps) && !isUpdatedSystemApp(ps))); 7141 } else if (bp.packageSetting == null) { 7142 // This permission is invalid; skip it. 7143 allowed = false; 7144 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 7145 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions); 7146 if (allowed) { 7147 allowedSig = true; 7148 } 7149 } else { 7150 allowed = false; 7151 } 7152 if (DEBUG_INSTALL) { 7153 if (gp != ps) { 7154 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 7155 } 7156 } 7157 if (allowed) { 7158 if (!isSystemApp(ps) && ps.permissionsFixed) { 7159 // If this is an existing, non-system package, then 7160 // we can't add any new permissions to it. 7161 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 7162 // Except... if this is a permission that was added 7163 // to the platform (note: need to only do this when 7164 // updating the platform). 7165 allowed = isNewPlatformPermissionForPackage(perm, pkg); 7166 } 7167 } 7168 if (allowed) { 7169 if (!gp.grantedPermissions.contains(perm)) { 7170 changedPermission = true; 7171 gp.grantedPermissions.add(perm); 7172 gp.gids = appendInts(gp.gids, bp.gids); 7173 } else if (!ps.haveGids) { 7174 gp.gids = appendInts(gp.gids, bp.gids); 7175 } 7176 } else { 7177 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7178 Slog.w(TAG, "Not granting permission " + perm 7179 + " to package " + pkg.packageName 7180 + " because it was previously installed without"); 7181 } 7182 } 7183 } else { 7184 if (gp.grantedPermissions.remove(perm)) { 7185 changedPermission = true; 7186 gp.gids = removeInts(gp.gids, bp.gids); 7187 Slog.i(TAG, "Un-granting permission " + perm 7188 + " from package " + pkg.packageName 7189 + " (protectionLevel=" + bp.protectionLevel 7190 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7191 + ")"); 7192 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 7193 // Don't print warning for app op permissions, since it is fine for them 7194 // not to be granted, there is a UI for the user to decide. 7195 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7196 Slog.w(TAG, "Not granting permission " + perm 7197 + " to package " + pkg.packageName 7198 + " (protectionLevel=" + bp.protectionLevel 7199 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7200 + ")"); 7201 } 7202 } 7203 } 7204 } 7205 7206 if ((changedPermission || replace) && !ps.permissionsFixed && 7207 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 7208 // This is the first that we have heard about this package, so the 7209 // permissions we have now selected are fixed until explicitly 7210 // changed. 7211 ps.permissionsFixed = true; 7212 } 7213 ps.haveGids = true; 7214 } 7215 7216 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 7217 boolean allowed = false; 7218 final int NP = PackageParser.NEW_PERMISSIONS.length; 7219 for (int ip=0; ip<NP; ip++) { 7220 final PackageParser.NewPermissionInfo npi 7221 = PackageParser.NEW_PERMISSIONS[ip]; 7222 if (npi.name.equals(perm) 7223 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 7224 allowed = true; 7225 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 7226 + pkg.packageName); 7227 break; 7228 } 7229 } 7230 return allowed; 7231 } 7232 7233 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 7234 BasePermission bp, ArraySet<String> origPermissions) { 7235 boolean allowed; 7236 allowed = (compareSignatures( 7237 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 7238 == PackageManager.SIGNATURE_MATCH) 7239 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 7240 == PackageManager.SIGNATURE_MATCH); 7241 if (!allowed && (bp.protectionLevel 7242 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 7243 if (isSystemApp(pkg)) { 7244 // For updated system applications, a system permission 7245 // is granted only if it had been defined by the original application. 7246 if (isUpdatedSystemApp(pkg)) { 7247 final PackageSetting sysPs = mSettings 7248 .getDisabledSystemPkgLPr(pkg.packageName); 7249 final GrantedPermissions origGp = sysPs.sharedUser != null 7250 ? sysPs.sharedUser : sysPs; 7251 7252 if (origGp.grantedPermissions.contains(perm)) { 7253 // If the original was granted this permission, we take 7254 // that grant decision as read and propagate it to the 7255 // update. 7256 if (sysPs.isPrivileged()) { 7257 allowed = true; 7258 } 7259 } else { 7260 // The system apk may have been updated with an older 7261 // version of the one on the data partition, but which 7262 // granted a new system permission that it didn't have 7263 // before. In this case we do want to allow the app to 7264 // now get the new permission if the ancestral apk is 7265 // privileged to get it. 7266 if (sysPs.pkg != null && sysPs.isPrivileged()) { 7267 for (int j=0; 7268 j<sysPs.pkg.requestedPermissions.size(); j++) { 7269 if (perm.equals( 7270 sysPs.pkg.requestedPermissions.get(j))) { 7271 allowed = true; 7272 break; 7273 } 7274 } 7275 } 7276 } 7277 } else { 7278 allowed = isPrivilegedApp(pkg); 7279 } 7280 } 7281 } 7282 if (!allowed && (bp.protectionLevel 7283 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 7284 // For development permissions, a development permission 7285 // is granted only if it was already granted. 7286 allowed = origPermissions.contains(perm); 7287 } 7288 return allowed; 7289 } 7290 7291 final class ActivityIntentResolver 7292 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 7293 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7294 boolean defaultOnly, int userId) { 7295 if (!sUserManager.exists(userId)) return null; 7296 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7297 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7298 } 7299 7300 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7301 int userId) { 7302 if (!sUserManager.exists(userId)) return null; 7303 mFlags = flags; 7304 return super.queryIntent(intent, resolvedType, 7305 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7306 } 7307 7308 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7309 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 7310 if (!sUserManager.exists(userId)) return null; 7311 if (packageActivities == null) { 7312 return null; 7313 } 7314 mFlags = flags; 7315 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7316 final int N = packageActivities.size(); 7317 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 7318 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 7319 7320 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 7321 for (int i = 0; i < N; ++i) { 7322 intentFilters = packageActivities.get(i).intents; 7323 if (intentFilters != null && intentFilters.size() > 0) { 7324 PackageParser.ActivityIntentInfo[] array = 7325 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 7326 intentFilters.toArray(array); 7327 listCut.add(array); 7328 } 7329 } 7330 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7331 } 7332 7333 public final void addActivity(PackageParser.Activity a, String type) { 7334 final boolean systemApp = isSystemApp(a.info.applicationInfo); 7335 mActivities.put(a.getComponentName(), a); 7336 if (DEBUG_SHOW_INFO) 7337 Log.v( 7338 TAG, " " + type + " " + 7339 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 7340 if (DEBUG_SHOW_INFO) 7341 Log.v(TAG, " Class=" + a.info.name); 7342 final int NI = a.intents.size(); 7343 for (int j=0; j<NI; j++) { 7344 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7345 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 7346 intent.setPriority(0); 7347 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 7348 + a.className + " with priority > 0, forcing to 0"); 7349 } 7350 if (DEBUG_SHOW_INFO) { 7351 Log.v(TAG, " IntentFilter:"); 7352 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7353 } 7354 if (!intent.debugCheck()) { 7355 Log.w(TAG, "==> For Activity " + a.info.name); 7356 } 7357 addFilter(intent); 7358 } 7359 } 7360 7361 public final void removeActivity(PackageParser.Activity a, String type) { 7362 mActivities.remove(a.getComponentName()); 7363 if (DEBUG_SHOW_INFO) { 7364 Log.v(TAG, " " + type + " " 7365 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 7366 : a.info.name) + ":"); 7367 Log.v(TAG, " Class=" + a.info.name); 7368 } 7369 final int NI = a.intents.size(); 7370 for (int j=0; j<NI; j++) { 7371 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7372 if (DEBUG_SHOW_INFO) { 7373 Log.v(TAG, " IntentFilter:"); 7374 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7375 } 7376 removeFilter(intent); 7377 } 7378 } 7379 7380 @Override 7381 protected boolean allowFilterResult( 7382 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 7383 ActivityInfo filterAi = filter.activity.info; 7384 for (int i=dest.size()-1; i>=0; i--) { 7385 ActivityInfo destAi = dest.get(i).activityInfo; 7386 if (destAi.name == filterAi.name 7387 && destAi.packageName == filterAi.packageName) { 7388 return false; 7389 } 7390 } 7391 return true; 7392 } 7393 7394 @Override 7395 protected ActivityIntentInfo[] newArray(int size) { 7396 return new ActivityIntentInfo[size]; 7397 } 7398 7399 @Override 7400 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 7401 if (!sUserManager.exists(userId)) return true; 7402 PackageParser.Package p = filter.activity.owner; 7403 if (p != null) { 7404 PackageSetting ps = (PackageSetting)p.mExtras; 7405 if (ps != null) { 7406 // System apps are never considered stopped for purposes of 7407 // filtering, because there may be no way for the user to 7408 // actually re-launch them. 7409 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 7410 && ps.getStopped(userId); 7411 } 7412 } 7413 return false; 7414 } 7415 7416 @Override 7417 protected boolean isPackageForFilter(String packageName, 7418 PackageParser.ActivityIntentInfo info) { 7419 return packageName.equals(info.activity.owner.packageName); 7420 } 7421 7422 @Override 7423 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7424 int match, int userId) { 7425 if (!sUserManager.exists(userId)) return null; 7426 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7427 return null; 7428 } 7429 final PackageParser.Activity activity = info.activity; 7430 if (mSafeMode && (activity.info.applicationInfo.flags 7431 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7432 return null; 7433 } 7434 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7435 if (ps == null) { 7436 return null; 7437 } 7438 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7439 ps.readUserState(userId), userId); 7440 if (ai == null) { 7441 return null; 7442 } 7443 final ResolveInfo res = new ResolveInfo(); 7444 res.activityInfo = ai; 7445 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7446 res.filter = info; 7447 } 7448 res.priority = info.getPriority(); 7449 res.preferredOrder = activity.owner.mPreferredOrder; 7450 //System.out.println("Result: " + res.activityInfo.className + 7451 // " = " + res.priority); 7452 res.match = match; 7453 res.isDefault = info.hasDefault; 7454 res.labelRes = info.labelRes; 7455 res.nonLocalizedLabel = info.nonLocalizedLabel; 7456 if (userNeedsBadging(userId)) { 7457 res.noResourceId = true; 7458 } else { 7459 res.icon = info.icon; 7460 } 7461 res.system = isSystemApp(res.activityInfo.applicationInfo); 7462 return res; 7463 } 7464 7465 @Override 7466 protected void sortResults(List<ResolveInfo> results) { 7467 Collections.sort(results, mResolvePrioritySorter); 7468 } 7469 7470 @Override 7471 protected void dumpFilter(PrintWriter out, String prefix, 7472 PackageParser.ActivityIntentInfo filter) { 7473 out.print(prefix); out.print( 7474 Integer.toHexString(System.identityHashCode(filter.activity))); 7475 out.print(' '); 7476 filter.activity.printComponentShortName(out); 7477 out.print(" filter "); 7478 out.println(Integer.toHexString(System.identityHashCode(filter))); 7479 } 7480 7481 @Override 7482 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 7483 return filter.activity; 7484 } 7485 7486 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 7487 PackageParser.Activity activity = (PackageParser.Activity)label; 7488 out.print(prefix); out.print( 7489 Integer.toHexString(System.identityHashCode(activity))); 7490 out.print(' '); 7491 activity.printComponentShortName(out); 7492 if (count > 1) { 7493 out.print(" ("); out.print(count); out.print(" filters)"); 7494 } 7495 out.println(); 7496 } 7497 7498// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7499// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7500// final List<ResolveInfo> retList = Lists.newArrayList(); 7501// while (i.hasNext()) { 7502// final ResolveInfo resolveInfo = i.next(); 7503// if (isEnabledLP(resolveInfo.activityInfo)) { 7504// retList.add(resolveInfo); 7505// } 7506// } 7507// return retList; 7508// } 7509 7510 // Keys are String (activity class name), values are Activity. 7511 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 7512 = new ArrayMap<ComponentName, PackageParser.Activity>(); 7513 private int mFlags; 7514 } 7515 7516 private final class ServiceIntentResolver 7517 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 7518 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7519 boolean defaultOnly, int userId) { 7520 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7521 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7522 } 7523 7524 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7525 int userId) { 7526 if (!sUserManager.exists(userId)) return null; 7527 mFlags = flags; 7528 return super.queryIntent(intent, resolvedType, 7529 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7530 } 7531 7532 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7533 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 7534 if (!sUserManager.exists(userId)) return null; 7535 if (packageServices == null) { 7536 return null; 7537 } 7538 mFlags = flags; 7539 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7540 final int N = packageServices.size(); 7541 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 7542 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 7543 7544 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 7545 for (int i = 0; i < N; ++i) { 7546 intentFilters = packageServices.get(i).intents; 7547 if (intentFilters != null && intentFilters.size() > 0) { 7548 PackageParser.ServiceIntentInfo[] array = 7549 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 7550 intentFilters.toArray(array); 7551 listCut.add(array); 7552 } 7553 } 7554 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7555 } 7556 7557 public final void addService(PackageParser.Service s) { 7558 mServices.put(s.getComponentName(), s); 7559 if (DEBUG_SHOW_INFO) { 7560 Log.v(TAG, " " 7561 + (s.info.nonLocalizedLabel != null 7562 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7563 Log.v(TAG, " Class=" + s.info.name); 7564 } 7565 final int NI = s.intents.size(); 7566 int j; 7567 for (j=0; j<NI; j++) { 7568 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7569 if (DEBUG_SHOW_INFO) { 7570 Log.v(TAG, " IntentFilter:"); 7571 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7572 } 7573 if (!intent.debugCheck()) { 7574 Log.w(TAG, "==> For Service " + s.info.name); 7575 } 7576 addFilter(intent); 7577 } 7578 } 7579 7580 public final void removeService(PackageParser.Service s) { 7581 mServices.remove(s.getComponentName()); 7582 if (DEBUG_SHOW_INFO) { 7583 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 7584 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7585 Log.v(TAG, " Class=" + s.info.name); 7586 } 7587 final int NI = s.intents.size(); 7588 int j; 7589 for (j=0; j<NI; j++) { 7590 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7591 if (DEBUG_SHOW_INFO) { 7592 Log.v(TAG, " IntentFilter:"); 7593 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7594 } 7595 removeFilter(intent); 7596 } 7597 } 7598 7599 @Override 7600 protected boolean allowFilterResult( 7601 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 7602 ServiceInfo filterSi = filter.service.info; 7603 for (int i=dest.size()-1; i>=0; i--) { 7604 ServiceInfo destAi = dest.get(i).serviceInfo; 7605 if (destAi.name == filterSi.name 7606 && destAi.packageName == filterSi.packageName) { 7607 return false; 7608 } 7609 } 7610 return true; 7611 } 7612 7613 @Override 7614 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 7615 return new PackageParser.ServiceIntentInfo[size]; 7616 } 7617 7618 @Override 7619 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 7620 if (!sUserManager.exists(userId)) return true; 7621 PackageParser.Package p = filter.service.owner; 7622 if (p != null) { 7623 PackageSetting ps = (PackageSetting)p.mExtras; 7624 if (ps != null) { 7625 // System apps are never considered stopped for purposes of 7626 // filtering, because there may be no way for the user to 7627 // actually re-launch them. 7628 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7629 && ps.getStopped(userId); 7630 } 7631 } 7632 return false; 7633 } 7634 7635 @Override 7636 protected boolean isPackageForFilter(String packageName, 7637 PackageParser.ServiceIntentInfo info) { 7638 return packageName.equals(info.service.owner.packageName); 7639 } 7640 7641 @Override 7642 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 7643 int match, int userId) { 7644 if (!sUserManager.exists(userId)) return null; 7645 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 7646 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 7647 return null; 7648 } 7649 final PackageParser.Service service = info.service; 7650 if (mSafeMode && (service.info.applicationInfo.flags 7651 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7652 return null; 7653 } 7654 PackageSetting ps = (PackageSetting) service.owner.mExtras; 7655 if (ps == null) { 7656 return null; 7657 } 7658 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 7659 ps.readUserState(userId), userId); 7660 if (si == null) { 7661 return null; 7662 } 7663 final ResolveInfo res = new ResolveInfo(); 7664 res.serviceInfo = si; 7665 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7666 res.filter = filter; 7667 } 7668 res.priority = info.getPriority(); 7669 res.preferredOrder = service.owner.mPreferredOrder; 7670 //System.out.println("Result: " + res.activityInfo.className + 7671 // " = " + res.priority); 7672 res.match = match; 7673 res.isDefault = info.hasDefault; 7674 res.labelRes = info.labelRes; 7675 res.nonLocalizedLabel = info.nonLocalizedLabel; 7676 res.icon = info.icon; 7677 res.system = isSystemApp(res.serviceInfo.applicationInfo); 7678 return res; 7679 } 7680 7681 @Override 7682 protected void sortResults(List<ResolveInfo> results) { 7683 Collections.sort(results, mResolvePrioritySorter); 7684 } 7685 7686 @Override 7687 protected void dumpFilter(PrintWriter out, String prefix, 7688 PackageParser.ServiceIntentInfo filter) { 7689 out.print(prefix); out.print( 7690 Integer.toHexString(System.identityHashCode(filter.service))); 7691 out.print(' '); 7692 filter.service.printComponentShortName(out); 7693 out.print(" filter "); 7694 out.println(Integer.toHexString(System.identityHashCode(filter))); 7695 } 7696 7697 @Override 7698 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 7699 return filter.service; 7700 } 7701 7702 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 7703 PackageParser.Service service = (PackageParser.Service)label; 7704 out.print(prefix); out.print( 7705 Integer.toHexString(System.identityHashCode(service))); 7706 out.print(' '); 7707 service.printComponentShortName(out); 7708 if (count > 1) { 7709 out.print(" ("); out.print(count); out.print(" filters)"); 7710 } 7711 out.println(); 7712 } 7713 7714// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7715// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7716// final List<ResolveInfo> retList = Lists.newArrayList(); 7717// while (i.hasNext()) { 7718// final ResolveInfo resolveInfo = (ResolveInfo) i; 7719// if (isEnabledLP(resolveInfo.serviceInfo)) { 7720// retList.add(resolveInfo); 7721// } 7722// } 7723// return retList; 7724// } 7725 7726 // Keys are String (activity class name), values are Activity. 7727 private final ArrayMap<ComponentName, PackageParser.Service> mServices 7728 = new ArrayMap<ComponentName, PackageParser.Service>(); 7729 private int mFlags; 7730 }; 7731 7732 private final class ProviderIntentResolver 7733 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 7734 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7735 boolean defaultOnly, int userId) { 7736 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7737 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7738 } 7739 7740 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7741 int userId) { 7742 if (!sUserManager.exists(userId)) 7743 return null; 7744 mFlags = flags; 7745 return super.queryIntent(intent, resolvedType, 7746 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7747 } 7748 7749 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7750 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 7751 if (!sUserManager.exists(userId)) 7752 return null; 7753 if (packageProviders == null) { 7754 return null; 7755 } 7756 mFlags = flags; 7757 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 7758 final int N = packageProviders.size(); 7759 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 7760 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 7761 7762 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 7763 for (int i = 0; i < N; ++i) { 7764 intentFilters = packageProviders.get(i).intents; 7765 if (intentFilters != null && intentFilters.size() > 0) { 7766 PackageParser.ProviderIntentInfo[] array = 7767 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 7768 intentFilters.toArray(array); 7769 listCut.add(array); 7770 } 7771 } 7772 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7773 } 7774 7775 public final void addProvider(PackageParser.Provider p) { 7776 if (mProviders.containsKey(p.getComponentName())) { 7777 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 7778 return; 7779 } 7780 7781 mProviders.put(p.getComponentName(), p); 7782 if (DEBUG_SHOW_INFO) { 7783 Log.v(TAG, " " 7784 + (p.info.nonLocalizedLabel != null 7785 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7786 Log.v(TAG, " Class=" + p.info.name); 7787 } 7788 final int NI = p.intents.size(); 7789 int j; 7790 for (j = 0; j < NI; j++) { 7791 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7792 if (DEBUG_SHOW_INFO) { 7793 Log.v(TAG, " IntentFilter:"); 7794 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7795 } 7796 if (!intent.debugCheck()) { 7797 Log.w(TAG, "==> For Provider " + p.info.name); 7798 } 7799 addFilter(intent); 7800 } 7801 } 7802 7803 public final void removeProvider(PackageParser.Provider p) { 7804 mProviders.remove(p.getComponentName()); 7805 if (DEBUG_SHOW_INFO) { 7806 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 7807 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7808 Log.v(TAG, " Class=" + p.info.name); 7809 } 7810 final int NI = p.intents.size(); 7811 int j; 7812 for (j = 0; j < NI; j++) { 7813 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7814 if (DEBUG_SHOW_INFO) { 7815 Log.v(TAG, " IntentFilter:"); 7816 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7817 } 7818 removeFilter(intent); 7819 } 7820 } 7821 7822 @Override 7823 protected boolean allowFilterResult( 7824 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 7825 ProviderInfo filterPi = filter.provider.info; 7826 for (int i = dest.size() - 1; i >= 0; i--) { 7827 ProviderInfo destPi = dest.get(i).providerInfo; 7828 if (destPi.name == filterPi.name 7829 && destPi.packageName == filterPi.packageName) { 7830 return false; 7831 } 7832 } 7833 return true; 7834 } 7835 7836 @Override 7837 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 7838 return new PackageParser.ProviderIntentInfo[size]; 7839 } 7840 7841 @Override 7842 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 7843 if (!sUserManager.exists(userId)) 7844 return true; 7845 PackageParser.Package p = filter.provider.owner; 7846 if (p != null) { 7847 PackageSetting ps = (PackageSetting) p.mExtras; 7848 if (ps != null) { 7849 // System apps are never considered stopped for purposes of 7850 // filtering, because there may be no way for the user to 7851 // actually re-launch them. 7852 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7853 && ps.getStopped(userId); 7854 } 7855 } 7856 return false; 7857 } 7858 7859 @Override 7860 protected boolean isPackageForFilter(String packageName, 7861 PackageParser.ProviderIntentInfo info) { 7862 return packageName.equals(info.provider.owner.packageName); 7863 } 7864 7865 @Override 7866 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 7867 int match, int userId) { 7868 if (!sUserManager.exists(userId)) 7869 return null; 7870 final PackageParser.ProviderIntentInfo info = filter; 7871 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 7872 return null; 7873 } 7874 final PackageParser.Provider provider = info.provider; 7875 if (mSafeMode && (provider.info.applicationInfo.flags 7876 & ApplicationInfo.FLAG_SYSTEM) == 0) { 7877 return null; 7878 } 7879 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 7880 if (ps == null) { 7881 return null; 7882 } 7883 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 7884 ps.readUserState(userId), userId); 7885 if (pi == null) { 7886 return null; 7887 } 7888 final ResolveInfo res = new ResolveInfo(); 7889 res.providerInfo = pi; 7890 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 7891 res.filter = filter; 7892 } 7893 res.priority = info.getPriority(); 7894 res.preferredOrder = provider.owner.mPreferredOrder; 7895 res.match = match; 7896 res.isDefault = info.hasDefault; 7897 res.labelRes = info.labelRes; 7898 res.nonLocalizedLabel = info.nonLocalizedLabel; 7899 res.icon = info.icon; 7900 res.system = isSystemApp(res.providerInfo.applicationInfo); 7901 return res; 7902 } 7903 7904 @Override 7905 protected void sortResults(List<ResolveInfo> results) { 7906 Collections.sort(results, mResolvePrioritySorter); 7907 } 7908 7909 @Override 7910 protected void dumpFilter(PrintWriter out, String prefix, 7911 PackageParser.ProviderIntentInfo filter) { 7912 out.print(prefix); 7913 out.print( 7914 Integer.toHexString(System.identityHashCode(filter.provider))); 7915 out.print(' '); 7916 filter.provider.printComponentShortName(out); 7917 out.print(" filter "); 7918 out.println(Integer.toHexString(System.identityHashCode(filter))); 7919 } 7920 7921 @Override 7922 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 7923 return filter.provider; 7924 } 7925 7926 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 7927 PackageParser.Provider provider = (PackageParser.Provider)label; 7928 out.print(prefix); out.print( 7929 Integer.toHexString(System.identityHashCode(provider))); 7930 out.print(' '); 7931 provider.printComponentShortName(out); 7932 if (count > 1) { 7933 out.print(" ("); out.print(count); out.print(" filters)"); 7934 } 7935 out.println(); 7936 } 7937 7938 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 7939 = new ArrayMap<ComponentName, PackageParser.Provider>(); 7940 private int mFlags; 7941 }; 7942 7943 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 7944 new Comparator<ResolveInfo>() { 7945 public int compare(ResolveInfo r1, ResolveInfo r2) { 7946 int v1 = r1.priority; 7947 int v2 = r2.priority; 7948 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 7949 if (v1 != v2) { 7950 return (v1 > v2) ? -1 : 1; 7951 } 7952 v1 = r1.preferredOrder; 7953 v2 = r2.preferredOrder; 7954 if (v1 != v2) { 7955 return (v1 > v2) ? -1 : 1; 7956 } 7957 if (r1.isDefault != r2.isDefault) { 7958 return r1.isDefault ? -1 : 1; 7959 } 7960 v1 = r1.match; 7961 v2 = r2.match; 7962 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 7963 if (v1 != v2) { 7964 return (v1 > v2) ? -1 : 1; 7965 } 7966 if (r1.system != r2.system) { 7967 return r1.system ? -1 : 1; 7968 } 7969 return 0; 7970 } 7971 }; 7972 7973 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 7974 new Comparator<ProviderInfo>() { 7975 public int compare(ProviderInfo p1, ProviderInfo p2) { 7976 final int v1 = p1.initOrder; 7977 final int v2 = p2.initOrder; 7978 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 7979 } 7980 }; 7981 7982 static final void sendPackageBroadcast(String action, String pkg, 7983 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 7984 int[] userIds) { 7985 IActivityManager am = ActivityManagerNative.getDefault(); 7986 if (am != null) { 7987 try { 7988 if (userIds == null) { 7989 userIds = am.getRunningUserIds(); 7990 } 7991 for (int id : userIds) { 7992 final Intent intent = new Intent(action, 7993 pkg != null ? Uri.fromParts("package", pkg, null) : null); 7994 if (extras != null) { 7995 intent.putExtras(extras); 7996 } 7997 if (targetPkg != null) { 7998 intent.setPackage(targetPkg); 7999 } 8000 // Modify the UID when posting to other users 8001 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 8002 if (uid > 0 && UserHandle.getUserId(uid) != id) { 8003 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 8004 intent.putExtra(Intent.EXTRA_UID, uid); 8005 } 8006 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 8007 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 8008 if (DEBUG_BROADCASTS) { 8009 RuntimeException here = new RuntimeException("here"); 8010 here.fillInStackTrace(); 8011 Slog.d(TAG, "Sending to user " + id + ": " 8012 + intent.toShortString(false, true, false, false) 8013 + " " + intent.getExtras(), here); 8014 } 8015 am.broadcastIntent(null, intent, null, finishedReceiver, 8016 0, null, null, null, android.app.AppOpsManager.OP_NONE, 8017 finishedReceiver != null, false, id); 8018 } 8019 } catch (RemoteException ex) { 8020 } 8021 } 8022 } 8023 8024 /** 8025 * Check if the external storage media is available. This is true if there 8026 * is a mounted external storage medium or if the external storage is 8027 * emulated. 8028 */ 8029 private boolean isExternalMediaAvailable() { 8030 return mMediaMounted || Environment.isExternalStorageEmulated(); 8031 } 8032 8033 @Override 8034 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 8035 // writer 8036 synchronized (mPackages) { 8037 if (!isExternalMediaAvailable()) { 8038 // If the external storage is no longer mounted at this point, 8039 // the caller may not have been able to delete all of this 8040 // packages files and can not delete any more. Bail. 8041 return null; 8042 } 8043 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 8044 if (lastPackage != null) { 8045 pkgs.remove(lastPackage); 8046 } 8047 if (pkgs.size() > 0) { 8048 return pkgs.get(0); 8049 } 8050 } 8051 return null; 8052 } 8053 8054 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 8055 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 8056 userId, andCode ? 1 : 0, packageName); 8057 if (mSystemReady) { 8058 msg.sendToTarget(); 8059 } else { 8060 if (mPostSystemReadyMessages == null) { 8061 mPostSystemReadyMessages = new ArrayList<>(); 8062 } 8063 mPostSystemReadyMessages.add(msg); 8064 } 8065 } 8066 8067 void startCleaningPackages() { 8068 // reader 8069 synchronized (mPackages) { 8070 if (!isExternalMediaAvailable()) { 8071 return; 8072 } 8073 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 8074 return; 8075 } 8076 } 8077 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 8078 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 8079 IActivityManager am = ActivityManagerNative.getDefault(); 8080 if (am != null) { 8081 try { 8082 am.startService(null, intent, null, UserHandle.USER_OWNER); 8083 } catch (RemoteException e) { 8084 } 8085 } 8086 } 8087 8088 @Override 8089 public void installPackage(String originPath, IPackageInstallObserver2 observer, 8090 int installFlags, String installerPackageName, VerificationParams verificationParams, 8091 String packageAbiOverride) { 8092 installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams, 8093 packageAbiOverride, UserHandle.getCallingUserId()); 8094 } 8095 8096 @Override 8097 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 8098 int installFlags, String installerPackageName, VerificationParams verificationParams, 8099 String packageAbiOverride, int userId) { 8100 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 8101 8102 final int callingUid = Binder.getCallingUid(); 8103 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 8104 8105 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8106 try { 8107 if (observer != null) { 8108 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 8109 } 8110 } catch (RemoteException re) { 8111 } 8112 return; 8113 } 8114 8115 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 8116 installFlags |= PackageManager.INSTALL_FROM_ADB; 8117 8118 } else { 8119 // Caller holds INSTALL_PACKAGES permission, so we're less strict 8120 // about installerPackageName. 8121 8122 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 8123 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 8124 } 8125 8126 UserHandle user; 8127 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 8128 user = UserHandle.ALL; 8129 } else { 8130 user = new UserHandle(userId); 8131 } 8132 8133 verificationParams.setInstallerUid(callingUid); 8134 8135 final File originFile = new File(originPath); 8136 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 8137 8138 final Message msg = mHandler.obtainMessage(INIT_COPY); 8139 msg.obj = new InstallParams(origin, observer, installFlags, 8140 installerPackageName, verificationParams, user, packageAbiOverride); 8141 mHandler.sendMessage(msg); 8142 } 8143 8144 void installStage(String packageName, File stagedDir, String stagedCid, 8145 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 8146 String installerPackageName, int installerUid, UserHandle user) { 8147 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 8148 params.referrerUri, installerUid, null); 8149 8150 final OriginInfo origin; 8151 if (stagedDir != null) { 8152 origin = OriginInfo.fromStagedFile(stagedDir); 8153 } else { 8154 origin = OriginInfo.fromStagedContainer(stagedCid); 8155 } 8156 8157 final Message msg = mHandler.obtainMessage(INIT_COPY); 8158 msg.obj = new InstallParams(origin, observer, params.installFlags, 8159 installerPackageName, verifParams, user, params.abiOverride); 8160 mHandler.sendMessage(msg); 8161 } 8162 8163 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 8164 Bundle extras = new Bundle(1); 8165 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 8166 8167 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 8168 packageName, extras, null, null, new int[] {userId}); 8169 try { 8170 IActivityManager am = ActivityManagerNative.getDefault(); 8171 final boolean isSystem = 8172 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 8173 if (isSystem && am.isUserRunning(userId, false)) { 8174 // The just-installed/enabled app is bundled on the system, so presumed 8175 // to be able to run automatically without needing an explicit launch. 8176 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 8177 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 8178 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 8179 .setPackage(packageName); 8180 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 8181 android.app.AppOpsManager.OP_NONE, false, false, userId); 8182 } 8183 } catch (RemoteException e) { 8184 // shouldn't happen 8185 Slog.w(TAG, "Unable to bootstrap installed package", e); 8186 } 8187 } 8188 8189 @Override 8190 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 8191 int userId) { 8192 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8193 PackageSetting pkgSetting; 8194 final int uid = Binder.getCallingUid(); 8195 enforceCrossUserPermission(uid, userId, true, true, 8196 "setApplicationHiddenSetting for user " + userId); 8197 8198 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 8199 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 8200 return false; 8201 } 8202 8203 long callingId = Binder.clearCallingIdentity(); 8204 try { 8205 boolean sendAdded = false; 8206 boolean sendRemoved = false; 8207 // writer 8208 synchronized (mPackages) { 8209 pkgSetting = mSettings.mPackages.get(packageName); 8210 if (pkgSetting == null) { 8211 return false; 8212 } 8213 if (pkgSetting.getHidden(userId) != hidden) { 8214 pkgSetting.setHidden(hidden, userId); 8215 mSettings.writePackageRestrictionsLPr(userId); 8216 if (hidden) { 8217 sendRemoved = true; 8218 } else { 8219 sendAdded = true; 8220 } 8221 } 8222 } 8223 if (sendAdded) { 8224 sendPackageAddedForUser(packageName, pkgSetting, userId); 8225 return true; 8226 } 8227 if (sendRemoved) { 8228 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 8229 "hiding pkg"); 8230 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 8231 } 8232 } finally { 8233 Binder.restoreCallingIdentity(callingId); 8234 } 8235 return false; 8236 } 8237 8238 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 8239 int userId) { 8240 final PackageRemovedInfo info = new PackageRemovedInfo(); 8241 info.removedPackage = packageName; 8242 info.removedUsers = new int[] {userId}; 8243 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 8244 info.sendBroadcast(false, false, false); 8245 } 8246 8247 /** 8248 * Returns true if application is not found or there was an error. Otherwise it returns 8249 * the hidden state of the package for the given user. 8250 */ 8251 @Override 8252 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 8253 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8254 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 8255 false, "getApplicationHidden for user " + userId); 8256 PackageSetting pkgSetting; 8257 long callingId = Binder.clearCallingIdentity(); 8258 try { 8259 // writer 8260 synchronized (mPackages) { 8261 pkgSetting = mSettings.mPackages.get(packageName); 8262 if (pkgSetting == null) { 8263 return true; 8264 } 8265 return pkgSetting.getHidden(userId); 8266 } 8267 } finally { 8268 Binder.restoreCallingIdentity(callingId); 8269 } 8270 } 8271 8272 /** 8273 * @hide 8274 */ 8275 @Override 8276 public int installExistingPackageAsUser(String packageName, int userId) { 8277 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 8278 null); 8279 PackageSetting pkgSetting; 8280 final int uid = Binder.getCallingUid(); 8281 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 8282 + userId); 8283 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8284 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 8285 } 8286 8287 long callingId = Binder.clearCallingIdentity(); 8288 try { 8289 boolean sendAdded = false; 8290 Bundle extras = new Bundle(1); 8291 8292 // writer 8293 synchronized (mPackages) { 8294 pkgSetting = mSettings.mPackages.get(packageName); 8295 if (pkgSetting == null) { 8296 return PackageManager.INSTALL_FAILED_INVALID_URI; 8297 } 8298 if (!pkgSetting.getInstalled(userId)) { 8299 pkgSetting.setInstalled(true, userId); 8300 pkgSetting.setHidden(false, userId); 8301 mSettings.writePackageRestrictionsLPr(userId); 8302 sendAdded = true; 8303 } 8304 } 8305 8306 if (sendAdded) { 8307 sendPackageAddedForUser(packageName, pkgSetting, userId); 8308 } 8309 } finally { 8310 Binder.restoreCallingIdentity(callingId); 8311 } 8312 8313 return PackageManager.INSTALL_SUCCEEDED; 8314 } 8315 8316 boolean isUserRestricted(int userId, String restrictionKey) { 8317 Bundle restrictions = sUserManager.getUserRestrictions(userId); 8318 if (restrictions.getBoolean(restrictionKey, false)) { 8319 Log.w(TAG, "User is restricted: " + restrictionKey); 8320 return true; 8321 } 8322 return false; 8323 } 8324 8325 @Override 8326 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 8327 mContext.enforceCallingOrSelfPermission( 8328 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8329 "Only package verification agents can verify applications"); 8330 8331 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8332 final PackageVerificationResponse response = new PackageVerificationResponse( 8333 verificationCode, Binder.getCallingUid()); 8334 msg.arg1 = id; 8335 msg.obj = response; 8336 mHandler.sendMessage(msg); 8337 } 8338 8339 @Override 8340 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 8341 long millisecondsToDelay) { 8342 mContext.enforceCallingOrSelfPermission( 8343 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8344 "Only package verification agents can extend verification timeouts"); 8345 8346 final PackageVerificationState state = mPendingVerification.get(id); 8347 final PackageVerificationResponse response = new PackageVerificationResponse( 8348 verificationCodeAtTimeout, Binder.getCallingUid()); 8349 8350 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 8351 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 8352 } 8353 if (millisecondsToDelay < 0) { 8354 millisecondsToDelay = 0; 8355 } 8356 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 8357 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 8358 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 8359 } 8360 8361 if ((state != null) && !state.timeoutExtended()) { 8362 state.extendTimeout(); 8363 8364 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8365 msg.arg1 = id; 8366 msg.obj = response; 8367 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 8368 } 8369 } 8370 8371 private void broadcastPackageVerified(int verificationId, Uri packageUri, 8372 int verificationCode, UserHandle user) { 8373 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 8374 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 8375 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8376 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8377 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 8378 8379 mContext.sendBroadcastAsUser(intent, user, 8380 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 8381 } 8382 8383 private ComponentName matchComponentForVerifier(String packageName, 8384 List<ResolveInfo> receivers) { 8385 ActivityInfo targetReceiver = null; 8386 8387 final int NR = receivers.size(); 8388 for (int i = 0; i < NR; i++) { 8389 final ResolveInfo info = receivers.get(i); 8390 if (info.activityInfo == null) { 8391 continue; 8392 } 8393 8394 if (packageName.equals(info.activityInfo.packageName)) { 8395 targetReceiver = info.activityInfo; 8396 break; 8397 } 8398 } 8399 8400 if (targetReceiver == null) { 8401 return null; 8402 } 8403 8404 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8405 } 8406 8407 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8408 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8409 if (pkgInfo.verifiers.length == 0) { 8410 return null; 8411 } 8412 8413 final int N = pkgInfo.verifiers.length; 8414 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8415 for (int i = 0; i < N; i++) { 8416 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8417 8418 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8419 receivers); 8420 if (comp == null) { 8421 continue; 8422 } 8423 8424 final int verifierUid = getUidForVerifier(verifierInfo); 8425 if (verifierUid == -1) { 8426 continue; 8427 } 8428 8429 if (DEBUG_VERIFY) { 8430 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8431 + " with the correct signature"); 8432 } 8433 sufficientVerifiers.add(comp); 8434 verificationState.addSufficientVerifier(verifierUid); 8435 } 8436 8437 return sufficientVerifiers; 8438 } 8439 8440 private int getUidForVerifier(VerifierInfo verifierInfo) { 8441 synchronized (mPackages) { 8442 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8443 if (pkg == null) { 8444 return -1; 8445 } else if (pkg.mSignatures.length != 1) { 8446 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8447 + " has more than one signature; ignoring"); 8448 return -1; 8449 } 8450 8451 /* 8452 * If the public key of the package's signature does not match 8453 * our expected public key, then this is a different package and 8454 * we should skip. 8455 */ 8456 8457 final byte[] expectedPublicKey; 8458 try { 8459 final Signature verifierSig = pkg.mSignatures[0]; 8460 final PublicKey publicKey = verifierSig.getPublicKey(); 8461 expectedPublicKey = publicKey.getEncoded(); 8462 } catch (CertificateException e) { 8463 return -1; 8464 } 8465 8466 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8467 8468 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8469 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8470 + " does not have the expected public key; ignoring"); 8471 return -1; 8472 } 8473 8474 return pkg.applicationInfo.uid; 8475 } 8476 } 8477 8478 @Override 8479 public void finishPackageInstall(int token) { 8480 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8481 8482 if (DEBUG_INSTALL) { 8483 Slog.v(TAG, "BM finishing package install for " + token); 8484 } 8485 8486 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8487 mHandler.sendMessage(msg); 8488 } 8489 8490 /** 8491 * Get the verification agent timeout. 8492 * 8493 * @return verification timeout in milliseconds 8494 */ 8495 private long getVerificationTimeout() { 8496 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8497 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8498 DEFAULT_VERIFICATION_TIMEOUT); 8499 } 8500 8501 /** 8502 * Get the default verification agent response code. 8503 * 8504 * @return default verification response code 8505 */ 8506 private int getDefaultVerificationResponse() { 8507 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8508 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8509 DEFAULT_VERIFICATION_RESPONSE); 8510 } 8511 8512 /** 8513 * Check whether or not package verification has been enabled. 8514 * 8515 * @return true if verification should be performed 8516 */ 8517 private boolean isVerificationEnabled(int userId, int installFlags) { 8518 if (!DEFAULT_VERIFY_ENABLE) { 8519 return false; 8520 } 8521 8522 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 8523 8524 // Check if installing from ADB 8525 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 8526 // Do not run verification in a test harness environment 8527 if (ActivityManager.isRunningInTestHarness()) { 8528 return false; 8529 } 8530 if (ensureVerifyAppsEnabled) { 8531 return true; 8532 } 8533 // Check if the developer does not want package verification for ADB installs 8534 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8535 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8536 return false; 8537 } 8538 } 8539 8540 if (ensureVerifyAppsEnabled) { 8541 return true; 8542 } 8543 8544 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8545 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8546 } 8547 8548 /** 8549 * Get the "allow unknown sources" setting. 8550 * 8551 * @return the current "allow unknown sources" setting 8552 */ 8553 private int getUnknownSourcesSettings() { 8554 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8555 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 8556 -1); 8557 } 8558 8559 @Override 8560 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 8561 final int uid = Binder.getCallingUid(); 8562 // writer 8563 synchronized (mPackages) { 8564 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 8565 if (targetPackageSetting == null) { 8566 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 8567 } 8568 8569 PackageSetting installerPackageSetting; 8570 if (installerPackageName != null) { 8571 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 8572 if (installerPackageSetting == null) { 8573 throw new IllegalArgumentException("Unknown installer package: " 8574 + installerPackageName); 8575 } 8576 } else { 8577 installerPackageSetting = null; 8578 } 8579 8580 Signature[] callerSignature; 8581 Object obj = mSettings.getUserIdLPr(uid); 8582 if (obj != null) { 8583 if (obj instanceof SharedUserSetting) { 8584 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 8585 } else if (obj instanceof PackageSetting) { 8586 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 8587 } else { 8588 throw new SecurityException("Bad object " + obj + " for uid " + uid); 8589 } 8590 } else { 8591 throw new SecurityException("Unknown calling uid " + uid); 8592 } 8593 8594 // Verify: can't set installerPackageName to a package that is 8595 // not signed with the same cert as the caller. 8596 if (installerPackageSetting != null) { 8597 if (compareSignatures(callerSignature, 8598 installerPackageSetting.signatures.mSignatures) 8599 != PackageManager.SIGNATURE_MATCH) { 8600 throw new SecurityException( 8601 "Caller does not have same cert as new installer package " 8602 + installerPackageName); 8603 } 8604 } 8605 8606 // Verify: if target already has an installer package, it must 8607 // be signed with the same cert as the caller. 8608 if (targetPackageSetting.installerPackageName != null) { 8609 PackageSetting setting = mSettings.mPackages.get( 8610 targetPackageSetting.installerPackageName); 8611 // If the currently set package isn't valid, then it's always 8612 // okay to change it. 8613 if (setting != null) { 8614 if (compareSignatures(callerSignature, 8615 setting.signatures.mSignatures) 8616 != PackageManager.SIGNATURE_MATCH) { 8617 throw new SecurityException( 8618 "Caller does not have same cert as old installer package " 8619 + targetPackageSetting.installerPackageName); 8620 } 8621 } 8622 } 8623 8624 // Okay! 8625 targetPackageSetting.installerPackageName = installerPackageName; 8626 scheduleWriteSettingsLocked(); 8627 } 8628 } 8629 8630 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 8631 // Queue up an async operation since the package installation may take a little while. 8632 mHandler.post(new Runnable() { 8633 public void run() { 8634 mHandler.removeCallbacks(this); 8635 // Result object to be returned 8636 PackageInstalledInfo res = new PackageInstalledInfo(); 8637 res.returnCode = currentStatus; 8638 res.uid = -1; 8639 res.pkg = null; 8640 res.removedInfo = new PackageRemovedInfo(); 8641 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 8642 args.doPreInstall(res.returnCode); 8643 synchronized (mInstallLock) { 8644 installPackageLI(args, res); 8645 } 8646 args.doPostInstall(res.returnCode, res.uid); 8647 } 8648 8649 // A restore should be performed at this point if (a) the install 8650 // succeeded, (b) the operation is not an update, and (c) the new 8651 // package has not opted out of backup participation. 8652 final boolean update = res.removedInfo.removedPackage != null; 8653 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 8654 boolean doRestore = !update 8655 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 8656 8657 // Set up the post-install work request bookkeeping. This will be used 8658 // and cleaned up by the post-install event handling regardless of whether 8659 // there's a restore pass performed. Token values are >= 1. 8660 int token; 8661 if (mNextInstallToken < 0) mNextInstallToken = 1; 8662 token = mNextInstallToken++; 8663 8664 PostInstallData data = new PostInstallData(args, res); 8665 mRunningInstalls.put(token, data); 8666 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 8667 8668 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 8669 // Pass responsibility to the Backup Manager. It will perform a 8670 // restore if appropriate, then pass responsibility back to the 8671 // Package Manager to run the post-install observer callbacks 8672 // and broadcasts. 8673 IBackupManager bm = IBackupManager.Stub.asInterface( 8674 ServiceManager.getService(Context.BACKUP_SERVICE)); 8675 if (bm != null) { 8676 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 8677 + " to BM for possible restore"); 8678 try { 8679 if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) { 8680 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 8681 } else { 8682 doRestore = false; 8683 } 8684 } catch (RemoteException e) { 8685 // can't happen; the backup manager is local 8686 } catch (Exception e) { 8687 Slog.e(TAG, "Exception trying to enqueue restore", e); 8688 doRestore = false; 8689 } 8690 } else { 8691 Slog.e(TAG, "Backup Manager not found!"); 8692 doRestore = false; 8693 } 8694 } 8695 8696 if (!doRestore) { 8697 // No restore possible, or the Backup Manager was mysteriously not 8698 // available -- just fire the post-install work request directly. 8699 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 8700 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8701 mHandler.sendMessage(msg); 8702 } 8703 } 8704 }); 8705 } 8706 8707 private abstract class HandlerParams { 8708 private static final int MAX_RETRIES = 4; 8709 8710 /** 8711 * Number of times startCopy() has been attempted and had a non-fatal 8712 * error. 8713 */ 8714 private int mRetries = 0; 8715 8716 /** User handle for the user requesting the information or installation. */ 8717 private final UserHandle mUser; 8718 8719 HandlerParams(UserHandle user) { 8720 mUser = user; 8721 } 8722 8723 UserHandle getUser() { 8724 return mUser; 8725 } 8726 8727 final boolean startCopy() { 8728 boolean res; 8729 try { 8730 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 8731 8732 if (++mRetries > MAX_RETRIES) { 8733 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 8734 mHandler.sendEmptyMessage(MCS_GIVE_UP); 8735 handleServiceError(); 8736 return false; 8737 } else { 8738 handleStartCopy(); 8739 res = true; 8740 } 8741 } catch (RemoteException e) { 8742 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 8743 mHandler.sendEmptyMessage(MCS_RECONNECT); 8744 res = false; 8745 } 8746 handleReturnCode(); 8747 return res; 8748 } 8749 8750 final void serviceError() { 8751 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 8752 handleServiceError(); 8753 handleReturnCode(); 8754 } 8755 8756 abstract void handleStartCopy() throws RemoteException; 8757 abstract void handleServiceError(); 8758 abstract void handleReturnCode(); 8759 } 8760 8761 class MeasureParams extends HandlerParams { 8762 private final PackageStats mStats; 8763 private boolean mSuccess; 8764 8765 private final IPackageStatsObserver mObserver; 8766 8767 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 8768 super(new UserHandle(stats.userHandle)); 8769 mObserver = observer; 8770 mStats = stats; 8771 } 8772 8773 @Override 8774 public String toString() { 8775 return "MeasureParams{" 8776 + Integer.toHexString(System.identityHashCode(this)) 8777 + " " + mStats.packageName + "}"; 8778 } 8779 8780 @Override 8781 void handleStartCopy() throws RemoteException { 8782 synchronized (mInstallLock) { 8783 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 8784 } 8785 8786 if (mSuccess) { 8787 final boolean mounted; 8788 if (Environment.isExternalStorageEmulated()) { 8789 mounted = true; 8790 } else { 8791 final String status = Environment.getExternalStorageState(); 8792 mounted = (Environment.MEDIA_MOUNTED.equals(status) 8793 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 8794 } 8795 8796 if (mounted) { 8797 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 8798 8799 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 8800 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 8801 8802 mStats.externalDataSize = calculateDirectorySize(mContainerService, 8803 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 8804 8805 // Always subtract cache size, since it's a subdirectory 8806 mStats.externalDataSize -= mStats.externalCacheSize; 8807 8808 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 8809 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 8810 8811 mStats.externalObbSize = calculateDirectorySize(mContainerService, 8812 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 8813 } 8814 } 8815 } 8816 8817 @Override 8818 void handleReturnCode() { 8819 if (mObserver != null) { 8820 try { 8821 mObserver.onGetStatsCompleted(mStats, mSuccess); 8822 } catch (RemoteException e) { 8823 Slog.i(TAG, "Observer no longer exists."); 8824 } 8825 } 8826 } 8827 8828 @Override 8829 void handleServiceError() { 8830 Slog.e(TAG, "Could not measure application " + mStats.packageName 8831 + " external storage"); 8832 } 8833 } 8834 8835 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 8836 throws RemoteException { 8837 long result = 0; 8838 for (File path : paths) { 8839 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 8840 } 8841 return result; 8842 } 8843 8844 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 8845 for (File path : paths) { 8846 try { 8847 mcs.clearDirectory(path.getAbsolutePath()); 8848 } catch (RemoteException e) { 8849 } 8850 } 8851 } 8852 8853 static class OriginInfo { 8854 /** 8855 * Location where install is coming from, before it has been 8856 * copied/renamed into place. This could be a single monolithic APK 8857 * file, or a cluster directory. This location may be untrusted. 8858 */ 8859 final File file; 8860 final String cid; 8861 8862 /** 8863 * Flag indicating that {@link #file} or {@link #cid} has already been 8864 * staged, meaning downstream users don't need to defensively copy the 8865 * contents. 8866 */ 8867 final boolean staged; 8868 8869 /** 8870 * Flag indicating that {@link #file} or {@link #cid} is an already 8871 * installed app that is being moved. 8872 */ 8873 final boolean existing; 8874 8875 final String resolvedPath; 8876 final File resolvedFile; 8877 8878 static OriginInfo fromNothing() { 8879 return new OriginInfo(null, null, false, false); 8880 } 8881 8882 static OriginInfo fromUntrustedFile(File file) { 8883 return new OriginInfo(file, null, false, false); 8884 } 8885 8886 static OriginInfo fromExistingFile(File file) { 8887 return new OriginInfo(file, null, false, true); 8888 } 8889 8890 static OriginInfo fromStagedFile(File file) { 8891 return new OriginInfo(file, null, true, false); 8892 } 8893 8894 static OriginInfo fromStagedContainer(String cid) { 8895 return new OriginInfo(null, cid, true, false); 8896 } 8897 8898 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 8899 this.file = file; 8900 this.cid = cid; 8901 this.staged = staged; 8902 this.existing = existing; 8903 8904 if (cid != null) { 8905 resolvedPath = PackageHelper.getSdDir(cid); 8906 resolvedFile = new File(resolvedPath); 8907 } else if (file != null) { 8908 resolvedPath = file.getAbsolutePath(); 8909 resolvedFile = file; 8910 } else { 8911 resolvedPath = null; 8912 resolvedFile = null; 8913 } 8914 } 8915 } 8916 8917 class InstallParams extends HandlerParams { 8918 final OriginInfo origin; 8919 final IPackageInstallObserver2 observer; 8920 int installFlags; 8921 final String installerPackageName; 8922 final VerificationParams verificationParams; 8923 private InstallArgs mArgs; 8924 private int mRet; 8925 final String packageAbiOverride; 8926 8927 InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 8928 String installerPackageName, VerificationParams verificationParams, UserHandle user, 8929 String packageAbiOverride) { 8930 super(user); 8931 this.origin = origin; 8932 this.observer = observer; 8933 this.installFlags = installFlags; 8934 this.installerPackageName = installerPackageName; 8935 this.verificationParams = verificationParams; 8936 this.packageAbiOverride = packageAbiOverride; 8937 } 8938 8939 @Override 8940 public String toString() { 8941 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 8942 + " file=" + origin.file + " cid=" + origin.cid + "}"; 8943 } 8944 8945 public ManifestDigest getManifestDigest() { 8946 if (verificationParams == null) { 8947 return null; 8948 } 8949 return verificationParams.getManifestDigest(); 8950 } 8951 8952 private int installLocationPolicy(PackageInfoLite pkgLite) { 8953 String packageName = pkgLite.packageName; 8954 int installLocation = pkgLite.installLocation; 8955 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 8956 // reader 8957 synchronized (mPackages) { 8958 PackageParser.Package pkg = mPackages.get(packageName); 8959 if (pkg != null) { 8960 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 8961 // Check for downgrading. 8962 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 8963 try { 8964 checkDowngrade(pkg, pkgLite); 8965 } catch (PackageManagerException e) { 8966 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 8967 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 8968 } 8969 } 8970 // Check for updated system application. 8971 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8972 if (onSd) { 8973 Slog.w(TAG, "Cannot install update to system app on sdcard"); 8974 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 8975 } 8976 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8977 } else { 8978 if (onSd) { 8979 // Install flag overrides everything. 8980 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8981 } 8982 // If current upgrade specifies particular preference 8983 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 8984 // Application explicitly specified internal. 8985 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8986 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 8987 // App explictly prefers external. Let policy decide 8988 } else { 8989 // Prefer previous location 8990 if (isExternal(pkg)) { 8991 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8992 } 8993 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8994 } 8995 } 8996 } else { 8997 // Invalid install. Return error code 8998 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 8999 } 9000 } 9001 } 9002 // All the special cases have been taken care of. 9003 // Return result based on recommended install location. 9004 if (onSd) { 9005 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 9006 } 9007 return pkgLite.recommendedInstallLocation; 9008 } 9009 9010 /* 9011 * Invoke remote method to get package information and install 9012 * location values. Override install location based on default 9013 * policy if needed and then create install arguments based 9014 * on the install location. 9015 */ 9016 public void handleStartCopy() throws RemoteException { 9017 int ret = PackageManager.INSTALL_SUCCEEDED; 9018 9019 // If we're already staged, we've firmly committed to an install location 9020 if (origin.staged) { 9021 if (origin.file != null) { 9022 installFlags |= PackageManager.INSTALL_INTERNAL; 9023 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9024 } else if (origin.cid != null) { 9025 installFlags |= PackageManager.INSTALL_EXTERNAL; 9026 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9027 } else { 9028 throw new IllegalStateException("Invalid stage location"); 9029 } 9030 } 9031 9032 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9033 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 9034 9035 PackageInfoLite pkgLite = null; 9036 9037 if (onInt && onSd) { 9038 // Check if both bits are set. 9039 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 9040 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9041 } else { 9042 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 9043 packageAbiOverride); 9044 9045 /* 9046 * If we have too little free space, try to free cache 9047 * before giving up. 9048 */ 9049 if (!origin.staged && pkgLite.recommendedInstallLocation 9050 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9051 // TODO: focus freeing disk space on the target device 9052 final StorageManager storage = StorageManager.from(mContext); 9053 final long lowThreshold = storage.getStorageLowBytes( 9054 Environment.getDataDirectory()); 9055 9056 final long sizeBytes = mContainerService.calculateInstalledSize( 9057 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 9058 9059 if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) { 9060 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 9061 installFlags, packageAbiOverride); 9062 } 9063 9064 /* 9065 * The cache free must have deleted the file we 9066 * downloaded to install. 9067 * 9068 * TODO: fix the "freeCache" call to not delete 9069 * the file we care about. 9070 */ 9071 if (pkgLite.recommendedInstallLocation 9072 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9073 pkgLite.recommendedInstallLocation 9074 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 9075 } 9076 } 9077 } 9078 9079 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9080 int loc = pkgLite.recommendedInstallLocation; 9081 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 9082 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9083 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 9084 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9085 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9086 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9087 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 9088 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 9089 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9090 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 9091 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 9092 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 9093 } else { 9094 // Override with defaults if needed. 9095 loc = installLocationPolicy(pkgLite); 9096 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 9097 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 9098 } else if (!onSd && !onInt) { 9099 // Override install location with flags 9100 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 9101 // Set the flag to install on external media. 9102 installFlags |= PackageManager.INSTALL_EXTERNAL; 9103 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9104 } else { 9105 // Make sure the flag for installing on external 9106 // media is unset 9107 installFlags |= PackageManager.INSTALL_INTERNAL; 9108 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9109 } 9110 } 9111 } 9112 } 9113 9114 final InstallArgs args = createInstallArgs(this); 9115 mArgs = args; 9116 9117 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9118 /* 9119 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 9120 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 9121 */ 9122 int userIdentifier = getUser().getIdentifier(); 9123 if (userIdentifier == UserHandle.USER_ALL 9124 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 9125 userIdentifier = UserHandle.USER_OWNER; 9126 } 9127 9128 /* 9129 * Determine if we have any installed package verifiers. If we 9130 * do, then we'll defer to them to verify the packages. 9131 */ 9132 final int requiredUid = mRequiredVerifierPackage == null ? -1 9133 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 9134 if (!origin.existing && requiredUid != -1 9135 && isVerificationEnabled(userIdentifier, installFlags)) { 9136 final Intent verification = new Intent( 9137 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 9138 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 9139 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 9140 PACKAGE_MIME_TYPE); 9141 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9142 9143 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 9144 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 9145 0 /* TODO: Which userId? */); 9146 9147 if (DEBUG_VERIFY) { 9148 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 9149 + verification.toString() + " with " + pkgLite.verifiers.length 9150 + " optional verifiers"); 9151 } 9152 9153 final int verificationId = mPendingVerificationToken++; 9154 9155 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9156 9157 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 9158 installerPackageName); 9159 9160 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 9161 installFlags); 9162 9163 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 9164 pkgLite.packageName); 9165 9166 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 9167 pkgLite.versionCode); 9168 9169 if (verificationParams != null) { 9170 if (verificationParams.getVerificationURI() != null) { 9171 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 9172 verificationParams.getVerificationURI()); 9173 } 9174 if (verificationParams.getOriginatingURI() != null) { 9175 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 9176 verificationParams.getOriginatingURI()); 9177 } 9178 if (verificationParams.getReferrer() != null) { 9179 verification.putExtra(Intent.EXTRA_REFERRER, 9180 verificationParams.getReferrer()); 9181 } 9182 if (verificationParams.getOriginatingUid() >= 0) { 9183 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 9184 verificationParams.getOriginatingUid()); 9185 } 9186 if (verificationParams.getInstallerUid() >= 0) { 9187 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 9188 verificationParams.getInstallerUid()); 9189 } 9190 } 9191 9192 final PackageVerificationState verificationState = new PackageVerificationState( 9193 requiredUid, args); 9194 9195 mPendingVerification.append(verificationId, verificationState); 9196 9197 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 9198 receivers, verificationState); 9199 9200 /* 9201 * If any sufficient verifiers were listed in the package 9202 * manifest, attempt to ask them. 9203 */ 9204 if (sufficientVerifiers != null) { 9205 final int N = sufficientVerifiers.size(); 9206 if (N == 0) { 9207 Slog.i(TAG, "Additional verifiers required, but none installed."); 9208 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 9209 } else { 9210 for (int i = 0; i < N; i++) { 9211 final ComponentName verifierComponent = sufficientVerifiers.get(i); 9212 9213 final Intent sufficientIntent = new Intent(verification); 9214 sufficientIntent.setComponent(verifierComponent); 9215 9216 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 9217 } 9218 } 9219 } 9220 9221 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 9222 mRequiredVerifierPackage, receivers); 9223 if (ret == PackageManager.INSTALL_SUCCEEDED 9224 && mRequiredVerifierPackage != null) { 9225 /* 9226 * Send the intent to the required verification agent, 9227 * but only start the verification timeout after the 9228 * target BroadcastReceivers have run. 9229 */ 9230 verification.setComponent(requiredVerifierComponent); 9231 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 9232 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9233 new BroadcastReceiver() { 9234 @Override 9235 public void onReceive(Context context, Intent intent) { 9236 final Message msg = mHandler 9237 .obtainMessage(CHECK_PENDING_VERIFICATION); 9238 msg.arg1 = verificationId; 9239 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 9240 } 9241 }, null, 0, null, null); 9242 9243 /* 9244 * We don't want the copy to proceed until verification 9245 * succeeds, so null out this field. 9246 */ 9247 mArgs = null; 9248 } 9249 } else { 9250 /* 9251 * No package verification is enabled, so immediately start 9252 * the remote call to initiate copy using temporary file. 9253 */ 9254 ret = args.copyApk(mContainerService, true); 9255 } 9256 } 9257 9258 mRet = ret; 9259 } 9260 9261 @Override 9262 void handleReturnCode() { 9263 // If mArgs is null, then MCS couldn't be reached. When it 9264 // reconnects, it will try again to install. At that point, this 9265 // will succeed. 9266 if (mArgs != null) { 9267 processPendingInstall(mArgs, mRet); 9268 } 9269 } 9270 9271 @Override 9272 void handleServiceError() { 9273 mArgs = createInstallArgs(this); 9274 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9275 } 9276 9277 public boolean isForwardLocked() { 9278 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9279 } 9280 } 9281 9282 /** 9283 * Used during creation of InstallArgs 9284 * 9285 * @param installFlags package installation flags 9286 * @return true if should be installed on external storage 9287 */ 9288 private static boolean installOnSd(int installFlags) { 9289 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 9290 return false; 9291 } 9292 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 9293 return true; 9294 } 9295 return false; 9296 } 9297 9298 /** 9299 * Used during creation of InstallArgs 9300 * 9301 * @param installFlags package installation flags 9302 * @return true if should be installed as forward locked 9303 */ 9304 private static boolean installForwardLocked(int installFlags) { 9305 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9306 } 9307 9308 private InstallArgs createInstallArgs(InstallParams params) { 9309 if (installOnSd(params.installFlags) || params.isForwardLocked()) { 9310 return new AsecInstallArgs(params); 9311 } else { 9312 return new FileInstallArgs(params); 9313 } 9314 } 9315 9316 /** 9317 * Create args that describe an existing installed package. Typically used 9318 * when cleaning up old installs, or used as a move source. 9319 */ 9320 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 9321 String resourcePath, String nativeLibraryRoot, String[] instructionSets) { 9322 final boolean isInAsec; 9323 if (installOnSd(installFlags)) { 9324 /* Apps on SD card are always in ASEC containers. */ 9325 isInAsec = true; 9326 } else if (installForwardLocked(installFlags) 9327 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 9328 /* 9329 * Forward-locked apps are only in ASEC containers if they're the 9330 * new style 9331 */ 9332 isInAsec = true; 9333 } else { 9334 isInAsec = false; 9335 } 9336 9337 if (isInAsec) { 9338 return new AsecInstallArgs(codePath, instructionSets, 9339 installOnSd(installFlags), installForwardLocked(installFlags)); 9340 } else { 9341 return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot, 9342 instructionSets); 9343 } 9344 } 9345 9346 static abstract class InstallArgs { 9347 /** @see InstallParams#origin */ 9348 final OriginInfo origin; 9349 9350 final IPackageInstallObserver2 observer; 9351 // Always refers to PackageManager flags only 9352 final int installFlags; 9353 final String installerPackageName; 9354 final ManifestDigest manifestDigest; 9355 final UserHandle user; 9356 final String abiOverride; 9357 9358 // The list of instruction sets supported by this app. This is currently 9359 // only used during the rmdex() phase to clean up resources. We can get rid of this 9360 // if we move dex files under the common app path. 9361 /* nullable */ String[] instructionSets; 9362 9363 InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 9364 String installerPackageName, ManifestDigest manifestDigest, UserHandle user, 9365 String[] instructionSets, String abiOverride) { 9366 this.origin = origin; 9367 this.installFlags = installFlags; 9368 this.observer = observer; 9369 this.installerPackageName = installerPackageName; 9370 this.manifestDigest = manifestDigest; 9371 this.user = user; 9372 this.instructionSets = instructionSets; 9373 this.abiOverride = abiOverride; 9374 } 9375 9376 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 9377 abstract int doPreInstall(int status); 9378 9379 /** 9380 * Rename package into final resting place. All paths on the given 9381 * scanned package should be updated to reflect the rename. 9382 */ 9383 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 9384 abstract int doPostInstall(int status, int uid); 9385 9386 /** @see PackageSettingBase#codePathString */ 9387 abstract String getCodePath(); 9388 /** @see PackageSettingBase#resourcePathString */ 9389 abstract String getResourcePath(); 9390 abstract String getLegacyNativeLibraryPath(); 9391 9392 // Need installer lock especially for dex file removal. 9393 abstract void cleanUpResourcesLI(); 9394 abstract boolean doPostDeleteLI(boolean delete); 9395 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9396 9397 /** 9398 * Called before the source arguments are copied. This is used mostly 9399 * for MoveParams when it needs to read the source file to put it in the 9400 * destination. 9401 */ 9402 int doPreCopy() { 9403 return PackageManager.INSTALL_SUCCEEDED; 9404 } 9405 9406 /** 9407 * Called after the source arguments are copied. This is used mostly for 9408 * MoveParams when it needs to read the source file to put it in the 9409 * destination. 9410 * 9411 * @return 9412 */ 9413 int doPostCopy(int uid) { 9414 return PackageManager.INSTALL_SUCCEEDED; 9415 } 9416 9417 protected boolean isFwdLocked() { 9418 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9419 } 9420 9421 protected boolean isExternal() { 9422 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9423 } 9424 9425 UserHandle getUser() { 9426 return user; 9427 } 9428 } 9429 9430 /** 9431 * Logic to handle installation of non-ASEC applications, including copying 9432 * and renaming logic. 9433 */ 9434 class FileInstallArgs extends InstallArgs { 9435 private File codeFile; 9436 private File resourceFile; 9437 private File legacyNativeLibraryPath; 9438 9439 // Example topology: 9440 // /data/app/com.example/base.apk 9441 // /data/app/com.example/split_foo.apk 9442 // /data/app/com.example/lib/arm/libfoo.so 9443 // /data/app/com.example/lib/arm64/libfoo.so 9444 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 9445 9446 /** New install */ 9447 FileInstallArgs(InstallParams params) { 9448 super(params.origin, params.observer, params.installFlags, 9449 params.installerPackageName, params.getManifestDigest(), params.getUser(), 9450 null /* instruction sets */, params.packageAbiOverride); 9451 if (isFwdLocked()) { 9452 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 9453 } 9454 } 9455 9456 /** Existing install */ 9457 FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath, 9458 String[] instructionSets) { 9459 super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null); 9460 this.codeFile = (codePath != null) ? new File(codePath) : null; 9461 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 9462 this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ? 9463 new File(legacyNativeLibraryPath) : null; 9464 } 9465 9466 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9467 final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(), 9468 isFwdLocked(), abiOverride); 9469 9470 final StorageManager storage = StorageManager.from(mContext); 9471 return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory())); 9472 } 9473 9474 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9475 if (origin.staged) { 9476 Slog.d(TAG, origin.file + " already staged; skipping copy"); 9477 codeFile = origin.file; 9478 resourceFile = origin.file; 9479 return PackageManager.INSTALL_SUCCEEDED; 9480 } 9481 9482 try { 9483 final File tempDir = mInstallerService.allocateInternalStageDirLegacy(); 9484 codeFile = tempDir; 9485 resourceFile = tempDir; 9486 } catch (IOException e) { 9487 Slog.w(TAG, "Failed to create copy file: " + e); 9488 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9489 } 9490 9491 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 9492 @Override 9493 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 9494 if (!FileUtils.isValidExtFilename(name)) { 9495 throw new IllegalArgumentException("Invalid filename: " + name); 9496 } 9497 try { 9498 final File file = new File(codeFile, name); 9499 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 9500 O_RDWR | O_CREAT, 0644); 9501 Os.chmod(file.getAbsolutePath(), 0644); 9502 return new ParcelFileDescriptor(fd); 9503 } catch (ErrnoException e) { 9504 throw new RemoteException("Failed to open: " + e.getMessage()); 9505 } 9506 } 9507 }; 9508 9509 int ret = PackageManager.INSTALL_SUCCEEDED; 9510 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 9511 if (ret != PackageManager.INSTALL_SUCCEEDED) { 9512 Slog.e(TAG, "Failed to copy package"); 9513 return ret; 9514 } 9515 9516 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 9517 NativeLibraryHelper.Handle handle = null; 9518 try { 9519 handle = NativeLibraryHelper.Handle.create(codeFile); 9520 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 9521 abiOverride); 9522 } catch (IOException e) { 9523 Slog.e(TAG, "Copying native libraries failed", e); 9524 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9525 } finally { 9526 IoUtils.closeQuietly(handle); 9527 } 9528 9529 return ret; 9530 } 9531 9532 int doPreInstall(int status) { 9533 if (status != PackageManager.INSTALL_SUCCEEDED) { 9534 cleanUp(); 9535 } 9536 return status; 9537 } 9538 9539 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9540 if (status != PackageManager.INSTALL_SUCCEEDED) { 9541 cleanUp(); 9542 return false; 9543 } else { 9544 final File beforeCodeFile = codeFile; 9545 final File afterCodeFile = getNextCodePath(pkg.packageName); 9546 9547 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 9548 try { 9549 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 9550 } catch (ErrnoException e) { 9551 Slog.d(TAG, "Failed to rename", e); 9552 return false; 9553 } 9554 9555 if (!SELinux.restoreconRecursive(afterCodeFile)) { 9556 Slog.d(TAG, "Failed to restorecon"); 9557 return false; 9558 } 9559 9560 // Reflect the rename internally 9561 codeFile = afterCodeFile; 9562 resourceFile = afterCodeFile; 9563 9564 // Reflect the rename in scanned details 9565 pkg.codePath = afterCodeFile.getAbsolutePath(); 9566 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9567 pkg.baseCodePath); 9568 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9569 pkg.splitCodePaths); 9570 9571 // Reflect the rename in app info 9572 pkg.applicationInfo.setCodePath(pkg.codePath); 9573 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9574 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9575 pkg.applicationInfo.setResourcePath(pkg.codePath); 9576 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9577 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9578 9579 return true; 9580 } 9581 } 9582 9583 int doPostInstall(int status, int uid) { 9584 if (status != PackageManager.INSTALL_SUCCEEDED) { 9585 cleanUp(); 9586 } 9587 return status; 9588 } 9589 9590 @Override 9591 String getCodePath() { 9592 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 9593 } 9594 9595 @Override 9596 String getResourcePath() { 9597 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 9598 } 9599 9600 @Override 9601 String getLegacyNativeLibraryPath() { 9602 return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null; 9603 } 9604 9605 private boolean cleanUp() { 9606 if (codeFile == null || !codeFile.exists()) { 9607 return false; 9608 } 9609 9610 if (codeFile.isDirectory()) { 9611 FileUtils.deleteContents(codeFile); 9612 } 9613 codeFile.delete(); 9614 9615 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 9616 resourceFile.delete(); 9617 } 9618 9619 if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) { 9620 if (!FileUtils.deleteContents(legacyNativeLibraryPath)) { 9621 Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath); 9622 } 9623 legacyNativeLibraryPath.delete(); 9624 } 9625 9626 return true; 9627 } 9628 9629 void cleanUpResourcesLI() { 9630 // Try enumerating all code paths before deleting 9631 List<String> allCodePaths = Collections.EMPTY_LIST; 9632 if (codeFile != null && codeFile.exists()) { 9633 try { 9634 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9635 allCodePaths = pkg.getAllCodePaths(); 9636 } catch (PackageParserException e) { 9637 // Ignored; we tried our best 9638 } 9639 } 9640 9641 cleanUp(); 9642 9643 if (!allCodePaths.isEmpty()) { 9644 if (instructionSets == null) { 9645 throw new IllegalStateException("instructionSet == null"); 9646 } 9647 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9648 for (String codePath : allCodePaths) { 9649 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9650 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9651 if (retCode < 0) { 9652 Slog.w(TAG, "Couldn't remove dex file for package: " 9653 + " at location " + codePath + ", retcode=" + retCode); 9654 // we don't consider this to be a failure of the core package deletion 9655 } 9656 } 9657 } 9658 } 9659 } 9660 9661 boolean doPostDeleteLI(boolean delete) { 9662 // XXX err, shouldn't we respect the delete flag? 9663 cleanUpResourcesLI(); 9664 return true; 9665 } 9666 } 9667 9668 private boolean isAsecExternal(String cid) { 9669 final String asecPath = PackageHelper.getSdFilesystem(cid); 9670 return !asecPath.startsWith(mAsecInternalPath); 9671 } 9672 9673 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 9674 PackageManagerException { 9675 if (copyRet < 0) { 9676 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 9677 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 9678 throw new PackageManagerException(copyRet, message); 9679 } 9680 } 9681 } 9682 9683 /** 9684 * Extract the MountService "container ID" from the full code path of an 9685 * .apk. 9686 */ 9687 static String cidFromCodePath(String fullCodePath) { 9688 int eidx = fullCodePath.lastIndexOf("/"); 9689 String subStr1 = fullCodePath.substring(0, eidx); 9690 int sidx = subStr1.lastIndexOf("/"); 9691 return subStr1.substring(sidx+1, eidx); 9692 } 9693 9694 /** 9695 * Logic to handle installation of ASEC applications, including copying and 9696 * renaming logic. 9697 */ 9698 class AsecInstallArgs extends InstallArgs { 9699 static final String RES_FILE_NAME = "pkg.apk"; 9700 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 9701 9702 String cid; 9703 String packagePath; 9704 String resourcePath; 9705 String legacyNativeLibraryDir; 9706 9707 /** New install */ 9708 AsecInstallArgs(InstallParams params) { 9709 super(params.origin, params.observer, params.installFlags, 9710 params.installerPackageName, params.getManifestDigest(), 9711 params.getUser(), null /* instruction sets */, 9712 params.packageAbiOverride); 9713 } 9714 9715 /** Existing install */ 9716 AsecInstallArgs(String fullCodePath, String[] instructionSets, 9717 boolean isExternal, boolean isForwardLocked) { 9718 super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0) 9719 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9720 instructionSets, null); 9721 // Hackily pretend we're still looking at a full code path 9722 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 9723 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 9724 } 9725 9726 // Extract cid from fullCodePath 9727 int eidx = fullCodePath.lastIndexOf("/"); 9728 String subStr1 = fullCodePath.substring(0, eidx); 9729 int sidx = subStr1.lastIndexOf("/"); 9730 cid = subStr1.substring(sidx+1, eidx); 9731 setMountPath(subStr1); 9732 } 9733 9734 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 9735 super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 9736 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9737 instructionSets, null); 9738 this.cid = cid; 9739 setMountPath(PackageHelper.getSdDir(cid)); 9740 } 9741 9742 void createCopyFile() { 9743 cid = mInstallerService.allocateExternalStageCidLegacy(); 9744 } 9745 9746 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9747 final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(), 9748 abiOverride); 9749 9750 final File target; 9751 if (isExternal()) { 9752 target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory(); 9753 } else { 9754 target = Environment.getDataDirectory(); 9755 } 9756 9757 final StorageManager storage = StorageManager.from(mContext); 9758 return (sizeBytes <= storage.getStorageBytesUntilLow(target)); 9759 } 9760 9761 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9762 if (origin.staged) { 9763 Slog.d(TAG, origin.cid + " already staged; skipping copy"); 9764 cid = origin.cid; 9765 setMountPath(PackageHelper.getSdDir(cid)); 9766 return PackageManager.INSTALL_SUCCEEDED; 9767 } 9768 9769 if (temp) { 9770 createCopyFile(); 9771 } else { 9772 /* 9773 * Pre-emptively destroy the container since it's destroyed if 9774 * copying fails due to it existing anyway. 9775 */ 9776 PackageHelper.destroySdDir(cid); 9777 } 9778 9779 final String newMountPath = imcs.copyPackageToContainer( 9780 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(), 9781 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 9782 9783 if (newMountPath != null) { 9784 setMountPath(newMountPath); 9785 return PackageManager.INSTALL_SUCCEEDED; 9786 } else { 9787 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9788 } 9789 } 9790 9791 @Override 9792 String getCodePath() { 9793 return packagePath; 9794 } 9795 9796 @Override 9797 String getResourcePath() { 9798 return resourcePath; 9799 } 9800 9801 @Override 9802 String getLegacyNativeLibraryPath() { 9803 return legacyNativeLibraryDir; 9804 } 9805 9806 int doPreInstall(int status) { 9807 if (status != PackageManager.INSTALL_SUCCEEDED) { 9808 // Destroy container 9809 PackageHelper.destroySdDir(cid); 9810 } else { 9811 boolean mounted = PackageHelper.isContainerMounted(cid); 9812 if (!mounted) { 9813 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 9814 Process.SYSTEM_UID); 9815 if (newMountPath != null) { 9816 setMountPath(newMountPath); 9817 } else { 9818 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9819 } 9820 } 9821 } 9822 return status; 9823 } 9824 9825 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9826 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 9827 String newMountPath = null; 9828 if (PackageHelper.isContainerMounted(cid)) { 9829 // Unmount the container 9830 if (!PackageHelper.unMountSdDir(cid)) { 9831 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9832 return false; 9833 } 9834 } 9835 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9836 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9837 " which might be stale. Will try to clean up."); 9838 // Clean up the stale container and proceed to recreate. 9839 if (!PackageHelper.destroySdDir(newCacheId)) { 9840 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9841 return false; 9842 } 9843 // Successfully cleaned up stale container. Try to rename again. 9844 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9845 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9846 + " inspite of cleaning it up."); 9847 return false; 9848 } 9849 } 9850 if (!PackageHelper.isContainerMounted(newCacheId)) { 9851 Slog.w(TAG, "Mounting container " + newCacheId); 9852 newMountPath = PackageHelper.mountSdDir(newCacheId, 9853 getEncryptKey(), Process.SYSTEM_UID); 9854 } else { 9855 newMountPath = PackageHelper.getSdDir(newCacheId); 9856 } 9857 if (newMountPath == null) { 9858 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9859 return false; 9860 } 9861 Log.i(TAG, "Succesfully renamed " + cid + 9862 " to " + newCacheId + 9863 " at new path: " + newMountPath); 9864 cid = newCacheId; 9865 9866 final File beforeCodeFile = new File(packagePath); 9867 setMountPath(newMountPath); 9868 final File afterCodeFile = new File(packagePath); 9869 9870 // Reflect the rename in scanned details 9871 pkg.codePath = afterCodeFile.getAbsolutePath(); 9872 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9873 pkg.baseCodePath); 9874 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9875 pkg.splitCodePaths); 9876 9877 // Reflect the rename in app info 9878 pkg.applicationInfo.setCodePath(pkg.codePath); 9879 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9880 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9881 pkg.applicationInfo.setResourcePath(pkg.codePath); 9882 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9883 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9884 9885 return true; 9886 } 9887 9888 private void setMountPath(String mountPath) { 9889 final File mountFile = new File(mountPath); 9890 9891 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 9892 if (monolithicFile.exists()) { 9893 packagePath = monolithicFile.getAbsolutePath(); 9894 if (isFwdLocked()) { 9895 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 9896 } else { 9897 resourcePath = packagePath; 9898 } 9899 } else { 9900 packagePath = mountFile.getAbsolutePath(); 9901 resourcePath = packagePath; 9902 } 9903 9904 legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath(); 9905 } 9906 9907 int doPostInstall(int status, int uid) { 9908 if (status != PackageManager.INSTALL_SUCCEEDED) { 9909 cleanUp(); 9910 } else { 9911 final int groupOwner; 9912 final String protectedFile; 9913 if (isFwdLocked()) { 9914 groupOwner = UserHandle.getSharedAppGid(uid); 9915 protectedFile = RES_FILE_NAME; 9916 } else { 9917 groupOwner = -1; 9918 protectedFile = null; 9919 } 9920 9921 if (uid < Process.FIRST_APPLICATION_UID 9922 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9923 Slog.e(TAG, "Failed to finalize " + cid); 9924 PackageHelper.destroySdDir(cid); 9925 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9926 } 9927 9928 boolean mounted = PackageHelper.isContainerMounted(cid); 9929 if (!mounted) { 9930 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9931 } 9932 } 9933 return status; 9934 } 9935 9936 private void cleanUp() { 9937 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9938 9939 // Destroy secure container 9940 PackageHelper.destroySdDir(cid); 9941 } 9942 9943 private List<String> getAllCodePaths() { 9944 final File codeFile = new File(getCodePath()); 9945 if (codeFile != null && codeFile.exists()) { 9946 try { 9947 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9948 return pkg.getAllCodePaths(); 9949 } catch (PackageParserException e) { 9950 // Ignored; we tried our best 9951 } 9952 } 9953 return Collections.EMPTY_LIST; 9954 } 9955 9956 void cleanUpResourcesLI() { 9957 // Enumerate all code paths before deleting 9958 cleanUpResourcesLI(getAllCodePaths()); 9959 } 9960 9961 private void cleanUpResourcesLI(List<String> allCodePaths) { 9962 cleanUp(); 9963 9964 if (!allCodePaths.isEmpty()) { 9965 if (instructionSets == null) { 9966 throw new IllegalStateException("instructionSet == null"); 9967 } 9968 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9969 for (String codePath : allCodePaths) { 9970 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9971 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9972 if (retCode < 0) { 9973 Slog.w(TAG, "Couldn't remove dex file for package: " 9974 + " at location " + codePath + ", retcode=" + retCode); 9975 // we don't consider this to be a failure of the core package deletion 9976 } 9977 } 9978 } 9979 } 9980 } 9981 9982 boolean matchContainer(String app) { 9983 if (cid.startsWith(app)) { 9984 return true; 9985 } 9986 return false; 9987 } 9988 9989 String getPackageName() { 9990 return getAsecPackageName(cid); 9991 } 9992 9993 boolean doPostDeleteLI(boolean delete) { 9994 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 9995 final List<String> allCodePaths = getAllCodePaths(); 9996 boolean mounted = PackageHelper.isContainerMounted(cid); 9997 if (mounted) { 9998 // Unmount first 9999 if (PackageHelper.unMountSdDir(cid)) { 10000 mounted = false; 10001 } 10002 } 10003 if (!mounted && delete) { 10004 cleanUpResourcesLI(allCodePaths); 10005 } 10006 return !mounted; 10007 } 10008 10009 @Override 10010 int doPreCopy() { 10011 if (isFwdLocked()) { 10012 if (!PackageHelper.fixSdPermissions(cid, 10013 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 10014 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10015 } 10016 } 10017 10018 return PackageManager.INSTALL_SUCCEEDED; 10019 } 10020 10021 @Override 10022 int doPostCopy(int uid) { 10023 if (isFwdLocked()) { 10024 if (uid < Process.FIRST_APPLICATION_UID 10025 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 10026 RES_FILE_NAME)) { 10027 Slog.e(TAG, "Failed to finalize " + cid); 10028 PackageHelper.destroySdDir(cid); 10029 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10030 } 10031 } 10032 10033 return PackageManager.INSTALL_SUCCEEDED; 10034 } 10035 } 10036 10037 static String getAsecPackageName(String packageCid) { 10038 int idx = packageCid.lastIndexOf("-"); 10039 if (idx == -1) { 10040 return packageCid; 10041 } 10042 return packageCid.substring(0, idx); 10043 } 10044 10045 // Utility method used to create code paths based on package name and available index. 10046 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 10047 String idxStr = ""; 10048 int idx = 1; 10049 // Fall back to default value of idx=1 if prefix is not 10050 // part of oldCodePath 10051 if (oldCodePath != null) { 10052 String subStr = oldCodePath; 10053 // Drop the suffix right away 10054 if (suffix != null && subStr.endsWith(suffix)) { 10055 subStr = subStr.substring(0, subStr.length() - suffix.length()); 10056 } 10057 // If oldCodePath already contains prefix find out the 10058 // ending index to either increment or decrement. 10059 int sidx = subStr.lastIndexOf(prefix); 10060 if (sidx != -1) { 10061 subStr = subStr.substring(sidx + prefix.length()); 10062 if (subStr != null) { 10063 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 10064 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 10065 } 10066 try { 10067 idx = Integer.parseInt(subStr); 10068 if (idx <= 1) { 10069 idx++; 10070 } else { 10071 idx--; 10072 } 10073 } catch(NumberFormatException e) { 10074 } 10075 } 10076 } 10077 } 10078 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 10079 return prefix + idxStr; 10080 } 10081 10082 private File getNextCodePath(String packageName) { 10083 int suffix = 1; 10084 File result; 10085 do { 10086 result = new File(mAppInstallDir, packageName + "-" + suffix); 10087 suffix++; 10088 } while (result.exists()); 10089 return result; 10090 } 10091 10092 // Utility method used to ignore ADD/REMOVE events 10093 // by directory observer. 10094 private static boolean ignoreCodePath(String fullPathStr) { 10095 String apkName = deriveCodePathName(fullPathStr); 10096 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 10097 if (idx != -1 && ((idx+1) < apkName.length())) { 10098 // Make sure the package ends with a numeral 10099 String version = apkName.substring(idx+1); 10100 try { 10101 Integer.parseInt(version); 10102 return true; 10103 } catch (NumberFormatException e) {} 10104 } 10105 return false; 10106 } 10107 10108 // Utility method that returns the relative package path with respect 10109 // to the installation directory. Like say for /data/data/com.test-1.apk 10110 // string com.test-1 is returned. 10111 static String deriveCodePathName(String codePath) { 10112 if (codePath == null) { 10113 return null; 10114 } 10115 final File codeFile = new File(codePath); 10116 final String name = codeFile.getName(); 10117 if (codeFile.isDirectory()) { 10118 return name; 10119 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 10120 final int lastDot = name.lastIndexOf('.'); 10121 return name.substring(0, lastDot); 10122 } else { 10123 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 10124 return null; 10125 } 10126 } 10127 10128 class PackageInstalledInfo { 10129 String name; 10130 int uid; 10131 // The set of users that originally had this package installed. 10132 int[] origUsers; 10133 // The set of users that now have this package installed. 10134 int[] newUsers; 10135 PackageParser.Package pkg; 10136 int returnCode; 10137 String returnMsg; 10138 PackageRemovedInfo removedInfo; 10139 10140 public void setError(int code, String msg) { 10141 returnCode = code; 10142 returnMsg = msg; 10143 Slog.w(TAG, msg); 10144 } 10145 10146 public void setError(String msg, PackageParserException e) { 10147 returnCode = e.error; 10148 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 10149 Slog.w(TAG, msg, e); 10150 } 10151 10152 public void setError(String msg, PackageManagerException e) { 10153 returnCode = e.error; 10154 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 10155 Slog.w(TAG, msg, e); 10156 } 10157 10158 // In some error cases we want to convey more info back to the observer 10159 String origPackage; 10160 String origPermission; 10161 } 10162 10163 /* 10164 * Install a non-existing package. 10165 */ 10166 private void installNewPackageLI(PackageParser.Package pkg, 10167 int parseFlags, int scanFlags, UserHandle user, 10168 String installerPackageName, PackageInstalledInfo res) { 10169 // Remember this for later, in case we need to rollback this install 10170 String pkgName = pkg.packageName; 10171 10172 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 10173 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 10174 synchronized(mPackages) { 10175 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 10176 // A package with the same name is already installed, though 10177 // it has been renamed to an older name. The package we 10178 // are trying to install should be installed as an update to 10179 // the existing one, but that has not been requested, so bail. 10180 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10181 + " without first uninstalling package running as " 10182 + mSettings.mRenamedPackages.get(pkgName)); 10183 return; 10184 } 10185 if (mPackages.containsKey(pkgName)) { 10186 // Don't allow installation over an existing package with the same name. 10187 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10188 + " without first uninstalling."); 10189 return; 10190 } 10191 } 10192 10193 try { 10194 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 10195 System.currentTimeMillis(), user); 10196 10197 updateSettingsLI(newPackage, installerPackageName, null, null, res); 10198 // delete the partially installed application. the data directory will have to be 10199 // restored if it was already existing 10200 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10201 // remove package from internal structures. Note that we want deletePackageX to 10202 // delete the package data and cache directories that it created in 10203 // scanPackageLocked, unless those directories existed before we even tried to 10204 // install. 10205 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 10206 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 10207 res.removedInfo, true); 10208 } 10209 10210 } catch (PackageManagerException e) { 10211 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10212 } 10213 } 10214 10215 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 10216 // Upgrade keysets are being used. Determine if new package has a superset of the 10217 // required keys. 10218 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 10219 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10220 for (int i = 0; i < upgradeKeySets.length; i++) { 10221 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 10222 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 10223 return true; 10224 } 10225 } 10226 return false; 10227 } 10228 10229 private void replacePackageLI(PackageParser.Package pkg, 10230 int parseFlags, int scanFlags, UserHandle user, 10231 String installerPackageName, PackageInstalledInfo res) { 10232 PackageParser.Package oldPackage; 10233 String pkgName = pkg.packageName; 10234 int[] allUsers; 10235 boolean[] perUserInstalled; 10236 10237 // First find the old package info and check signatures 10238 synchronized(mPackages) { 10239 oldPackage = mPackages.get(pkgName); 10240 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 10241 PackageSetting ps = mSettings.mPackages.get(pkgName); 10242 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 10243 // default to original signature matching 10244 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 10245 != PackageManager.SIGNATURE_MATCH) { 10246 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10247 "New package has a different signature: " + pkgName); 10248 return; 10249 } 10250 } else { 10251 if(!checkUpgradeKeySetLP(ps, pkg)) { 10252 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10253 "New package not signed by keys specified by upgrade-keysets: " 10254 + pkgName); 10255 return; 10256 } 10257 } 10258 10259 // In case of rollback, remember per-user/profile install state 10260 allUsers = sUserManager.getUserIds(); 10261 perUserInstalled = new boolean[allUsers.length]; 10262 for (int i = 0; i < allUsers.length; i++) { 10263 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10264 } 10265 } 10266 10267 boolean sysPkg = (isSystemApp(oldPackage)); 10268 if (sysPkg) { 10269 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10270 user, allUsers, perUserInstalled, installerPackageName, res); 10271 } else { 10272 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10273 user, allUsers, perUserInstalled, installerPackageName, res); 10274 } 10275 } 10276 10277 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 10278 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10279 int[] allUsers, boolean[] perUserInstalled, 10280 String installerPackageName, PackageInstalledInfo res) { 10281 String pkgName = deletedPackage.packageName; 10282 boolean deletedPkg = true; 10283 boolean updatedSettings = false; 10284 10285 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 10286 + deletedPackage); 10287 long origUpdateTime; 10288 if (pkg.mExtras != null) { 10289 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 10290 } else { 10291 origUpdateTime = 0; 10292 } 10293 10294 // First delete the existing package while retaining the data directory 10295 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 10296 res.removedInfo, true)) { 10297 // If the existing package wasn't successfully deleted 10298 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 10299 deletedPkg = false; 10300 } else { 10301 // Successfully deleted the old package; proceed with replace. 10302 10303 // If deleted package lived in a container, give users a chance to 10304 // relinquish resources before killing. 10305 if (isForwardLocked(deletedPackage) || isExternal(deletedPackage)) { 10306 if (DEBUG_INSTALL) { 10307 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 10308 } 10309 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 10310 final ArrayList<String> pkgList = new ArrayList<String>(1); 10311 pkgList.add(deletedPackage.applicationInfo.packageName); 10312 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 10313 } 10314 10315 deleteCodeCacheDirsLI(pkgName); 10316 try { 10317 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 10318 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 10319 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10320 updatedSettings = true; 10321 } catch (PackageManagerException e) { 10322 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10323 } 10324 } 10325 10326 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10327 // remove package from internal structures. Note that we want deletePackageX to 10328 // delete the package data and cache directories that it created in 10329 // scanPackageLocked, unless those directories existed before we even tried to 10330 // install. 10331 if(updatedSettings) { 10332 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 10333 deletePackageLI( 10334 pkgName, null, true, allUsers, perUserInstalled, 10335 PackageManager.DELETE_KEEP_DATA, 10336 res.removedInfo, true); 10337 } 10338 // Since we failed to install the new package we need to restore the old 10339 // package that we deleted. 10340 if (deletedPkg) { 10341 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 10342 File restoreFile = new File(deletedPackage.codePath); 10343 // Parse old package 10344 boolean oldOnSd = isExternal(deletedPackage); 10345 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 10346 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) | 10347 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 10348 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 10349 try { 10350 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 10351 } catch (PackageManagerException e) { 10352 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 10353 + e.getMessage()); 10354 return; 10355 } 10356 // Restore of old package succeeded. Update permissions. 10357 // writer 10358 synchronized (mPackages) { 10359 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 10360 UPDATE_PERMISSIONS_ALL); 10361 // can downgrade to reader 10362 mSettings.writeLPr(); 10363 } 10364 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 10365 } 10366 } 10367 } 10368 10369 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 10370 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10371 int[] allUsers, boolean[] perUserInstalled, 10372 String installerPackageName, PackageInstalledInfo res) { 10373 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 10374 + ", old=" + deletedPackage); 10375 boolean disabledSystem = false; 10376 boolean updatedSettings = false; 10377 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 10378 if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 10379 != 0) { 10380 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10381 } 10382 String packageName = deletedPackage.packageName; 10383 if (packageName == null) { 10384 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10385 "Attempt to delete null packageName."); 10386 return; 10387 } 10388 PackageParser.Package oldPkg; 10389 PackageSetting oldPkgSetting; 10390 // reader 10391 synchronized (mPackages) { 10392 oldPkg = mPackages.get(packageName); 10393 oldPkgSetting = mSettings.mPackages.get(packageName); 10394 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 10395 (oldPkgSetting == null)) { 10396 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10397 "Couldn't find package:" + packageName + " information"); 10398 return; 10399 } 10400 } 10401 10402 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 10403 10404 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10405 res.removedInfo.removedPackage = packageName; 10406 // Remove existing system package 10407 removePackageLI(oldPkgSetting, true); 10408 // writer 10409 synchronized (mPackages) { 10410 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 10411 if (!disabledSystem && deletedPackage != null) { 10412 // We didn't need to disable the .apk as a current system package, 10413 // which means we are replacing another update that is already 10414 // installed. We need to make sure to delete the older one's .apk. 10415 res.removedInfo.args = createInstallArgsForExisting(0, 10416 deletedPackage.applicationInfo.getCodePath(), 10417 deletedPackage.applicationInfo.getResourcePath(), 10418 deletedPackage.applicationInfo.nativeLibraryRootDir, 10419 getAppDexInstructionSets(deletedPackage.applicationInfo)); 10420 } else { 10421 res.removedInfo.args = null; 10422 } 10423 } 10424 10425 // Successfully disabled the old package. Now proceed with re-installation 10426 deleteCodeCacheDirsLI(packageName); 10427 10428 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10429 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10430 10431 PackageParser.Package newPackage = null; 10432 try { 10433 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 10434 if (newPackage.mExtras != null) { 10435 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 10436 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10437 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10438 10439 // is the update attempting to change shared user? that isn't going to work... 10440 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10441 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 10442 "Forbidding shared user change from " + oldPkgSetting.sharedUser 10443 + " to " + newPkgSetting.sharedUser); 10444 updatedSettings = true; 10445 } 10446 } 10447 10448 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10449 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10450 updatedSettings = true; 10451 } 10452 10453 } catch (PackageManagerException e) { 10454 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10455 } 10456 10457 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10458 // Re installation failed. Restore old information 10459 // Remove new pkg information 10460 if (newPackage != null) { 10461 removeInstalledPackageLI(newPackage, true); 10462 } 10463 // Add back the old system package 10464 try { 10465 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 10466 } catch (PackageManagerException e) { 10467 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 10468 } 10469 // Restore the old system information in Settings 10470 synchronized (mPackages) { 10471 if (disabledSystem) { 10472 mSettings.enableSystemPackageLPw(packageName); 10473 } 10474 if (updatedSettings) { 10475 mSettings.setInstallerPackageName(packageName, 10476 oldPkgSetting.installerPackageName); 10477 } 10478 mSettings.writeLPr(); 10479 } 10480 } 10481 } 10482 10483 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10484 int[] allUsers, boolean[] perUserInstalled, 10485 PackageInstalledInfo res) { 10486 String pkgName = newPackage.packageName; 10487 synchronized (mPackages) { 10488 //write settings. the installStatus will be incomplete at this stage. 10489 //note that the new package setting would have already been 10490 //added to mPackages. It hasn't been persisted yet. 10491 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10492 mSettings.writeLPr(); 10493 } 10494 10495 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10496 10497 synchronized (mPackages) { 10498 updatePermissionsLPw(newPackage.packageName, newPackage, 10499 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10500 ? UPDATE_PERMISSIONS_ALL : 0)); 10501 // For system-bundled packages, we assume that installing an upgraded version 10502 // of the package implies that the user actually wants to run that new code, 10503 // so we enable the package. 10504 if (isSystemApp(newPackage)) { 10505 // NB: implicit assumption that system package upgrades apply to all users 10506 if (DEBUG_INSTALL) { 10507 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10508 } 10509 PackageSetting ps = mSettings.mPackages.get(pkgName); 10510 if (ps != null) { 10511 if (res.origUsers != null) { 10512 for (int userHandle : res.origUsers) { 10513 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10514 userHandle, installerPackageName); 10515 } 10516 } 10517 // Also convey the prior install/uninstall state 10518 if (allUsers != null && perUserInstalled != null) { 10519 for (int i = 0; i < allUsers.length; i++) { 10520 if (DEBUG_INSTALL) { 10521 Slog.d(TAG, " user " + allUsers[i] 10522 + " => " + perUserInstalled[i]); 10523 } 10524 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10525 } 10526 // these install state changes will be persisted in the 10527 // upcoming call to mSettings.writeLPr(). 10528 } 10529 } 10530 } 10531 res.name = pkgName; 10532 res.uid = newPackage.applicationInfo.uid; 10533 res.pkg = newPackage; 10534 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10535 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10536 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10537 //to update install status 10538 mSettings.writeLPr(); 10539 } 10540 } 10541 10542 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 10543 final int installFlags = args.installFlags; 10544 String installerPackageName = args.installerPackageName; 10545 File tmpPackageFile = new File(args.getCodePath()); 10546 boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10547 boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0); 10548 boolean replace = false; 10549 final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE; 10550 // Result object to be returned 10551 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10552 10553 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10554 // Retrieve PackageSettings and parse package 10555 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10556 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10557 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 10558 PackageParser pp = new PackageParser(); 10559 pp.setSeparateProcesses(mSeparateProcesses); 10560 pp.setDisplayMetrics(mMetrics); 10561 10562 final PackageParser.Package pkg; 10563 try { 10564 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 10565 } catch (PackageParserException e) { 10566 res.setError("Failed parse during installPackageLI", e); 10567 return; 10568 } 10569 10570 // Mark that we have an install time CPU ABI override. 10571 pkg.cpuAbiOverride = args.abiOverride; 10572 10573 String pkgName = res.name = pkg.packageName; 10574 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 10575 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 10576 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 10577 return; 10578 } 10579 } 10580 10581 try { 10582 pp.collectCertificates(pkg, parseFlags); 10583 pp.collectManifestDigest(pkg); 10584 } catch (PackageParserException e) { 10585 res.setError("Failed collect during installPackageLI", e); 10586 return; 10587 } 10588 10589 /* If the installer passed in a manifest digest, compare it now. */ 10590 if (args.manifestDigest != null) { 10591 if (DEBUG_INSTALL) { 10592 final String parsedManifest = pkg.manifestDigest == null ? "null" 10593 : pkg.manifestDigest.toString(); 10594 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 10595 + parsedManifest); 10596 } 10597 10598 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 10599 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 10600 return; 10601 } 10602 } else if (DEBUG_INSTALL) { 10603 final String parsedManifest = pkg.manifestDigest == null 10604 ? "null" : pkg.manifestDigest.toString(); 10605 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 10606 } 10607 10608 // Get rid of all references to package scan path via parser. 10609 pp = null; 10610 String oldCodePath = null; 10611 boolean systemApp = false; 10612 synchronized (mPackages) { 10613 // Check if installing already existing package 10614 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10615 String oldName = mSettings.mRenamedPackages.get(pkgName); 10616 if (pkg.mOriginalPackages != null 10617 && pkg.mOriginalPackages.contains(oldName) 10618 && mPackages.containsKey(oldName)) { 10619 // This package is derived from an original package, 10620 // and this device has been updating from that original 10621 // name. We must continue using the original name, so 10622 // rename the new package here. 10623 pkg.setPackageName(oldName); 10624 pkgName = pkg.packageName; 10625 replace = true; 10626 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 10627 + oldName + " pkgName=" + pkgName); 10628 } else if (mPackages.containsKey(pkgName)) { 10629 // This package, under its official name, already exists 10630 // on the device; we should replace it. 10631 replace = true; 10632 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 10633 } 10634 } 10635 10636 PackageSetting ps = mSettings.mPackages.get(pkgName); 10637 if (ps != null) { 10638 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 10639 10640 // Quick sanity check that we're signed correctly if updating; 10641 // we'll check this again later when scanning, but we want to 10642 // bail early here before tripping over redefined permissions. 10643 if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 10644 try { 10645 verifySignaturesLP(ps, pkg); 10646 } catch (PackageManagerException e) { 10647 res.setError(e.error, e.getMessage()); 10648 return; 10649 } 10650 } else { 10651 if (!checkUpgradeKeySetLP(ps, pkg)) { 10652 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 10653 + pkg.packageName + " upgrade keys do not match the " 10654 + "previously installed version"); 10655 return; 10656 } 10657 } 10658 10659 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 10660 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 10661 systemApp = (ps.pkg.applicationInfo.flags & 10662 ApplicationInfo.FLAG_SYSTEM) != 0; 10663 } 10664 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10665 } 10666 10667 // Check whether the newly-scanned package wants to define an already-defined perm 10668 int N = pkg.permissions.size(); 10669 for (int i = N-1; i >= 0; i--) { 10670 PackageParser.Permission perm = pkg.permissions.get(i); 10671 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 10672 if (bp != null) { 10673 // If the defining package is signed with our cert, it's okay. This 10674 // also includes the "updating the same package" case, of course. 10675 // "updating same package" could also involve key-rotation. 10676 final boolean sigsOk; 10677 if (!bp.sourcePackage.equals(pkg.packageName) 10678 || !(bp.packageSetting instanceof PackageSetting) 10679 || !bp.packageSetting.keySetData.isUsingUpgradeKeySets() 10680 || ((PackageSetting) bp.packageSetting).sharedUser != null) { 10681 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 10682 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 10683 } else { 10684 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 10685 } 10686 if (!sigsOk) { 10687 // If the owning package is the system itself, we log but allow 10688 // install to proceed; we fail the install on all other permission 10689 // redefinitions. 10690 if (!bp.sourcePackage.equals("android")) { 10691 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 10692 + pkg.packageName + " attempting to redeclare permission " 10693 + perm.info.name + " already owned by " + bp.sourcePackage); 10694 res.origPermission = perm.info.name; 10695 res.origPackage = bp.sourcePackage; 10696 return; 10697 } else { 10698 Slog.w(TAG, "Package " + pkg.packageName 10699 + " attempting to redeclare system permission " 10700 + perm.info.name + "; ignoring new declaration"); 10701 pkg.permissions.remove(i); 10702 } 10703 } 10704 } 10705 } 10706 10707 } 10708 10709 if (systemApp && onSd) { 10710 // Disable updates to system apps on sdcard 10711 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 10712 "Cannot install updates to system apps on sdcard"); 10713 return; 10714 } 10715 10716 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 10717 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 10718 return; 10719 } 10720 10721 if (replace) { 10722 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 10723 installerPackageName, res); 10724 } else { 10725 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 10726 args.user, installerPackageName, res); 10727 } 10728 synchronized (mPackages) { 10729 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10730 if (ps != null) { 10731 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10732 } 10733 } 10734 } 10735 10736 private static boolean isForwardLocked(PackageParser.Package pkg) { 10737 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_FORWARD_LOCK) != 0; 10738 } 10739 10740 private static boolean isForwardLocked(ApplicationInfo info) { 10741 return (info.privateFlags & ApplicationInfo.PRIVATE_FLAG_FORWARD_LOCK) != 0; 10742 } 10743 10744 private boolean isForwardLocked(PackageSetting ps) { 10745 return (ps.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_FORWARD_LOCK) != 0; 10746 } 10747 10748 private static boolean isMultiArch(PackageSetting ps) { 10749 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10750 } 10751 10752 private static boolean isMultiArch(ApplicationInfo info) { 10753 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10754 } 10755 10756 private static boolean isExternal(PackageParser.Package pkg) { 10757 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10758 } 10759 10760 private static boolean isExternal(PackageSetting ps) { 10761 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10762 } 10763 10764 private static boolean isExternal(ApplicationInfo info) { 10765 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10766 } 10767 10768 private static boolean isSystemApp(PackageParser.Package pkg) { 10769 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10770 } 10771 10772 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 10773 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 10774 } 10775 10776 private static boolean isSystemApp(ApplicationInfo info) { 10777 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10778 } 10779 10780 private static boolean isSystemApp(PackageSetting ps) { 10781 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 10782 } 10783 10784 private static boolean isUpdatedSystemApp(PackageSetting ps) { 10785 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10786 } 10787 10788 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 10789 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10790 } 10791 10792 private static boolean isUpdatedSystemApp(ApplicationInfo info) { 10793 return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10794 } 10795 10796 private int packageFlagsToInstallFlags(PackageSetting ps) { 10797 int installFlags = 0; 10798 if (isExternal(ps)) { 10799 installFlags |= PackageManager.INSTALL_EXTERNAL; 10800 } 10801 if (isForwardLocked(ps)) { 10802 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 10803 } 10804 return installFlags; 10805 } 10806 10807 private void deleteTempPackageFiles() { 10808 final FilenameFilter filter = new FilenameFilter() { 10809 public boolean accept(File dir, String name) { 10810 return name.startsWith("vmdl") && name.endsWith(".tmp"); 10811 } 10812 }; 10813 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 10814 file.delete(); 10815 } 10816 } 10817 10818 @Override 10819 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 10820 int flags) { 10821 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 10822 flags); 10823 } 10824 10825 @Override 10826 public void deletePackage(final String packageName, 10827 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 10828 mContext.enforceCallingOrSelfPermission( 10829 android.Manifest.permission.DELETE_PACKAGES, null); 10830 final int uid = Binder.getCallingUid(); 10831 if (UserHandle.getUserId(uid) != userId) { 10832 mContext.enforceCallingPermission( 10833 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 10834 "deletePackage for user " + userId); 10835 } 10836 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 10837 try { 10838 observer.onPackageDeleted(packageName, 10839 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 10840 } catch (RemoteException re) { 10841 } 10842 return; 10843 } 10844 10845 boolean uninstallBlocked = false; 10846 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 10847 int[] users = sUserManager.getUserIds(); 10848 for (int i = 0; i < users.length; ++i) { 10849 if (getBlockUninstallForUser(packageName, users[i])) { 10850 uninstallBlocked = true; 10851 break; 10852 } 10853 } 10854 } else { 10855 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 10856 } 10857 if (uninstallBlocked) { 10858 try { 10859 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 10860 null); 10861 } catch (RemoteException re) { 10862 } 10863 return; 10864 } 10865 10866 if (DEBUG_REMOVE) { 10867 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 10868 } 10869 // Queue up an async operation since the package deletion may take a little while. 10870 mHandler.post(new Runnable() { 10871 public void run() { 10872 mHandler.removeCallbacks(this); 10873 final int returnCode = deletePackageX(packageName, userId, flags); 10874 if (observer != null) { 10875 try { 10876 observer.onPackageDeleted(packageName, returnCode, null); 10877 } catch (RemoteException e) { 10878 Log.i(TAG, "Observer no longer exists."); 10879 } //end catch 10880 } //end if 10881 } //end run 10882 }); 10883 } 10884 10885 private boolean isPackageDeviceAdmin(String packageName, int userId) { 10886 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 10887 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 10888 try { 10889 if (dpm != null) { 10890 if (dpm.isDeviceOwner(packageName)) { 10891 return true; 10892 } 10893 int[] users; 10894 if (userId == UserHandle.USER_ALL) { 10895 users = sUserManager.getUserIds(); 10896 } else { 10897 users = new int[]{userId}; 10898 } 10899 for (int i = 0; i < users.length; ++i) { 10900 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 10901 return true; 10902 } 10903 } 10904 } 10905 } catch (RemoteException e) { 10906 } 10907 return false; 10908 } 10909 10910 /** 10911 * This method is an internal method that could be get invoked either 10912 * to delete an installed package or to clean up a failed installation. 10913 * After deleting an installed package, a broadcast is sent to notify any 10914 * listeners that the package has been installed. For cleaning up a failed 10915 * installation, the broadcast is not necessary since the package's 10916 * installation wouldn't have sent the initial broadcast either 10917 * The key steps in deleting a package are 10918 * deleting the package information in internal structures like mPackages, 10919 * deleting the packages base directories through installd 10920 * updating mSettings to reflect current status 10921 * persisting settings for later use 10922 * sending a broadcast if necessary 10923 */ 10924 private int deletePackageX(String packageName, int userId, int flags) { 10925 final PackageRemovedInfo info = new PackageRemovedInfo(); 10926 final boolean res; 10927 10928 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 10929 ? UserHandle.ALL : new UserHandle(userId); 10930 10931 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 10932 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 10933 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 10934 } 10935 10936 boolean removedForAllUsers = false; 10937 boolean systemUpdate = false; 10938 10939 // for the uninstall-updates case and restricted profiles, remember the per- 10940 // userhandle installed state 10941 int[] allUsers; 10942 boolean[] perUserInstalled; 10943 synchronized (mPackages) { 10944 PackageSetting ps = mSettings.mPackages.get(packageName); 10945 allUsers = sUserManager.getUserIds(); 10946 perUserInstalled = new boolean[allUsers.length]; 10947 for (int i = 0; i < allUsers.length; i++) { 10948 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10949 } 10950 } 10951 10952 synchronized (mInstallLock) { 10953 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 10954 res = deletePackageLI(packageName, removeForUser, 10955 true, allUsers, perUserInstalled, 10956 flags | REMOVE_CHATTY, info, true); 10957 systemUpdate = info.isRemovedPackageSystemUpdate; 10958 if (res && !systemUpdate && mPackages.get(packageName) == null) { 10959 removedForAllUsers = true; 10960 } 10961 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 10962 + " removedForAllUsers=" + removedForAllUsers); 10963 } 10964 10965 if (res) { 10966 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 10967 10968 // If the removed package was a system update, the old system package 10969 // was re-enabled; we need to broadcast this information 10970 if (systemUpdate) { 10971 Bundle extras = new Bundle(1); 10972 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 10973 ? info.removedAppId : info.uid); 10974 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10975 10976 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 10977 extras, null, null, null); 10978 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 10979 extras, null, null, null); 10980 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 10981 null, packageName, null, null); 10982 } 10983 } 10984 // Force a gc here. 10985 Runtime.getRuntime().gc(); 10986 // Delete the resources here after sending the broadcast to let 10987 // other processes clean up before deleting resources. 10988 if (info.args != null) { 10989 synchronized (mInstallLock) { 10990 info.args.doPostDeleteLI(true); 10991 } 10992 } 10993 10994 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10995 } 10996 10997 static class PackageRemovedInfo { 10998 String removedPackage; 10999 int uid = -1; 11000 int removedAppId = -1; 11001 int[] removedUsers = null; 11002 boolean isRemovedPackageSystemUpdate = false; 11003 // Clean up resources deleted packages. 11004 InstallArgs args = null; 11005 11006 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 11007 Bundle extras = new Bundle(1); 11008 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 11009 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 11010 if (replacing) { 11011 extras.putBoolean(Intent.EXTRA_REPLACING, true); 11012 } 11013 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 11014 if (removedPackage != null) { 11015 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 11016 extras, null, null, removedUsers); 11017 if (fullRemove && !replacing) { 11018 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 11019 extras, null, null, removedUsers); 11020 } 11021 } 11022 if (removedAppId >= 0) { 11023 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 11024 removedUsers); 11025 } 11026 } 11027 } 11028 11029 /* 11030 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 11031 * flag is not set, the data directory is removed as well. 11032 * make sure this flag is set for partially installed apps. If not its meaningless to 11033 * delete a partially installed application. 11034 */ 11035 private void removePackageDataLI(PackageSetting ps, 11036 int[] allUserHandles, boolean[] perUserInstalled, 11037 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 11038 String packageName = ps.name; 11039 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 11040 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 11041 // Retrieve object to delete permissions for shared user later on 11042 final PackageSetting deletedPs; 11043 // reader 11044 synchronized (mPackages) { 11045 deletedPs = mSettings.mPackages.get(packageName); 11046 if (outInfo != null) { 11047 outInfo.removedPackage = packageName; 11048 outInfo.removedUsers = deletedPs != null 11049 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 11050 : null; 11051 } 11052 } 11053 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 11054 removeDataDirsLI(packageName); 11055 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 11056 } 11057 // writer 11058 synchronized (mPackages) { 11059 if (deletedPs != null) { 11060 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 11061 if (outInfo != null) { 11062 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 11063 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 11064 } 11065 if (deletedPs != null) { 11066 updatePermissionsLPw(deletedPs.name, null, 0); 11067 if (deletedPs.sharedUser != null) { 11068 // remove permissions associated with package 11069 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 11070 } 11071 } 11072 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 11073 } 11074 // make sure to preserve per-user disabled state if this removal was just 11075 // a downgrade of a system app to the factory package 11076 if (allUserHandles != null && perUserInstalled != null) { 11077 if (DEBUG_REMOVE) { 11078 Slog.d(TAG, "Propagating install state across downgrade"); 11079 } 11080 for (int i = 0; i < allUserHandles.length; i++) { 11081 if (DEBUG_REMOVE) { 11082 Slog.d(TAG, " user " + allUserHandles[i] 11083 + " => " + perUserInstalled[i]); 11084 } 11085 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 11086 } 11087 } 11088 } 11089 // can downgrade to reader 11090 if (writeSettings) { 11091 // Save settings now 11092 mSettings.writeLPr(); 11093 } 11094 } 11095 if (outInfo != null) { 11096 // A user ID was deleted here. Go through all users and remove it 11097 // from KeyStore. 11098 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 11099 } 11100 } 11101 11102 static boolean locationIsPrivileged(File path) { 11103 try { 11104 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 11105 .getCanonicalPath(); 11106 return path.getCanonicalPath().startsWith(privilegedAppDir); 11107 } catch (IOException e) { 11108 Slog.e(TAG, "Unable to access code path " + path); 11109 } 11110 return false; 11111 } 11112 11113 /* 11114 * Tries to delete system package. 11115 */ 11116 private boolean deleteSystemPackageLI(PackageSetting newPs, 11117 int[] allUserHandles, boolean[] perUserInstalled, 11118 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 11119 final boolean applyUserRestrictions 11120 = (allUserHandles != null) && (perUserInstalled != null); 11121 PackageSetting disabledPs = null; 11122 // Confirm if the system package has been updated 11123 // An updated system app can be deleted. This will also have to restore 11124 // the system pkg from system partition 11125 // reader 11126 synchronized (mPackages) { 11127 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 11128 } 11129 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 11130 + " disabledPs=" + disabledPs); 11131 if (disabledPs == null) { 11132 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 11133 return false; 11134 } else if (DEBUG_REMOVE) { 11135 Slog.d(TAG, "Deleting system pkg from data partition"); 11136 } 11137 if (DEBUG_REMOVE) { 11138 if (applyUserRestrictions) { 11139 Slog.d(TAG, "Remembering install states:"); 11140 for (int i = 0; i < allUserHandles.length; i++) { 11141 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 11142 } 11143 } 11144 } 11145 // Delete the updated package 11146 outInfo.isRemovedPackageSystemUpdate = true; 11147 if (disabledPs.versionCode < newPs.versionCode) { 11148 // Delete data for downgrades 11149 flags &= ~PackageManager.DELETE_KEEP_DATA; 11150 } else { 11151 // Preserve data by setting flag 11152 flags |= PackageManager.DELETE_KEEP_DATA; 11153 } 11154 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 11155 allUserHandles, perUserInstalled, outInfo, writeSettings); 11156 if (!ret) { 11157 return false; 11158 } 11159 // writer 11160 synchronized (mPackages) { 11161 // Reinstate the old system package 11162 mSettings.enableSystemPackageLPw(newPs.name); 11163 // Remove any native libraries from the upgraded package. 11164 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 11165 } 11166 // Install the system package 11167 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 11168 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 11169 if (locationIsPrivileged(disabledPs.codePath)) { 11170 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11171 } 11172 11173 final PackageParser.Package newPkg; 11174 try { 11175 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 11176 } catch (PackageManagerException e) { 11177 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 11178 return false; 11179 } 11180 11181 // writer 11182 synchronized (mPackages) { 11183 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 11184 updatePermissionsLPw(newPkg.packageName, newPkg, 11185 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 11186 if (applyUserRestrictions) { 11187 if (DEBUG_REMOVE) { 11188 Slog.d(TAG, "Propagating install state across reinstall"); 11189 } 11190 for (int i = 0; i < allUserHandles.length; i++) { 11191 if (DEBUG_REMOVE) { 11192 Slog.d(TAG, " user " + allUserHandles[i] 11193 + " => " + perUserInstalled[i]); 11194 } 11195 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 11196 } 11197 // Regardless of writeSettings we need to ensure that this restriction 11198 // state propagation is persisted 11199 mSettings.writeAllUsersPackageRestrictionsLPr(); 11200 } 11201 // can downgrade to reader here 11202 if (writeSettings) { 11203 mSettings.writeLPr(); 11204 } 11205 } 11206 return true; 11207 } 11208 11209 private boolean deleteInstalledPackageLI(PackageSetting ps, 11210 boolean deleteCodeAndResources, int flags, 11211 int[] allUserHandles, boolean[] perUserInstalled, 11212 PackageRemovedInfo outInfo, boolean writeSettings) { 11213 if (outInfo != null) { 11214 outInfo.uid = ps.appId; 11215 } 11216 11217 // Delete package data from internal structures and also remove data if flag is set 11218 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 11219 11220 // Delete application code and resources 11221 if (deleteCodeAndResources && (outInfo != null)) { 11222 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 11223 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 11224 getAppDexInstructionSets(ps)); 11225 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 11226 } 11227 return true; 11228 } 11229 11230 @Override 11231 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 11232 int userId) { 11233 mContext.enforceCallingOrSelfPermission( 11234 android.Manifest.permission.DELETE_PACKAGES, null); 11235 synchronized (mPackages) { 11236 PackageSetting ps = mSettings.mPackages.get(packageName); 11237 if (ps == null) { 11238 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 11239 return false; 11240 } 11241 if (!ps.getInstalled(userId)) { 11242 // Can't block uninstall for an app that is not installed or enabled. 11243 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 11244 return false; 11245 } 11246 ps.setBlockUninstall(blockUninstall, userId); 11247 mSettings.writePackageRestrictionsLPr(userId); 11248 } 11249 return true; 11250 } 11251 11252 @Override 11253 public boolean getBlockUninstallForUser(String packageName, int userId) { 11254 synchronized (mPackages) { 11255 PackageSetting ps = mSettings.mPackages.get(packageName); 11256 if (ps == null) { 11257 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 11258 return false; 11259 } 11260 return ps.getBlockUninstall(userId); 11261 } 11262 } 11263 11264 /* 11265 * This method handles package deletion in general 11266 */ 11267 private boolean deletePackageLI(String packageName, UserHandle user, 11268 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 11269 int flags, PackageRemovedInfo outInfo, 11270 boolean writeSettings) { 11271 if (packageName == null) { 11272 Slog.w(TAG, "Attempt to delete null packageName."); 11273 return false; 11274 } 11275 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 11276 PackageSetting ps; 11277 boolean dataOnly = false; 11278 int removeUser = -1; 11279 int appId = -1; 11280 synchronized (mPackages) { 11281 ps = mSettings.mPackages.get(packageName); 11282 if (ps == null) { 11283 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11284 return false; 11285 } 11286 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 11287 && user.getIdentifier() != UserHandle.USER_ALL) { 11288 // The caller is asking that the package only be deleted for a single 11289 // user. To do this, we just mark its uninstalled state and delete 11290 // its data. If this is a system app, we only allow this to happen if 11291 // they have set the special DELETE_SYSTEM_APP which requests different 11292 // semantics than normal for uninstalling system apps. 11293 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 11294 ps.setUserState(user.getIdentifier(), 11295 COMPONENT_ENABLED_STATE_DEFAULT, 11296 false, //installed 11297 true, //stopped 11298 true, //notLaunched 11299 false, //hidden 11300 null, null, null, 11301 false // blockUninstall 11302 ); 11303 if (!isSystemApp(ps)) { 11304 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 11305 // Other user still have this package installed, so all 11306 // we need to do is clear this user's data and save that 11307 // it is uninstalled. 11308 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 11309 removeUser = user.getIdentifier(); 11310 appId = ps.appId; 11311 mSettings.writePackageRestrictionsLPr(removeUser); 11312 } else { 11313 // We need to set it back to 'installed' so the uninstall 11314 // broadcasts will be sent correctly. 11315 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 11316 ps.setInstalled(true, user.getIdentifier()); 11317 } 11318 } else { 11319 // This is a system app, so we assume that the 11320 // other users still have this package installed, so all 11321 // we need to do is clear this user's data and save that 11322 // it is uninstalled. 11323 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 11324 removeUser = user.getIdentifier(); 11325 appId = ps.appId; 11326 mSettings.writePackageRestrictionsLPr(removeUser); 11327 } 11328 } 11329 } 11330 11331 if (removeUser >= 0) { 11332 // From above, we determined that we are deleting this only 11333 // for a single user. Continue the work here. 11334 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 11335 if (outInfo != null) { 11336 outInfo.removedPackage = packageName; 11337 outInfo.removedAppId = appId; 11338 outInfo.removedUsers = new int[] {removeUser}; 11339 } 11340 mInstaller.clearUserData(packageName, removeUser); 11341 removeKeystoreDataIfNeeded(removeUser, appId); 11342 schedulePackageCleaning(packageName, removeUser, false); 11343 return true; 11344 } 11345 11346 if (dataOnly) { 11347 // Delete application data first 11348 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 11349 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 11350 return true; 11351 } 11352 11353 boolean ret = false; 11354 if (isSystemApp(ps)) { 11355 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 11356 // When an updated system application is deleted we delete the existing resources as well and 11357 // fall back to existing code in system partition 11358 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 11359 flags, outInfo, writeSettings); 11360 } else { 11361 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 11362 // Kill application pre-emptively especially for apps on sd. 11363 killApplication(packageName, ps.appId, "uninstall pkg"); 11364 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 11365 allUserHandles, perUserInstalled, 11366 outInfo, writeSettings); 11367 } 11368 11369 return ret; 11370 } 11371 11372 private final class ClearStorageConnection implements ServiceConnection { 11373 IMediaContainerService mContainerService; 11374 11375 @Override 11376 public void onServiceConnected(ComponentName name, IBinder service) { 11377 synchronized (this) { 11378 mContainerService = IMediaContainerService.Stub.asInterface(service); 11379 notifyAll(); 11380 } 11381 } 11382 11383 @Override 11384 public void onServiceDisconnected(ComponentName name) { 11385 } 11386 } 11387 11388 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 11389 final boolean mounted; 11390 if (Environment.isExternalStorageEmulated()) { 11391 mounted = true; 11392 } else { 11393 final String status = Environment.getExternalStorageState(); 11394 11395 mounted = status.equals(Environment.MEDIA_MOUNTED) 11396 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 11397 } 11398 11399 if (!mounted) { 11400 return; 11401 } 11402 11403 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 11404 int[] users; 11405 if (userId == UserHandle.USER_ALL) { 11406 users = sUserManager.getUserIds(); 11407 } else { 11408 users = new int[] { userId }; 11409 } 11410 final ClearStorageConnection conn = new ClearStorageConnection(); 11411 if (mContext.bindServiceAsUser( 11412 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 11413 try { 11414 for (int curUser : users) { 11415 long timeout = SystemClock.uptimeMillis() + 5000; 11416 synchronized (conn) { 11417 long now = SystemClock.uptimeMillis(); 11418 while (conn.mContainerService == null && now < timeout) { 11419 try { 11420 conn.wait(timeout - now); 11421 } catch (InterruptedException e) { 11422 } 11423 } 11424 } 11425 if (conn.mContainerService == null) { 11426 return; 11427 } 11428 11429 final UserEnvironment userEnv = new UserEnvironment(curUser); 11430 clearDirectory(conn.mContainerService, 11431 userEnv.buildExternalStorageAppCacheDirs(packageName)); 11432 if (allData) { 11433 clearDirectory(conn.mContainerService, 11434 userEnv.buildExternalStorageAppDataDirs(packageName)); 11435 clearDirectory(conn.mContainerService, 11436 userEnv.buildExternalStorageAppMediaDirs(packageName)); 11437 } 11438 } 11439 } finally { 11440 mContext.unbindService(conn); 11441 } 11442 } 11443 } 11444 11445 @Override 11446 public void clearApplicationUserData(final String packageName, 11447 final IPackageDataObserver observer, final int userId) { 11448 mContext.enforceCallingOrSelfPermission( 11449 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 11450 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 11451 // Queue up an async operation since the package deletion may take a little while. 11452 mHandler.post(new Runnable() { 11453 public void run() { 11454 mHandler.removeCallbacks(this); 11455 final boolean succeeded; 11456 synchronized (mInstallLock) { 11457 succeeded = clearApplicationUserDataLI(packageName, userId); 11458 } 11459 clearExternalStorageDataSync(packageName, userId, true); 11460 if (succeeded) { 11461 // invoke DeviceStorageMonitor's update method to clear any notifications 11462 DeviceStorageMonitorInternal 11463 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 11464 if (dsm != null) { 11465 dsm.checkMemory(); 11466 } 11467 } 11468 if(observer != null) { 11469 try { 11470 observer.onRemoveCompleted(packageName, succeeded); 11471 } catch (RemoteException e) { 11472 Log.i(TAG, "Observer no longer exists."); 11473 } 11474 } //end if observer 11475 } //end run 11476 }); 11477 } 11478 11479 private boolean clearApplicationUserDataLI(String packageName, int userId) { 11480 if (packageName == null) { 11481 Slog.w(TAG, "Attempt to delete null packageName."); 11482 return false; 11483 } 11484 11485 // Try finding details about the requested package 11486 PackageParser.Package pkg; 11487 synchronized (mPackages) { 11488 pkg = mPackages.get(packageName); 11489 if (pkg == null) { 11490 final PackageSetting ps = mSettings.mPackages.get(packageName); 11491 if (ps != null) { 11492 pkg = ps.pkg; 11493 } 11494 } 11495 } 11496 11497 if (pkg == null) { 11498 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11499 } 11500 11501 // Always delete data directories for package, even if we found no other 11502 // record of app. This helps users recover from UID mismatches without 11503 // resorting to a full data wipe. 11504 int retCode = mInstaller.clearUserData(packageName, userId); 11505 if (retCode < 0) { 11506 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 11507 return false; 11508 } 11509 11510 if (pkg == null) { 11511 return false; 11512 } 11513 11514 if (pkg != null && pkg.applicationInfo != null) { 11515 final int appId = pkg.applicationInfo.uid; 11516 removeKeystoreDataIfNeeded(userId, appId); 11517 } 11518 11519 // Create a native library symlink only if we have native libraries 11520 // and if the native libraries are 32 bit libraries. We do not provide 11521 // this symlink for 64 bit libraries. 11522 if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null && 11523 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 11524 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 11525 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 11526 Slog.w(TAG, "Failed linking native library dir"); 11527 return false; 11528 } 11529 } 11530 11531 return true; 11532 } 11533 11534 /** 11535 * Remove entries from the keystore daemon. Will only remove it if the 11536 * {@code appId} is valid. 11537 */ 11538 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 11539 if (appId < 0) { 11540 return; 11541 } 11542 11543 final KeyStore keyStore = KeyStore.getInstance(); 11544 if (keyStore != null) { 11545 if (userId == UserHandle.USER_ALL) { 11546 for (final int individual : sUserManager.getUserIds()) { 11547 keyStore.clearUid(UserHandle.getUid(individual, appId)); 11548 } 11549 } else { 11550 keyStore.clearUid(UserHandle.getUid(userId, appId)); 11551 } 11552 } else { 11553 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 11554 } 11555 } 11556 11557 @Override 11558 public void deleteApplicationCacheFiles(final String packageName, 11559 final IPackageDataObserver observer) { 11560 mContext.enforceCallingOrSelfPermission( 11561 android.Manifest.permission.DELETE_CACHE_FILES, null); 11562 // Queue up an async operation since the package deletion may take a little while. 11563 final int userId = UserHandle.getCallingUserId(); 11564 mHandler.post(new Runnable() { 11565 public void run() { 11566 mHandler.removeCallbacks(this); 11567 final boolean succeded; 11568 synchronized (mInstallLock) { 11569 succeded = deleteApplicationCacheFilesLI(packageName, userId); 11570 } 11571 clearExternalStorageDataSync(packageName, userId, false); 11572 if(observer != null) { 11573 try { 11574 observer.onRemoveCompleted(packageName, succeded); 11575 } catch (RemoteException e) { 11576 Log.i(TAG, "Observer no longer exists."); 11577 } 11578 } //end if observer 11579 } //end run 11580 }); 11581 } 11582 11583 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 11584 if (packageName == null) { 11585 Slog.w(TAG, "Attempt to delete null packageName."); 11586 return false; 11587 } 11588 PackageParser.Package p; 11589 synchronized (mPackages) { 11590 p = mPackages.get(packageName); 11591 } 11592 if (p == null) { 11593 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11594 return false; 11595 } 11596 final ApplicationInfo applicationInfo = p.applicationInfo; 11597 if (applicationInfo == null) { 11598 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11599 return false; 11600 } 11601 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 11602 if (retCode < 0) { 11603 Slog.w(TAG, "Couldn't remove cache files for package: " 11604 + packageName + " u" + userId); 11605 return false; 11606 } 11607 return true; 11608 } 11609 11610 @Override 11611 public void getPackageSizeInfo(final String packageName, int userHandle, 11612 final IPackageStatsObserver observer) { 11613 mContext.enforceCallingOrSelfPermission( 11614 android.Manifest.permission.GET_PACKAGE_SIZE, null); 11615 if (packageName == null) { 11616 throw new IllegalArgumentException("Attempt to get size of null packageName"); 11617 } 11618 11619 PackageStats stats = new PackageStats(packageName, userHandle); 11620 11621 /* 11622 * Queue up an async operation since the package measurement may take a 11623 * little while. 11624 */ 11625 Message msg = mHandler.obtainMessage(INIT_COPY); 11626 msg.obj = new MeasureParams(stats, observer); 11627 mHandler.sendMessage(msg); 11628 } 11629 11630 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 11631 PackageStats pStats) { 11632 if (packageName == null) { 11633 Slog.w(TAG, "Attempt to get size of null packageName."); 11634 return false; 11635 } 11636 PackageParser.Package p; 11637 boolean dataOnly = false; 11638 String libDirRoot = null; 11639 String asecPath = null; 11640 PackageSetting ps = null; 11641 synchronized (mPackages) { 11642 p = mPackages.get(packageName); 11643 ps = mSettings.mPackages.get(packageName); 11644 if(p == null) { 11645 dataOnly = true; 11646 if((ps == null) || (ps.pkg == null)) { 11647 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11648 return false; 11649 } 11650 p = ps.pkg; 11651 } 11652 if (ps != null) { 11653 libDirRoot = ps.legacyNativeLibraryPathString; 11654 } 11655 if (p != null && (isExternal(p) || isForwardLocked(p))) { 11656 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 11657 if (secureContainerId != null) { 11658 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 11659 } 11660 } 11661 } 11662 String publicSrcDir = null; 11663 if(!dataOnly) { 11664 final ApplicationInfo applicationInfo = p.applicationInfo; 11665 if (applicationInfo == null) { 11666 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11667 return false; 11668 } 11669 if (isForwardLocked(p)) { 11670 publicSrcDir = applicationInfo.getBaseResourcePath(); 11671 } 11672 } 11673 // TODO: extend to measure size of split APKs 11674 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 11675 // not just the first level. 11676 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 11677 // just the primary. 11678 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 11679 int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot, 11680 publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 11681 if (res < 0) { 11682 return false; 11683 } 11684 11685 // Fix-up for forward-locked applications in ASEC containers. 11686 if (!isExternal(p)) { 11687 pStats.codeSize += pStats.externalCodeSize; 11688 pStats.externalCodeSize = 0L; 11689 } 11690 11691 return true; 11692 } 11693 11694 11695 @Override 11696 public void addPackageToPreferred(String packageName) { 11697 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 11698 } 11699 11700 @Override 11701 public void removePackageFromPreferred(String packageName) { 11702 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 11703 } 11704 11705 @Override 11706 public List<PackageInfo> getPreferredPackages(int flags) { 11707 return new ArrayList<PackageInfo>(); 11708 } 11709 11710 private int getUidTargetSdkVersionLockedLPr(int uid) { 11711 Object obj = mSettings.getUserIdLPr(uid); 11712 if (obj instanceof SharedUserSetting) { 11713 final SharedUserSetting sus = (SharedUserSetting) obj; 11714 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 11715 final Iterator<PackageSetting> it = sus.packages.iterator(); 11716 while (it.hasNext()) { 11717 final PackageSetting ps = it.next(); 11718 if (ps.pkg != null) { 11719 int v = ps.pkg.applicationInfo.targetSdkVersion; 11720 if (v < vers) vers = v; 11721 } 11722 } 11723 return vers; 11724 } else if (obj instanceof PackageSetting) { 11725 final PackageSetting ps = (PackageSetting) obj; 11726 if (ps.pkg != null) { 11727 return ps.pkg.applicationInfo.targetSdkVersion; 11728 } 11729 } 11730 return Build.VERSION_CODES.CUR_DEVELOPMENT; 11731 } 11732 11733 @Override 11734 public void addPreferredActivity(IntentFilter filter, int match, 11735 ComponentName[] set, ComponentName activity, int userId) { 11736 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11737 "Adding preferred"); 11738 } 11739 11740 private void addPreferredActivityInternal(IntentFilter filter, int match, 11741 ComponentName[] set, ComponentName activity, boolean always, int userId, 11742 String opname) { 11743 // writer 11744 int callingUid = Binder.getCallingUid(); 11745 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 11746 if (filter.countActions() == 0) { 11747 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11748 return; 11749 } 11750 synchronized (mPackages) { 11751 if (mContext.checkCallingOrSelfPermission( 11752 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11753 != PackageManager.PERMISSION_GRANTED) { 11754 if (getUidTargetSdkVersionLockedLPr(callingUid) 11755 < Build.VERSION_CODES.FROYO) { 11756 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 11757 + callingUid); 11758 return; 11759 } 11760 mContext.enforceCallingOrSelfPermission( 11761 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11762 } 11763 11764 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 11765 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 11766 + userId + ":"); 11767 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11768 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 11769 scheduleWritePackageRestrictionsLocked(userId); 11770 } 11771 } 11772 11773 @Override 11774 public void replacePreferredActivity(IntentFilter filter, int match, 11775 ComponentName[] set, ComponentName activity, int userId) { 11776 if (filter.countActions() != 1) { 11777 throw new IllegalArgumentException( 11778 "replacePreferredActivity expects filter to have only 1 action."); 11779 } 11780 if (filter.countDataAuthorities() != 0 11781 || filter.countDataPaths() != 0 11782 || filter.countDataSchemes() > 1 11783 || filter.countDataTypes() != 0) { 11784 throw new IllegalArgumentException( 11785 "replacePreferredActivity expects filter to have no data authorities, " + 11786 "paths, or types; and at most one scheme."); 11787 } 11788 11789 final int callingUid = Binder.getCallingUid(); 11790 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 11791 synchronized (mPackages) { 11792 if (mContext.checkCallingOrSelfPermission( 11793 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11794 != PackageManager.PERMISSION_GRANTED) { 11795 if (getUidTargetSdkVersionLockedLPr(callingUid) 11796 < Build.VERSION_CODES.FROYO) { 11797 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 11798 + Binder.getCallingUid()); 11799 return; 11800 } 11801 mContext.enforceCallingOrSelfPermission( 11802 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11803 } 11804 11805 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11806 if (pir != null) { 11807 // Get all of the existing entries that exactly match this filter. 11808 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 11809 if (existing != null && existing.size() == 1) { 11810 PreferredActivity cur = existing.get(0); 11811 if (DEBUG_PREFERRED) { 11812 Slog.i(TAG, "Checking replace of preferred:"); 11813 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11814 if (!cur.mPref.mAlways) { 11815 Slog.i(TAG, " -- CUR; not mAlways!"); 11816 } else { 11817 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 11818 Slog.i(TAG, " -- CUR: mSet=" 11819 + Arrays.toString(cur.mPref.mSetComponents)); 11820 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 11821 Slog.i(TAG, " -- NEW: mMatch=" 11822 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 11823 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 11824 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 11825 } 11826 } 11827 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 11828 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 11829 && cur.mPref.sameSet(set)) { 11830 // Setting the preferred activity to what it happens to be already 11831 if (DEBUG_PREFERRED) { 11832 Slog.i(TAG, "Replacing with same preferred activity " 11833 + cur.mPref.mShortComponent + " for user " 11834 + userId + ":"); 11835 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11836 } 11837 return; 11838 } 11839 } 11840 11841 if (existing != null) { 11842 if (DEBUG_PREFERRED) { 11843 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 11844 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11845 } 11846 for (int i = 0; i < existing.size(); i++) { 11847 PreferredActivity pa = existing.get(i); 11848 if (DEBUG_PREFERRED) { 11849 Slog.i(TAG, "Removing existing preferred activity " 11850 + pa.mPref.mComponent + ":"); 11851 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 11852 } 11853 pir.removeFilter(pa); 11854 } 11855 } 11856 } 11857 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11858 "Replacing preferred"); 11859 } 11860 } 11861 11862 @Override 11863 public void clearPackagePreferredActivities(String packageName) { 11864 final int uid = Binder.getCallingUid(); 11865 // writer 11866 synchronized (mPackages) { 11867 PackageParser.Package pkg = mPackages.get(packageName); 11868 if (pkg == null || pkg.applicationInfo.uid != uid) { 11869 if (mContext.checkCallingOrSelfPermission( 11870 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11871 != PackageManager.PERMISSION_GRANTED) { 11872 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11873 < Build.VERSION_CODES.FROYO) { 11874 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 11875 + Binder.getCallingUid()); 11876 return; 11877 } 11878 mContext.enforceCallingOrSelfPermission( 11879 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11880 } 11881 } 11882 11883 int user = UserHandle.getCallingUserId(); 11884 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 11885 scheduleWritePackageRestrictionsLocked(user); 11886 } 11887 } 11888 } 11889 11890 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 11891 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 11892 ArrayList<PreferredActivity> removed = null; 11893 boolean changed = false; 11894 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11895 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 11896 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11897 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 11898 continue; 11899 } 11900 Iterator<PreferredActivity> it = pir.filterIterator(); 11901 while (it.hasNext()) { 11902 PreferredActivity pa = it.next(); 11903 // Mark entry for removal only if it matches the package name 11904 // and the entry is of type "always". 11905 if (packageName == null || 11906 (pa.mPref.mComponent.getPackageName().equals(packageName) 11907 && pa.mPref.mAlways)) { 11908 if (removed == null) { 11909 removed = new ArrayList<PreferredActivity>(); 11910 } 11911 removed.add(pa); 11912 } 11913 } 11914 if (removed != null) { 11915 for (int j=0; j<removed.size(); j++) { 11916 PreferredActivity pa = removed.get(j); 11917 pir.removeFilter(pa); 11918 } 11919 changed = true; 11920 } 11921 } 11922 return changed; 11923 } 11924 11925 @Override 11926 public void resetPreferredActivities(int userId) { 11927 /* TODO: Actually use userId. Why is it being passed in? */ 11928 mContext.enforceCallingOrSelfPermission( 11929 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11930 // writer 11931 synchronized (mPackages) { 11932 int user = UserHandle.getCallingUserId(); 11933 clearPackagePreferredActivitiesLPw(null, user); 11934 mSettings.readDefaultPreferredAppsLPw(this, user); 11935 scheduleWritePackageRestrictionsLocked(user); 11936 } 11937 } 11938 11939 @Override 11940 public int getPreferredActivities(List<IntentFilter> outFilters, 11941 List<ComponentName> outActivities, String packageName) { 11942 11943 int num = 0; 11944 final int userId = UserHandle.getCallingUserId(); 11945 // reader 11946 synchronized (mPackages) { 11947 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11948 if (pir != null) { 11949 final Iterator<PreferredActivity> it = pir.filterIterator(); 11950 while (it.hasNext()) { 11951 final PreferredActivity pa = it.next(); 11952 if (packageName == null 11953 || (pa.mPref.mComponent.getPackageName().equals(packageName) 11954 && pa.mPref.mAlways)) { 11955 if (outFilters != null) { 11956 outFilters.add(new IntentFilter(pa)); 11957 } 11958 if (outActivities != null) { 11959 outActivities.add(pa.mPref.mComponent); 11960 } 11961 } 11962 } 11963 } 11964 } 11965 11966 return num; 11967 } 11968 11969 @Override 11970 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 11971 int userId) { 11972 int callingUid = Binder.getCallingUid(); 11973 if (callingUid != Process.SYSTEM_UID) { 11974 throw new SecurityException( 11975 "addPersistentPreferredActivity can only be run by the system"); 11976 } 11977 if (filter.countActions() == 0) { 11978 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11979 return; 11980 } 11981 synchronized (mPackages) { 11982 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 11983 " :"); 11984 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11985 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 11986 new PersistentPreferredActivity(filter, activity)); 11987 scheduleWritePackageRestrictionsLocked(userId); 11988 } 11989 } 11990 11991 @Override 11992 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 11993 int callingUid = Binder.getCallingUid(); 11994 if (callingUid != Process.SYSTEM_UID) { 11995 throw new SecurityException( 11996 "clearPackagePersistentPreferredActivities can only be run by the system"); 11997 } 11998 ArrayList<PersistentPreferredActivity> removed = null; 11999 boolean changed = false; 12000 synchronized (mPackages) { 12001 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 12002 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 12003 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 12004 .valueAt(i); 12005 if (userId != thisUserId) { 12006 continue; 12007 } 12008 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 12009 while (it.hasNext()) { 12010 PersistentPreferredActivity ppa = it.next(); 12011 // Mark entry for removal only if it matches the package name. 12012 if (ppa.mComponent.getPackageName().equals(packageName)) { 12013 if (removed == null) { 12014 removed = new ArrayList<PersistentPreferredActivity>(); 12015 } 12016 removed.add(ppa); 12017 } 12018 } 12019 if (removed != null) { 12020 for (int j=0; j<removed.size(); j++) { 12021 PersistentPreferredActivity ppa = removed.get(j); 12022 ppir.removeFilter(ppa); 12023 } 12024 changed = true; 12025 } 12026 } 12027 12028 if (changed) { 12029 scheduleWritePackageRestrictionsLocked(userId); 12030 } 12031 } 12032 } 12033 12034 @Override 12035 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 12036 int ownerUserId, int sourceUserId, int targetUserId, int flags) { 12037 mContext.enforceCallingOrSelfPermission( 12038 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 12039 int callingUid = Binder.getCallingUid(); 12040 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 12041 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 12042 if (intentFilter.countActions() == 0) { 12043 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 12044 return; 12045 } 12046 synchronized (mPackages) { 12047 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 12048 ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags); 12049 CrossProfileIntentResolver resolver = 12050 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 12051 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 12052 // We have all those whose filter is equal. Now checking if the rest is equal as well. 12053 if (existing != null) { 12054 int size = existing.size(); 12055 for (int i = 0; i < size; i++) { 12056 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 12057 return; 12058 } 12059 } 12060 } 12061 resolver.addFilter(newFilter); 12062 scheduleWritePackageRestrictionsLocked(sourceUserId); 12063 } 12064 } 12065 12066 @Override 12067 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage, 12068 int ownerUserId) { 12069 mContext.enforceCallingOrSelfPermission( 12070 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 12071 int callingUid = Binder.getCallingUid(); 12072 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 12073 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 12074 int callingUserId = UserHandle.getUserId(callingUid); 12075 synchronized (mPackages) { 12076 CrossProfileIntentResolver resolver = 12077 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 12078 ArraySet<CrossProfileIntentFilter> set = 12079 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 12080 for (CrossProfileIntentFilter filter : set) { 12081 if (filter.getOwnerPackage().equals(ownerPackage) 12082 && filter.getOwnerUserId() == callingUserId) { 12083 resolver.removeFilter(filter); 12084 } 12085 } 12086 scheduleWritePackageRestrictionsLocked(sourceUserId); 12087 } 12088 } 12089 12090 // Enforcing that callingUid is owning pkg on userId 12091 private void enforceOwnerRights(String pkg, int userId, int callingUid) { 12092 // The system owns everything. 12093 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 12094 return; 12095 } 12096 int callingUserId = UserHandle.getUserId(callingUid); 12097 if (callingUserId != userId) { 12098 throw new SecurityException("calling uid " + callingUid 12099 + " pretends to own " + pkg + " on user " + userId + " but belongs to user " 12100 + callingUserId); 12101 } 12102 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 12103 if (pi == null) { 12104 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 12105 + callingUserId); 12106 } 12107 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 12108 throw new SecurityException("Calling uid " + callingUid 12109 + " does not own package " + pkg); 12110 } 12111 } 12112 12113 @Override 12114 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 12115 Intent intent = new Intent(Intent.ACTION_MAIN); 12116 intent.addCategory(Intent.CATEGORY_HOME); 12117 12118 final int callingUserId = UserHandle.getCallingUserId(); 12119 List<ResolveInfo> list = queryIntentActivities(intent, null, 12120 PackageManager.GET_META_DATA, callingUserId); 12121 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 12122 true, false, false, callingUserId); 12123 12124 allHomeCandidates.clear(); 12125 if (list != null) { 12126 for (ResolveInfo ri : list) { 12127 allHomeCandidates.add(ri); 12128 } 12129 } 12130 return (preferred == null || preferred.activityInfo == null) 12131 ? null 12132 : new ComponentName(preferred.activityInfo.packageName, 12133 preferred.activityInfo.name); 12134 } 12135 12136 @Override 12137 public void setApplicationEnabledSetting(String appPackageName, 12138 int newState, int flags, int userId, String callingPackage) { 12139 if (!sUserManager.exists(userId)) return; 12140 if (callingPackage == null) { 12141 callingPackage = Integer.toString(Binder.getCallingUid()); 12142 } 12143 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 12144 } 12145 12146 @Override 12147 public void setComponentEnabledSetting(ComponentName componentName, 12148 int newState, int flags, int userId) { 12149 if (!sUserManager.exists(userId)) return; 12150 setEnabledSetting(componentName.getPackageName(), 12151 componentName.getClassName(), newState, flags, userId, null); 12152 } 12153 12154 private void setEnabledSetting(final String packageName, String className, int newState, 12155 final int flags, int userId, String callingPackage) { 12156 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 12157 || newState == COMPONENT_ENABLED_STATE_ENABLED 12158 || newState == COMPONENT_ENABLED_STATE_DISABLED 12159 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 12160 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 12161 throw new IllegalArgumentException("Invalid new component state: " 12162 + newState); 12163 } 12164 PackageSetting pkgSetting; 12165 final int uid = Binder.getCallingUid(); 12166 final int permission = mContext.checkCallingOrSelfPermission( 12167 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 12168 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 12169 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 12170 boolean sendNow = false; 12171 boolean isApp = (className == null); 12172 String componentName = isApp ? packageName : className; 12173 int packageUid = -1; 12174 ArrayList<String> components; 12175 12176 // writer 12177 synchronized (mPackages) { 12178 pkgSetting = mSettings.mPackages.get(packageName); 12179 if (pkgSetting == null) { 12180 if (className == null) { 12181 throw new IllegalArgumentException( 12182 "Unknown package: " + packageName); 12183 } 12184 throw new IllegalArgumentException( 12185 "Unknown component: " + packageName 12186 + "/" + className); 12187 } 12188 // Allow root and verify that userId is not being specified by a different user 12189 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 12190 throw new SecurityException( 12191 "Permission Denial: attempt to change component state from pid=" 12192 + Binder.getCallingPid() 12193 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 12194 } 12195 if (className == null) { 12196 // We're dealing with an application/package level state change 12197 if (pkgSetting.getEnabled(userId) == newState) { 12198 // Nothing to do 12199 return; 12200 } 12201 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 12202 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 12203 // Don't care about who enables an app. 12204 callingPackage = null; 12205 } 12206 pkgSetting.setEnabled(newState, userId, callingPackage); 12207 // pkgSetting.pkg.mSetEnabled = newState; 12208 } else { 12209 // We're dealing with a component level state change 12210 // First, verify that this is a valid class name. 12211 PackageParser.Package pkg = pkgSetting.pkg; 12212 if (pkg == null || !pkg.hasComponentClassName(className)) { 12213 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 12214 throw new IllegalArgumentException("Component class " + className 12215 + " does not exist in " + packageName); 12216 } else { 12217 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 12218 + className + " does not exist in " + packageName); 12219 } 12220 } 12221 switch (newState) { 12222 case COMPONENT_ENABLED_STATE_ENABLED: 12223 if (!pkgSetting.enableComponentLPw(className, userId)) { 12224 return; 12225 } 12226 break; 12227 case COMPONENT_ENABLED_STATE_DISABLED: 12228 if (!pkgSetting.disableComponentLPw(className, userId)) { 12229 return; 12230 } 12231 break; 12232 case COMPONENT_ENABLED_STATE_DEFAULT: 12233 if (!pkgSetting.restoreComponentLPw(className, userId)) { 12234 return; 12235 } 12236 break; 12237 default: 12238 Slog.e(TAG, "Invalid new component state: " + newState); 12239 return; 12240 } 12241 } 12242 scheduleWritePackageRestrictionsLocked(userId); 12243 components = mPendingBroadcasts.get(userId, packageName); 12244 final boolean newPackage = components == null; 12245 if (newPackage) { 12246 components = new ArrayList<String>(); 12247 } 12248 if (!components.contains(componentName)) { 12249 components.add(componentName); 12250 } 12251 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 12252 sendNow = true; 12253 // Purge entry from pending broadcast list if another one exists already 12254 // since we are sending one right away. 12255 mPendingBroadcasts.remove(userId, packageName); 12256 } else { 12257 if (newPackage) { 12258 mPendingBroadcasts.put(userId, packageName, components); 12259 } 12260 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 12261 // Schedule a message 12262 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 12263 } 12264 } 12265 } 12266 12267 long callingId = Binder.clearCallingIdentity(); 12268 try { 12269 if (sendNow) { 12270 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 12271 sendPackageChangedBroadcast(packageName, 12272 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 12273 } 12274 } finally { 12275 Binder.restoreCallingIdentity(callingId); 12276 } 12277 } 12278 12279 private void sendPackageChangedBroadcast(String packageName, 12280 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 12281 if (DEBUG_INSTALL) 12282 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 12283 + componentNames); 12284 Bundle extras = new Bundle(4); 12285 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 12286 String nameList[] = new String[componentNames.size()]; 12287 componentNames.toArray(nameList); 12288 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 12289 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 12290 extras.putInt(Intent.EXTRA_UID, packageUid); 12291 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 12292 new int[] {UserHandle.getUserId(packageUid)}); 12293 } 12294 12295 @Override 12296 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 12297 if (!sUserManager.exists(userId)) return; 12298 final int uid = Binder.getCallingUid(); 12299 final int permission = mContext.checkCallingOrSelfPermission( 12300 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 12301 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 12302 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 12303 // writer 12304 synchronized (mPackages) { 12305 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 12306 uid, userId)) { 12307 scheduleWritePackageRestrictionsLocked(userId); 12308 } 12309 } 12310 } 12311 12312 @Override 12313 public String getInstallerPackageName(String packageName) { 12314 // reader 12315 synchronized (mPackages) { 12316 return mSettings.getInstallerPackageNameLPr(packageName); 12317 } 12318 } 12319 12320 @Override 12321 public int getApplicationEnabledSetting(String packageName, int userId) { 12322 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12323 int uid = Binder.getCallingUid(); 12324 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 12325 // reader 12326 synchronized (mPackages) { 12327 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 12328 } 12329 } 12330 12331 @Override 12332 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 12333 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12334 int uid = Binder.getCallingUid(); 12335 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 12336 // reader 12337 synchronized (mPackages) { 12338 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 12339 } 12340 } 12341 12342 @Override 12343 public void enterSafeMode() { 12344 enforceSystemOrRoot("Only the system can request entering safe mode"); 12345 12346 if (!mSystemReady) { 12347 mSafeMode = true; 12348 } 12349 } 12350 12351 @Override 12352 public void systemReady() { 12353 mSystemReady = true; 12354 12355 // Read the compatibilty setting when the system is ready. 12356 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 12357 mContext.getContentResolver(), 12358 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 12359 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 12360 if (DEBUG_SETTINGS) { 12361 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 12362 } 12363 12364 synchronized (mPackages) { 12365 // Verify that all of the preferred activity components actually 12366 // exist. It is possible for applications to be updated and at 12367 // that point remove a previously declared activity component that 12368 // had been set as a preferred activity. We try to clean this up 12369 // the next time we encounter that preferred activity, but it is 12370 // possible for the user flow to never be able to return to that 12371 // situation so here we do a sanity check to make sure we haven't 12372 // left any junk around. 12373 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 12374 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12375 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12376 removed.clear(); 12377 for (PreferredActivity pa : pir.filterSet()) { 12378 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 12379 removed.add(pa); 12380 } 12381 } 12382 if (removed.size() > 0) { 12383 for (int r=0; r<removed.size(); r++) { 12384 PreferredActivity pa = removed.get(r); 12385 Slog.w(TAG, "Removing dangling preferred activity: " 12386 + pa.mPref.mComponent); 12387 pir.removeFilter(pa); 12388 } 12389 mSettings.writePackageRestrictionsLPr( 12390 mSettings.mPreferredActivities.keyAt(i)); 12391 } 12392 } 12393 } 12394 sUserManager.systemReady(); 12395 12396 // Kick off any messages waiting for system ready 12397 if (mPostSystemReadyMessages != null) { 12398 for (Message msg : mPostSystemReadyMessages) { 12399 msg.sendToTarget(); 12400 } 12401 mPostSystemReadyMessages = null; 12402 } 12403 } 12404 12405 @Override 12406 public boolean isSafeMode() { 12407 return mSafeMode; 12408 } 12409 12410 @Override 12411 public boolean hasSystemUidErrors() { 12412 return mHasSystemUidErrors; 12413 } 12414 12415 static String arrayToString(int[] array) { 12416 StringBuffer buf = new StringBuffer(128); 12417 buf.append('['); 12418 if (array != null) { 12419 for (int i=0; i<array.length; i++) { 12420 if (i > 0) buf.append(", "); 12421 buf.append(array[i]); 12422 } 12423 } 12424 buf.append(']'); 12425 return buf.toString(); 12426 } 12427 12428 static class DumpState { 12429 public static final int DUMP_LIBS = 1 << 0; 12430 public static final int DUMP_FEATURES = 1 << 1; 12431 public static final int DUMP_RESOLVERS = 1 << 2; 12432 public static final int DUMP_PERMISSIONS = 1 << 3; 12433 public static final int DUMP_PACKAGES = 1 << 4; 12434 public static final int DUMP_SHARED_USERS = 1 << 5; 12435 public static final int DUMP_MESSAGES = 1 << 6; 12436 public static final int DUMP_PROVIDERS = 1 << 7; 12437 public static final int DUMP_VERIFIERS = 1 << 8; 12438 public static final int DUMP_PREFERRED = 1 << 9; 12439 public static final int DUMP_PREFERRED_XML = 1 << 10; 12440 public static final int DUMP_KEYSETS = 1 << 11; 12441 public static final int DUMP_VERSION = 1 << 12; 12442 public static final int DUMP_INSTALLS = 1 << 13; 12443 12444 public static final int OPTION_SHOW_FILTERS = 1 << 0; 12445 12446 private int mTypes; 12447 12448 private int mOptions; 12449 12450 private boolean mTitlePrinted; 12451 12452 private SharedUserSetting mSharedUser; 12453 12454 public boolean isDumping(int type) { 12455 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 12456 return true; 12457 } 12458 12459 return (mTypes & type) != 0; 12460 } 12461 12462 public void setDump(int type) { 12463 mTypes |= type; 12464 } 12465 12466 public boolean isOptionEnabled(int option) { 12467 return (mOptions & option) != 0; 12468 } 12469 12470 public void setOptionEnabled(int option) { 12471 mOptions |= option; 12472 } 12473 12474 public boolean onTitlePrinted() { 12475 final boolean printed = mTitlePrinted; 12476 mTitlePrinted = true; 12477 return printed; 12478 } 12479 12480 public boolean getTitlePrinted() { 12481 return mTitlePrinted; 12482 } 12483 12484 public void setTitlePrinted(boolean enabled) { 12485 mTitlePrinted = enabled; 12486 } 12487 12488 public SharedUserSetting getSharedUser() { 12489 return mSharedUser; 12490 } 12491 12492 public void setSharedUser(SharedUserSetting user) { 12493 mSharedUser = user; 12494 } 12495 } 12496 12497 @Override 12498 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 12499 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 12500 != PackageManager.PERMISSION_GRANTED) { 12501 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 12502 + Binder.getCallingPid() 12503 + ", uid=" + Binder.getCallingUid() 12504 + " without permission " 12505 + android.Manifest.permission.DUMP); 12506 return; 12507 } 12508 12509 DumpState dumpState = new DumpState(); 12510 boolean fullPreferred = false; 12511 boolean checkin = false; 12512 12513 String packageName = null; 12514 12515 int opti = 0; 12516 while (opti < args.length) { 12517 String opt = args[opti]; 12518 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 12519 break; 12520 } 12521 opti++; 12522 12523 if ("-a".equals(opt)) { 12524 // Right now we only know how to print all. 12525 } else if ("-h".equals(opt)) { 12526 pw.println("Package manager dump options:"); 12527 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 12528 pw.println(" --checkin: dump for a checkin"); 12529 pw.println(" -f: print details of intent filters"); 12530 pw.println(" -h: print this help"); 12531 pw.println(" cmd may be one of:"); 12532 pw.println(" l[ibraries]: list known shared libraries"); 12533 pw.println(" f[ibraries]: list device features"); 12534 pw.println(" k[eysets]: print known keysets"); 12535 pw.println(" r[esolvers]: dump intent resolvers"); 12536 pw.println(" perm[issions]: dump permissions"); 12537 pw.println(" pref[erred]: print preferred package settings"); 12538 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 12539 pw.println(" prov[iders]: dump content providers"); 12540 pw.println(" p[ackages]: dump installed packages"); 12541 pw.println(" s[hared-users]: dump shared user IDs"); 12542 pw.println(" m[essages]: print collected runtime messages"); 12543 pw.println(" v[erifiers]: print package verifier info"); 12544 pw.println(" version: print database version info"); 12545 pw.println(" write: write current settings now"); 12546 pw.println(" <package.name>: info about given package"); 12547 pw.println(" installs: details about install sessions"); 12548 return; 12549 } else if ("--checkin".equals(opt)) { 12550 checkin = true; 12551 } else if ("-f".equals(opt)) { 12552 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12553 } else { 12554 pw.println("Unknown argument: " + opt + "; use -h for help"); 12555 } 12556 } 12557 12558 // Is the caller requesting to dump a particular piece of data? 12559 if (opti < args.length) { 12560 String cmd = args[opti]; 12561 opti++; 12562 // Is this a package name? 12563 if ("android".equals(cmd) || cmd.contains(".")) { 12564 packageName = cmd; 12565 // When dumping a single package, we always dump all of its 12566 // filter information since the amount of data will be reasonable. 12567 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12568 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 12569 dumpState.setDump(DumpState.DUMP_LIBS); 12570 } else if ("f".equals(cmd) || "features".equals(cmd)) { 12571 dumpState.setDump(DumpState.DUMP_FEATURES); 12572 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 12573 dumpState.setDump(DumpState.DUMP_RESOLVERS); 12574 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 12575 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 12576 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 12577 dumpState.setDump(DumpState.DUMP_PREFERRED); 12578 } else if ("preferred-xml".equals(cmd)) { 12579 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 12580 if (opti < args.length && "--full".equals(args[opti])) { 12581 fullPreferred = true; 12582 opti++; 12583 } 12584 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 12585 dumpState.setDump(DumpState.DUMP_PACKAGES); 12586 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 12587 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 12588 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 12589 dumpState.setDump(DumpState.DUMP_PROVIDERS); 12590 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 12591 dumpState.setDump(DumpState.DUMP_MESSAGES); 12592 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 12593 dumpState.setDump(DumpState.DUMP_VERIFIERS); 12594 } else if ("version".equals(cmd)) { 12595 dumpState.setDump(DumpState.DUMP_VERSION); 12596 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 12597 dumpState.setDump(DumpState.DUMP_KEYSETS); 12598 } else if ("installs".equals(cmd)) { 12599 dumpState.setDump(DumpState.DUMP_INSTALLS); 12600 } else if ("write".equals(cmd)) { 12601 synchronized (mPackages) { 12602 mSettings.writeLPr(); 12603 pw.println("Settings written."); 12604 return; 12605 } 12606 } 12607 } 12608 12609 if (checkin) { 12610 pw.println("vers,1"); 12611 } 12612 12613 // reader 12614 synchronized (mPackages) { 12615 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 12616 if (!checkin) { 12617 if (dumpState.onTitlePrinted()) 12618 pw.println(); 12619 pw.println("Database versions:"); 12620 pw.print(" SDK Version:"); 12621 pw.print(" internal="); 12622 pw.print(mSettings.mInternalSdkPlatform); 12623 pw.print(" external="); 12624 pw.println(mSettings.mExternalSdkPlatform); 12625 pw.print(" DB Version:"); 12626 pw.print(" internal="); 12627 pw.print(mSettings.mInternalDatabaseVersion); 12628 pw.print(" external="); 12629 pw.println(mSettings.mExternalDatabaseVersion); 12630 } 12631 } 12632 12633 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 12634 if (!checkin) { 12635 if (dumpState.onTitlePrinted()) 12636 pw.println(); 12637 pw.println("Verifiers:"); 12638 pw.print(" Required: "); 12639 pw.print(mRequiredVerifierPackage); 12640 pw.print(" (uid="); 12641 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 12642 pw.println(")"); 12643 } else if (mRequiredVerifierPackage != null) { 12644 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 12645 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 12646 } 12647 } 12648 12649 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 12650 boolean printedHeader = false; 12651 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 12652 while (it.hasNext()) { 12653 String name = it.next(); 12654 SharedLibraryEntry ent = mSharedLibraries.get(name); 12655 if (!checkin) { 12656 if (!printedHeader) { 12657 if (dumpState.onTitlePrinted()) 12658 pw.println(); 12659 pw.println("Libraries:"); 12660 printedHeader = true; 12661 } 12662 pw.print(" "); 12663 } else { 12664 pw.print("lib,"); 12665 } 12666 pw.print(name); 12667 if (!checkin) { 12668 pw.print(" -> "); 12669 } 12670 if (ent.path != null) { 12671 if (!checkin) { 12672 pw.print("(jar) "); 12673 pw.print(ent.path); 12674 } else { 12675 pw.print(",jar,"); 12676 pw.print(ent.path); 12677 } 12678 } else { 12679 if (!checkin) { 12680 pw.print("(apk) "); 12681 pw.print(ent.apk); 12682 } else { 12683 pw.print(",apk,"); 12684 pw.print(ent.apk); 12685 } 12686 } 12687 pw.println(); 12688 } 12689 } 12690 12691 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 12692 if (dumpState.onTitlePrinted()) 12693 pw.println(); 12694 if (!checkin) { 12695 pw.println("Features:"); 12696 } 12697 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 12698 while (it.hasNext()) { 12699 String name = it.next(); 12700 if (!checkin) { 12701 pw.print(" "); 12702 } else { 12703 pw.print("feat,"); 12704 } 12705 pw.println(name); 12706 } 12707 } 12708 12709 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 12710 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 12711 : "Activity Resolver Table:", " ", packageName, 12712 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 12713 dumpState.setTitlePrinted(true); 12714 } 12715 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 12716 : "Receiver Resolver Table:", " ", packageName, 12717 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 12718 dumpState.setTitlePrinted(true); 12719 } 12720 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 12721 : "Service Resolver Table:", " ", packageName, 12722 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 12723 dumpState.setTitlePrinted(true); 12724 } 12725 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 12726 : "Provider Resolver Table:", " ", packageName, 12727 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 12728 dumpState.setTitlePrinted(true); 12729 } 12730 } 12731 12732 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 12733 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12734 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12735 int user = mSettings.mPreferredActivities.keyAt(i); 12736 if (pir.dump(pw, 12737 dumpState.getTitlePrinted() 12738 ? "\nPreferred Activities User " + user + ":" 12739 : "Preferred Activities User " + user + ":", " ", 12740 packageName, true, false)) { 12741 dumpState.setTitlePrinted(true); 12742 } 12743 } 12744 } 12745 12746 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 12747 pw.flush(); 12748 FileOutputStream fout = new FileOutputStream(fd); 12749 BufferedOutputStream str = new BufferedOutputStream(fout); 12750 XmlSerializer serializer = new FastXmlSerializer(); 12751 try { 12752 serializer.setOutput(str, "utf-8"); 12753 serializer.startDocument(null, true); 12754 serializer.setFeature( 12755 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 12756 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 12757 serializer.endDocument(); 12758 serializer.flush(); 12759 } catch (IllegalArgumentException e) { 12760 pw.println("Failed writing: " + e); 12761 } catch (IllegalStateException e) { 12762 pw.println("Failed writing: " + e); 12763 } catch (IOException e) { 12764 pw.println("Failed writing: " + e); 12765 } 12766 } 12767 12768 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 12769 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 12770 if (packageName == null) { 12771 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 12772 if (iperm == 0) { 12773 if (dumpState.onTitlePrinted()) 12774 pw.println(); 12775 pw.println("AppOp Permissions:"); 12776 } 12777 pw.print(" AppOp Permission "); 12778 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 12779 pw.println(":"); 12780 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 12781 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 12782 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 12783 } 12784 } 12785 } 12786 } 12787 12788 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 12789 boolean printedSomething = false; 12790 for (PackageParser.Provider p : mProviders.mProviders.values()) { 12791 if (packageName != null && !packageName.equals(p.info.packageName)) { 12792 continue; 12793 } 12794 if (!printedSomething) { 12795 if (dumpState.onTitlePrinted()) 12796 pw.println(); 12797 pw.println("Registered ContentProviders:"); 12798 printedSomething = true; 12799 } 12800 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 12801 pw.print(" "); pw.println(p.toString()); 12802 } 12803 printedSomething = false; 12804 for (Map.Entry<String, PackageParser.Provider> entry : 12805 mProvidersByAuthority.entrySet()) { 12806 PackageParser.Provider p = entry.getValue(); 12807 if (packageName != null && !packageName.equals(p.info.packageName)) { 12808 continue; 12809 } 12810 if (!printedSomething) { 12811 if (dumpState.onTitlePrinted()) 12812 pw.println(); 12813 pw.println("ContentProvider Authorities:"); 12814 printedSomething = true; 12815 } 12816 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 12817 pw.print(" "); pw.println(p.toString()); 12818 if (p.info != null && p.info.applicationInfo != null) { 12819 final String appInfo = p.info.applicationInfo.toString(); 12820 pw.print(" applicationInfo="); pw.println(appInfo); 12821 } 12822 } 12823 } 12824 12825 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 12826 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 12827 } 12828 12829 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 12830 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 12831 } 12832 12833 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 12834 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin); 12835 } 12836 12837 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 12838 // XXX should handle packageName != null by dumping only install data that 12839 // the given package is involved with. 12840 if (dumpState.onTitlePrinted()) pw.println(); 12841 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 12842 } 12843 12844 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 12845 if (dumpState.onTitlePrinted()) pw.println(); 12846 mSettings.dumpReadMessagesLPr(pw, dumpState); 12847 12848 pw.println(); 12849 pw.println("Package warning messages:"); 12850 BufferedReader in = null; 12851 String line = null; 12852 try { 12853 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 12854 while ((line = in.readLine()) != null) { 12855 if (line.contains("ignored: updated version")) continue; 12856 pw.println(line); 12857 } 12858 } catch (IOException ignored) { 12859 } finally { 12860 IoUtils.closeQuietly(in); 12861 } 12862 } 12863 12864 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 12865 BufferedReader in = null; 12866 String line = null; 12867 try { 12868 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 12869 while ((line = in.readLine()) != null) { 12870 if (line.contains("ignored: updated version")) continue; 12871 pw.print("msg,"); 12872 pw.println(line); 12873 } 12874 } catch (IOException ignored) { 12875 } finally { 12876 IoUtils.closeQuietly(in); 12877 } 12878 } 12879 } 12880 } 12881 12882 // ------- apps on sdcard specific code ------- 12883 static final boolean DEBUG_SD_INSTALL = false; 12884 12885 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 12886 12887 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 12888 12889 private boolean mMediaMounted = false; 12890 12891 static String getEncryptKey() { 12892 try { 12893 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 12894 SD_ENCRYPTION_KEYSTORE_NAME); 12895 if (sdEncKey == null) { 12896 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 12897 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 12898 if (sdEncKey == null) { 12899 Slog.e(TAG, "Failed to create encryption keys"); 12900 return null; 12901 } 12902 } 12903 return sdEncKey; 12904 } catch (NoSuchAlgorithmException nsae) { 12905 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 12906 return null; 12907 } catch (IOException ioe) { 12908 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 12909 return null; 12910 } 12911 } 12912 12913 /* 12914 * Update media status on PackageManager. 12915 */ 12916 @Override 12917 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 12918 int callingUid = Binder.getCallingUid(); 12919 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 12920 throw new SecurityException("Media status can only be updated by the system"); 12921 } 12922 // reader; this apparently protects mMediaMounted, but should probably 12923 // be a different lock in that case. 12924 synchronized (mPackages) { 12925 Log.i(TAG, "Updating external media status from " 12926 + (mMediaMounted ? "mounted" : "unmounted") + " to " 12927 + (mediaStatus ? "mounted" : "unmounted")); 12928 if (DEBUG_SD_INSTALL) 12929 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 12930 + ", mMediaMounted=" + mMediaMounted); 12931 if (mediaStatus == mMediaMounted) { 12932 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 12933 : 0, -1); 12934 mHandler.sendMessage(msg); 12935 return; 12936 } 12937 mMediaMounted = mediaStatus; 12938 } 12939 // Queue up an async operation since the package installation may take a 12940 // little while. 12941 mHandler.post(new Runnable() { 12942 public void run() { 12943 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 12944 } 12945 }); 12946 } 12947 12948 /** 12949 * Called by MountService when the initial ASECs to scan are available. 12950 * Should block until all the ASEC containers are finished being scanned. 12951 */ 12952 public void scanAvailableAsecs() { 12953 updateExternalMediaStatusInner(true, false, false); 12954 if (mShouldRestoreconData) { 12955 SELinuxMMAC.setRestoreconDone(); 12956 mShouldRestoreconData = false; 12957 } 12958 } 12959 12960 /* 12961 * Collect information of applications on external media, map them against 12962 * existing containers and update information based on current mount status. 12963 * Please note that we always have to report status if reportStatus has been 12964 * set to true especially when unloading packages. 12965 */ 12966 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 12967 boolean externalStorage) { 12968 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 12969 int[] uidArr = EmptyArray.INT; 12970 12971 final String[] list = PackageHelper.getSecureContainerList(); 12972 if (ArrayUtils.isEmpty(list)) { 12973 Log.i(TAG, "No secure containers found"); 12974 } else { 12975 // Process list of secure containers and categorize them 12976 // as active or stale based on their package internal state. 12977 12978 // reader 12979 synchronized (mPackages) { 12980 for (String cid : list) { 12981 // Leave stages untouched for now; installer service owns them 12982 if (PackageInstallerService.isStageName(cid)) continue; 12983 12984 if (DEBUG_SD_INSTALL) 12985 Log.i(TAG, "Processing container " + cid); 12986 String pkgName = getAsecPackageName(cid); 12987 if (pkgName == null) { 12988 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 12989 continue; 12990 } 12991 if (DEBUG_SD_INSTALL) 12992 Log.i(TAG, "Looking for pkg : " + pkgName); 12993 12994 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12995 if (ps == null) { 12996 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 12997 continue; 12998 } 12999 13000 /* 13001 * Skip packages that are not external if we're unmounting 13002 * external storage. 13003 */ 13004 if (externalStorage && !isMounted && !isExternal(ps)) { 13005 continue; 13006 } 13007 13008 final AsecInstallArgs args = new AsecInstallArgs(cid, 13009 getAppDexInstructionSets(ps), isForwardLocked(ps)); 13010 // The package status is changed only if the code path 13011 // matches between settings and the container id. 13012 if (ps.codePathString != null 13013 && ps.codePathString.startsWith(args.getCodePath())) { 13014 if (DEBUG_SD_INSTALL) { 13015 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 13016 + " at code path: " + ps.codePathString); 13017 } 13018 13019 // We do have a valid package installed on sdcard 13020 processCids.put(args, ps.codePathString); 13021 final int uid = ps.appId; 13022 if (uid != -1) { 13023 uidArr = ArrayUtils.appendInt(uidArr, uid); 13024 } 13025 } else { 13026 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 13027 + ps.codePathString); 13028 } 13029 } 13030 } 13031 13032 Arrays.sort(uidArr); 13033 } 13034 13035 // Process packages with valid entries. 13036 if (isMounted) { 13037 if (DEBUG_SD_INSTALL) 13038 Log.i(TAG, "Loading packages"); 13039 loadMediaPackages(processCids, uidArr); 13040 startCleaningPackages(); 13041 mInstallerService.onSecureContainersAvailable(); 13042 } else { 13043 if (DEBUG_SD_INSTALL) 13044 Log.i(TAG, "Unloading packages"); 13045 unloadMediaPackages(processCids, uidArr, reportStatus); 13046 } 13047 } 13048 13049 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 13050 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 13051 int size = pkgList.size(); 13052 if (size > 0) { 13053 // Send broadcasts here 13054 Bundle extras = new Bundle(); 13055 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 13056 .toArray(new String[size])); 13057 if (uidArr != null) { 13058 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 13059 } 13060 if (replacing) { 13061 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 13062 } 13063 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 13064 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 13065 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 13066 } 13067 } 13068 13069 /* 13070 * Look at potentially valid container ids from processCids If package 13071 * information doesn't match the one on record or package scanning fails, 13072 * the cid is added to list of removeCids. We currently don't delete stale 13073 * containers. 13074 */ 13075 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 13076 ArrayList<String> pkgList = new ArrayList<String>(); 13077 Set<AsecInstallArgs> keys = processCids.keySet(); 13078 13079 for (AsecInstallArgs args : keys) { 13080 String codePath = processCids.get(args); 13081 if (DEBUG_SD_INSTALL) 13082 Log.i(TAG, "Loading container : " + args.cid); 13083 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13084 try { 13085 // Make sure there are no container errors first. 13086 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 13087 Slog.e(TAG, "Failed to mount cid : " + args.cid 13088 + " when installing from sdcard"); 13089 continue; 13090 } 13091 // Check code path here. 13092 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 13093 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 13094 + " does not match one in settings " + codePath); 13095 continue; 13096 } 13097 // Parse package 13098 int parseFlags = mDefParseFlags; 13099 if (args.isExternal()) { 13100 parseFlags |= PackageParser.PARSE_ON_SDCARD; 13101 } 13102 if (args.isFwdLocked()) { 13103 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 13104 } 13105 13106 synchronized (mInstallLock) { 13107 PackageParser.Package pkg = null; 13108 try { 13109 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 13110 } catch (PackageManagerException e) { 13111 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 13112 } 13113 // Scan the package 13114 if (pkg != null) { 13115 /* 13116 * TODO why is the lock being held? doPostInstall is 13117 * called in other places without the lock. This needs 13118 * to be straightened out. 13119 */ 13120 // writer 13121 synchronized (mPackages) { 13122 retCode = PackageManager.INSTALL_SUCCEEDED; 13123 pkgList.add(pkg.packageName); 13124 // Post process args 13125 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 13126 pkg.applicationInfo.uid); 13127 } 13128 } else { 13129 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 13130 } 13131 } 13132 13133 } finally { 13134 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 13135 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 13136 } 13137 } 13138 } 13139 // writer 13140 synchronized (mPackages) { 13141 // If the platform SDK has changed since the last time we booted, 13142 // we need to re-grant app permission to catch any new ones that 13143 // appear. This is really a hack, and means that apps can in some 13144 // cases get permissions that the user didn't initially explicitly 13145 // allow... it would be nice to have some better way to handle 13146 // this situation. 13147 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 13148 if (regrantPermissions) 13149 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 13150 + mSdkVersion + "; regranting permissions for external storage"); 13151 mSettings.mExternalSdkPlatform = mSdkVersion; 13152 13153 // Make sure group IDs have been assigned, and any permission 13154 // changes in other apps are accounted for 13155 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 13156 | (regrantPermissions 13157 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 13158 : 0)); 13159 13160 mSettings.updateExternalDatabaseVersion(); 13161 13162 // can downgrade to reader 13163 // Persist settings 13164 mSettings.writeLPr(); 13165 } 13166 // Send a broadcast to let everyone know we are done processing 13167 if (pkgList.size() > 0) { 13168 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 13169 } 13170 } 13171 13172 /* 13173 * Utility method to unload a list of specified containers 13174 */ 13175 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 13176 // Just unmount all valid containers. 13177 for (AsecInstallArgs arg : cidArgs) { 13178 synchronized (mInstallLock) { 13179 arg.doPostDeleteLI(false); 13180 } 13181 } 13182 } 13183 13184 /* 13185 * Unload packages mounted on external media. This involves deleting package 13186 * data from internal structures, sending broadcasts about diabled packages, 13187 * gc'ing to free up references, unmounting all secure containers 13188 * corresponding to packages on external media, and posting a 13189 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 13190 * that we always have to post this message if status has been requested no 13191 * matter what. 13192 */ 13193 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 13194 final boolean reportStatus) { 13195 if (DEBUG_SD_INSTALL) 13196 Log.i(TAG, "unloading media packages"); 13197 ArrayList<String> pkgList = new ArrayList<String>(); 13198 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 13199 final Set<AsecInstallArgs> keys = processCids.keySet(); 13200 for (AsecInstallArgs args : keys) { 13201 String pkgName = args.getPackageName(); 13202 if (DEBUG_SD_INSTALL) 13203 Log.i(TAG, "Trying to unload pkg : " + pkgName); 13204 // Delete package internally 13205 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 13206 synchronized (mInstallLock) { 13207 boolean res = deletePackageLI(pkgName, null, false, null, null, 13208 PackageManager.DELETE_KEEP_DATA, outInfo, false); 13209 if (res) { 13210 pkgList.add(pkgName); 13211 } else { 13212 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 13213 failedList.add(args); 13214 } 13215 } 13216 } 13217 13218 // reader 13219 synchronized (mPackages) { 13220 // We didn't update the settings after removing each package; 13221 // write them now for all packages. 13222 mSettings.writeLPr(); 13223 } 13224 13225 // We have to absolutely send UPDATED_MEDIA_STATUS only 13226 // after confirming that all the receivers processed the ordered 13227 // broadcast when packages get disabled, force a gc to clean things up. 13228 // and unload all the containers. 13229 if (pkgList.size() > 0) { 13230 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 13231 new IIntentReceiver.Stub() { 13232 public void performReceive(Intent intent, int resultCode, String data, 13233 Bundle extras, boolean ordered, boolean sticky, 13234 int sendingUser) throws RemoteException { 13235 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 13236 reportStatus ? 1 : 0, 1, keys); 13237 mHandler.sendMessage(msg); 13238 } 13239 }); 13240 } else { 13241 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 13242 keys); 13243 mHandler.sendMessage(msg); 13244 } 13245 } 13246 13247 /** Binder call */ 13248 @Override 13249 public void movePackage(final String packageName, final IPackageMoveObserver observer, 13250 final int flags) { 13251 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 13252 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 13253 int returnCode = PackageManager.MOVE_SUCCEEDED; 13254 int currInstallFlags = 0; 13255 int newInstallFlags = 0; 13256 13257 File codeFile = null; 13258 String installerPackageName = null; 13259 String packageAbiOverride = null; 13260 13261 // reader 13262 synchronized (mPackages) { 13263 final PackageParser.Package pkg = mPackages.get(packageName); 13264 final PackageSetting ps = mSettings.mPackages.get(packageName); 13265 if (pkg == null || ps == null) { 13266 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 13267 } else { 13268 // Disable moving fwd locked apps and system packages 13269 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 13270 Slog.w(TAG, "Cannot move system application"); 13271 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 13272 } else if (pkg.mOperationPending) { 13273 Slog.w(TAG, "Attempt to move package which has pending operations"); 13274 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 13275 } else { 13276 // Find install location first 13277 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 13278 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 13279 Slog.w(TAG, "Ambigous flags specified for move location."); 13280 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 13281 } else { 13282 newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 13283 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 13284 currInstallFlags = isExternal(pkg) 13285 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 13286 13287 if (newInstallFlags == currInstallFlags) { 13288 Slog.w(TAG, "No move required. Trying to move to same location"); 13289 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 13290 } else { 13291 if (isForwardLocked(pkg)) { 13292 currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13293 newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13294 } 13295 } 13296 } 13297 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13298 pkg.mOperationPending = true; 13299 } 13300 } 13301 13302 codeFile = new File(pkg.codePath); 13303 installerPackageName = ps.installerPackageName; 13304 packageAbiOverride = ps.cpuAbiOverrideString; 13305 } 13306 } 13307 13308 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 13309 try { 13310 observer.packageMoved(packageName, returnCode); 13311 } catch (RemoteException ignored) { 13312 } 13313 return; 13314 } 13315 13316 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 13317 @Override 13318 public void onUserActionRequired(Intent intent) throws RemoteException { 13319 throw new IllegalStateException(); 13320 } 13321 13322 @Override 13323 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 13324 Bundle extras) throws RemoteException { 13325 Slog.d(TAG, "Install result for move: " 13326 + PackageManager.installStatusToString(returnCode, msg)); 13327 13328 // We usually have a new package now after the install, but if 13329 // we failed we need to clear the pending flag on the original 13330 // package object. 13331 synchronized (mPackages) { 13332 final PackageParser.Package pkg = mPackages.get(packageName); 13333 if (pkg != null) { 13334 pkg.mOperationPending = false; 13335 } 13336 } 13337 13338 final int status = PackageManager.installStatusToPublicStatus(returnCode); 13339 switch (status) { 13340 case PackageInstaller.STATUS_SUCCESS: 13341 observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED); 13342 break; 13343 case PackageInstaller.STATUS_FAILURE_STORAGE: 13344 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 13345 break; 13346 default: 13347 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR); 13348 break; 13349 } 13350 } 13351 }; 13352 13353 // Treat a move like reinstalling an existing app, which ensures that we 13354 // process everythign uniformly, like unpacking native libraries. 13355 newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 13356 13357 final Message msg = mHandler.obtainMessage(INIT_COPY); 13358 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 13359 msg.obj = new InstallParams(origin, installObserver, newInstallFlags, 13360 installerPackageName, null, user, packageAbiOverride); 13361 mHandler.sendMessage(msg); 13362 } 13363 13364 @Override 13365 public boolean setInstallLocation(int loc) { 13366 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 13367 null); 13368 if (getInstallLocation() == loc) { 13369 return true; 13370 } 13371 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 13372 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 13373 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 13374 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 13375 return true; 13376 } 13377 return false; 13378 } 13379 13380 @Override 13381 public int getInstallLocation() { 13382 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13383 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 13384 PackageHelper.APP_INSTALL_AUTO); 13385 } 13386 13387 /** Called by UserManagerService */ 13388 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 13389 mDirtyUsers.remove(userHandle); 13390 mSettings.removeUserLPw(userHandle); 13391 mPendingBroadcasts.remove(userHandle); 13392 if (mInstaller != null) { 13393 // Technically, we shouldn't be doing this with the package lock 13394 // held. However, this is very rare, and there is already so much 13395 // other disk I/O going on, that we'll let it slide for now. 13396 mInstaller.removeUserDataDirs(userHandle); 13397 } 13398 mUserNeedsBadging.delete(userHandle); 13399 removeUnusedPackagesLILPw(userManager, userHandle); 13400 } 13401 13402 /** 13403 * We're removing userHandle and would like to remove any downloaded packages 13404 * that are no longer in use by any other user. 13405 * @param userHandle the user being removed 13406 */ 13407 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 13408 final boolean DEBUG_CLEAN_APKS = false; 13409 int [] users = userManager.getUserIdsLPr(); 13410 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 13411 while (psit.hasNext()) { 13412 PackageSetting ps = psit.next(); 13413 if (ps.pkg == null) { 13414 continue; 13415 } 13416 final String packageName = ps.pkg.packageName; 13417 // Skip over if system app 13418 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 13419 continue; 13420 } 13421 if (DEBUG_CLEAN_APKS) { 13422 Slog.i(TAG, "Checking package " + packageName); 13423 } 13424 boolean keep = false; 13425 for (int i = 0; i < users.length; i++) { 13426 if (users[i] != userHandle && ps.getInstalled(users[i])) { 13427 keep = true; 13428 if (DEBUG_CLEAN_APKS) { 13429 Slog.i(TAG, " Keeping package " + packageName + " for user " 13430 + users[i]); 13431 } 13432 break; 13433 } 13434 } 13435 if (!keep) { 13436 if (DEBUG_CLEAN_APKS) { 13437 Slog.i(TAG, " Removing package " + packageName); 13438 } 13439 mHandler.post(new Runnable() { 13440 public void run() { 13441 deletePackageX(packageName, userHandle, 0); 13442 } //end run 13443 }); 13444 } 13445 } 13446 } 13447 13448 /** Called by UserManagerService */ 13449 void createNewUserLILPw(int userHandle, File path) { 13450 if (mInstaller != null) { 13451 mInstaller.createUserConfig(userHandle); 13452 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 13453 } 13454 } 13455 13456 @Override 13457 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 13458 mContext.enforceCallingOrSelfPermission( 13459 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13460 "Only package verification agents can read the verifier device identity"); 13461 13462 synchronized (mPackages) { 13463 return mSettings.getVerifierDeviceIdentityLPw(); 13464 } 13465 } 13466 13467 @Override 13468 public void setPermissionEnforced(String permission, boolean enforced) { 13469 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 13470 if (READ_EXTERNAL_STORAGE.equals(permission)) { 13471 synchronized (mPackages) { 13472 if (mSettings.mReadExternalStorageEnforced == null 13473 || mSettings.mReadExternalStorageEnforced != enforced) { 13474 mSettings.mReadExternalStorageEnforced = enforced; 13475 mSettings.writeLPr(); 13476 } 13477 } 13478 // kill any non-foreground processes so we restart them and 13479 // grant/revoke the GID. 13480 final IActivityManager am = ActivityManagerNative.getDefault(); 13481 if (am != null) { 13482 final long token = Binder.clearCallingIdentity(); 13483 try { 13484 am.killProcessesBelowForeground("setPermissionEnforcement"); 13485 } catch (RemoteException e) { 13486 } finally { 13487 Binder.restoreCallingIdentity(token); 13488 } 13489 } 13490 } else { 13491 throw new IllegalArgumentException("No selective enforcement for " + permission); 13492 } 13493 } 13494 13495 @Override 13496 @Deprecated 13497 public boolean isPermissionEnforced(String permission) { 13498 return true; 13499 } 13500 13501 @Override 13502 public boolean isStorageLow() { 13503 final long token = Binder.clearCallingIdentity(); 13504 try { 13505 final DeviceStorageMonitorInternal 13506 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13507 if (dsm != null) { 13508 return dsm.isMemoryLow(); 13509 } else { 13510 return false; 13511 } 13512 } finally { 13513 Binder.restoreCallingIdentity(token); 13514 } 13515 } 13516 13517 @Override 13518 public IPackageInstaller getPackageInstaller() { 13519 return mInstallerService; 13520 } 13521 13522 private boolean userNeedsBadging(int userId) { 13523 int index = mUserNeedsBadging.indexOfKey(userId); 13524 if (index < 0) { 13525 final UserInfo userInfo; 13526 final long token = Binder.clearCallingIdentity(); 13527 try { 13528 userInfo = sUserManager.getUserInfo(userId); 13529 } finally { 13530 Binder.restoreCallingIdentity(token); 13531 } 13532 final boolean b; 13533 if (userInfo != null && userInfo.isManagedProfile()) { 13534 b = true; 13535 } else { 13536 b = false; 13537 } 13538 mUserNeedsBadging.put(userId, b); 13539 return b; 13540 } 13541 return mUserNeedsBadging.valueAt(index); 13542 } 13543 13544 @Override 13545 public KeySet getKeySetByAlias(String packageName, String alias) { 13546 if (packageName == null || alias == null) { 13547 return null; 13548 } 13549 synchronized(mPackages) { 13550 final PackageParser.Package pkg = mPackages.get(packageName); 13551 if (pkg == null) { 13552 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13553 throw new IllegalArgumentException("Unknown package: " + packageName); 13554 } 13555 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13556 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 13557 } 13558 } 13559 13560 @Override 13561 public KeySet getSigningKeySet(String packageName) { 13562 if (packageName == null) { 13563 return null; 13564 } 13565 synchronized(mPackages) { 13566 final PackageParser.Package pkg = mPackages.get(packageName); 13567 if (pkg == null) { 13568 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13569 throw new IllegalArgumentException("Unknown package: " + packageName); 13570 } 13571 if (pkg.applicationInfo.uid != Binder.getCallingUid() 13572 && Process.SYSTEM_UID != Binder.getCallingUid()) { 13573 throw new SecurityException("May not access signing KeySet of other apps."); 13574 } 13575 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13576 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 13577 } 13578 } 13579 13580 @Override 13581 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 13582 if (packageName == null || ks == null) { 13583 return false; 13584 } 13585 synchronized(mPackages) { 13586 final PackageParser.Package pkg = mPackages.get(packageName); 13587 if (pkg == null) { 13588 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13589 throw new IllegalArgumentException("Unknown package: " + packageName); 13590 } 13591 IBinder ksh = ks.getToken(); 13592 if (ksh instanceof KeySetHandle) { 13593 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13594 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 13595 } 13596 return false; 13597 } 13598 } 13599 13600 @Override 13601 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 13602 if (packageName == null || ks == null) { 13603 return false; 13604 } 13605 synchronized(mPackages) { 13606 final PackageParser.Package pkg = mPackages.get(packageName); 13607 if (pkg == null) { 13608 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13609 throw new IllegalArgumentException("Unknown package: " + packageName); 13610 } 13611 IBinder ksh = ks.getToken(); 13612 if (ksh instanceof KeySetHandle) { 13613 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13614 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 13615 } 13616 return false; 13617 } 13618 } 13619 13620 public void getUsageStatsIfNoPackageUsageInfo() { 13621 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 13622 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 13623 if (usm == null) { 13624 throw new IllegalStateException("UsageStatsManager must be initialized"); 13625 } 13626 long now = System.currentTimeMillis(); 13627 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 13628 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 13629 String packageName = entry.getKey(); 13630 PackageParser.Package pkg = mPackages.get(packageName); 13631 if (pkg == null) { 13632 continue; 13633 } 13634 UsageStats usage = entry.getValue(); 13635 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 13636 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 13637 } 13638 } 13639 } 13640 13641 /** 13642 * Check and throw if the given before/after packages would be considered a 13643 * downgrade. 13644 */ 13645 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 13646 throws PackageManagerException { 13647 if (after.versionCode < before.mVersionCode) { 13648 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 13649 "Update version code " + after.versionCode + " is older than current " 13650 + before.mVersionCode); 13651 } else if (after.versionCode == before.mVersionCode) { 13652 if (after.baseRevisionCode < before.baseRevisionCode) { 13653 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 13654 "Update base revision code " + after.baseRevisionCode 13655 + " is older than current " + before.baseRevisionCode); 13656 } 13657 13658 if (!ArrayUtils.isEmpty(after.splitNames)) { 13659 for (int i = 0; i < after.splitNames.length; i++) { 13660 final String splitName = after.splitNames[i]; 13661 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 13662 if (j != -1) { 13663 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 13664 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 13665 "Update split " + splitName + " revision code " 13666 + after.splitRevisionCodes[i] + " is older than current " 13667 + before.splitRevisionCodes[j]); 13668 } 13669 } 13670 } 13671 } 13672 } 13673 } 13674} 13675