PackageManagerService.java revision 703d1c43a25fe6e80c5fea46cc0ff14f0e1fbc00
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.FLAG_PRIVILEGED); 1303 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1304 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1305 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1306 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1307 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1308 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1309 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1310 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1311 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1312 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.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.dataDir = 2128 getDataPathForPackage(packageName, 0).getPath(); 2129 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 2130 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 2131 } 2132 return generatePackageInfo(pkg, flags, userId); 2133 } 2134 return null; 2135 } 2136 2137 @Override 2138 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2139 if (!sUserManager.exists(userId)) return null; 2140 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info"); 2141 // writer 2142 synchronized (mPackages) { 2143 PackageParser.Package p = mPackages.get(packageName); 2144 if (DEBUG_PACKAGE_INFO) Log.v( 2145 TAG, "getApplicationInfo " + packageName 2146 + ": " + p); 2147 if (p != null) { 2148 PackageSetting ps = mSettings.mPackages.get(packageName); 2149 if (ps == null) return null; 2150 // Note: isEnabledLP() does not apply here - always return info 2151 return PackageParser.generateApplicationInfo( 2152 p, flags, ps.readUserState(userId), userId); 2153 } 2154 if ("android".equals(packageName)||"system".equals(packageName)) { 2155 return mAndroidApplication; 2156 } 2157 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2158 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2159 } 2160 } 2161 return null; 2162 } 2163 2164 2165 @Override 2166 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2167 mContext.enforceCallingOrSelfPermission( 2168 android.Manifest.permission.CLEAR_APP_CACHE, null); 2169 // Queue up an async operation since clearing cache may take a little while. 2170 mHandler.post(new Runnable() { 2171 public void run() { 2172 mHandler.removeCallbacks(this); 2173 int retCode = -1; 2174 synchronized (mInstallLock) { 2175 retCode = mInstaller.freeCache(freeStorageSize); 2176 if (retCode < 0) { 2177 Slog.w(TAG, "Couldn't clear application caches"); 2178 } 2179 } 2180 if (observer != null) { 2181 try { 2182 observer.onRemoveCompleted(null, (retCode >= 0)); 2183 } catch (RemoteException e) { 2184 Slog.w(TAG, "RemoveException when invoking call back"); 2185 } 2186 } 2187 } 2188 }); 2189 } 2190 2191 @Override 2192 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2193 mContext.enforceCallingOrSelfPermission( 2194 android.Manifest.permission.CLEAR_APP_CACHE, null); 2195 // Queue up an async operation since clearing cache may take a little while. 2196 mHandler.post(new Runnable() { 2197 public void run() { 2198 mHandler.removeCallbacks(this); 2199 int retCode = -1; 2200 synchronized (mInstallLock) { 2201 retCode = mInstaller.freeCache(freeStorageSize); 2202 if (retCode < 0) { 2203 Slog.w(TAG, "Couldn't clear application caches"); 2204 } 2205 } 2206 if(pi != null) { 2207 try { 2208 // Callback via pending intent 2209 int code = (retCode >= 0) ? 1 : 0; 2210 pi.sendIntent(null, code, null, 2211 null, null); 2212 } catch (SendIntentException e1) { 2213 Slog.i(TAG, "Failed to send pending intent"); 2214 } 2215 } 2216 } 2217 }); 2218 } 2219 2220 void freeStorage(long freeStorageSize) throws IOException { 2221 synchronized (mInstallLock) { 2222 if (mInstaller.freeCache(freeStorageSize) < 0) { 2223 throw new IOException("Failed to free enough space"); 2224 } 2225 } 2226 } 2227 2228 @Override 2229 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2230 if (!sUserManager.exists(userId)) return null; 2231 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info"); 2232 synchronized (mPackages) { 2233 PackageParser.Activity a = mActivities.mActivities.get(component); 2234 2235 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2236 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2237 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2238 if (ps == null) return null; 2239 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2240 userId); 2241 } 2242 if (mResolveComponentName.equals(component)) { 2243 return PackageParser.generateActivityInfo(mResolveActivity, flags, 2244 new PackageUserState(), userId); 2245 } 2246 } 2247 return null; 2248 } 2249 2250 @Override 2251 public boolean activitySupportsIntent(ComponentName component, Intent intent, 2252 String resolvedType) { 2253 synchronized (mPackages) { 2254 PackageParser.Activity a = mActivities.mActivities.get(component); 2255 if (a == null) { 2256 return false; 2257 } 2258 for (int i=0; i<a.intents.size(); i++) { 2259 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 2260 intent.getData(), intent.getCategories(), TAG) >= 0) { 2261 return true; 2262 } 2263 } 2264 return false; 2265 } 2266 } 2267 2268 @Override 2269 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2270 if (!sUserManager.exists(userId)) return null; 2271 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info"); 2272 synchronized (mPackages) { 2273 PackageParser.Activity a = mReceivers.mActivities.get(component); 2274 if (DEBUG_PACKAGE_INFO) Log.v( 2275 TAG, "getReceiverInfo " + component + ": " + a); 2276 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2277 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2278 if (ps == null) return null; 2279 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2280 userId); 2281 } 2282 } 2283 return null; 2284 } 2285 2286 @Override 2287 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2288 if (!sUserManager.exists(userId)) return null; 2289 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info"); 2290 synchronized (mPackages) { 2291 PackageParser.Service s = mServices.mServices.get(component); 2292 if (DEBUG_PACKAGE_INFO) Log.v( 2293 TAG, "getServiceInfo " + component + ": " + s); 2294 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2295 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2296 if (ps == null) return null; 2297 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2298 userId); 2299 } 2300 } 2301 return null; 2302 } 2303 2304 @Override 2305 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2306 if (!sUserManager.exists(userId)) return null; 2307 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info"); 2308 synchronized (mPackages) { 2309 PackageParser.Provider p = mProviders.mProviders.get(component); 2310 if (DEBUG_PACKAGE_INFO) Log.v( 2311 TAG, "getProviderInfo " + component + ": " + p); 2312 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2313 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2314 if (ps == null) return null; 2315 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2316 userId); 2317 } 2318 } 2319 return null; 2320 } 2321 2322 @Override 2323 public String[] getSystemSharedLibraryNames() { 2324 Set<String> libSet; 2325 synchronized (mPackages) { 2326 libSet = mSharedLibraries.keySet(); 2327 int size = libSet.size(); 2328 if (size > 0) { 2329 String[] libs = new String[size]; 2330 libSet.toArray(libs); 2331 return libs; 2332 } 2333 } 2334 return null; 2335 } 2336 2337 @Override 2338 public FeatureInfo[] getSystemAvailableFeatures() { 2339 Collection<FeatureInfo> featSet; 2340 synchronized (mPackages) { 2341 featSet = mAvailableFeatures.values(); 2342 int size = featSet.size(); 2343 if (size > 0) { 2344 FeatureInfo[] features = new FeatureInfo[size+1]; 2345 featSet.toArray(features); 2346 FeatureInfo fi = new FeatureInfo(); 2347 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2348 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2349 features[size] = fi; 2350 return features; 2351 } 2352 } 2353 return null; 2354 } 2355 2356 @Override 2357 public boolean hasSystemFeature(String name) { 2358 synchronized (mPackages) { 2359 return mAvailableFeatures.containsKey(name); 2360 } 2361 } 2362 2363 private void checkValidCaller(int uid, int userId) { 2364 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2365 return; 2366 2367 throw new SecurityException("Caller uid=" + uid 2368 + " is not privileged to communicate with user=" + userId); 2369 } 2370 2371 @Override 2372 public int checkPermission(String permName, String pkgName) { 2373 synchronized (mPackages) { 2374 PackageParser.Package p = mPackages.get(pkgName); 2375 if (p != null && p.mExtras != null) { 2376 PackageSetting ps = (PackageSetting)p.mExtras; 2377 if (ps.sharedUser != null) { 2378 if (ps.sharedUser.grantedPermissions.contains(permName)) { 2379 return PackageManager.PERMISSION_GRANTED; 2380 } 2381 } else if (ps.grantedPermissions.contains(permName)) { 2382 return PackageManager.PERMISSION_GRANTED; 2383 } 2384 } 2385 } 2386 return PackageManager.PERMISSION_DENIED; 2387 } 2388 2389 @Override 2390 public int checkUidPermission(String permName, int uid) { 2391 synchronized (mPackages) { 2392 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2393 if (obj != null) { 2394 GrantedPermissions gp = (GrantedPermissions)obj; 2395 if (gp.grantedPermissions.contains(permName)) { 2396 return PackageManager.PERMISSION_GRANTED; 2397 } 2398 } else { 2399 ArraySet<String> perms = mSystemPermissions.get(uid); 2400 if (perms != null && perms.contains(permName)) { 2401 return PackageManager.PERMISSION_GRANTED; 2402 } 2403 } 2404 } 2405 return PackageManager.PERMISSION_DENIED; 2406 } 2407 2408 /** 2409 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2410 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2411 * @param checkShell TODO(yamasani): 2412 * @param message the message to log on security exception 2413 */ 2414 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 2415 boolean checkShell, String message) { 2416 if (userId < 0) { 2417 throw new IllegalArgumentException("Invalid userId " + userId); 2418 } 2419 if (checkShell) { 2420 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 2421 } 2422 if (userId == UserHandle.getUserId(callingUid)) return; 2423 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2424 if (requireFullPermission) { 2425 mContext.enforceCallingOrSelfPermission( 2426 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2427 } else { 2428 try { 2429 mContext.enforceCallingOrSelfPermission( 2430 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2431 } catch (SecurityException se) { 2432 mContext.enforceCallingOrSelfPermission( 2433 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2434 } 2435 } 2436 } 2437 } 2438 2439 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 2440 if (callingUid == Process.SHELL_UID) { 2441 if (userHandle >= 0 2442 && sUserManager.hasUserRestriction(restriction, userHandle)) { 2443 throw new SecurityException("Shell does not have permission to access user " 2444 + userHandle); 2445 } else if (userHandle < 0) { 2446 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 2447 + Debug.getCallers(3)); 2448 } 2449 } 2450 } 2451 2452 private BasePermission findPermissionTreeLP(String permName) { 2453 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2454 if (permName.startsWith(bp.name) && 2455 permName.length() > bp.name.length() && 2456 permName.charAt(bp.name.length()) == '.') { 2457 return bp; 2458 } 2459 } 2460 return null; 2461 } 2462 2463 private BasePermission checkPermissionTreeLP(String permName) { 2464 if (permName != null) { 2465 BasePermission bp = findPermissionTreeLP(permName); 2466 if (bp != null) { 2467 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2468 return bp; 2469 } 2470 throw new SecurityException("Calling uid " 2471 + Binder.getCallingUid() 2472 + " is not allowed to add to permission tree " 2473 + bp.name + " owned by uid " + bp.uid); 2474 } 2475 } 2476 throw new SecurityException("No permission tree found for " + permName); 2477 } 2478 2479 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2480 if (s1 == null) { 2481 return s2 == null; 2482 } 2483 if (s2 == null) { 2484 return false; 2485 } 2486 if (s1.getClass() != s2.getClass()) { 2487 return false; 2488 } 2489 return s1.equals(s2); 2490 } 2491 2492 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2493 if (pi1.icon != pi2.icon) return false; 2494 if (pi1.logo != pi2.logo) return false; 2495 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2496 if (!compareStrings(pi1.name, pi2.name)) return false; 2497 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2498 // We'll take care of setting this one. 2499 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2500 // These are not currently stored in settings. 2501 //if (!compareStrings(pi1.group, pi2.group)) return false; 2502 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2503 //if (pi1.labelRes != pi2.labelRes) return false; 2504 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2505 return true; 2506 } 2507 2508 int permissionInfoFootprint(PermissionInfo info) { 2509 int size = info.name.length(); 2510 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 2511 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 2512 return size; 2513 } 2514 2515 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 2516 int size = 0; 2517 for (BasePermission perm : mSettings.mPermissions.values()) { 2518 if (perm.uid == tree.uid) { 2519 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 2520 } 2521 } 2522 return size; 2523 } 2524 2525 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 2526 // We calculate the max size of permissions defined by this uid and throw 2527 // if that plus the size of 'info' would exceed our stated maximum. 2528 if (tree.uid != Process.SYSTEM_UID) { 2529 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 2530 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 2531 throw new SecurityException("Permission tree size cap exceeded"); 2532 } 2533 } 2534 } 2535 2536 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2537 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2538 throw new SecurityException("Label must be specified in permission"); 2539 } 2540 BasePermission tree = checkPermissionTreeLP(info.name); 2541 BasePermission bp = mSettings.mPermissions.get(info.name); 2542 boolean added = bp == null; 2543 boolean changed = true; 2544 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2545 if (added) { 2546 enforcePermissionCapLocked(info, tree); 2547 bp = new BasePermission(info.name, tree.sourcePackage, 2548 BasePermission.TYPE_DYNAMIC); 2549 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2550 throw new SecurityException( 2551 "Not allowed to modify non-dynamic permission " 2552 + info.name); 2553 } else { 2554 if (bp.protectionLevel == fixedLevel 2555 && bp.perm.owner.equals(tree.perm.owner) 2556 && bp.uid == tree.uid 2557 && comparePermissionInfos(bp.perm.info, info)) { 2558 changed = false; 2559 } 2560 } 2561 bp.protectionLevel = fixedLevel; 2562 info = new PermissionInfo(info); 2563 info.protectionLevel = fixedLevel; 2564 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 2565 bp.perm.info.packageName = tree.perm.info.packageName; 2566 bp.uid = tree.uid; 2567 if (added) { 2568 mSettings.mPermissions.put(info.name, bp); 2569 } 2570 if (changed) { 2571 if (!async) { 2572 mSettings.writeLPr(); 2573 } else { 2574 scheduleWriteSettingsLocked(); 2575 } 2576 } 2577 return added; 2578 } 2579 2580 @Override 2581 public boolean addPermission(PermissionInfo info) { 2582 synchronized (mPackages) { 2583 return addPermissionLocked(info, false); 2584 } 2585 } 2586 2587 @Override 2588 public boolean addPermissionAsync(PermissionInfo info) { 2589 synchronized (mPackages) { 2590 return addPermissionLocked(info, true); 2591 } 2592 } 2593 2594 @Override 2595 public void removePermission(String name) { 2596 synchronized (mPackages) { 2597 checkPermissionTreeLP(name); 2598 BasePermission bp = mSettings.mPermissions.get(name); 2599 if (bp != null) { 2600 if (bp.type != BasePermission.TYPE_DYNAMIC) { 2601 throw new SecurityException( 2602 "Not allowed to modify non-dynamic permission " 2603 + name); 2604 } 2605 mSettings.mPermissions.remove(name); 2606 mSettings.writeLPr(); 2607 } 2608 } 2609 } 2610 2611 private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) { 2612 int index = pkg.requestedPermissions.indexOf(bp.name); 2613 if (index == -1) { 2614 throw new SecurityException("Package " + pkg.packageName 2615 + " has not requested permission " + bp.name); 2616 } 2617 boolean isNormal = 2618 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2619 == PermissionInfo.PROTECTION_NORMAL); 2620 boolean isDangerous = 2621 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2622 == PermissionInfo.PROTECTION_DANGEROUS); 2623 boolean isDevelopment = 2624 ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0); 2625 2626 if (!isNormal && !isDangerous && !isDevelopment) { 2627 throw new SecurityException("Permission " + bp.name 2628 + " is not a changeable permission type"); 2629 } 2630 2631 if (isNormal || isDangerous) { 2632 if (pkg.requestedPermissionsRequired.get(index)) { 2633 throw new SecurityException("Can't change " + bp.name 2634 + ". It is required by the application"); 2635 } 2636 } 2637 } 2638 2639 @Override 2640 public void grantPermission(String packageName, String permissionName) { 2641 mContext.enforceCallingOrSelfPermission( 2642 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2643 synchronized (mPackages) { 2644 final PackageParser.Package pkg = mPackages.get(packageName); 2645 if (pkg == null) { 2646 throw new IllegalArgumentException("Unknown package: " + packageName); 2647 } 2648 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2649 if (bp == null) { 2650 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2651 } 2652 2653 checkGrantRevokePermissions(pkg, bp); 2654 2655 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2656 if (ps == null) { 2657 return; 2658 } 2659 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2660 if (gp.grantedPermissions.add(permissionName)) { 2661 if (ps.haveGids) { 2662 gp.gids = appendInts(gp.gids, bp.gids); 2663 } 2664 mSettings.writeLPr(); 2665 } 2666 } 2667 } 2668 2669 @Override 2670 public void revokePermission(String packageName, String permissionName) { 2671 int changedAppId = -1; 2672 2673 synchronized (mPackages) { 2674 final PackageParser.Package pkg = mPackages.get(packageName); 2675 if (pkg == null) { 2676 throw new IllegalArgumentException("Unknown package: " + packageName); 2677 } 2678 if (pkg.applicationInfo.uid != Binder.getCallingUid()) { 2679 mContext.enforceCallingOrSelfPermission( 2680 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2681 } 2682 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2683 if (bp == null) { 2684 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2685 } 2686 2687 checkGrantRevokePermissions(pkg, bp); 2688 2689 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2690 if (ps == null) { 2691 return; 2692 } 2693 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2694 if (gp.grantedPermissions.remove(permissionName)) { 2695 gp.grantedPermissions.remove(permissionName); 2696 if (ps.haveGids) { 2697 gp.gids = removeInts(gp.gids, bp.gids); 2698 } 2699 mSettings.writeLPr(); 2700 changedAppId = ps.appId; 2701 } 2702 } 2703 2704 if (changedAppId >= 0) { 2705 // We changed the perm on someone, kill its processes. 2706 IActivityManager am = ActivityManagerNative.getDefault(); 2707 if (am != null) { 2708 final int callingUserId = UserHandle.getCallingUserId(); 2709 final long ident = Binder.clearCallingIdentity(); 2710 try { 2711 //XXX we should only revoke for the calling user's app permissions, 2712 // but for now we impact all users. 2713 //am.killUid(UserHandle.getUid(callingUserId, changedAppId), 2714 // "revoke " + permissionName); 2715 int[] users = sUserManager.getUserIds(); 2716 for (int user : users) { 2717 am.killUid(UserHandle.getUid(user, changedAppId), 2718 "revoke " + permissionName); 2719 } 2720 } catch (RemoteException e) { 2721 } finally { 2722 Binder.restoreCallingIdentity(ident); 2723 } 2724 } 2725 } 2726 } 2727 2728 @Override 2729 public boolean isProtectedBroadcast(String actionName) { 2730 synchronized (mPackages) { 2731 return mProtectedBroadcasts.contains(actionName); 2732 } 2733 } 2734 2735 @Override 2736 public int checkSignatures(String pkg1, String pkg2) { 2737 synchronized (mPackages) { 2738 final PackageParser.Package p1 = mPackages.get(pkg1); 2739 final PackageParser.Package p2 = mPackages.get(pkg2); 2740 if (p1 == null || p1.mExtras == null 2741 || p2 == null || p2.mExtras == null) { 2742 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2743 } 2744 return compareSignatures(p1.mSignatures, p2.mSignatures); 2745 } 2746 } 2747 2748 @Override 2749 public int checkUidSignatures(int uid1, int uid2) { 2750 // Map to base uids. 2751 uid1 = UserHandle.getAppId(uid1); 2752 uid2 = UserHandle.getAppId(uid2); 2753 // reader 2754 synchronized (mPackages) { 2755 Signature[] s1; 2756 Signature[] s2; 2757 Object obj = mSettings.getUserIdLPr(uid1); 2758 if (obj != null) { 2759 if (obj instanceof SharedUserSetting) { 2760 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 2761 } else if (obj instanceof PackageSetting) { 2762 s1 = ((PackageSetting)obj).signatures.mSignatures; 2763 } else { 2764 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2765 } 2766 } else { 2767 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2768 } 2769 obj = mSettings.getUserIdLPr(uid2); 2770 if (obj != null) { 2771 if (obj instanceof SharedUserSetting) { 2772 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 2773 } else if (obj instanceof PackageSetting) { 2774 s2 = ((PackageSetting)obj).signatures.mSignatures; 2775 } else { 2776 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2777 } 2778 } else { 2779 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2780 } 2781 return compareSignatures(s1, s2); 2782 } 2783 } 2784 2785 /** 2786 * Compares two sets of signatures. Returns: 2787 * <br /> 2788 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 2789 * <br /> 2790 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 2791 * <br /> 2792 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 2793 * <br /> 2794 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 2795 * <br /> 2796 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 2797 */ 2798 static int compareSignatures(Signature[] s1, Signature[] s2) { 2799 if (s1 == null) { 2800 return s2 == null 2801 ? PackageManager.SIGNATURE_NEITHER_SIGNED 2802 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 2803 } 2804 2805 if (s2 == null) { 2806 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 2807 } 2808 2809 if (s1.length != s2.length) { 2810 return PackageManager.SIGNATURE_NO_MATCH; 2811 } 2812 2813 // Since both signature sets are of size 1, we can compare without HashSets. 2814 if (s1.length == 1) { 2815 return s1[0].equals(s2[0]) ? 2816 PackageManager.SIGNATURE_MATCH : 2817 PackageManager.SIGNATURE_NO_MATCH; 2818 } 2819 2820 ArraySet<Signature> set1 = new ArraySet<Signature>(); 2821 for (Signature sig : s1) { 2822 set1.add(sig); 2823 } 2824 ArraySet<Signature> set2 = new ArraySet<Signature>(); 2825 for (Signature sig : s2) { 2826 set2.add(sig); 2827 } 2828 // Make sure s2 contains all signatures in s1. 2829 if (set1.equals(set2)) { 2830 return PackageManager.SIGNATURE_MATCH; 2831 } 2832 return PackageManager.SIGNATURE_NO_MATCH; 2833 } 2834 2835 /** 2836 * If the database version for this type of package (internal storage or 2837 * external storage) is less than the version where package signatures 2838 * were updated, return true. 2839 */ 2840 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2841 return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan( 2842 DatabaseVersion.SIGNATURE_END_ENTITY)) 2843 || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan( 2844 DatabaseVersion.SIGNATURE_END_ENTITY)); 2845 } 2846 2847 /** 2848 * Used for backward compatibility to make sure any packages with 2849 * certificate chains get upgraded to the new style. {@code existingSigs} 2850 * will be in the old format (since they were stored on disk from before the 2851 * system upgrade) and {@code scannedSigs} will be in the newer format. 2852 */ 2853 private int compareSignaturesCompat(PackageSignatures existingSigs, 2854 PackageParser.Package scannedPkg) { 2855 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 2856 return PackageManager.SIGNATURE_NO_MATCH; 2857 } 2858 2859 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 2860 for (Signature sig : existingSigs.mSignatures) { 2861 existingSet.add(sig); 2862 } 2863 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 2864 for (Signature sig : scannedPkg.mSignatures) { 2865 try { 2866 Signature[] chainSignatures = sig.getChainSignatures(); 2867 for (Signature chainSig : chainSignatures) { 2868 scannedCompatSet.add(chainSig); 2869 } 2870 } catch (CertificateEncodingException e) { 2871 scannedCompatSet.add(sig); 2872 } 2873 } 2874 /* 2875 * Make sure the expanded scanned set contains all signatures in the 2876 * existing one. 2877 */ 2878 if (scannedCompatSet.equals(existingSet)) { 2879 // Migrate the old signatures to the new scheme. 2880 existingSigs.assignSignatures(scannedPkg.mSignatures); 2881 // The new KeySets will be re-added later in the scanning process. 2882 synchronized (mPackages) { 2883 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 2884 } 2885 return PackageManager.SIGNATURE_MATCH; 2886 } 2887 return PackageManager.SIGNATURE_NO_MATCH; 2888 } 2889 2890 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 2891 if (isExternal(scannedPkg)) { 2892 return mSettings.isExternalDatabaseVersionOlderThan( 2893 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 2894 } else { 2895 return mSettings.isInternalDatabaseVersionOlderThan( 2896 DatabaseVersion.SIGNATURE_MALFORMED_RECOVER); 2897 } 2898 } 2899 2900 private int compareSignaturesRecover(PackageSignatures existingSigs, 2901 PackageParser.Package scannedPkg) { 2902 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 2903 return PackageManager.SIGNATURE_NO_MATCH; 2904 } 2905 2906 String msg = null; 2907 try { 2908 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 2909 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 2910 + scannedPkg.packageName); 2911 return PackageManager.SIGNATURE_MATCH; 2912 } 2913 } catch (CertificateException e) { 2914 msg = e.getMessage(); 2915 } 2916 2917 logCriticalInfo(Log.INFO, 2918 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 2919 return PackageManager.SIGNATURE_NO_MATCH; 2920 } 2921 2922 @Override 2923 public String[] getPackagesForUid(int uid) { 2924 uid = UserHandle.getAppId(uid); 2925 // reader 2926 synchronized (mPackages) { 2927 Object obj = mSettings.getUserIdLPr(uid); 2928 if (obj instanceof SharedUserSetting) { 2929 final SharedUserSetting sus = (SharedUserSetting) obj; 2930 final int N = sus.packages.size(); 2931 final String[] res = new String[N]; 2932 final Iterator<PackageSetting> it = sus.packages.iterator(); 2933 int i = 0; 2934 while (it.hasNext()) { 2935 res[i++] = it.next().name; 2936 } 2937 return res; 2938 } else if (obj instanceof PackageSetting) { 2939 final PackageSetting ps = (PackageSetting) obj; 2940 return new String[] { ps.name }; 2941 } 2942 } 2943 return null; 2944 } 2945 2946 @Override 2947 public String getNameForUid(int uid) { 2948 // reader 2949 synchronized (mPackages) { 2950 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2951 if (obj instanceof SharedUserSetting) { 2952 final SharedUserSetting sus = (SharedUserSetting) obj; 2953 return sus.name + ":" + sus.userId; 2954 } else if (obj instanceof PackageSetting) { 2955 final PackageSetting ps = (PackageSetting) obj; 2956 return ps.name; 2957 } 2958 } 2959 return null; 2960 } 2961 2962 @Override 2963 public int getUidForSharedUser(String sharedUserName) { 2964 if(sharedUserName == null) { 2965 return -1; 2966 } 2967 // reader 2968 synchronized (mPackages) { 2969 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false); 2970 if (suid == null) { 2971 return -1; 2972 } 2973 return suid.userId; 2974 } 2975 } 2976 2977 @Override 2978 public int getFlagsForUid(int uid) { 2979 synchronized (mPackages) { 2980 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2981 if (obj instanceof SharedUserSetting) { 2982 final SharedUserSetting sus = (SharedUserSetting) obj; 2983 return sus.pkgFlags; 2984 } else if (obj instanceof PackageSetting) { 2985 final PackageSetting ps = (PackageSetting) obj; 2986 return ps.pkgFlags; 2987 } 2988 } 2989 return 0; 2990 } 2991 2992 @Override 2993 public boolean isUidPrivileged(int uid) { 2994 uid = UserHandle.getAppId(uid); 2995 // reader 2996 synchronized (mPackages) { 2997 Object obj = mSettings.getUserIdLPr(uid); 2998 if (obj instanceof SharedUserSetting) { 2999 final SharedUserSetting sus = (SharedUserSetting) obj; 3000 final Iterator<PackageSetting> it = sus.packages.iterator(); 3001 while (it.hasNext()) { 3002 if (it.next().isPrivileged()) { 3003 return true; 3004 } 3005 } 3006 } else if (obj instanceof PackageSetting) { 3007 final PackageSetting ps = (PackageSetting) obj; 3008 return ps.isPrivileged(); 3009 } 3010 } 3011 return false; 3012 } 3013 3014 @Override 3015 public String[] getAppOpPermissionPackages(String permissionName) { 3016 synchronized (mPackages) { 3017 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 3018 if (pkgs == null) { 3019 return null; 3020 } 3021 return pkgs.toArray(new String[pkgs.size()]); 3022 } 3023 } 3024 3025 @Override 3026 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 3027 int flags, int userId) { 3028 if (!sUserManager.exists(userId)) return null; 3029 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); 3030 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3031 return chooseBestActivity(intent, resolvedType, flags, query, userId); 3032 } 3033 3034 @Override 3035 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 3036 IntentFilter filter, int match, ComponentName activity) { 3037 final int userId = UserHandle.getCallingUserId(); 3038 if (DEBUG_PREFERRED) { 3039 Log.v(TAG, "setLastChosenActivity intent=" + intent 3040 + " resolvedType=" + resolvedType 3041 + " flags=" + flags 3042 + " filter=" + filter 3043 + " match=" + match 3044 + " activity=" + activity); 3045 filter.dump(new PrintStreamPrinter(System.out), " "); 3046 } 3047 intent.setComponent(null); 3048 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3049 // Find any earlier preferred or last chosen entries and nuke them 3050 findPreferredActivity(intent, resolvedType, 3051 flags, query, 0, false, true, false, userId); 3052 // Add the new activity as the last chosen for this filter 3053 addPreferredActivityInternal(filter, match, null, activity, false, userId, 3054 "Setting last chosen"); 3055 } 3056 3057 @Override 3058 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 3059 final int userId = UserHandle.getCallingUserId(); 3060 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 3061 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 3062 return findPreferredActivity(intent, resolvedType, flags, query, 0, 3063 false, false, false, userId); 3064 } 3065 3066 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 3067 int flags, List<ResolveInfo> query, int userId) { 3068 if (query != null) { 3069 final int N = query.size(); 3070 if (N == 1) { 3071 return query.get(0); 3072 } else if (N > 1) { 3073 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 3074 // If there is more than one activity with the same priority, 3075 // then let the user decide between them. 3076 ResolveInfo r0 = query.get(0); 3077 ResolveInfo r1 = query.get(1); 3078 if (DEBUG_INTENT_MATCHING || debug) { 3079 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 3080 + r1.activityInfo.name + "=" + r1.priority); 3081 } 3082 // If the first activity has a higher priority, or a different 3083 // default, then it is always desireable to pick it. 3084 if (r0.priority != r1.priority 3085 || r0.preferredOrder != r1.preferredOrder 3086 || r0.isDefault != r1.isDefault) { 3087 return query.get(0); 3088 } 3089 // If we have saved a preference for a preferred activity for 3090 // this Intent, use that. 3091 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 3092 flags, query, r0.priority, true, false, debug, userId); 3093 if (ri != null) { 3094 return ri; 3095 } 3096 if (userId != 0) { 3097 ri = new ResolveInfo(mResolveInfo); 3098 ri.activityInfo = new ActivityInfo(ri.activityInfo); 3099 ri.activityInfo.applicationInfo = new ApplicationInfo( 3100 ri.activityInfo.applicationInfo); 3101 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 3102 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 3103 return ri; 3104 } 3105 return mResolveInfo; 3106 } 3107 } 3108 return null; 3109 } 3110 3111 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 3112 int flags, List<ResolveInfo> query, boolean debug, int userId) { 3113 final int N = query.size(); 3114 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 3115 .get(userId); 3116 // Get the list of persistent preferred activities that handle the intent 3117 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 3118 List<PersistentPreferredActivity> pprefs = ppir != null 3119 ? ppir.queryIntent(intent, resolvedType, 3120 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3121 : null; 3122 if (pprefs != null && pprefs.size() > 0) { 3123 final int M = pprefs.size(); 3124 for (int i=0; i<M; i++) { 3125 final PersistentPreferredActivity ppa = pprefs.get(i); 3126 if (DEBUG_PREFERRED || debug) { 3127 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3128 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3129 + "\n component=" + ppa.mComponent); 3130 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3131 } 3132 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3133 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3134 if (DEBUG_PREFERRED || debug) { 3135 Slog.v(TAG, "Found persistent preferred activity:"); 3136 if (ai != null) { 3137 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3138 } else { 3139 Slog.v(TAG, " null"); 3140 } 3141 } 3142 if (ai == null) { 3143 // This previously registered persistent preferred activity 3144 // component is no longer known. Ignore it and do NOT remove it. 3145 continue; 3146 } 3147 for (int j=0; j<N; j++) { 3148 final ResolveInfo ri = query.get(j); 3149 if (!ri.activityInfo.applicationInfo.packageName 3150 .equals(ai.applicationInfo.packageName)) { 3151 continue; 3152 } 3153 if (!ri.activityInfo.name.equals(ai.name)) { 3154 continue; 3155 } 3156 // Found a persistent preference that can handle the intent. 3157 if (DEBUG_PREFERRED || debug) { 3158 Slog.v(TAG, "Returning persistent preferred activity: " + 3159 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3160 } 3161 return ri; 3162 } 3163 } 3164 } 3165 return null; 3166 } 3167 3168 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 3169 List<ResolveInfo> query, int priority, boolean always, 3170 boolean removeMatches, boolean debug, int userId) { 3171 if (!sUserManager.exists(userId)) return null; 3172 // writer 3173 synchronized (mPackages) { 3174 if (intent.getSelector() != null) { 3175 intent = intent.getSelector(); 3176 } 3177 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3178 3179 // Try to find a matching persistent preferred activity. 3180 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 3181 debug, userId); 3182 3183 // If a persistent preferred activity matched, use it. 3184 if (pri != null) { 3185 return pri; 3186 } 3187 3188 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 3189 // Get the list of preferred activities that handle the intent 3190 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3191 List<PreferredActivity> prefs = pir != null 3192 ? pir.queryIntent(intent, resolvedType, 3193 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3194 : null; 3195 if (prefs != null && prefs.size() > 0) { 3196 boolean changed = false; 3197 try { 3198 // First figure out how good the original match set is. 3199 // We will only allow preferred activities that came 3200 // from the same match quality. 3201 int match = 0; 3202 3203 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3204 3205 final int N = query.size(); 3206 for (int j=0; j<N; j++) { 3207 final ResolveInfo ri = query.get(j); 3208 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3209 + ": 0x" + Integer.toHexString(match)); 3210 if (ri.match > match) { 3211 match = ri.match; 3212 } 3213 } 3214 3215 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3216 + Integer.toHexString(match)); 3217 3218 match &= IntentFilter.MATCH_CATEGORY_MASK; 3219 final int M = prefs.size(); 3220 for (int i=0; i<M; i++) { 3221 final PreferredActivity pa = prefs.get(i); 3222 if (DEBUG_PREFERRED || debug) { 3223 Slog.v(TAG, "Checking PreferredActivity ds=" 3224 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3225 + "\n component=" + pa.mPref.mComponent); 3226 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3227 } 3228 if (pa.mPref.mMatch != match) { 3229 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3230 + Integer.toHexString(pa.mPref.mMatch)); 3231 continue; 3232 } 3233 // If it's not an "always" type preferred activity and that's what we're 3234 // looking for, skip it. 3235 if (always && !pa.mPref.mAlways) { 3236 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3237 continue; 3238 } 3239 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3240 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3241 if (DEBUG_PREFERRED || debug) { 3242 Slog.v(TAG, "Found preferred activity:"); 3243 if (ai != null) { 3244 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3245 } else { 3246 Slog.v(TAG, " null"); 3247 } 3248 } 3249 if (ai == null) { 3250 // This previously registered preferred activity 3251 // component is no longer known. Most likely an update 3252 // to the app was installed and in the new version this 3253 // component no longer exists. Clean it up by removing 3254 // it from the preferred activities list, and skip it. 3255 Slog.w(TAG, "Removing dangling preferred activity: " 3256 + pa.mPref.mComponent); 3257 pir.removeFilter(pa); 3258 changed = true; 3259 continue; 3260 } 3261 for (int j=0; j<N; j++) { 3262 final ResolveInfo ri = query.get(j); 3263 if (!ri.activityInfo.applicationInfo.packageName 3264 .equals(ai.applicationInfo.packageName)) { 3265 continue; 3266 } 3267 if (!ri.activityInfo.name.equals(ai.name)) { 3268 continue; 3269 } 3270 3271 if (removeMatches) { 3272 pir.removeFilter(pa); 3273 changed = true; 3274 if (DEBUG_PREFERRED) { 3275 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3276 } 3277 break; 3278 } 3279 3280 // Okay we found a previously set preferred or last chosen app. 3281 // If the result set is different from when this 3282 // was created, we need to clear it and re-ask the 3283 // user their preference, if we're looking for an "always" type entry. 3284 if (always && !pa.mPref.sameSet(query, priority)) { 3285 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3286 + intent + " type " + resolvedType); 3287 if (DEBUG_PREFERRED) { 3288 Slog.v(TAG, "Removing preferred activity since set changed " 3289 + pa.mPref.mComponent); 3290 } 3291 pir.removeFilter(pa); 3292 // Re-add the filter as a "last chosen" entry (!always) 3293 PreferredActivity lastChosen = new PreferredActivity( 3294 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3295 pir.addFilter(lastChosen); 3296 changed = true; 3297 return null; 3298 } 3299 3300 // Yay! Either the set matched or we're looking for the last chosen 3301 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3302 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3303 return ri; 3304 } 3305 } 3306 } finally { 3307 if (changed) { 3308 if (DEBUG_PREFERRED) { 3309 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 3310 } 3311 scheduleWritePackageRestrictionsLocked(userId); 3312 } 3313 } 3314 } 3315 } 3316 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3317 return null; 3318 } 3319 3320 /* 3321 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 3322 */ 3323 @Override 3324 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 3325 int targetUserId) { 3326 mContext.enforceCallingOrSelfPermission( 3327 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3328 List<CrossProfileIntentFilter> matches = 3329 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 3330 if (matches != null) { 3331 int size = matches.size(); 3332 for (int i = 0; i < size; i++) { 3333 if (matches.get(i).getTargetUserId() == targetUserId) return true; 3334 } 3335 } 3336 return false; 3337 } 3338 3339 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 3340 String resolvedType, int userId) { 3341 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 3342 if (resolver != null) { 3343 return resolver.queryIntent(intent, resolvedType, false, userId); 3344 } 3345 return null; 3346 } 3347 3348 @Override 3349 public List<ResolveInfo> queryIntentActivities(Intent intent, 3350 String resolvedType, int flags, int userId) { 3351 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3352 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities"); 3353 ComponentName comp = intent.getComponent(); 3354 if (comp == null) { 3355 if (intent.getSelector() != null) { 3356 intent = intent.getSelector(); 3357 comp = intent.getComponent(); 3358 } 3359 } 3360 3361 if (comp != null) { 3362 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3363 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3364 if (ai != null) { 3365 final ResolveInfo ri = new ResolveInfo(); 3366 ri.activityInfo = ai; 3367 list.add(ri); 3368 } 3369 return list; 3370 } 3371 3372 // reader 3373 synchronized (mPackages) { 3374 final String pkgName = intent.getPackage(); 3375 if (pkgName == null) { 3376 List<CrossProfileIntentFilter> matchingFilters = 3377 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 3378 // Check for results that need to skip the current profile. 3379 ResolveInfo resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 3380 resolvedType, flags, userId); 3381 if (resolveInfo != null) { 3382 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 3383 result.add(resolveInfo); 3384 return filterIfNotPrimaryUser(result, userId); 3385 } 3386 // Check for cross profile results. 3387 resolveInfo = queryCrossProfileIntents( 3388 matchingFilters, intent, resolvedType, flags, userId); 3389 3390 // Check for results in the current profile. 3391 List<ResolveInfo> result = mActivities.queryIntent( 3392 intent, resolvedType, flags, userId); 3393 if (resolveInfo != null) { 3394 result.add(resolveInfo); 3395 Collections.sort(result, mResolvePrioritySorter); 3396 } 3397 return filterIfNotPrimaryUser(result, userId); 3398 } 3399 final PackageParser.Package pkg = mPackages.get(pkgName); 3400 if (pkg != null) { 3401 return filterIfNotPrimaryUser( 3402 mActivities.queryIntentForPackage( 3403 intent, resolvedType, flags, pkg.activities, userId), 3404 userId); 3405 } 3406 return new ArrayList<ResolveInfo>(); 3407 } 3408 } 3409 3410 /** 3411 * Filter out activities with primaryUserOnly flag set, when current user is not the owner. 3412 * 3413 * @return filtered list 3414 */ 3415 private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) { 3416 if (userId == UserHandle.USER_OWNER) { 3417 return resolveInfos; 3418 } 3419 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 3420 ResolveInfo info = resolveInfos.get(i); 3421 if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 3422 resolveInfos.remove(i); 3423 } 3424 } 3425 return resolveInfos; 3426 } 3427 3428 3429 private ResolveInfo querySkipCurrentProfileIntents( 3430 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3431 int flags, int sourceUserId) { 3432 if (matchingFilters != null) { 3433 int size = matchingFilters.size(); 3434 for (int i = 0; i < size; i ++) { 3435 CrossProfileIntentFilter filter = matchingFilters.get(i); 3436 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 3437 // Checking if there are activities in the target user that can handle the 3438 // intent. 3439 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3440 flags, sourceUserId); 3441 if (resolveInfo != null) { 3442 return resolveInfo; 3443 } 3444 } 3445 } 3446 } 3447 return null; 3448 } 3449 3450 // Return matching ResolveInfo if any for skip current profile intent filters. 3451 private ResolveInfo queryCrossProfileIntents( 3452 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 3453 int flags, int sourceUserId) { 3454 if (matchingFilters != null) { 3455 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 3456 // match the same intent. For performance reasons, it is better not to 3457 // run queryIntent twice for the same userId 3458 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 3459 int size = matchingFilters.size(); 3460 for (int i = 0; i < size; i++) { 3461 CrossProfileIntentFilter filter = matchingFilters.get(i); 3462 int targetUserId = filter.getTargetUserId(); 3463 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0 3464 && !alreadyTriedUserIds.get(targetUserId)) { 3465 // Checking if there are activities in the target user that can handle the 3466 // intent. 3467 ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType, 3468 flags, sourceUserId); 3469 if (resolveInfo != null) return resolveInfo; 3470 alreadyTriedUserIds.put(targetUserId, true); 3471 } 3472 } 3473 } 3474 return null; 3475 } 3476 3477 private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent, 3478 String resolvedType, int flags, int sourceUserId) { 3479 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 3480 resolvedType, flags, filter.getTargetUserId()); 3481 if (resultTargetUser != null && !resultTargetUser.isEmpty()) { 3482 return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId()); 3483 } 3484 return null; 3485 } 3486 3487 private ResolveInfo createForwardingResolveInfo(IntentFilter filter, 3488 int sourceUserId, int targetUserId) { 3489 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 3490 String className; 3491 if (targetUserId == UserHandle.USER_OWNER) { 3492 className = FORWARD_INTENT_TO_USER_OWNER; 3493 } else { 3494 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 3495 } 3496 ComponentName forwardingActivityComponentName = new ComponentName( 3497 mAndroidApplication.packageName, className); 3498 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 3499 sourceUserId); 3500 if (targetUserId == UserHandle.USER_OWNER) { 3501 forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER; 3502 forwardingResolveInfo.noResourceId = true; 3503 } 3504 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 3505 forwardingResolveInfo.priority = 0; 3506 forwardingResolveInfo.preferredOrder = 0; 3507 forwardingResolveInfo.match = 0; 3508 forwardingResolveInfo.isDefault = true; 3509 forwardingResolveInfo.filter = filter; 3510 forwardingResolveInfo.targetUserId = targetUserId; 3511 return forwardingResolveInfo; 3512 } 3513 3514 @Override 3515 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 3516 Intent[] specifics, String[] specificTypes, Intent intent, 3517 String resolvedType, int flags, int userId) { 3518 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3519 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 3520 false, "query intent activity options"); 3521 final String resultsAction = intent.getAction(); 3522 3523 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 3524 | PackageManager.GET_RESOLVED_FILTER, userId); 3525 3526 if (DEBUG_INTENT_MATCHING) { 3527 Log.v(TAG, "Query " + intent + ": " + results); 3528 } 3529 3530 int specificsPos = 0; 3531 int N; 3532 3533 // todo: note that the algorithm used here is O(N^2). This 3534 // isn't a problem in our current environment, but if we start running 3535 // into situations where we have more than 5 or 10 matches then this 3536 // should probably be changed to something smarter... 3537 3538 // First we go through and resolve each of the specific items 3539 // that were supplied, taking care of removing any corresponding 3540 // duplicate items in the generic resolve list. 3541 if (specifics != null) { 3542 for (int i=0; i<specifics.length; i++) { 3543 final Intent sintent = specifics[i]; 3544 if (sintent == null) { 3545 continue; 3546 } 3547 3548 if (DEBUG_INTENT_MATCHING) { 3549 Log.v(TAG, "Specific #" + i + ": " + sintent); 3550 } 3551 3552 String action = sintent.getAction(); 3553 if (resultsAction != null && resultsAction.equals(action)) { 3554 // If this action was explicitly requested, then don't 3555 // remove things that have it. 3556 action = null; 3557 } 3558 3559 ResolveInfo ri = null; 3560 ActivityInfo ai = null; 3561 3562 ComponentName comp = sintent.getComponent(); 3563 if (comp == null) { 3564 ri = resolveIntent( 3565 sintent, 3566 specificTypes != null ? specificTypes[i] : null, 3567 flags, userId); 3568 if (ri == null) { 3569 continue; 3570 } 3571 if (ri == mResolveInfo) { 3572 // ACK! Must do something better with this. 3573 } 3574 ai = ri.activityInfo; 3575 comp = new ComponentName(ai.applicationInfo.packageName, 3576 ai.name); 3577 } else { 3578 ai = getActivityInfo(comp, flags, userId); 3579 if (ai == null) { 3580 continue; 3581 } 3582 } 3583 3584 // Look for any generic query activities that are duplicates 3585 // of this specific one, and remove them from the results. 3586 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 3587 N = results.size(); 3588 int j; 3589 for (j=specificsPos; j<N; j++) { 3590 ResolveInfo sri = results.get(j); 3591 if ((sri.activityInfo.name.equals(comp.getClassName()) 3592 && sri.activityInfo.applicationInfo.packageName.equals( 3593 comp.getPackageName())) 3594 || (action != null && sri.filter.matchAction(action))) { 3595 results.remove(j); 3596 if (DEBUG_INTENT_MATCHING) Log.v( 3597 TAG, "Removing duplicate item from " + j 3598 + " due to specific " + specificsPos); 3599 if (ri == null) { 3600 ri = sri; 3601 } 3602 j--; 3603 N--; 3604 } 3605 } 3606 3607 // Add this specific item to its proper place. 3608 if (ri == null) { 3609 ri = new ResolveInfo(); 3610 ri.activityInfo = ai; 3611 } 3612 results.add(specificsPos, ri); 3613 ri.specificIndex = i; 3614 specificsPos++; 3615 } 3616 } 3617 3618 // Now we go through the remaining generic results and remove any 3619 // duplicate actions that are found here. 3620 N = results.size(); 3621 for (int i=specificsPos; i<N-1; i++) { 3622 final ResolveInfo rii = results.get(i); 3623 if (rii.filter == null) { 3624 continue; 3625 } 3626 3627 // Iterate over all of the actions of this result's intent 3628 // filter... typically this should be just one. 3629 final Iterator<String> it = rii.filter.actionsIterator(); 3630 if (it == null) { 3631 continue; 3632 } 3633 while (it.hasNext()) { 3634 final String action = it.next(); 3635 if (resultsAction != null && resultsAction.equals(action)) { 3636 // If this action was explicitly requested, then don't 3637 // remove things that have it. 3638 continue; 3639 } 3640 for (int j=i+1; j<N; j++) { 3641 final ResolveInfo rij = results.get(j); 3642 if (rij.filter != null && rij.filter.hasAction(action)) { 3643 results.remove(j); 3644 if (DEBUG_INTENT_MATCHING) Log.v( 3645 TAG, "Removing duplicate item from " + j 3646 + " due to action " + action + " at " + i); 3647 j--; 3648 N--; 3649 } 3650 } 3651 } 3652 3653 // If the caller didn't request filter information, drop it now 3654 // so we don't have to marshall/unmarshall it. 3655 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3656 rii.filter = null; 3657 } 3658 } 3659 3660 // Filter out the caller activity if so requested. 3661 if (caller != null) { 3662 N = results.size(); 3663 for (int i=0; i<N; i++) { 3664 ActivityInfo ainfo = results.get(i).activityInfo; 3665 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 3666 && caller.getClassName().equals(ainfo.name)) { 3667 results.remove(i); 3668 break; 3669 } 3670 } 3671 } 3672 3673 // If the caller didn't request filter information, 3674 // drop them now so we don't have to 3675 // marshall/unmarshall it. 3676 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3677 N = results.size(); 3678 for (int i=0; i<N; i++) { 3679 results.get(i).filter = null; 3680 } 3681 } 3682 3683 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 3684 return results; 3685 } 3686 3687 @Override 3688 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 3689 int userId) { 3690 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3691 ComponentName comp = intent.getComponent(); 3692 if (comp == null) { 3693 if (intent.getSelector() != null) { 3694 intent = intent.getSelector(); 3695 comp = intent.getComponent(); 3696 } 3697 } 3698 if (comp != null) { 3699 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3700 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 3701 if (ai != null) { 3702 ResolveInfo ri = new ResolveInfo(); 3703 ri.activityInfo = ai; 3704 list.add(ri); 3705 } 3706 return list; 3707 } 3708 3709 // reader 3710 synchronized (mPackages) { 3711 String pkgName = intent.getPackage(); 3712 if (pkgName == null) { 3713 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 3714 } 3715 final PackageParser.Package pkg = mPackages.get(pkgName); 3716 if (pkg != null) { 3717 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 3718 userId); 3719 } 3720 return null; 3721 } 3722 } 3723 3724 @Override 3725 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 3726 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 3727 if (!sUserManager.exists(userId)) return null; 3728 if (query != null) { 3729 if (query.size() >= 1) { 3730 // If there is more than one service with the same priority, 3731 // just arbitrarily pick the first one. 3732 return query.get(0); 3733 } 3734 } 3735 return null; 3736 } 3737 3738 @Override 3739 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 3740 int userId) { 3741 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3742 ComponentName comp = intent.getComponent(); 3743 if (comp == null) { 3744 if (intent.getSelector() != null) { 3745 intent = intent.getSelector(); 3746 comp = intent.getComponent(); 3747 } 3748 } 3749 if (comp != null) { 3750 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3751 final ServiceInfo si = getServiceInfo(comp, flags, userId); 3752 if (si != null) { 3753 final ResolveInfo ri = new ResolveInfo(); 3754 ri.serviceInfo = si; 3755 list.add(ri); 3756 } 3757 return list; 3758 } 3759 3760 // reader 3761 synchronized (mPackages) { 3762 String pkgName = intent.getPackage(); 3763 if (pkgName == null) { 3764 return mServices.queryIntent(intent, resolvedType, flags, userId); 3765 } 3766 final PackageParser.Package pkg = mPackages.get(pkgName); 3767 if (pkg != null) { 3768 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 3769 userId); 3770 } 3771 return null; 3772 } 3773 } 3774 3775 @Override 3776 public List<ResolveInfo> queryIntentContentProviders( 3777 Intent intent, String resolvedType, int flags, int userId) { 3778 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3779 ComponentName comp = intent.getComponent(); 3780 if (comp == null) { 3781 if (intent.getSelector() != null) { 3782 intent = intent.getSelector(); 3783 comp = intent.getComponent(); 3784 } 3785 } 3786 if (comp != null) { 3787 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3788 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 3789 if (pi != null) { 3790 final ResolveInfo ri = new ResolveInfo(); 3791 ri.providerInfo = pi; 3792 list.add(ri); 3793 } 3794 return list; 3795 } 3796 3797 // reader 3798 synchronized (mPackages) { 3799 String pkgName = intent.getPackage(); 3800 if (pkgName == null) { 3801 return mProviders.queryIntent(intent, resolvedType, flags, userId); 3802 } 3803 final PackageParser.Package pkg = mPackages.get(pkgName); 3804 if (pkg != null) { 3805 return mProviders.queryIntentForPackage( 3806 intent, resolvedType, flags, pkg.providers, userId); 3807 } 3808 return null; 3809 } 3810 } 3811 3812 @Override 3813 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 3814 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3815 3816 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages"); 3817 3818 // writer 3819 synchronized (mPackages) { 3820 ArrayList<PackageInfo> list; 3821 if (listUninstalled) { 3822 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 3823 for (PackageSetting ps : mSettings.mPackages.values()) { 3824 PackageInfo pi; 3825 if (ps.pkg != null) { 3826 pi = generatePackageInfo(ps.pkg, flags, userId); 3827 } else { 3828 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3829 } 3830 if (pi != null) { 3831 list.add(pi); 3832 } 3833 } 3834 } else { 3835 list = new ArrayList<PackageInfo>(mPackages.size()); 3836 for (PackageParser.Package p : mPackages.values()) { 3837 PackageInfo pi = generatePackageInfo(p, flags, userId); 3838 if (pi != null) { 3839 list.add(pi); 3840 } 3841 } 3842 } 3843 3844 return new ParceledListSlice<PackageInfo>(list); 3845 } 3846 } 3847 3848 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 3849 String[] permissions, boolean[] tmp, int flags, int userId) { 3850 int numMatch = 0; 3851 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 3852 for (int i=0; i<permissions.length; i++) { 3853 if (gp.grantedPermissions.contains(permissions[i])) { 3854 tmp[i] = true; 3855 numMatch++; 3856 } else { 3857 tmp[i] = false; 3858 } 3859 } 3860 if (numMatch == 0) { 3861 return; 3862 } 3863 PackageInfo pi; 3864 if (ps.pkg != null) { 3865 pi = generatePackageInfo(ps.pkg, flags, userId); 3866 } else { 3867 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3868 } 3869 // The above might return null in cases of uninstalled apps or install-state 3870 // skew across users/profiles. 3871 if (pi != null) { 3872 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 3873 if (numMatch == permissions.length) { 3874 pi.requestedPermissions = permissions; 3875 } else { 3876 pi.requestedPermissions = new String[numMatch]; 3877 numMatch = 0; 3878 for (int i=0; i<permissions.length; i++) { 3879 if (tmp[i]) { 3880 pi.requestedPermissions[numMatch] = permissions[i]; 3881 numMatch++; 3882 } 3883 } 3884 } 3885 } 3886 list.add(pi); 3887 } 3888 } 3889 3890 @Override 3891 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 3892 String[] permissions, int flags, int userId) { 3893 if (!sUserManager.exists(userId)) return null; 3894 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3895 3896 // writer 3897 synchronized (mPackages) { 3898 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 3899 boolean[] tmpBools = new boolean[permissions.length]; 3900 if (listUninstalled) { 3901 for (PackageSetting ps : mSettings.mPackages.values()) { 3902 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 3903 } 3904 } else { 3905 for (PackageParser.Package pkg : mPackages.values()) { 3906 PackageSetting ps = (PackageSetting)pkg.mExtras; 3907 if (ps != null) { 3908 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 3909 userId); 3910 } 3911 } 3912 } 3913 3914 return new ParceledListSlice<PackageInfo>(list); 3915 } 3916 } 3917 3918 @Override 3919 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 3920 if (!sUserManager.exists(userId)) return null; 3921 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3922 3923 // writer 3924 synchronized (mPackages) { 3925 ArrayList<ApplicationInfo> list; 3926 if (listUninstalled) { 3927 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 3928 for (PackageSetting ps : mSettings.mPackages.values()) { 3929 ApplicationInfo ai; 3930 if (ps.pkg != null) { 3931 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3932 ps.readUserState(userId), userId); 3933 } else { 3934 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 3935 } 3936 if (ai != null) { 3937 list.add(ai); 3938 } 3939 } 3940 } else { 3941 list = new ArrayList<ApplicationInfo>(mPackages.size()); 3942 for (PackageParser.Package p : mPackages.values()) { 3943 if (p.mExtras != null) { 3944 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3945 ((PackageSetting)p.mExtras).readUserState(userId), userId); 3946 if (ai != null) { 3947 list.add(ai); 3948 } 3949 } 3950 } 3951 } 3952 3953 return new ParceledListSlice<ApplicationInfo>(list); 3954 } 3955 } 3956 3957 public List<ApplicationInfo> getPersistentApplications(int flags) { 3958 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 3959 3960 // reader 3961 synchronized (mPackages) { 3962 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 3963 final int userId = UserHandle.getCallingUserId(); 3964 while (i.hasNext()) { 3965 final PackageParser.Package p = i.next(); 3966 if (p.applicationInfo != null 3967 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 3968 && (!mSafeMode || isSystemApp(p))) { 3969 PackageSetting ps = mSettings.mPackages.get(p.packageName); 3970 if (ps != null) { 3971 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3972 ps.readUserState(userId), userId); 3973 if (ai != null) { 3974 finalList.add(ai); 3975 } 3976 } 3977 } 3978 } 3979 } 3980 3981 return finalList; 3982 } 3983 3984 @Override 3985 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 3986 if (!sUserManager.exists(userId)) return null; 3987 // reader 3988 synchronized (mPackages) { 3989 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 3990 PackageSetting ps = provider != null 3991 ? mSettings.mPackages.get(provider.owner.packageName) 3992 : null; 3993 return ps != null 3994 && mSettings.isEnabledLPr(provider.info, flags, userId) 3995 && (!mSafeMode || (provider.info.applicationInfo.flags 3996 &ApplicationInfo.FLAG_SYSTEM) != 0) 3997 ? PackageParser.generateProviderInfo(provider, flags, 3998 ps.readUserState(userId), userId) 3999 : null; 4000 } 4001 } 4002 4003 /** 4004 * @deprecated 4005 */ 4006 @Deprecated 4007 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 4008 // reader 4009 synchronized (mPackages) { 4010 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 4011 .entrySet().iterator(); 4012 final int userId = UserHandle.getCallingUserId(); 4013 while (i.hasNext()) { 4014 Map.Entry<String, PackageParser.Provider> entry = i.next(); 4015 PackageParser.Provider p = entry.getValue(); 4016 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4017 4018 if (ps != null && p.syncable 4019 && (!mSafeMode || (p.info.applicationInfo.flags 4020 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 4021 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 4022 ps.readUserState(userId), userId); 4023 if (info != null) { 4024 outNames.add(entry.getKey()); 4025 outInfo.add(info); 4026 } 4027 } 4028 } 4029 } 4030 } 4031 4032 @Override 4033 public List<ProviderInfo> queryContentProviders(String processName, 4034 int uid, int flags) { 4035 ArrayList<ProviderInfo> finalList = null; 4036 // reader 4037 synchronized (mPackages) { 4038 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 4039 final int userId = processName != null ? 4040 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 4041 while (i.hasNext()) { 4042 final PackageParser.Provider p = i.next(); 4043 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 4044 if (ps != null && p.info.authority != null 4045 && (processName == null 4046 || (p.info.processName.equals(processName) 4047 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 4048 && mSettings.isEnabledLPr(p.info, flags, userId) 4049 && (!mSafeMode 4050 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 4051 if (finalList == null) { 4052 finalList = new ArrayList<ProviderInfo>(3); 4053 } 4054 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 4055 ps.readUserState(userId), userId); 4056 if (info != null) { 4057 finalList.add(info); 4058 } 4059 } 4060 } 4061 } 4062 4063 if (finalList != null) { 4064 Collections.sort(finalList, mProviderInitOrderSorter); 4065 } 4066 4067 return finalList; 4068 } 4069 4070 @Override 4071 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 4072 int flags) { 4073 // reader 4074 synchronized (mPackages) { 4075 final PackageParser.Instrumentation i = mInstrumentation.get(name); 4076 return PackageParser.generateInstrumentationInfo(i, flags); 4077 } 4078 } 4079 4080 @Override 4081 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 4082 int flags) { 4083 ArrayList<InstrumentationInfo> finalList = 4084 new ArrayList<InstrumentationInfo>(); 4085 4086 // reader 4087 synchronized (mPackages) { 4088 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 4089 while (i.hasNext()) { 4090 final PackageParser.Instrumentation p = i.next(); 4091 if (targetPackage == null 4092 || targetPackage.equals(p.info.targetPackage)) { 4093 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 4094 flags); 4095 if (ii != null) { 4096 finalList.add(ii); 4097 } 4098 } 4099 } 4100 } 4101 4102 return finalList; 4103 } 4104 4105 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 4106 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 4107 if (overlays == null) { 4108 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 4109 return; 4110 } 4111 for (PackageParser.Package opkg : overlays.values()) { 4112 // Not much to do if idmap fails: we already logged the error 4113 // and we certainly don't want to abort installation of pkg simply 4114 // because an overlay didn't fit properly. For these reasons, 4115 // ignore the return value of createIdmapForPackagePairLI. 4116 createIdmapForPackagePairLI(pkg, opkg); 4117 } 4118 } 4119 4120 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 4121 PackageParser.Package opkg) { 4122 if (!opkg.mTrustedOverlay) { 4123 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 4124 opkg.baseCodePath + ": overlay not trusted"); 4125 return false; 4126 } 4127 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 4128 if (overlaySet == null) { 4129 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 4130 opkg.baseCodePath + " but target package has no known overlays"); 4131 return false; 4132 } 4133 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4134 // TODO: generate idmap for split APKs 4135 if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) { 4136 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 4137 + opkg.baseCodePath); 4138 return false; 4139 } 4140 PackageParser.Package[] overlayArray = 4141 overlaySet.values().toArray(new PackageParser.Package[0]); 4142 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 4143 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 4144 return p1.mOverlayPriority - p2.mOverlayPriority; 4145 } 4146 }; 4147 Arrays.sort(overlayArray, cmp); 4148 4149 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 4150 int i = 0; 4151 for (PackageParser.Package p : overlayArray) { 4152 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 4153 } 4154 return true; 4155 } 4156 4157 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 4158 final File[] files = dir.listFiles(); 4159 if (ArrayUtils.isEmpty(files)) { 4160 Log.d(TAG, "No files in app dir " + dir); 4161 return; 4162 } 4163 4164 if (DEBUG_PACKAGE_SCANNING) { 4165 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 4166 + " flags=0x" + Integer.toHexString(parseFlags)); 4167 } 4168 4169 for (File file : files) { 4170 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 4171 && !PackageInstallerService.isStageName(file.getName()); 4172 if (!isPackage) { 4173 // Ignore entries which are not packages 4174 continue; 4175 } 4176 try { 4177 scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 4178 scanFlags, currentTime, null); 4179 } catch (PackageManagerException e) { 4180 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 4181 4182 // Delete invalid userdata apps 4183 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 4184 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 4185 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 4186 if (file.isDirectory()) { 4187 FileUtils.deleteContents(file); 4188 } 4189 file.delete(); 4190 } 4191 } 4192 } 4193 } 4194 4195 private static File getSettingsProblemFile() { 4196 File dataDir = Environment.getDataDirectory(); 4197 File systemDir = new File(dataDir, "system"); 4198 File fname = new File(systemDir, "uiderrors.txt"); 4199 return fname; 4200 } 4201 4202 static void reportSettingsProblem(int priority, String msg) { 4203 logCriticalInfo(priority, msg); 4204 } 4205 4206 static void logCriticalInfo(int priority, String msg) { 4207 Slog.println(priority, TAG, msg); 4208 EventLogTags.writePmCriticalInfo(msg); 4209 try { 4210 File fname = getSettingsProblemFile(); 4211 FileOutputStream out = new FileOutputStream(fname, true); 4212 PrintWriter pw = new FastPrintWriter(out); 4213 SimpleDateFormat formatter = new SimpleDateFormat(); 4214 String dateString = formatter.format(new Date(System.currentTimeMillis())); 4215 pw.println(dateString + ": " + msg); 4216 pw.close(); 4217 FileUtils.setPermissions( 4218 fname.toString(), 4219 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 4220 -1, -1); 4221 } catch (java.io.IOException e) { 4222 } 4223 } 4224 4225 private void collectCertificatesLI(PackageParser pp, PackageSetting ps, 4226 PackageParser.Package pkg, File srcFile, int parseFlags) 4227 throws PackageManagerException { 4228 if (ps != null 4229 && ps.codePath.equals(srcFile) 4230 && ps.timeStamp == srcFile.lastModified() 4231 && !isCompatSignatureUpdateNeeded(pkg) 4232 && !isRecoverSignatureUpdateNeeded(pkg)) { 4233 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 4234 if (ps.signatures.mSignatures != null 4235 && ps.signatures.mSignatures.length != 0 4236 && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) { 4237 // Optimization: reuse the existing cached certificates 4238 // if the package appears to be unchanged. 4239 pkg.mSignatures = ps.signatures.mSignatures; 4240 KeySetManagerService ksms = mSettings.mKeySetManagerService; 4241 synchronized (mPackages) { 4242 pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 4243 } 4244 return; 4245 } 4246 4247 Slog.w(TAG, "PackageSetting for " + ps.name 4248 + " is missing signatures. Collecting certs again to recover them."); 4249 } else { 4250 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 4251 } 4252 4253 try { 4254 pp.collectCertificates(pkg, parseFlags); 4255 pp.collectManifestDigest(pkg); 4256 } catch (PackageParserException e) { 4257 throw PackageManagerException.from(e); 4258 } 4259 } 4260 4261 /* 4262 * Scan a package and return the newly parsed package. 4263 * Returns null in case of errors and the error code is stored in mLastScanError 4264 */ 4265 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 4266 long currentTime, UserHandle user) throws PackageManagerException { 4267 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 4268 parseFlags |= mDefParseFlags; 4269 PackageParser pp = new PackageParser(); 4270 pp.setSeparateProcesses(mSeparateProcesses); 4271 pp.setOnlyCoreApps(mOnlyCore); 4272 pp.setDisplayMetrics(mMetrics); 4273 4274 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 4275 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 4276 } 4277 4278 final PackageParser.Package pkg; 4279 try { 4280 pkg = pp.parsePackage(scanFile, parseFlags); 4281 } catch (PackageParserException e) { 4282 throw PackageManagerException.from(e); 4283 } 4284 4285 PackageSetting ps = null; 4286 PackageSetting updatedPkg; 4287 // reader 4288 synchronized (mPackages) { 4289 // Look to see if we already know about this package. 4290 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 4291 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 4292 // This package has been renamed to its original name. Let's 4293 // use that. 4294 ps = mSettings.peekPackageLPr(oldName); 4295 } 4296 // If there was no original package, see one for the real package name. 4297 if (ps == null) { 4298 ps = mSettings.peekPackageLPr(pkg.packageName); 4299 } 4300 // Check to see if this package could be hiding/updating a system 4301 // package. Must look for it either under the original or real 4302 // package name depending on our state. 4303 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 4304 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 4305 } 4306 boolean updatedPkgBetter = false; 4307 // First check if this is a system package that may involve an update 4308 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4309 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 4310 // it needs to drop FLAG_PRIVILEGED. 4311 if (locationIsPrivileged(scanFile)) { 4312 updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED; 4313 } else { 4314 updatedPkg.pkgFlags &= ~ApplicationInfo.FLAG_PRIVILEGED; 4315 } 4316 4317 if (ps != null && !ps.codePath.equals(scanFile)) { 4318 // The path has changed from what was last scanned... check the 4319 // version of the new path against what we have stored to determine 4320 // what to do. 4321 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 4322 if (pkg.mVersionCode <= ps.versionCode) { 4323 // The system package has been updated and the code path does not match 4324 // Ignore entry. Skip it. 4325 Slog.i(TAG, "Package " + ps.name + " at " + scanFile 4326 + " ignored: updated version " + ps.versionCode 4327 + " better than this " + pkg.mVersionCode); 4328 if (!updatedPkg.codePath.equals(scanFile)) { 4329 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 4330 + ps.name + " changing from " + updatedPkg.codePathString 4331 + " to " + scanFile); 4332 updatedPkg.codePath = scanFile; 4333 updatedPkg.codePathString = scanFile.toString(); 4334 updatedPkg.resourcePath = scanFile; 4335 updatedPkg.resourcePathString = scanFile.toString(); 4336 } 4337 updatedPkg.pkg = pkg; 4338 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null); 4339 } else { 4340 // The current app on the system partition is better than 4341 // what we have updated to on the data partition; switch 4342 // back to the system partition version. 4343 // At this point, its safely assumed that package installation for 4344 // apps in system partition will go through. If not there won't be a working 4345 // version of the app 4346 // writer 4347 synchronized (mPackages) { 4348 // Just remove the loaded entries from package lists. 4349 mPackages.remove(ps.name); 4350 } 4351 4352 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 4353 + " reverting from " + ps.codePathString 4354 + ": new version " + pkg.mVersionCode 4355 + " better than installed " + ps.versionCode); 4356 4357 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4358 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4359 getAppDexInstructionSets(ps)); 4360 synchronized (mInstallLock) { 4361 args.cleanUpResourcesLI(); 4362 } 4363 synchronized (mPackages) { 4364 mSettings.enableSystemPackageLPw(ps.name); 4365 } 4366 updatedPkgBetter = true; 4367 } 4368 } 4369 } 4370 4371 if (updatedPkg != null) { 4372 // An updated system app will not have the PARSE_IS_SYSTEM flag set 4373 // initially 4374 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 4375 4376 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 4377 // flag set initially 4378 if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) { 4379 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 4380 } 4381 } 4382 4383 // Verify certificates against what was last scanned 4384 collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags); 4385 4386 /* 4387 * A new system app appeared, but we already had a non-system one of the 4388 * same name installed earlier. 4389 */ 4390 boolean shouldHideSystemApp = false; 4391 if (updatedPkg == null && ps != null 4392 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4393 /* 4394 * Check to make sure the signatures match first. If they don't, 4395 * wipe the installed application and its data. 4396 */ 4397 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4398 != PackageManager.SIGNATURE_MATCH) { 4399 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 4400 + " signatures don't match existing userdata copy; removing"); 4401 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4402 ps = null; 4403 } else { 4404 /* 4405 * If the newly-added system app is an older version than the 4406 * already installed version, hide it. It will be scanned later 4407 * and re-added like an update. 4408 */ 4409 if (pkg.mVersionCode <= ps.versionCode) { 4410 shouldHideSystemApp = true; 4411 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 4412 + " but new version " + pkg.mVersionCode + " better than installed " 4413 + ps.versionCode + "; hiding system"); 4414 } else { 4415 /* 4416 * The newly found system app is a newer version that the 4417 * one previously installed. Simply remove the 4418 * already-installed application and replace it with our own 4419 * while keeping the application data. 4420 */ 4421 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 4422 + " reverting from " + ps.codePathString + ": new version " 4423 + pkg.mVersionCode + " better than installed " + ps.versionCode); 4424 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 4425 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 4426 getAppDexInstructionSets(ps)); 4427 synchronized (mInstallLock) { 4428 args.cleanUpResourcesLI(); 4429 } 4430 } 4431 } 4432 } 4433 4434 // The apk is forward locked (not public) if its code and resources 4435 // are kept in different files. (except for app in either system or 4436 // vendor path). 4437 // TODO grab this value from PackageSettings 4438 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4439 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4440 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 4441 } 4442 } 4443 4444 // TODO: extend to support forward-locked splits 4445 String resourcePath = null; 4446 String baseResourcePath = null; 4447 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 4448 if (ps != null && ps.resourcePathString != null) { 4449 resourcePath = ps.resourcePathString; 4450 baseResourcePath = ps.resourcePathString; 4451 } else { 4452 // Should not happen at all. Just log an error. 4453 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 4454 } 4455 } else { 4456 resourcePath = pkg.codePath; 4457 baseResourcePath = pkg.baseCodePath; 4458 } 4459 4460 // Set application objects path explicitly. 4461 pkg.applicationInfo.setCodePath(pkg.codePath); 4462 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 4463 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 4464 pkg.applicationInfo.setResourcePath(resourcePath); 4465 pkg.applicationInfo.setBaseResourcePath(baseResourcePath); 4466 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 4467 4468 // Note that we invoke the following method only if we are about to unpack an application 4469 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 4470 | SCAN_UPDATE_SIGNATURE, currentTime, user); 4471 4472 /* 4473 * If the system app should be overridden by a previously installed 4474 * data, hide the system app now and let the /data/app scan pick it up 4475 * again. 4476 */ 4477 if (shouldHideSystemApp) { 4478 synchronized (mPackages) { 4479 /* 4480 * We have to grant systems permissions before we hide, because 4481 * grantPermissions will assume the package update is trying to 4482 * expand its permissions. 4483 */ 4484 grantPermissionsLPw(pkg, true, pkg.packageName); 4485 mSettings.disableSystemPackageLPw(pkg.packageName); 4486 } 4487 } 4488 4489 return scannedPkg; 4490 } 4491 4492 private static String fixProcessName(String defProcessName, 4493 String processName, int uid) { 4494 if (processName == null) { 4495 return defProcessName; 4496 } 4497 return processName; 4498 } 4499 4500 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 4501 throws PackageManagerException { 4502 if (pkgSetting.signatures.mSignatures != null) { 4503 // Already existing package. Make sure signatures match 4504 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 4505 == PackageManager.SIGNATURE_MATCH; 4506 if (!match) { 4507 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 4508 == PackageManager.SIGNATURE_MATCH; 4509 } 4510 if (!match) { 4511 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 4512 == PackageManager.SIGNATURE_MATCH; 4513 } 4514 if (!match) { 4515 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 4516 + pkg.packageName + " signatures do not match the " 4517 + "previously installed version; ignoring!"); 4518 } 4519 } 4520 4521 // Check for shared user signatures 4522 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 4523 // Already existing package. Make sure signatures match 4524 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4525 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 4526 if (!match) { 4527 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 4528 == PackageManager.SIGNATURE_MATCH; 4529 } 4530 if (!match) { 4531 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 4532 == PackageManager.SIGNATURE_MATCH; 4533 } 4534 if (!match) { 4535 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 4536 "Package " + pkg.packageName 4537 + " has no signatures that match those in shared user " 4538 + pkgSetting.sharedUser.name + "; ignoring!"); 4539 } 4540 } 4541 } 4542 4543 /** 4544 * Enforces that only the system UID or root's UID can call a method exposed 4545 * via Binder. 4546 * 4547 * @param message used as message if SecurityException is thrown 4548 * @throws SecurityException if the caller is not system or root 4549 */ 4550 private static final void enforceSystemOrRoot(String message) { 4551 final int uid = Binder.getCallingUid(); 4552 if (uid != Process.SYSTEM_UID && uid != 0) { 4553 throw new SecurityException(message); 4554 } 4555 } 4556 4557 @Override 4558 public void performBootDexOpt() { 4559 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4560 4561 // Before everything else, see whether we need to fstrim. 4562 try { 4563 IMountService ms = PackageHelper.getMountService(); 4564 if (ms != null) { 4565 final boolean isUpgrade = isUpgrade(); 4566 boolean doTrim = isUpgrade; 4567 if (doTrim) { 4568 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 4569 } else { 4570 final long interval = android.provider.Settings.Global.getLong( 4571 mContext.getContentResolver(), 4572 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 4573 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 4574 if (interval > 0) { 4575 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 4576 if (timeSinceLast > interval) { 4577 doTrim = true; 4578 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 4579 + "; running immediately"); 4580 } 4581 } 4582 } 4583 if (doTrim) { 4584 if (!isFirstBoot()) { 4585 try { 4586 ActivityManagerNative.getDefault().showBootMessage( 4587 mContext.getResources().getString( 4588 R.string.android_upgrading_fstrim), true); 4589 } catch (RemoteException e) { 4590 } 4591 } 4592 ms.runMaintenance(); 4593 } 4594 } else { 4595 Slog.e(TAG, "Mount service unavailable!"); 4596 } 4597 } catch (RemoteException e) { 4598 // Can't happen; MountService is local 4599 } 4600 4601 final ArraySet<PackageParser.Package> pkgs; 4602 synchronized (mPackages) { 4603 pkgs = mDeferredDexOpt; 4604 mDeferredDexOpt = null; 4605 } 4606 4607 if (pkgs != null) { 4608 // Sort apps by importance for dexopt ordering. Important apps are given more priority 4609 // in case the device runs out of space. 4610 ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>(); 4611 // Give priority to core apps. 4612 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4613 PackageParser.Package pkg = it.next(); 4614 if (pkg.coreApp) { 4615 if (DEBUG_DEXOPT) { 4616 Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName); 4617 } 4618 sortedPkgs.add(pkg); 4619 it.remove(); 4620 } 4621 } 4622 // Give priority to system apps that listen for pre boot complete. 4623 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 4624 ArraySet<String> pkgNames = getPackageNamesForIntent(intent); 4625 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4626 PackageParser.Package pkg = it.next(); 4627 if (pkgNames.contains(pkg.packageName)) { 4628 if (DEBUG_DEXOPT) { 4629 Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName); 4630 } 4631 sortedPkgs.add(pkg); 4632 it.remove(); 4633 } 4634 } 4635 // Give priority to system apps. 4636 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4637 PackageParser.Package pkg = it.next(); 4638 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 4639 if (DEBUG_DEXOPT) { 4640 Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName); 4641 } 4642 sortedPkgs.add(pkg); 4643 it.remove(); 4644 } 4645 } 4646 // Give priority to updated system apps. 4647 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4648 PackageParser.Package pkg = it.next(); 4649 if (isUpdatedSystemApp(pkg)) { 4650 if (DEBUG_DEXOPT) { 4651 Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName); 4652 } 4653 sortedPkgs.add(pkg); 4654 it.remove(); 4655 } 4656 } 4657 // Give priority to apps that listen for boot complete. 4658 intent = new Intent(Intent.ACTION_BOOT_COMPLETED); 4659 pkgNames = getPackageNamesForIntent(intent); 4660 for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) { 4661 PackageParser.Package pkg = it.next(); 4662 if (pkgNames.contains(pkg.packageName)) { 4663 if (DEBUG_DEXOPT) { 4664 Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName); 4665 } 4666 sortedPkgs.add(pkg); 4667 it.remove(); 4668 } 4669 } 4670 // Filter out packages that aren't recently used. 4671 filterRecentlyUsedApps(pkgs); 4672 // Add all remaining apps. 4673 for (PackageParser.Package pkg : pkgs) { 4674 if (DEBUG_DEXOPT) { 4675 Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName); 4676 } 4677 sortedPkgs.add(pkg); 4678 } 4679 4680 // If we want to be lazy, filter everything that wasn't recently used. 4681 if (mLazyDexOpt) { 4682 filterRecentlyUsedApps(sortedPkgs); 4683 } 4684 4685 int i = 0; 4686 int total = sortedPkgs.size(); 4687 File dataDir = Environment.getDataDirectory(); 4688 long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir); 4689 if (lowThreshold == 0) { 4690 throw new IllegalStateException("Invalid low memory threshold"); 4691 } 4692 for (PackageParser.Package pkg : sortedPkgs) { 4693 long usableSpace = dataDir.getUsableSpace(); 4694 if (usableSpace < lowThreshold) { 4695 Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace); 4696 break; 4697 } 4698 performBootDexOpt(pkg, ++i, total); 4699 } 4700 } 4701 } 4702 4703 private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) { 4704 // Filter out packages that aren't recently used. 4705 // 4706 // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which 4707 // should do a full dexopt. 4708 if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 4709 int total = pkgs.size(); 4710 int skipped = 0; 4711 long now = System.currentTimeMillis(); 4712 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 4713 PackageParser.Package pkg = i.next(); 4714 long then = pkg.mLastPackageUsageTimeInMills; 4715 if (then + mDexOptLRUThresholdInMills < now) { 4716 if (DEBUG_DEXOPT) { 4717 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 4718 ((then == 0) ? "never" : new Date(then))); 4719 } 4720 i.remove(); 4721 skipped++; 4722 } 4723 } 4724 if (DEBUG_DEXOPT) { 4725 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 4726 } 4727 } 4728 } 4729 4730 private ArraySet<String> getPackageNamesForIntent(Intent intent) { 4731 List<ResolveInfo> ris = null; 4732 try { 4733 ris = AppGlobals.getPackageManager().queryIntentReceivers( 4734 intent, null, 0, UserHandle.USER_OWNER); 4735 } catch (RemoteException e) { 4736 } 4737 ArraySet<String> pkgNames = new ArraySet<String>(); 4738 if (ris != null) { 4739 for (ResolveInfo ri : ris) { 4740 pkgNames.add(ri.activityInfo.packageName); 4741 } 4742 } 4743 return pkgNames; 4744 } 4745 4746 private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) { 4747 if (DEBUG_DEXOPT) { 4748 Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName); 4749 } 4750 if (!isFirstBoot()) { 4751 try { 4752 ActivityManagerNative.getDefault().showBootMessage( 4753 mContext.getResources().getString(R.string.android_upgrading_apk, 4754 curr, total), true); 4755 } catch (RemoteException e) { 4756 } 4757 } 4758 PackageParser.Package p = pkg; 4759 synchronized (mInstallLock) { 4760 performDexOptLI(p, null /* instruction sets */, false /* force dex */, 4761 false /* defer */, true /* include dependencies */); 4762 } 4763 } 4764 4765 @Override 4766 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 4767 return performDexOpt(packageName, instructionSet, false); 4768 } 4769 4770 private static String getPrimaryInstructionSet(ApplicationInfo info) { 4771 if (info.primaryCpuAbi == null) { 4772 return getPreferredInstructionSet(); 4773 } 4774 4775 return VMRuntime.getInstructionSet(info.primaryCpuAbi); 4776 } 4777 4778 public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) { 4779 boolean dexopt = mLazyDexOpt || backgroundDexopt; 4780 boolean updateUsage = !backgroundDexopt; // Don't update usage if this is just a backgroundDexopt 4781 if (!dexopt && !updateUsage) { 4782 // We aren't going to dexopt or update usage, so bail early. 4783 return false; 4784 } 4785 PackageParser.Package p; 4786 final String targetInstructionSet; 4787 synchronized (mPackages) { 4788 p = mPackages.get(packageName); 4789 if (p == null) { 4790 return false; 4791 } 4792 if (updateUsage) { 4793 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 4794 } 4795 mPackageUsage.write(false); 4796 if (!dexopt) { 4797 // We aren't going to dexopt, so bail early. 4798 return false; 4799 } 4800 4801 targetInstructionSet = instructionSet != null ? instructionSet : 4802 getPrimaryInstructionSet(p.applicationInfo); 4803 if (p.mDexOptPerformed.contains(targetInstructionSet)) { 4804 return false; 4805 } 4806 } 4807 4808 synchronized (mInstallLock) { 4809 final String[] instructionSets = new String[] { targetInstructionSet }; 4810 return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */, 4811 true /* include dependencies */) == DEX_OPT_PERFORMED; 4812 } 4813 } 4814 4815 public ArraySet<String> getPackagesThatNeedDexOpt() { 4816 ArraySet<String> pkgs = null; 4817 synchronized (mPackages) { 4818 for (PackageParser.Package p : mPackages.values()) { 4819 if (DEBUG_DEXOPT) { 4820 Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray()); 4821 } 4822 if (!p.mDexOptPerformed.isEmpty()) { 4823 continue; 4824 } 4825 if (pkgs == null) { 4826 pkgs = new ArraySet<String>(); 4827 } 4828 pkgs.add(p.packageName); 4829 } 4830 } 4831 return pkgs; 4832 } 4833 4834 public void shutdown() { 4835 mPackageUsage.write(true); 4836 } 4837 4838 private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets, 4839 boolean forceDex, boolean defer, ArraySet<String> done) { 4840 for (int i=0; i<libs.size(); i++) { 4841 PackageParser.Package libPkg; 4842 String libName; 4843 synchronized (mPackages) { 4844 libName = libs.get(i); 4845 SharedLibraryEntry lib = mSharedLibraries.get(libName); 4846 if (lib != null && lib.apk != null) { 4847 libPkg = mPackages.get(lib.apk); 4848 } else { 4849 libPkg = null; 4850 } 4851 } 4852 if (libPkg != null && !done.contains(libName)) { 4853 performDexOptLI(libPkg, instructionSets, forceDex, defer, done); 4854 } 4855 } 4856 } 4857 4858 static final int DEX_OPT_SKIPPED = 0; 4859 static final int DEX_OPT_PERFORMED = 1; 4860 static final int DEX_OPT_DEFERRED = 2; 4861 static final int DEX_OPT_FAILED = -1; 4862 4863 private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets, 4864 boolean forceDex, boolean defer, ArraySet<String> done) { 4865 final String[] instructionSets = targetInstructionSets != null ? 4866 targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo); 4867 4868 if (done != null) { 4869 done.add(pkg.packageName); 4870 if (pkg.usesLibraries != null) { 4871 performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done); 4872 } 4873 if (pkg.usesOptionalLibraries != null) { 4874 performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done); 4875 } 4876 } 4877 4878 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) { 4879 return DEX_OPT_SKIPPED; 4880 } 4881 4882 final boolean vmSafeMode = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0; 4883 4884 final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly(); 4885 boolean performedDexOpt = false; 4886 // There are three basic cases here: 4887 // 1.) we need to dexopt, either because we are forced or it is needed 4888 // 2.) we are defering a needed dexopt 4889 // 3.) we are skipping an unneeded dexopt 4890 final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 4891 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 4892 if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) { 4893 continue; 4894 } 4895 4896 for (String path : paths) { 4897 try { 4898 // This will return DEXOPT_NEEDED if we either cannot find any odex file for this 4899 // patckage or the one we find does not match the image checksum (i.e. it was 4900 // compiled against an old image). It will return PATCHOAT_NEEDED if we can find a 4901 // odex file and it matches the checksum of the image but not its base address, 4902 // meaning we need to move it. 4903 final byte isDexOptNeeded = DexFile.isDexOptNeededInternal(path, 4904 pkg.packageName, dexCodeInstructionSet, defer); 4905 if (forceDex || (!defer && isDexOptNeeded == DexFile.DEXOPT_NEEDED)) { 4906 Log.i(TAG, "Running dexopt on: " + path + " pkg=" 4907 + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet 4908 + " vmSafeMode=" + vmSafeMode); 4909 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4910 final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg), 4911 pkg.packageName, dexCodeInstructionSet, vmSafeMode); 4912 4913 if (ret < 0) { 4914 // Don't bother running dexopt again if we failed, it will probably 4915 // just result in an error again. Also, don't bother dexopting for other 4916 // paths & ISAs. 4917 return DEX_OPT_FAILED; 4918 } 4919 4920 performedDexOpt = true; 4921 } else if (!defer && isDexOptNeeded == DexFile.PATCHOAT_NEEDED) { 4922 Log.i(TAG, "Running patchoat on: " + pkg.applicationInfo.packageName); 4923 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4924 final int ret = mInstaller.patchoat(path, sharedGid, !isForwardLocked(pkg), 4925 pkg.packageName, dexCodeInstructionSet); 4926 4927 if (ret < 0) { 4928 // Don't bother running patchoat again if we failed, it will probably 4929 // just result in an error again. Also, don't bother dexopting for other 4930 // paths & ISAs. 4931 return DEX_OPT_FAILED; 4932 } 4933 4934 performedDexOpt = true; 4935 } 4936 4937 // We're deciding to defer a needed dexopt. Don't bother dexopting for other 4938 // paths and instruction sets. We'll deal with them all together when we process 4939 // our list of deferred dexopts. 4940 if (defer && isDexOptNeeded != DexFile.UP_TO_DATE) { 4941 if (mDeferredDexOpt == null) { 4942 mDeferredDexOpt = new ArraySet<PackageParser.Package>(); 4943 } 4944 mDeferredDexOpt.add(pkg); 4945 return DEX_OPT_DEFERRED; 4946 } 4947 } catch (FileNotFoundException e) { 4948 Slog.w(TAG, "Apk not found for dexopt: " + path); 4949 return DEX_OPT_FAILED; 4950 } catch (IOException e) { 4951 Slog.w(TAG, "IOException reading apk: " + path, e); 4952 return DEX_OPT_FAILED; 4953 } catch (StaleDexCacheError e) { 4954 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e); 4955 return DEX_OPT_FAILED; 4956 } catch (Exception e) { 4957 Slog.w(TAG, "Exception when doing dexopt : ", e); 4958 return DEX_OPT_FAILED; 4959 } 4960 } 4961 4962 // At this point we haven't failed dexopt and we haven't deferred dexopt. We must 4963 // either have either succeeded dexopt, or have had isDexOptNeededInternal tell us 4964 // it isn't required. We therefore mark that this package doesn't need dexopt unless 4965 // it's forced. performedDexOpt will tell us whether we performed dex-opt or skipped 4966 // it. 4967 pkg.mDexOptPerformed.add(dexCodeInstructionSet); 4968 } 4969 4970 // If we've gotten here, we're sure that no error occurred and that we haven't 4971 // deferred dex-opt. We've either dex-opted one more paths or instruction sets or 4972 // we've skipped all of them because they are up to date. In both cases this 4973 // package doesn't need dexopt any longer. 4974 return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED; 4975 } 4976 4977 private static String[] getAppDexInstructionSets(ApplicationInfo info) { 4978 if (info.primaryCpuAbi != null) { 4979 if (info.secondaryCpuAbi != null) { 4980 return new String[] { 4981 VMRuntime.getInstructionSet(info.primaryCpuAbi), 4982 VMRuntime.getInstructionSet(info.secondaryCpuAbi) }; 4983 } else { 4984 return new String[] { 4985 VMRuntime.getInstructionSet(info.primaryCpuAbi) }; 4986 } 4987 } 4988 4989 return new String[] { getPreferredInstructionSet() }; 4990 } 4991 4992 private static String[] getAppDexInstructionSets(PackageSetting ps) { 4993 if (ps.primaryCpuAbiString != null) { 4994 if (ps.secondaryCpuAbiString != null) { 4995 return new String[] { 4996 VMRuntime.getInstructionSet(ps.primaryCpuAbiString), 4997 VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) }; 4998 } else { 4999 return new String[] { 5000 VMRuntime.getInstructionSet(ps.primaryCpuAbiString) }; 5001 } 5002 } 5003 5004 return new String[] { getPreferredInstructionSet() }; 5005 } 5006 5007 private static String getPreferredInstructionSet() { 5008 if (sPreferredInstructionSet == null) { 5009 sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]); 5010 } 5011 5012 return sPreferredInstructionSet; 5013 } 5014 5015 private static List<String> getAllInstructionSets() { 5016 final String[] allAbis = Build.SUPPORTED_ABIS; 5017 final List<String> allInstructionSets = new ArrayList<String>(allAbis.length); 5018 5019 for (String abi : allAbis) { 5020 final String instructionSet = VMRuntime.getInstructionSet(abi); 5021 if (!allInstructionSets.contains(instructionSet)) { 5022 allInstructionSets.add(instructionSet); 5023 } 5024 } 5025 5026 return allInstructionSets; 5027 } 5028 5029 /** 5030 * Returns the instruction set that should be used to compile dex code. In the presence of 5031 * a native bridge this might be different than the one shared libraries use. 5032 */ 5033 private static String getDexCodeInstructionSet(String sharedLibraryIsa) { 5034 String dexCodeIsa = SystemProperties.get("ro.dalvik.vm.isa." + sharedLibraryIsa); 5035 return (dexCodeIsa.isEmpty() ? sharedLibraryIsa : dexCodeIsa); 5036 } 5037 5038 private static String[] getDexCodeInstructionSets(String[] instructionSets) { 5039 ArraySet<String> dexCodeInstructionSets = new ArraySet<String>(instructionSets.length); 5040 for (String instructionSet : instructionSets) { 5041 dexCodeInstructionSets.add(getDexCodeInstructionSet(instructionSet)); 5042 } 5043 return dexCodeInstructionSets.toArray(new String[dexCodeInstructionSets.size()]); 5044 } 5045 5046 /** 5047 * Returns deduplicated list of supported instructions for dex code. 5048 */ 5049 public static String[] getAllDexCodeInstructionSets() { 5050 String[] supportedInstructionSets = new String[Build.SUPPORTED_ABIS.length]; 5051 for (int i = 0; i < supportedInstructionSets.length; i++) { 5052 String abi = Build.SUPPORTED_ABIS[i]; 5053 supportedInstructionSets[i] = VMRuntime.getInstructionSet(abi); 5054 } 5055 return getDexCodeInstructionSets(supportedInstructionSets); 5056 } 5057 5058 @Override 5059 public void forceDexOpt(String packageName) { 5060 enforceSystemOrRoot("forceDexOpt"); 5061 5062 PackageParser.Package pkg; 5063 synchronized (mPackages) { 5064 pkg = mPackages.get(packageName); 5065 if (pkg == null) { 5066 throw new IllegalArgumentException("Missing package: " + packageName); 5067 } 5068 } 5069 5070 synchronized (mInstallLock) { 5071 final String[] instructionSets = new String[] { 5072 getPrimaryInstructionSet(pkg.applicationInfo) }; 5073 final int res = performDexOptLI(pkg, instructionSets, true, false, true); 5074 if (res != DEX_OPT_PERFORMED) { 5075 throw new IllegalStateException("Failed to dexopt: " + res); 5076 } 5077 } 5078 } 5079 5080 private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets, 5081 boolean forceDex, boolean defer, boolean inclDependencies) { 5082 ArraySet<String> done; 5083 if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) { 5084 done = new ArraySet<String>(); 5085 done.add(pkg.packageName); 5086 } else { 5087 done = null; 5088 } 5089 return performDexOptLI(pkg, instructionSets, forceDex, defer, done); 5090 } 5091 5092 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 5093 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 5094 Slog.w(TAG, "Unable to update from " + oldPkg.name 5095 + " to " + newPkg.packageName 5096 + ": old package not in system partition"); 5097 return false; 5098 } else if (mPackages.get(oldPkg.name) != null) { 5099 Slog.w(TAG, "Unable to update from " + oldPkg.name 5100 + " to " + newPkg.packageName 5101 + ": old package still exists"); 5102 return false; 5103 } 5104 return true; 5105 } 5106 5107 File getDataPathForUser(int userId) { 5108 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId); 5109 } 5110 5111 private File getDataPathForPackage(String packageName, int userId) { 5112 /* 5113 * Until we fully support multiple users, return the directory we 5114 * previously would have. The PackageManagerTests will need to be 5115 * revised when this is changed back.. 5116 */ 5117 if (userId == 0) { 5118 return new File(mAppDataDir, packageName); 5119 } else { 5120 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 5121 + File.separator + packageName); 5122 } 5123 } 5124 5125 private int createDataDirsLI(String packageName, int uid, String seinfo) { 5126 int[] users = sUserManager.getUserIds(); 5127 int res = mInstaller.install(packageName, uid, uid, seinfo); 5128 if (res < 0) { 5129 return res; 5130 } 5131 for (int user : users) { 5132 if (user != 0) { 5133 res = mInstaller.createUserData(packageName, 5134 UserHandle.getUid(user, uid), user, seinfo); 5135 if (res < 0) { 5136 return res; 5137 } 5138 } 5139 } 5140 return res; 5141 } 5142 5143 private int removeDataDirsLI(String packageName) { 5144 int[] users = sUserManager.getUserIds(); 5145 int res = 0; 5146 for (int user : users) { 5147 int resInner = mInstaller.remove(packageName, user); 5148 if (resInner < 0) { 5149 res = resInner; 5150 } 5151 } 5152 5153 return res; 5154 } 5155 5156 private int deleteCodeCacheDirsLI(String packageName) { 5157 int[] users = sUserManager.getUserIds(); 5158 int res = 0; 5159 for (int user : users) { 5160 int resInner = mInstaller.deleteCodeCacheFiles(packageName, user); 5161 if (resInner < 0) { 5162 res = resInner; 5163 } 5164 } 5165 return res; 5166 } 5167 5168 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 5169 PackageParser.Package changingLib) { 5170 if (file.path != null) { 5171 usesLibraryFiles.add(file.path); 5172 return; 5173 } 5174 PackageParser.Package p = mPackages.get(file.apk); 5175 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 5176 // If we are doing this while in the middle of updating a library apk, 5177 // then we need to make sure to use that new apk for determining the 5178 // dependencies here. (We haven't yet finished committing the new apk 5179 // to the package manager state.) 5180 if (p == null || p.packageName.equals(changingLib.packageName)) { 5181 p = changingLib; 5182 } 5183 } 5184 if (p != null) { 5185 usesLibraryFiles.addAll(p.getAllCodePaths()); 5186 } 5187 } 5188 5189 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 5190 PackageParser.Package changingLib) throws PackageManagerException { 5191 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 5192 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 5193 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 5194 for (int i=0; i<N; i++) { 5195 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 5196 if (file == null) { 5197 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 5198 "Package " + pkg.packageName + " requires unavailable shared library " 5199 + pkg.usesLibraries.get(i) + "; failing!"); 5200 } 5201 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5202 } 5203 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 5204 for (int i=0; i<N; i++) { 5205 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 5206 if (file == null) { 5207 Slog.w(TAG, "Package " + pkg.packageName 5208 + " desires unavailable shared library " 5209 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 5210 } else { 5211 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 5212 } 5213 } 5214 N = usesLibraryFiles.size(); 5215 if (N > 0) { 5216 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 5217 } else { 5218 pkg.usesLibraryFiles = null; 5219 } 5220 } 5221 } 5222 5223 private static boolean hasString(List<String> list, List<String> which) { 5224 if (list == null) { 5225 return false; 5226 } 5227 for (int i=list.size()-1; i>=0; i--) { 5228 for (int j=which.size()-1; j>=0; j--) { 5229 if (which.get(j).equals(list.get(i))) { 5230 return true; 5231 } 5232 } 5233 } 5234 return false; 5235 } 5236 5237 private void updateAllSharedLibrariesLPw() { 5238 for (PackageParser.Package pkg : mPackages.values()) { 5239 try { 5240 updateSharedLibrariesLPw(pkg, null); 5241 } catch (PackageManagerException e) { 5242 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5243 } 5244 } 5245 } 5246 5247 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 5248 PackageParser.Package changingPkg) { 5249 ArrayList<PackageParser.Package> res = null; 5250 for (PackageParser.Package pkg : mPackages.values()) { 5251 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 5252 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 5253 if (res == null) { 5254 res = new ArrayList<PackageParser.Package>(); 5255 } 5256 res.add(pkg); 5257 try { 5258 updateSharedLibrariesLPw(pkg, changingPkg); 5259 } catch (PackageManagerException e) { 5260 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 5261 } 5262 } 5263 } 5264 return res; 5265 } 5266 5267 /** 5268 * Derive the value of the {@code cpuAbiOverride} based on the provided 5269 * value and an optional stored value from the package settings. 5270 */ 5271 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 5272 String cpuAbiOverride = null; 5273 5274 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 5275 cpuAbiOverride = null; 5276 } else if (abiOverride != null) { 5277 cpuAbiOverride = abiOverride; 5278 } else if (settings != null) { 5279 cpuAbiOverride = settings.cpuAbiOverrideString; 5280 } 5281 5282 return cpuAbiOverride; 5283 } 5284 5285 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 5286 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5287 boolean success = false; 5288 try { 5289 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 5290 currentTime, user); 5291 success = true; 5292 return res; 5293 } finally { 5294 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5295 removeDataDirsLI(pkg.packageName); 5296 } 5297 } 5298 } 5299 5300 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 5301 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 5302 final File scanFile = new File(pkg.codePath); 5303 if (pkg.applicationInfo.getCodePath() == null || 5304 pkg.applicationInfo.getResourcePath() == null) { 5305 // Bail out. The resource and code paths haven't been set. 5306 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 5307 "Code and resource paths haven't been set correctly"); 5308 } 5309 5310 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 5311 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 5312 } else { 5313 // Only allow system apps to be flagged as core apps. 5314 pkg.coreApp = false; 5315 } 5316 5317 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 5318 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED; 5319 } 5320 5321 if (mCustomResolverComponentName != null && 5322 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 5323 setUpCustomResolverActivity(pkg); 5324 } 5325 5326 if (pkg.packageName.equals("android")) { 5327 synchronized (mPackages) { 5328 if (mAndroidApplication != null) { 5329 Slog.w(TAG, "*************************************************"); 5330 Slog.w(TAG, "Core android package being redefined. Skipping."); 5331 Slog.w(TAG, " file=" + scanFile); 5332 Slog.w(TAG, "*************************************************"); 5333 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5334 "Core android package being redefined. Skipping."); 5335 } 5336 5337 // Set up information for our fall-back user intent resolution activity. 5338 mPlatformPackage = pkg; 5339 pkg.mVersionCode = mSdkVersion; 5340 mAndroidApplication = pkg.applicationInfo; 5341 5342 if (!mResolverReplaced) { 5343 mResolveActivity.applicationInfo = mAndroidApplication; 5344 mResolveActivity.name = ResolverActivity.class.getName(); 5345 mResolveActivity.packageName = mAndroidApplication.packageName; 5346 mResolveActivity.processName = "system:ui"; 5347 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5348 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 5349 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 5350 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 5351 mResolveActivity.exported = true; 5352 mResolveActivity.enabled = true; 5353 mResolveInfo.activityInfo = mResolveActivity; 5354 mResolveInfo.priority = 0; 5355 mResolveInfo.preferredOrder = 0; 5356 mResolveInfo.match = 0; 5357 mResolveComponentName = new ComponentName( 5358 mAndroidApplication.packageName, mResolveActivity.name); 5359 } 5360 } 5361 } 5362 5363 if (DEBUG_PACKAGE_SCANNING) { 5364 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5365 Log.d(TAG, "Scanning package " + pkg.packageName); 5366 } 5367 5368 if (mPackages.containsKey(pkg.packageName) 5369 || mSharedLibraries.containsKey(pkg.packageName)) { 5370 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 5371 "Application package " + pkg.packageName 5372 + " already installed. Skipping duplicate."); 5373 } 5374 5375 // Initialize package source and resource directories 5376 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 5377 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 5378 5379 SharedUserSetting suid = null; 5380 PackageSetting pkgSetting = null; 5381 5382 if (!isSystemApp(pkg)) { 5383 // Only system apps can use these features. 5384 pkg.mOriginalPackages = null; 5385 pkg.mRealPackage = null; 5386 pkg.mAdoptPermissions = null; 5387 } 5388 5389 // writer 5390 synchronized (mPackages) { 5391 if (pkg.mSharedUserId != null) { 5392 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true); 5393 if (suid == null) { 5394 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5395 "Creating application package " + pkg.packageName 5396 + " for shared user failed"); 5397 } 5398 if (DEBUG_PACKAGE_SCANNING) { 5399 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5400 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 5401 + "): packages=" + suid.packages); 5402 } 5403 } 5404 5405 // Check if we are renaming from an original package name. 5406 PackageSetting origPackage = null; 5407 String realName = null; 5408 if (pkg.mOriginalPackages != null) { 5409 // This package may need to be renamed to a previously 5410 // installed name. Let's check on that... 5411 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 5412 if (pkg.mOriginalPackages.contains(renamed)) { 5413 // This package had originally been installed as the 5414 // original name, and we have already taken care of 5415 // transitioning to the new one. Just update the new 5416 // one to continue using the old name. 5417 realName = pkg.mRealPackage; 5418 if (!pkg.packageName.equals(renamed)) { 5419 // Callers into this function may have already taken 5420 // care of renaming the package; only do it here if 5421 // it is not already done. 5422 pkg.setPackageName(renamed); 5423 } 5424 5425 } else { 5426 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 5427 if ((origPackage = mSettings.peekPackageLPr( 5428 pkg.mOriginalPackages.get(i))) != null) { 5429 // We do have the package already installed under its 5430 // original name... should we use it? 5431 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 5432 // New package is not compatible with original. 5433 origPackage = null; 5434 continue; 5435 } else if (origPackage.sharedUser != null) { 5436 // Make sure uid is compatible between packages. 5437 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 5438 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 5439 + " to " + pkg.packageName + ": old uid " 5440 + origPackage.sharedUser.name 5441 + " differs from " + pkg.mSharedUserId); 5442 origPackage = null; 5443 continue; 5444 } 5445 } else { 5446 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 5447 + pkg.packageName + " to old name " + origPackage.name); 5448 } 5449 break; 5450 } 5451 } 5452 } 5453 } 5454 5455 if (mTransferedPackages.contains(pkg.packageName)) { 5456 Slog.w(TAG, "Package " + pkg.packageName 5457 + " was transferred to another, but its .apk remains"); 5458 } 5459 5460 // Just create the setting, don't add it yet. For already existing packages 5461 // the PkgSetting exists already and doesn't have to be created. 5462 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 5463 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 5464 pkg.applicationInfo.primaryCpuAbi, 5465 pkg.applicationInfo.secondaryCpuAbi, 5466 pkg.applicationInfo.flags, user, false); 5467 if (pkgSetting == null) { 5468 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5469 "Creating application package " + pkg.packageName + " failed"); 5470 } 5471 5472 if (pkgSetting.origPackage != null) { 5473 // If we are first transitioning from an original package, 5474 // fix up the new package's name now. We need to do this after 5475 // looking up the package under its new name, so getPackageLP 5476 // can take care of fiddling things correctly. 5477 pkg.setPackageName(origPackage.name); 5478 5479 // File a report about this. 5480 String msg = "New package " + pkgSetting.realName 5481 + " renamed to replace old package " + pkgSetting.name; 5482 reportSettingsProblem(Log.WARN, msg); 5483 5484 // Make a note of it. 5485 mTransferedPackages.add(origPackage.name); 5486 5487 // No longer need to retain this. 5488 pkgSetting.origPackage = null; 5489 } 5490 5491 if (realName != null) { 5492 // Make a note of it. 5493 mTransferedPackages.add(pkg.packageName); 5494 } 5495 5496 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 5497 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 5498 } 5499 5500 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5501 // Check all shared libraries and map to their actual file path. 5502 // We only do this here for apps not on a system dir, because those 5503 // are the only ones that can fail an install due to this. We 5504 // will take care of the system apps by updating all of their 5505 // library paths after the scan is done. 5506 updateSharedLibrariesLPw(pkg, null); 5507 } 5508 5509 if (mFoundPolicyFile) { 5510 SELinuxMMAC.assignSeinfoValue(pkg); 5511 } 5512 5513 pkg.applicationInfo.uid = pkgSetting.appId; 5514 pkg.mExtras = pkgSetting; 5515 if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) { 5516 try { 5517 verifySignaturesLP(pkgSetting, pkg); 5518 // We just determined the app is signed correctly, so bring 5519 // over the latest parsed certs. 5520 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5521 } catch (PackageManagerException e) { 5522 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 5523 throw e; 5524 } 5525 // The signature has changed, but this package is in the system 5526 // image... let's recover! 5527 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5528 // However... if this package is part of a shared user, but it 5529 // doesn't match the signature of the shared user, let's fail. 5530 // What this means is that you can't change the signatures 5531 // associated with an overall shared user, which doesn't seem all 5532 // that unreasonable. 5533 if (pkgSetting.sharedUser != null) { 5534 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 5535 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 5536 throw new PackageManagerException( 5537 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 5538 "Signature mismatch for shared user : " 5539 + pkgSetting.sharedUser); 5540 } 5541 } 5542 // File a report about this. 5543 String msg = "System package " + pkg.packageName 5544 + " signature changed; retaining data."; 5545 reportSettingsProblem(Log.WARN, msg); 5546 } 5547 } else { 5548 if (!checkUpgradeKeySetLP(pkgSetting, pkg)) { 5549 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 5550 + pkg.packageName + " upgrade keys do not match the " 5551 + "previously installed version"); 5552 } else { 5553 // We just determined the app is signed correctly, so bring 5554 // over the latest parsed certs. 5555 pkgSetting.signatures.mSignatures = pkg.mSignatures; 5556 } 5557 } 5558 // Verify that this new package doesn't have any content providers 5559 // that conflict with existing packages. Only do this if the 5560 // package isn't already installed, since we don't want to break 5561 // things that are installed. 5562 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 5563 final int N = pkg.providers.size(); 5564 int i; 5565 for (i=0; i<N; i++) { 5566 PackageParser.Provider p = pkg.providers.get(i); 5567 if (p.info.authority != null) { 5568 String names[] = p.info.authority.split(";"); 5569 for (int j = 0; j < names.length; j++) { 5570 if (mProvidersByAuthority.containsKey(names[j])) { 5571 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5572 final String otherPackageName = 5573 ((other != null && other.getComponentName() != null) ? 5574 other.getComponentName().getPackageName() : "?"); 5575 throw new PackageManagerException( 5576 INSTALL_FAILED_CONFLICTING_PROVIDER, 5577 "Can't install because provider name " + names[j] 5578 + " (in package " + pkg.applicationInfo.packageName 5579 + ") is already used by " + otherPackageName); 5580 } 5581 } 5582 } 5583 } 5584 } 5585 5586 if (pkg.mAdoptPermissions != null) { 5587 // This package wants to adopt ownership of permissions from 5588 // another package. 5589 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 5590 final String origName = pkg.mAdoptPermissions.get(i); 5591 final PackageSetting orig = mSettings.peekPackageLPr(origName); 5592 if (orig != null) { 5593 if (verifyPackageUpdateLPr(orig, pkg)) { 5594 Slog.i(TAG, "Adopting permissions from " + origName + " to " 5595 + pkg.packageName); 5596 mSettings.transferPermissionsLPw(origName, pkg.packageName); 5597 } 5598 } 5599 } 5600 } 5601 } 5602 5603 final String pkgName = pkg.packageName; 5604 5605 final long scanFileTime = scanFile.lastModified(); 5606 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 5607 pkg.applicationInfo.processName = fixProcessName( 5608 pkg.applicationInfo.packageName, 5609 pkg.applicationInfo.processName, 5610 pkg.applicationInfo.uid); 5611 5612 File dataPath; 5613 if (mPlatformPackage == pkg) { 5614 // The system package is special. 5615 dataPath = new File(Environment.getDataDirectory(), "system"); 5616 5617 pkg.applicationInfo.dataDir = dataPath.getPath(); 5618 5619 } else { 5620 // This is a normal package, need to make its data directory. 5621 dataPath = getDataPathForPackage(pkg.packageName, 0); 5622 5623 boolean uidError = false; 5624 if (dataPath.exists()) { 5625 int currentUid = 0; 5626 try { 5627 StructStat stat = Os.stat(dataPath.getPath()); 5628 currentUid = stat.st_uid; 5629 } catch (ErrnoException e) { 5630 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 5631 } 5632 5633 // If we have mismatched owners for the data path, we have a problem. 5634 if (currentUid != pkg.applicationInfo.uid) { 5635 boolean recovered = false; 5636 if (currentUid == 0) { 5637 // The directory somehow became owned by root. Wow. 5638 // This is probably because the system was stopped while 5639 // installd was in the middle of messing with its libs 5640 // directory. Ask installd to fix that. 5641 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 5642 pkg.applicationInfo.uid); 5643 if (ret >= 0) { 5644 recovered = true; 5645 String msg = "Package " + pkg.packageName 5646 + " unexpectedly changed to uid 0; recovered to " + 5647 + pkg.applicationInfo.uid; 5648 reportSettingsProblem(Log.WARN, msg); 5649 } 5650 } 5651 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5652 || (scanFlags&SCAN_BOOTING) != 0)) { 5653 // If this is a system app, we can at least delete its 5654 // current data so the application will still work. 5655 int ret = removeDataDirsLI(pkgName); 5656 if (ret >= 0) { 5657 // TODO: Kill the processes first 5658 // Old data gone! 5659 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 5660 ? "System package " : "Third party package "; 5661 String msg = prefix + pkg.packageName 5662 + " has changed from uid: " 5663 + currentUid + " to " 5664 + pkg.applicationInfo.uid + "; old data erased"; 5665 reportSettingsProblem(Log.WARN, msg); 5666 recovered = true; 5667 5668 // And now re-install the app. 5669 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5670 pkg.applicationInfo.seinfo); 5671 if (ret == -1) { 5672 // Ack should not happen! 5673 msg = prefix + pkg.packageName 5674 + " could not have data directory re-created after delete."; 5675 reportSettingsProblem(Log.WARN, msg); 5676 throw new PackageManagerException( 5677 INSTALL_FAILED_INSUFFICIENT_STORAGE, msg); 5678 } 5679 } 5680 if (!recovered) { 5681 mHasSystemUidErrors = true; 5682 } 5683 } else if (!recovered) { 5684 // If we allow this install to proceed, we will be broken. 5685 // Abort, abort! 5686 throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED, 5687 "scanPackageLI"); 5688 } 5689 if (!recovered) { 5690 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 5691 + pkg.applicationInfo.uid + "/fs_" 5692 + currentUid; 5693 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 5694 pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir; 5695 String msg = "Package " + pkg.packageName 5696 + " has mismatched uid: " 5697 + currentUid + " on disk, " 5698 + pkg.applicationInfo.uid + " in settings"; 5699 // writer 5700 synchronized (mPackages) { 5701 mSettings.mReadMessages.append(msg); 5702 mSettings.mReadMessages.append('\n'); 5703 uidError = true; 5704 if (!pkgSetting.uidError) { 5705 reportSettingsProblem(Log.ERROR, msg); 5706 } 5707 } 5708 } 5709 } 5710 pkg.applicationInfo.dataDir = dataPath.getPath(); 5711 if (mShouldRestoreconData) { 5712 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 5713 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 5714 pkg.applicationInfo.uid); 5715 } 5716 } else { 5717 if (DEBUG_PACKAGE_SCANNING) { 5718 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5719 Log.v(TAG, "Want this data dir: " + dataPath); 5720 } 5721 //invoke installer to do the actual installation 5722 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5723 pkg.applicationInfo.seinfo); 5724 if (ret < 0) { 5725 // Error from installer 5726 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 5727 "Unable to create data dirs [errorCode=" + ret + "]"); 5728 } 5729 5730 if (dataPath.exists()) { 5731 pkg.applicationInfo.dataDir = dataPath.getPath(); 5732 } else { 5733 Slog.w(TAG, "Unable to create data directory: " + dataPath); 5734 pkg.applicationInfo.dataDir = null; 5735 } 5736 } 5737 5738 pkgSetting.uidError = uidError; 5739 } 5740 5741 final String path = scanFile.getPath(); 5742 final String codePath = pkg.applicationInfo.getCodePath(); 5743 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 5744 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 5745 setBundledAppAbisAndRoots(pkg, pkgSetting); 5746 5747 // If we haven't found any native libraries for the app, check if it has 5748 // renderscript code. We'll need to force the app to 32 bit if it has 5749 // renderscript bitcode. 5750 if (pkg.applicationInfo.primaryCpuAbi == null 5751 && pkg.applicationInfo.secondaryCpuAbi == null 5752 && Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5753 NativeLibraryHelper.Handle handle = null; 5754 try { 5755 handle = NativeLibraryHelper.Handle.create(scanFile); 5756 if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5757 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 5758 } 5759 } catch (IOException ioe) { 5760 Slog.w(TAG, "Error scanning system app : " + ioe); 5761 } finally { 5762 IoUtils.closeQuietly(handle); 5763 } 5764 } 5765 5766 setNativeLibraryPaths(pkg); 5767 } else { 5768 // TODO: We can probably be smarter about this stuff. For installed apps, 5769 // we can calculate this information at install time once and for all. For 5770 // system apps, we can probably assume that this information doesn't change 5771 // after the first boot scan. As things stand, we do lots of unnecessary work. 5772 5773 // Give ourselves some initial paths; we'll come back for another 5774 // pass once we've determined ABI below. 5775 setNativeLibraryPaths(pkg); 5776 5777 final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg); 5778 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 5779 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 5780 5781 NativeLibraryHelper.Handle handle = null; 5782 try { 5783 handle = NativeLibraryHelper.Handle.create(scanFile); 5784 // TODO(multiArch): This can be null for apps that didn't go through the 5785 // usual installation process. We can calculate it again, like we 5786 // do during install time. 5787 // 5788 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 5789 // unnecessary. 5790 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 5791 5792 // Null out the abis so that they can be recalculated. 5793 pkg.applicationInfo.primaryCpuAbi = null; 5794 pkg.applicationInfo.secondaryCpuAbi = null; 5795 if (isMultiArch(pkg.applicationInfo)) { 5796 // Warn if we've set an abiOverride for multi-lib packages.. 5797 // By definition, we need to copy both 32 and 64 bit libraries for 5798 // such packages. 5799 if (pkg.cpuAbiOverride != null 5800 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 5801 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 5802 } 5803 5804 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 5805 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 5806 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 5807 if (isAsec) { 5808 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 5809 } else { 5810 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5811 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 5812 useIsaSpecificSubdirs); 5813 } 5814 } 5815 5816 maybeThrowExceptionForMultiArchCopy( 5817 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 5818 5819 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 5820 if (isAsec) { 5821 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 5822 } else { 5823 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5824 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 5825 useIsaSpecificSubdirs); 5826 } 5827 } 5828 5829 maybeThrowExceptionForMultiArchCopy( 5830 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 5831 5832 if (abi64 >= 0) { 5833 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 5834 } 5835 5836 if (abi32 >= 0) { 5837 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 5838 if (abi64 >= 0) { 5839 pkg.applicationInfo.secondaryCpuAbi = abi; 5840 } else { 5841 pkg.applicationInfo.primaryCpuAbi = abi; 5842 } 5843 } 5844 } else { 5845 String[] abiList = (cpuAbiOverride != null) ? 5846 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 5847 5848 // Enable gross and lame hacks for apps that are built with old 5849 // SDK tools. We must scan their APKs for renderscript bitcode and 5850 // not launch them if it's present. Don't bother checking on devices 5851 // that don't have 64 bit support. 5852 boolean needsRenderScriptOverride = false; 5853 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 5854 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5855 abiList = Build.SUPPORTED_32_BIT_ABIS; 5856 needsRenderScriptOverride = true; 5857 } 5858 5859 final int copyRet; 5860 if (isAsec) { 5861 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 5862 } else { 5863 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 5864 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 5865 } 5866 5867 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5868 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5869 "Error unpackaging native libs for app, errorCode=" + copyRet); 5870 } 5871 5872 if (copyRet >= 0) { 5873 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 5874 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 5875 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 5876 } else if (needsRenderScriptOverride) { 5877 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 5878 } 5879 } 5880 } catch (IOException ioe) { 5881 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 5882 } finally { 5883 IoUtils.closeQuietly(handle); 5884 } 5885 5886 // Now that we've calculated the ABIs and determined if it's an internal app, 5887 // we will go ahead and populate the nativeLibraryPath. 5888 setNativeLibraryPaths(pkg); 5889 5890 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 5891 final int[] userIds = sUserManager.getUserIds(); 5892 synchronized (mInstallLock) { 5893 // Create a native library symlink only if we have native libraries 5894 // and if the native libraries are 32 bit libraries. We do not provide 5895 // this symlink for 64 bit libraries. 5896 if (pkg.applicationInfo.primaryCpuAbi != null && 5897 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 5898 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 5899 for (int userId : userIds) { 5900 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 5901 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 5902 "Failed linking native library dir (user=" + userId + ")"); 5903 } 5904 } 5905 } 5906 } 5907 } 5908 5909 // This is a special case for the "system" package, where the ABI is 5910 // dictated by the zygote configuration (and init.rc). We should keep track 5911 // of this ABI so that we can deal with "normal" applications that run under 5912 // the same UID correctly. 5913 if (mPlatformPackage == pkg) { 5914 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 5915 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 5916 } 5917 5918 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 5919 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 5920 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 5921 // Copy the derived override back to the parsed package, so that we can 5922 // update the package settings accordingly. 5923 pkg.cpuAbiOverride = cpuAbiOverride; 5924 5925 if (DEBUG_ABI_SELECTION) { 5926 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 5927 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 5928 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 5929 } 5930 5931 // Push the derived path down into PackageSettings so we know what to 5932 // clean up at uninstall time. 5933 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 5934 5935 if (DEBUG_ABI_SELECTION) { 5936 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 5937 " primary=" + pkg.applicationInfo.primaryCpuAbi + 5938 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 5939 } 5940 5941 if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 5942 // We don't do this here during boot because we can do it all 5943 // at once after scanning all existing packages. 5944 // 5945 // We also do this *before* we perform dexopt on this package, so that 5946 // we can avoid redundant dexopts, and also to make sure we've got the 5947 // code and package path correct. 5948 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 5949 pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0); 5950 } 5951 5952 if ((scanFlags & SCAN_NO_DEX) == 0) { 5953 if (performDexOptLI(pkg, null /* instruction sets */, forceDex, 5954 (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) { 5955 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI"); 5956 } 5957 } 5958 5959 if (mFactoryTest && pkg.requestedPermissions.contains( 5960 android.Manifest.permission.FACTORY_TEST)) { 5961 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 5962 } 5963 5964 ArrayList<PackageParser.Package> clientLibPkgs = null; 5965 5966 // writer 5967 synchronized (mPackages) { 5968 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5969 // Only system apps can add new shared libraries. 5970 if (pkg.libraryNames != null) { 5971 for (int i=0; i<pkg.libraryNames.size(); i++) { 5972 String name = pkg.libraryNames.get(i); 5973 boolean allowed = false; 5974 if (isUpdatedSystemApp(pkg)) { 5975 // New library entries can only be added through the 5976 // system image. This is important to get rid of a lot 5977 // of nasty edge cases: for example if we allowed a non- 5978 // system update of the app to add a library, then uninstalling 5979 // the update would make the library go away, and assumptions 5980 // we made such as through app install filtering would now 5981 // have allowed apps on the device which aren't compatible 5982 // with it. Better to just have the restriction here, be 5983 // conservative, and create many fewer cases that can negatively 5984 // impact the user experience. 5985 final PackageSetting sysPs = mSettings 5986 .getDisabledSystemPkgLPr(pkg.packageName); 5987 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 5988 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 5989 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 5990 allowed = true; 5991 allowed = true; 5992 break; 5993 } 5994 } 5995 } 5996 } else { 5997 allowed = true; 5998 } 5999 if (allowed) { 6000 if (!mSharedLibraries.containsKey(name)) { 6001 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 6002 } else if (!name.equals(pkg.packageName)) { 6003 Slog.w(TAG, "Package " + pkg.packageName + " library " 6004 + name + " already exists; skipping"); 6005 } 6006 } else { 6007 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 6008 + name + " that is not declared on system image; skipping"); 6009 } 6010 } 6011 if ((scanFlags&SCAN_BOOTING) == 0) { 6012 // If we are not booting, we need to update any applications 6013 // that are clients of our shared library. If we are booting, 6014 // this will all be done once the scan is complete. 6015 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 6016 } 6017 } 6018 } 6019 } 6020 6021 // We also need to dexopt any apps that are dependent on this library. Note that 6022 // if these fail, we should abort the install since installing the library will 6023 // result in some apps being broken. 6024 if (clientLibPkgs != null) { 6025 if ((scanFlags & SCAN_NO_DEX) == 0) { 6026 for (int i = 0; i < clientLibPkgs.size(); i++) { 6027 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6028 if (performDexOptLI(clientPkg, null /* instruction sets */, forceDex, 6029 (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) { 6030 throw new PackageManagerException(INSTALL_FAILED_DEXOPT, 6031 "scanPackageLI failed to dexopt clientLibPkgs"); 6032 } 6033 } 6034 } 6035 } 6036 6037 // Request the ActivityManager to kill the process(only for existing packages) 6038 // so that we do not end up in a confused state while the user is still using the older 6039 // version of the application while the new one gets installed. 6040 if ((scanFlags & SCAN_REPLACING) != 0) { 6041 killApplication(pkg.applicationInfo.packageName, 6042 pkg.applicationInfo.uid, "update pkg"); 6043 } 6044 6045 // Also need to kill any apps that are dependent on the library. 6046 if (clientLibPkgs != null) { 6047 for (int i=0; i<clientLibPkgs.size(); i++) { 6048 PackageParser.Package clientPkg = clientLibPkgs.get(i); 6049 killApplication(clientPkg.applicationInfo.packageName, 6050 clientPkg.applicationInfo.uid, "update lib"); 6051 } 6052 } 6053 6054 // writer 6055 synchronized (mPackages) { 6056 // We don't expect installation to fail beyond this point 6057 6058 // Add the new setting to mSettings 6059 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 6060 // Add the new setting to mPackages 6061 mPackages.put(pkg.applicationInfo.packageName, pkg); 6062 // Make sure we don't accidentally delete its data. 6063 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 6064 while (iter.hasNext()) { 6065 PackageCleanItem item = iter.next(); 6066 if (pkgName.equals(item.packageName)) { 6067 iter.remove(); 6068 } 6069 } 6070 6071 // Take care of first install / last update times. 6072 if (currentTime != 0) { 6073 if (pkgSetting.firstInstallTime == 0) { 6074 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 6075 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 6076 pkgSetting.lastUpdateTime = currentTime; 6077 } 6078 } else if (pkgSetting.firstInstallTime == 0) { 6079 // We need *something*. Take time time stamp of the file. 6080 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 6081 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 6082 if (scanFileTime != pkgSetting.timeStamp) { 6083 // A package on the system image has changed; consider this 6084 // to be an update. 6085 pkgSetting.lastUpdateTime = scanFileTime; 6086 } 6087 } 6088 6089 // Add the package's KeySets to the global KeySetManagerService 6090 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6091 try { 6092 // Old KeySetData no longer valid. 6093 ksms.removeAppKeySetDataLPw(pkg.packageName); 6094 ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys); 6095 if (pkg.mKeySetMapping != null) { 6096 for (Map.Entry<String, ArraySet<PublicKey>> entry : 6097 pkg.mKeySetMapping.entrySet()) { 6098 if (entry.getValue() != null) { 6099 ksms.addDefinedKeySetToPackageLPw(pkg.packageName, 6100 entry.getValue(), entry.getKey()); 6101 } 6102 } 6103 if (pkg.mUpgradeKeySets != null) { 6104 for (String upgradeAlias : pkg.mUpgradeKeySets) { 6105 ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias); 6106 } 6107 } 6108 } 6109 } catch (NullPointerException e) { 6110 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 6111 } catch (IllegalArgumentException e) { 6112 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 6113 } 6114 6115 int N = pkg.providers.size(); 6116 StringBuilder r = null; 6117 int i; 6118 for (i=0; i<N; i++) { 6119 PackageParser.Provider p = pkg.providers.get(i); 6120 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 6121 p.info.processName, pkg.applicationInfo.uid); 6122 mProviders.addProvider(p); 6123 p.syncable = p.info.isSyncable; 6124 if (p.info.authority != null) { 6125 String names[] = p.info.authority.split(";"); 6126 p.info.authority = null; 6127 for (int j = 0; j < names.length; j++) { 6128 if (j == 1 && p.syncable) { 6129 // We only want the first authority for a provider to possibly be 6130 // syncable, so if we already added this provider using a different 6131 // authority clear the syncable flag. We copy the provider before 6132 // changing it because the mProviders object contains a reference 6133 // to a provider that we don't want to change. 6134 // Only do this for the second authority since the resulting provider 6135 // object can be the same for all future authorities for this provider. 6136 p = new PackageParser.Provider(p); 6137 p.syncable = false; 6138 } 6139 if (!mProvidersByAuthority.containsKey(names[j])) { 6140 mProvidersByAuthority.put(names[j], p); 6141 if (p.info.authority == null) { 6142 p.info.authority = names[j]; 6143 } else { 6144 p.info.authority = p.info.authority + ";" + names[j]; 6145 } 6146 if (DEBUG_PACKAGE_SCANNING) { 6147 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 6148 Log.d(TAG, "Registered content provider: " + names[j] 6149 + ", className = " + p.info.name + ", isSyncable = " 6150 + p.info.isSyncable); 6151 } 6152 } else { 6153 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 6154 Slog.w(TAG, "Skipping provider name " + names[j] + 6155 " (in package " + pkg.applicationInfo.packageName + 6156 "): name already used by " 6157 + ((other != null && other.getComponentName() != null) 6158 ? other.getComponentName().getPackageName() : "?")); 6159 } 6160 } 6161 } 6162 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6163 if (r == null) { 6164 r = new StringBuilder(256); 6165 } else { 6166 r.append(' '); 6167 } 6168 r.append(p.info.name); 6169 } 6170 } 6171 if (r != null) { 6172 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 6173 } 6174 6175 N = pkg.services.size(); 6176 r = null; 6177 for (i=0; i<N; i++) { 6178 PackageParser.Service s = pkg.services.get(i); 6179 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 6180 s.info.processName, pkg.applicationInfo.uid); 6181 mServices.addService(s); 6182 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6183 if (r == null) { 6184 r = new StringBuilder(256); 6185 } else { 6186 r.append(' '); 6187 } 6188 r.append(s.info.name); 6189 } 6190 } 6191 if (r != null) { 6192 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 6193 } 6194 6195 N = pkg.receivers.size(); 6196 r = null; 6197 for (i=0; i<N; i++) { 6198 PackageParser.Activity a = pkg.receivers.get(i); 6199 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6200 a.info.processName, pkg.applicationInfo.uid); 6201 mReceivers.addActivity(a, "receiver"); 6202 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6203 if (r == null) { 6204 r = new StringBuilder(256); 6205 } else { 6206 r.append(' '); 6207 } 6208 r.append(a.info.name); 6209 } 6210 } 6211 if (r != null) { 6212 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 6213 } 6214 6215 N = pkg.activities.size(); 6216 r = null; 6217 for (i=0; i<N; i++) { 6218 PackageParser.Activity a = pkg.activities.get(i); 6219 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 6220 a.info.processName, pkg.applicationInfo.uid); 6221 mActivities.addActivity(a, "activity"); 6222 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6223 if (r == null) { 6224 r = new StringBuilder(256); 6225 } else { 6226 r.append(' '); 6227 } 6228 r.append(a.info.name); 6229 } 6230 } 6231 if (r != null) { 6232 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 6233 } 6234 6235 N = pkg.permissionGroups.size(); 6236 r = null; 6237 for (i=0; i<N; i++) { 6238 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 6239 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 6240 if (cur == null) { 6241 mPermissionGroups.put(pg.info.name, pg); 6242 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6243 if (r == null) { 6244 r = new StringBuilder(256); 6245 } else { 6246 r.append(' '); 6247 } 6248 r.append(pg.info.name); 6249 } 6250 } else { 6251 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 6252 + pg.info.packageName + " ignored: original from " 6253 + cur.info.packageName); 6254 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6255 if (r == null) { 6256 r = new StringBuilder(256); 6257 } else { 6258 r.append(' '); 6259 } 6260 r.append("DUP:"); 6261 r.append(pg.info.name); 6262 } 6263 } 6264 } 6265 if (r != null) { 6266 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 6267 } 6268 6269 N = pkg.permissions.size(); 6270 r = null; 6271 for (i=0; i<N; i++) { 6272 PackageParser.Permission p = pkg.permissions.get(i); 6273 ArrayMap<String, BasePermission> permissionMap = 6274 p.tree ? mSettings.mPermissionTrees 6275 : mSettings.mPermissions; 6276 p.group = mPermissionGroups.get(p.info.group); 6277 if (p.info.group == null || p.group != null) { 6278 BasePermission bp = permissionMap.get(p.info.name); 6279 6280 // Allow system apps to redefine non-system permissions 6281 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 6282 final boolean currentOwnerIsSystem = (bp.perm != null 6283 && isSystemApp(bp.perm.owner)); 6284 if (isSystemApp(p.owner)) { 6285 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 6286 // It's a built-in permission and no owner, take ownership now 6287 bp.packageSetting = pkgSetting; 6288 bp.perm = p; 6289 bp.uid = pkg.applicationInfo.uid; 6290 bp.sourcePackage = p.info.packageName; 6291 } else if (!currentOwnerIsSystem) { 6292 String msg = "New decl " + p.owner + " of permission " 6293 + p.info.name + " is system; overriding " + bp.sourcePackage; 6294 reportSettingsProblem(Log.WARN, msg); 6295 bp = null; 6296 } 6297 } 6298 } 6299 6300 if (bp == null) { 6301 bp = new BasePermission(p.info.name, p.info.packageName, 6302 BasePermission.TYPE_NORMAL); 6303 permissionMap.put(p.info.name, bp); 6304 } 6305 6306 if (bp.perm == null) { 6307 if (bp.sourcePackage == null 6308 || bp.sourcePackage.equals(p.info.packageName)) { 6309 BasePermission tree = findPermissionTreeLP(p.info.name); 6310 if (tree == null 6311 || tree.sourcePackage.equals(p.info.packageName)) { 6312 bp.packageSetting = pkgSetting; 6313 bp.perm = p; 6314 bp.uid = pkg.applicationInfo.uid; 6315 bp.sourcePackage = p.info.packageName; 6316 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6317 if (r == null) { 6318 r = new StringBuilder(256); 6319 } else { 6320 r.append(' '); 6321 } 6322 r.append(p.info.name); 6323 } 6324 } else { 6325 Slog.w(TAG, "Permission " + p.info.name + " from package " 6326 + p.info.packageName + " ignored: base tree " 6327 + tree.name + " is from package " 6328 + tree.sourcePackage); 6329 } 6330 } else { 6331 Slog.w(TAG, "Permission " + p.info.name + " from package " 6332 + p.info.packageName + " ignored: original from " 6333 + bp.sourcePackage); 6334 } 6335 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6336 if (r == null) { 6337 r = new StringBuilder(256); 6338 } else { 6339 r.append(' '); 6340 } 6341 r.append("DUP:"); 6342 r.append(p.info.name); 6343 } 6344 if (bp.perm == p) { 6345 bp.protectionLevel = p.info.protectionLevel; 6346 } 6347 } else { 6348 Slog.w(TAG, "Permission " + p.info.name + " from package " 6349 + p.info.packageName + " ignored: no group " 6350 + p.group); 6351 } 6352 } 6353 if (r != null) { 6354 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 6355 } 6356 6357 N = pkg.instrumentation.size(); 6358 r = null; 6359 for (i=0; i<N; i++) { 6360 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6361 a.info.packageName = pkg.applicationInfo.packageName; 6362 a.info.sourceDir = pkg.applicationInfo.sourceDir; 6363 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 6364 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 6365 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 6366 a.info.dataDir = pkg.applicationInfo.dataDir; 6367 6368 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 6369 // need other information about the application, like the ABI and what not ? 6370 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 6371 mInstrumentation.put(a.getComponentName(), a); 6372 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 6373 if (r == null) { 6374 r = new StringBuilder(256); 6375 } else { 6376 r.append(' '); 6377 } 6378 r.append(a.info.name); 6379 } 6380 } 6381 if (r != null) { 6382 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 6383 } 6384 6385 if (pkg.protectedBroadcasts != null) { 6386 N = pkg.protectedBroadcasts.size(); 6387 for (i=0; i<N; i++) { 6388 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 6389 } 6390 } 6391 6392 pkgSetting.setTimeStamp(scanFileTime); 6393 6394 // Create idmap files for pairs of (packages, overlay packages). 6395 // Note: "android", ie framework-res.apk, is handled by native layers. 6396 if (pkg.mOverlayTarget != null) { 6397 // This is an overlay package. 6398 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 6399 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 6400 mOverlays.put(pkg.mOverlayTarget, 6401 new ArrayMap<String, PackageParser.Package>()); 6402 } 6403 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 6404 map.put(pkg.packageName, pkg); 6405 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 6406 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 6407 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 6408 "scanPackageLI failed to createIdmap"); 6409 } 6410 } 6411 } else if (mOverlays.containsKey(pkg.packageName) && 6412 !pkg.packageName.equals("android")) { 6413 // This is a regular package, with one or more known overlay packages. 6414 createIdmapsForPackageLI(pkg); 6415 } 6416 } 6417 6418 return pkg; 6419 } 6420 6421 /** 6422 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 6423 * i.e, so that all packages can be run inside a single process if required. 6424 * 6425 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 6426 * this function will either try and make the ABI for all packages in {@code packagesForUser} 6427 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 6428 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 6429 * updating a package that belongs to a shared user. 6430 * 6431 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 6432 * adds unnecessary complexity. 6433 */ 6434 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 6435 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 6436 String requiredInstructionSet = null; 6437 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 6438 requiredInstructionSet = VMRuntime.getInstructionSet( 6439 scannedPackage.applicationInfo.primaryCpuAbi); 6440 } 6441 6442 PackageSetting requirer = null; 6443 for (PackageSetting ps : packagesForUser) { 6444 // If packagesForUser contains scannedPackage, we skip it. This will happen 6445 // when scannedPackage is an update of an existing package. Without this check, 6446 // we will never be able to change the ABI of any package belonging to a shared 6447 // user, even if it's compatible with other packages. 6448 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6449 if (ps.primaryCpuAbiString == null) { 6450 continue; 6451 } 6452 6453 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 6454 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 6455 // We have a mismatch between instruction sets (say arm vs arm64) warn about 6456 // this but there's not much we can do. 6457 String errorMessage = "Instruction set mismatch, " 6458 + ((requirer == null) ? "[caller]" : requirer) 6459 + " requires " + requiredInstructionSet + " whereas " + ps 6460 + " requires " + instructionSet; 6461 Slog.w(TAG, errorMessage); 6462 } 6463 6464 if (requiredInstructionSet == null) { 6465 requiredInstructionSet = instructionSet; 6466 requirer = ps; 6467 } 6468 } 6469 } 6470 6471 if (requiredInstructionSet != null) { 6472 String adjustedAbi; 6473 if (requirer != null) { 6474 // requirer != null implies that either scannedPackage was null or that scannedPackage 6475 // did not require an ABI, in which case we have to adjust scannedPackage to match 6476 // the ABI of the set (which is the same as requirer's ABI) 6477 adjustedAbi = requirer.primaryCpuAbiString; 6478 if (scannedPackage != null) { 6479 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 6480 } 6481 } else { 6482 // requirer == null implies that we're updating all ABIs in the set to 6483 // match scannedPackage. 6484 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 6485 } 6486 6487 for (PackageSetting ps : packagesForUser) { 6488 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 6489 if (ps.primaryCpuAbiString != null) { 6490 continue; 6491 } 6492 6493 ps.primaryCpuAbiString = adjustedAbi; 6494 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 6495 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 6496 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 6497 6498 if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt, 6499 deferDexOpt, true) == DEX_OPT_FAILED) { 6500 ps.primaryCpuAbiString = null; 6501 ps.pkg.applicationInfo.primaryCpuAbi = null; 6502 return; 6503 } else { 6504 mInstaller.rmdex(ps.codePathString, 6505 getDexCodeInstructionSet(getPreferredInstructionSet())); 6506 } 6507 } 6508 } 6509 } 6510 } 6511 } 6512 6513 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 6514 synchronized (mPackages) { 6515 mResolverReplaced = true; 6516 // Set up information for custom user intent resolution activity. 6517 mResolveActivity.applicationInfo = pkg.applicationInfo; 6518 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 6519 mResolveActivity.packageName = pkg.applicationInfo.packageName; 6520 mResolveActivity.processName = pkg.applicationInfo.packageName; 6521 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 6522 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 6523 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 6524 mResolveActivity.theme = 0; 6525 mResolveActivity.exported = true; 6526 mResolveActivity.enabled = true; 6527 mResolveInfo.activityInfo = mResolveActivity; 6528 mResolveInfo.priority = 0; 6529 mResolveInfo.preferredOrder = 0; 6530 mResolveInfo.match = 0; 6531 mResolveComponentName = mCustomResolverComponentName; 6532 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 6533 mResolveComponentName); 6534 } 6535 } 6536 6537 private static String calculateBundledApkRoot(final String codePathString) { 6538 final File codePath = new File(codePathString); 6539 final File codeRoot; 6540 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 6541 codeRoot = Environment.getRootDirectory(); 6542 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 6543 codeRoot = Environment.getOemDirectory(); 6544 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 6545 codeRoot = Environment.getVendorDirectory(); 6546 } else { 6547 // Unrecognized code path; take its top real segment as the apk root: 6548 // e.g. /something/app/blah.apk => /something 6549 try { 6550 File f = codePath.getCanonicalFile(); 6551 File parent = f.getParentFile(); // non-null because codePath is a file 6552 File tmp; 6553 while ((tmp = parent.getParentFile()) != null) { 6554 f = parent; 6555 parent = tmp; 6556 } 6557 codeRoot = f; 6558 Slog.w(TAG, "Unrecognized code path " 6559 + codePath + " - using " + codeRoot); 6560 } catch (IOException e) { 6561 // Can't canonicalize the code path -- shenanigans? 6562 Slog.w(TAG, "Can't canonicalize code path " + codePath); 6563 return Environment.getRootDirectory().getPath(); 6564 } 6565 } 6566 return codeRoot.getPath(); 6567 } 6568 6569 /** 6570 * Derive and set the location of native libraries for the given package, 6571 * which varies depending on where and how the package was installed. 6572 */ 6573 private void setNativeLibraryPaths(PackageParser.Package pkg) { 6574 final ApplicationInfo info = pkg.applicationInfo; 6575 final String codePath = pkg.codePath; 6576 final File codeFile = new File(codePath); 6577 final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info); 6578 final boolean asecApp = isForwardLocked(info) || isExternal(info); 6579 6580 info.nativeLibraryRootDir = null; 6581 info.nativeLibraryRootRequiresIsa = false; 6582 info.nativeLibraryDir = null; 6583 info.secondaryNativeLibraryDir = null; 6584 6585 if (isApkFile(codeFile)) { 6586 // Monolithic install 6587 if (bundledApp) { 6588 // If "/system/lib64/apkname" exists, assume that is the per-package 6589 // native library directory to use; otherwise use "/system/lib/apkname". 6590 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 6591 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 6592 getPrimaryInstructionSet(info)); 6593 6594 // This is a bundled system app so choose the path based on the ABI. 6595 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 6596 // is just the default path. 6597 final String apkName = deriveCodePathName(codePath); 6598 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 6599 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 6600 apkName).getAbsolutePath(); 6601 6602 if (info.secondaryCpuAbi != null) { 6603 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 6604 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 6605 secondaryLibDir, apkName).getAbsolutePath(); 6606 } 6607 } else if (asecApp) { 6608 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 6609 .getAbsolutePath(); 6610 } else { 6611 final String apkName = deriveCodePathName(codePath); 6612 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 6613 .getAbsolutePath(); 6614 } 6615 6616 info.nativeLibraryRootRequiresIsa = false; 6617 info.nativeLibraryDir = info.nativeLibraryRootDir; 6618 } else { 6619 // Cluster install 6620 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 6621 info.nativeLibraryRootRequiresIsa = true; 6622 6623 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 6624 getPrimaryInstructionSet(info)).getAbsolutePath(); 6625 6626 if (info.secondaryCpuAbi != null) { 6627 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 6628 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 6629 } 6630 } 6631 } 6632 6633 /** 6634 * Calculate the abis and roots for a bundled app. These can uniquely 6635 * be determined from the contents of the system partition, i.e whether 6636 * it contains 64 or 32 bit shared libraries etc. We do not validate any 6637 * of this information, and instead assume that the system was built 6638 * sensibly. 6639 */ 6640 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 6641 PackageSetting pkgSetting) { 6642 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 6643 6644 // If "/system/lib64/apkname" exists, assume that is the per-package 6645 // native library directory to use; otherwise use "/system/lib/apkname". 6646 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 6647 setBundledAppAbi(pkg, apkRoot, apkName); 6648 // pkgSetting might be null during rescan following uninstall of updates 6649 // to a bundled app, so accommodate that possibility. The settings in 6650 // that case will be established later from the parsed package. 6651 // 6652 // If the settings aren't null, sync them up with what we've just derived. 6653 // note that apkRoot isn't stored in the package settings. 6654 if (pkgSetting != null) { 6655 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 6656 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 6657 } 6658 } 6659 6660 /** 6661 * Deduces the ABI of a bundled app and sets the relevant fields on the 6662 * parsed pkg object. 6663 * 6664 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 6665 * under which system libraries are installed. 6666 * @param apkName the name of the installed package. 6667 */ 6668 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 6669 final File codeFile = new File(pkg.codePath); 6670 6671 final boolean has64BitLibs; 6672 final boolean has32BitLibs; 6673 if (isApkFile(codeFile)) { 6674 // Monolithic install 6675 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 6676 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 6677 } else { 6678 // Cluster install 6679 final File rootDir = new File(codeFile, LIB_DIR_NAME); 6680 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 6681 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 6682 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 6683 has64BitLibs = (new File(rootDir, isa)).exists(); 6684 } else { 6685 has64BitLibs = false; 6686 } 6687 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 6688 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 6689 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 6690 has32BitLibs = (new File(rootDir, isa)).exists(); 6691 } else { 6692 has32BitLibs = false; 6693 } 6694 } 6695 6696 if (has64BitLibs && !has32BitLibs) { 6697 // The package has 64 bit libs, but not 32 bit libs. Its primary 6698 // ABI should be 64 bit. We can safely assume here that the bundled 6699 // native libraries correspond to the most preferred ABI in the list. 6700 6701 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6702 pkg.applicationInfo.secondaryCpuAbi = null; 6703 } else if (has32BitLibs && !has64BitLibs) { 6704 // The package has 32 bit libs but not 64 bit libs. Its primary 6705 // ABI should be 32 bit. 6706 6707 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6708 pkg.applicationInfo.secondaryCpuAbi = null; 6709 } else if (has32BitLibs && has64BitLibs) { 6710 // The application has both 64 and 32 bit bundled libraries. We check 6711 // here that the app declares multiArch support, and warn if it doesn't. 6712 // 6713 // We will be lenient here and record both ABIs. The primary will be the 6714 // ABI that's higher on the list, i.e, a device that's configured to prefer 6715 // 64 bit apps will see a 64 bit primary ABI, 6716 6717 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 6718 Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch."); 6719 } 6720 6721 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 6722 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6723 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6724 } else { 6725 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 6726 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 6727 } 6728 } else { 6729 pkg.applicationInfo.primaryCpuAbi = null; 6730 pkg.applicationInfo.secondaryCpuAbi = null; 6731 } 6732 } 6733 6734 private void killApplication(String pkgName, int appId, String reason) { 6735 // Request the ActivityManager to kill the process(only for existing packages) 6736 // so that we do not end up in a confused state while the user is still using the older 6737 // version of the application while the new one gets installed. 6738 IActivityManager am = ActivityManagerNative.getDefault(); 6739 if (am != null) { 6740 try { 6741 am.killApplicationWithAppId(pkgName, appId, reason); 6742 } catch (RemoteException e) { 6743 } 6744 } 6745 } 6746 6747 void removePackageLI(PackageSetting ps, boolean chatty) { 6748 if (DEBUG_INSTALL) { 6749 if (chatty) 6750 Log.d(TAG, "Removing package " + ps.name); 6751 } 6752 6753 // writer 6754 synchronized (mPackages) { 6755 mPackages.remove(ps.name); 6756 final PackageParser.Package pkg = ps.pkg; 6757 if (pkg != null) { 6758 cleanPackageDataStructuresLILPw(pkg, chatty); 6759 } 6760 } 6761 } 6762 6763 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 6764 if (DEBUG_INSTALL) { 6765 if (chatty) 6766 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 6767 } 6768 6769 // writer 6770 synchronized (mPackages) { 6771 mPackages.remove(pkg.applicationInfo.packageName); 6772 cleanPackageDataStructuresLILPw(pkg, chatty); 6773 } 6774 } 6775 6776 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 6777 int N = pkg.providers.size(); 6778 StringBuilder r = null; 6779 int i; 6780 for (i=0; i<N; i++) { 6781 PackageParser.Provider p = pkg.providers.get(i); 6782 mProviders.removeProvider(p); 6783 if (p.info.authority == null) { 6784 6785 /* There was another ContentProvider with this authority when 6786 * this app was installed so this authority is null, 6787 * Ignore it as we don't have to unregister the provider. 6788 */ 6789 continue; 6790 } 6791 String names[] = p.info.authority.split(";"); 6792 for (int j = 0; j < names.length; j++) { 6793 if (mProvidersByAuthority.get(names[j]) == p) { 6794 mProvidersByAuthority.remove(names[j]); 6795 if (DEBUG_REMOVE) { 6796 if (chatty) 6797 Log.d(TAG, "Unregistered content provider: " + names[j] 6798 + ", className = " + p.info.name + ", isSyncable = " 6799 + p.info.isSyncable); 6800 } 6801 } 6802 } 6803 if (DEBUG_REMOVE && chatty) { 6804 if (r == null) { 6805 r = new StringBuilder(256); 6806 } else { 6807 r.append(' '); 6808 } 6809 r.append(p.info.name); 6810 } 6811 } 6812 if (r != null) { 6813 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 6814 } 6815 6816 N = pkg.services.size(); 6817 r = null; 6818 for (i=0; i<N; i++) { 6819 PackageParser.Service s = pkg.services.get(i); 6820 mServices.removeService(s); 6821 if (chatty) { 6822 if (r == null) { 6823 r = new StringBuilder(256); 6824 } else { 6825 r.append(' '); 6826 } 6827 r.append(s.info.name); 6828 } 6829 } 6830 if (r != null) { 6831 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 6832 } 6833 6834 N = pkg.receivers.size(); 6835 r = null; 6836 for (i=0; i<N; i++) { 6837 PackageParser.Activity a = pkg.receivers.get(i); 6838 mReceivers.removeActivity(a, "receiver"); 6839 if (DEBUG_REMOVE && chatty) { 6840 if (r == null) { 6841 r = new StringBuilder(256); 6842 } else { 6843 r.append(' '); 6844 } 6845 r.append(a.info.name); 6846 } 6847 } 6848 if (r != null) { 6849 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 6850 } 6851 6852 N = pkg.activities.size(); 6853 r = null; 6854 for (i=0; i<N; i++) { 6855 PackageParser.Activity a = pkg.activities.get(i); 6856 mActivities.removeActivity(a, "activity"); 6857 if (DEBUG_REMOVE && chatty) { 6858 if (r == null) { 6859 r = new StringBuilder(256); 6860 } else { 6861 r.append(' '); 6862 } 6863 r.append(a.info.name); 6864 } 6865 } 6866 if (r != null) { 6867 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 6868 } 6869 6870 N = pkg.permissions.size(); 6871 r = null; 6872 for (i=0; i<N; i++) { 6873 PackageParser.Permission p = pkg.permissions.get(i); 6874 BasePermission bp = mSettings.mPermissions.get(p.info.name); 6875 if (bp == null) { 6876 bp = mSettings.mPermissionTrees.get(p.info.name); 6877 } 6878 if (bp != null && bp.perm == p) { 6879 bp.perm = null; 6880 if (DEBUG_REMOVE && chatty) { 6881 if (r == null) { 6882 r = new StringBuilder(256); 6883 } else { 6884 r.append(' '); 6885 } 6886 r.append(p.info.name); 6887 } 6888 } 6889 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6890 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name); 6891 if (appOpPerms != null) { 6892 appOpPerms.remove(pkg.packageName); 6893 } 6894 } 6895 } 6896 if (r != null) { 6897 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6898 } 6899 6900 N = pkg.requestedPermissions.size(); 6901 r = null; 6902 for (i=0; i<N; i++) { 6903 String perm = pkg.requestedPermissions.get(i); 6904 BasePermission bp = mSettings.mPermissions.get(perm); 6905 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 6906 ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm); 6907 if (appOpPerms != null) { 6908 appOpPerms.remove(pkg.packageName); 6909 if (appOpPerms.isEmpty()) { 6910 mAppOpPermissionPackages.remove(perm); 6911 } 6912 } 6913 } 6914 } 6915 if (r != null) { 6916 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6917 } 6918 6919 N = pkg.instrumentation.size(); 6920 r = null; 6921 for (i=0; i<N; i++) { 6922 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6923 mInstrumentation.remove(a.getComponentName()); 6924 if (DEBUG_REMOVE && chatty) { 6925 if (r == null) { 6926 r = new StringBuilder(256); 6927 } else { 6928 r.append(' '); 6929 } 6930 r.append(a.info.name); 6931 } 6932 } 6933 if (r != null) { 6934 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 6935 } 6936 6937 r = null; 6938 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6939 // Only system apps can hold shared libraries. 6940 if (pkg.libraryNames != null) { 6941 for (i=0; i<pkg.libraryNames.size(); i++) { 6942 String name = pkg.libraryNames.get(i); 6943 SharedLibraryEntry cur = mSharedLibraries.get(name); 6944 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 6945 mSharedLibraries.remove(name); 6946 if (DEBUG_REMOVE && chatty) { 6947 if (r == null) { 6948 r = new StringBuilder(256); 6949 } else { 6950 r.append(' '); 6951 } 6952 r.append(name); 6953 } 6954 } 6955 } 6956 } 6957 } 6958 if (r != null) { 6959 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 6960 } 6961 } 6962 6963 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 6964 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 6965 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 6966 return true; 6967 } 6968 } 6969 return false; 6970 } 6971 6972 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 6973 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 6974 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 6975 6976 private void updatePermissionsLPw(String changingPkg, 6977 PackageParser.Package pkgInfo, int flags) { 6978 // Make sure there are no dangling permission trees. 6979 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 6980 while (it.hasNext()) { 6981 final BasePermission bp = it.next(); 6982 if (bp.packageSetting == null) { 6983 // We may not yet have parsed the package, so just see if 6984 // we still know about its settings. 6985 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6986 } 6987 if (bp.packageSetting == null) { 6988 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 6989 + " from package " + bp.sourcePackage); 6990 it.remove(); 6991 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6992 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6993 Slog.i(TAG, "Removing old permission tree: " + bp.name 6994 + " from package " + bp.sourcePackage); 6995 flags |= UPDATE_PERMISSIONS_ALL; 6996 it.remove(); 6997 } 6998 } 6999 } 7000 7001 // Make sure all dynamic permissions have been assigned to a package, 7002 // and make sure there are no dangling permissions. 7003 it = mSettings.mPermissions.values().iterator(); 7004 while (it.hasNext()) { 7005 final BasePermission bp = it.next(); 7006 if (bp.type == BasePermission.TYPE_DYNAMIC) { 7007 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 7008 + bp.name + " pkg=" + bp.sourcePackage 7009 + " info=" + bp.pendingInfo); 7010 if (bp.packageSetting == null && bp.pendingInfo != null) { 7011 final BasePermission tree = findPermissionTreeLP(bp.name); 7012 if (tree != null && tree.perm != null) { 7013 bp.packageSetting = tree.packageSetting; 7014 bp.perm = new PackageParser.Permission(tree.perm.owner, 7015 new PermissionInfo(bp.pendingInfo)); 7016 bp.perm.info.packageName = tree.perm.info.packageName; 7017 bp.perm.info.name = bp.name; 7018 bp.uid = tree.uid; 7019 } 7020 } 7021 } 7022 if (bp.packageSetting == null) { 7023 // We may not yet have parsed the package, so just see if 7024 // we still know about its settings. 7025 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 7026 } 7027 if (bp.packageSetting == null) { 7028 Slog.w(TAG, "Removing dangling permission: " + bp.name 7029 + " from package " + bp.sourcePackage); 7030 it.remove(); 7031 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 7032 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 7033 Slog.i(TAG, "Removing old permission: " + bp.name 7034 + " from package " + bp.sourcePackage); 7035 flags |= UPDATE_PERMISSIONS_ALL; 7036 it.remove(); 7037 } 7038 } 7039 } 7040 7041 // Now update the permissions for all packages, in particular 7042 // replace the granted permissions of the system packages. 7043 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 7044 for (PackageParser.Package pkg : mPackages.values()) { 7045 if (pkg != pkgInfo) { 7046 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0, 7047 changingPkg); 7048 } 7049 } 7050 } 7051 7052 if (pkgInfo != null) { 7053 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg); 7054 } 7055 } 7056 7057 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 7058 String packageOfInterest) { 7059 final PackageSetting ps = (PackageSetting) pkg.mExtras; 7060 if (ps == null) { 7061 return; 7062 } 7063 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 7064 ArraySet<String> origPermissions = gp.grantedPermissions; 7065 boolean changedPermission = false; 7066 7067 if (replace) { 7068 ps.permissionsFixed = false; 7069 if (gp == ps) { 7070 origPermissions = new ArraySet<String>(gp.grantedPermissions); 7071 gp.grantedPermissions.clear(); 7072 gp.gids = mGlobalGids; 7073 } 7074 } 7075 7076 if (gp.gids == null) { 7077 gp.gids = mGlobalGids; 7078 } 7079 7080 final int N = pkg.requestedPermissions.size(); 7081 for (int i=0; i<N; i++) { 7082 final String name = pkg.requestedPermissions.get(i); 7083 final boolean required = pkg.requestedPermissionsRequired.get(i); 7084 final BasePermission bp = mSettings.mPermissions.get(name); 7085 if (DEBUG_INSTALL) { 7086 if (gp != ps) { 7087 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 7088 } 7089 } 7090 7091 if (bp == null || bp.packageSetting == null) { 7092 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7093 Slog.w(TAG, "Unknown permission " + name 7094 + " in package " + pkg.packageName); 7095 } 7096 continue; 7097 } 7098 7099 final String perm = bp.name; 7100 boolean allowed; 7101 boolean allowedSig = false; 7102 if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 7103 // Keep track of app op permissions. 7104 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 7105 if (pkgs == null) { 7106 pkgs = new ArraySet<>(); 7107 mAppOpPermissionPackages.put(bp.name, pkgs); 7108 } 7109 pkgs.add(pkg.packageName); 7110 } 7111 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 7112 if (level == PermissionInfo.PROTECTION_NORMAL 7113 || level == PermissionInfo.PROTECTION_DANGEROUS) { 7114 // We grant a normal or dangerous permission if any of the following 7115 // are true: 7116 // 1) The permission is required 7117 // 2) The permission is optional, but was granted in the past 7118 // 3) The permission is optional, but was requested by an 7119 // app in /system (not /data) 7120 // 7121 // Otherwise, reject the permission. 7122 allowed = (required || origPermissions.contains(perm) 7123 || (isSystemApp(ps) && !isUpdatedSystemApp(ps))); 7124 } else if (bp.packageSetting == null) { 7125 // This permission is invalid; skip it. 7126 allowed = false; 7127 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 7128 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions); 7129 if (allowed) { 7130 allowedSig = true; 7131 } 7132 } else { 7133 allowed = false; 7134 } 7135 if (DEBUG_INSTALL) { 7136 if (gp != ps) { 7137 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 7138 } 7139 } 7140 if (allowed) { 7141 if (!isSystemApp(ps) && ps.permissionsFixed) { 7142 // If this is an existing, non-system package, then 7143 // we can't add any new permissions to it. 7144 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 7145 // Except... if this is a permission that was added 7146 // to the platform (note: need to only do this when 7147 // updating the platform). 7148 allowed = isNewPlatformPermissionForPackage(perm, pkg); 7149 } 7150 } 7151 if (allowed) { 7152 if (!gp.grantedPermissions.contains(perm)) { 7153 changedPermission = true; 7154 gp.grantedPermissions.add(perm); 7155 gp.gids = appendInts(gp.gids, bp.gids); 7156 } else if (!ps.haveGids) { 7157 gp.gids = appendInts(gp.gids, bp.gids); 7158 } 7159 } else { 7160 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7161 Slog.w(TAG, "Not granting permission " + perm 7162 + " to package " + pkg.packageName 7163 + " because it was previously installed without"); 7164 } 7165 } 7166 } else { 7167 if (gp.grantedPermissions.remove(perm)) { 7168 changedPermission = true; 7169 gp.gids = removeInts(gp.gids, bp.gids); 7170 Slog.i(TAG, "Un-granting permission " + perm 7171 + " from package " + pkg.packageName 7172 + " (protectionLevel=" + bp.protectionLevel 7173 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7174 + ")"); 7175 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 7176 // Don't print warning for app op permissions, since it is fine for them 7177 // not to be granted, there is a UI for the user to decide. 7178 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 7179 Slog.w(TAG, "Not granting permission " + perm 7180 + " to package " + pkg.packageName 7181 + " (protectionLevel=" + bp.protectionLevel 7182 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 7183 + ")"); 7184 } 7185 } 7186 } 7187 } 7188 7189 if ((changedPermission || replace) && !ps.permissionsFixed && 7190 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 7191 // This is the first that we have heard about this package, so the 7192 // permissions we have now selected are fixed until explicitly 7193 // changed. 7194 ps.permissionsFixed = true; 7195 } 7196 ps.haveGids = true; 7197 } 7198 7199 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 7200 boolean allowed = false; 7201 final int NP = PackageParser.NEW_PERMISSIONS.length; 7202 for (int ip=0; ip<NP; ip++) { 7203 final PackageParser.NewPermissionInfo npi 7204 = PackageParser.NEW_PERMISSIONS[ip]; 7205 if (npi.name.equals(perm) 7206 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 7207 allowed = true; 7208 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 7209 + pkg.packageName); 7210 break; 7211 } 7212 } 7213 return allowed; 7214 } 7215 7216 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 7217 BasePermission bp, ArraySet<String> origPermissions) { 7218 boolean allowed; 7219 allowed = (compareSignatures( 7220 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 7221 == PackageManager.SIGNATURE_MATCH) 7222 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 7223 == PackageManager.SIGNATURE_MATCH); 7224 if (!allowed && (bp.protectionLevel 7225 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 7226 if (isSystemApp(pkg)) { 7227 // For updated system applications, a system permission 7228 // is granted only if it had been defined by the original application. 7229 if (isUpdatedSystemApp(pkg)) { 7230 final PackageSetting sysPs = mSettings 7231 .getDisabledSystemPkgLPr(pkg.packageName); 7232 final GrantedPermissions origGp = sysPs.sharedUser != null 7233 ? sysPs.sharedUser : sysPs; 7234 7235 if (origGp.grantedPermissions.contains(perm)) { 7236 // If the original was granted this permission, we take 7237 // that grant decision as read and propagate it to the 7238 // update. 7239 if (sysPs.isPrivileged()) { 7240 allowed = true; 7241 } 7242 } else { 7243 // The system apk may have been updated with an older 7244 // version of the one on the data partition, but which 7245 // granted a new system permission that it didn't have 7246 // before. In this case we do want to allow the app to 7247 // now get the new permission if the ancestral apk is 7248 // privileged to get it. 7249 if (sysPs.pkg != null && sysPs.isPrivileged()) { 7250 for (int j=0; 7251 j<sysPs.pkg.requestedPermissions.size(); j++) { 7252 if (perm.equals( 7253 sysPs.pkg.requestedPermissions.get(j))) { 7254 allowed = true; 7255 break; 7256 } 7257 } 7258 } 7259 } 7260 } else { 7261 allowed = isPrivilegedApp(pkg); 7262 } 7263 } 7264 } 7265 if (!allowed && (bp.protectionLevel 7266 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 7267 // For development permissions, a development permission 7268 // is granted only if it was already granted. 7269 allowed = origPermissions.contains(perm); 7270 } 7271 return allowed; 7272 } 7273 7274 final class ActivityIntentResolver 7275 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 7276 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7277 boolean defaultOnly, int userId) { 7278 if (!sUserManager.exists(userId)) return null; 7279 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7280 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7281 } 7282 7283 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7284 int userId) { 7285 if (!sUserManager.exists(userId)) return null; 7286 mFlags = flags; 7287 return super.queryIntent(intent, resolvedType, 7288 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7289 } 7290 7291 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7292 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 7293 if (!sUserManager.exists(userId)) return null; 7294 if (packageActivities == null) { 7295 return null; 7296 } 7297 mFlags = flags; 7298 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7299 final int N = packageActivities.size(); 7300 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 7301 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 7302 7303 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 7304 for (int i = 0; i < N; ++i) { 7305 intentFilters = packageActivities.get(i).intents; 7306 if (intentFilters != null && intentFilters.size() > 0) { 7307 PackageParser.ActivityIntentInfo[] array = 7308 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 7309 intentFilters.toArray(array); 7310 listCut.add(array); 7311 } 7312 } 7313 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7314 } 7315 7316 public final void addActivity(PackageParser.Activity a, String type) { 7317 final boolean systemApp = isSystemApp(a.info.applicationInfo); 7318 mActivities.put(a.getComponentName(), a); 7319 if (DEBUG_SHOW_INFO) 7320 Log.v( 7321 TAG, " " + type + " " + 7322 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 7323 if (DEBUG_SHOW_INFO) 7324 Log.v(TAG, " Class=" + a.info.name); 7325 final int NI = a.intents.size(); 7326 for (int j=0; j<NI; j++) { 7327 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7328 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 7329 intent.setPriority(0); 7330 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 7331 + a.className + " with priority > 0, forcing to 0"); 7332 } 7333 if (DEBUG_SHOW_INFO) { 7334 Log.v(TAG, " IntentFilter:"); 7335 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7336 } 7337 if (!intent.debugCheck()) { 7338 Log.w(TAG, "==> For Activity " + a.info.name); 7339 } 7340 addFilter(intent); 7341 } 7342 } 7343 7344 public final void removeActivity(PackageParser.Activity a, String type) { 7345 mActivities.remove(a.getComponentName()); 7346 if (DEBUG_SHOW_INFO) { 7347 Log.v(TAG, " " + type + " " 7348 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 7349 : a.info.name) + ":"); 7350 Log.v(TAG, " Class=" + a.info.name); 7351 } 7352 final int NI = a.intents.size(); 7353 for (int j=0; j<NI; j++) { 7354 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 7355 if (DEBUG_SHOW_INFO) { 7356 Log.v(TAG, " IntentFilter:"); 7357 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7358 } 7359 removeFilter(intent); 7360 } 7361 } 7362 7363 @Override 7364 protected boolean allowFilterResult( 7365 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 7366 ActivityInfo filterAi = filter.activity.info; 7367 for (int i=dest.size()-1; i>=0; i--) { 7368 ActivityInfo destAi = dest.get(i).activityInfo; 7369 if (destAi.name == filterAi.name 7370 && destAi.packageName == filterAi.packageName) { 7371 return false; 7372 } 7373 } 7374 return true; 7375 } 7376 7377 @Override 7378 protected ActivityIntentInfo[] newArray(int size) { 7379 return new ActivityIntentInfo[size]; 7380 } 7381 7382 @Override 7383 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 7384 if (!sUserManager.exists(userId)) return true; 7385 PackageParser.Package p = filter.activity.owner; 7386 if (p != null) { 7387 PackageSetting ps = (PackageSetting)p.mExtras; 7388 if (ps != null) { 7389 // System apps are never considered stopped for purposes of 7390 // filtering, because there may be no way for the user to 7391 // actually re-launch them. 7392 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 7393 && ps.getStopped(userId); 7394 } 7395 } 7396 return false; 7397 } 7398 7399 @Override 7400 protected boolean isPackageForFilter(String packageName, 7401 PackageParser.ActivityIntentInfo info) { 7402 return packageName.equals(info.activity.owner.packageName); 7403 } 7404 7405 @Override 7406 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 7407 int match, int userId) { 7408 if (!sUserManager.exists(userId)) return null; 7409 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 7410 return null; 7411 } 7412 final PackageParser.Activity activity = info.activity; 7413 if (mSafeMode && (activity.info.applicationInfo.flags 7414 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7415 return null; 7416 } 7417 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 7418 if (ps == null) { 7419 return null; 7420 } 7421 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 7422 ps.readUserState(userId), userId); 7423 if (ai == null) { 7424 return null; 7425 } 7426 final ResolveInfo res = new ResolveInfo(); 7427 res.activityInfo = ai; 7428 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7429 res.filter = info; 7430 } 7431 res.priority = info.getPriority(); 7432 res.preferredOrder = activity.owner.mPreferredOrder; 7433 //System.out.println("Result: " + res.activityInfo.className + 7434 // " = " + res.priority); 7435 res.match = match; 7436 res.isDefault = info.hasDefault; 7437 res.labelRes = info.labelRes; 7438 res.nonLocalizedLabel = info.nonLocalizedLabel; 7439 if (userNeedsBadging(userId)) { 7440 res.noResourceId = true; 7441 } else { 7442 res.icon = info.icon; 7443 } 7444 res.system = isSystemApp(res.activityInfo.applicationInfo); 7445 return res; 7446 } 7447 7448 @Override 7449 protected void sortResults(List<ResolveInfo> results) { 7450 Collections.sort(results, mResolvePrioritySorter); 7451 } 7452 7453 @Override 7454 protected void dumpFilter(PrintWriter out, String prefix, 7455 PackageParser.ActivityIntentInfo filter) { 7456 out.print(prefix); out.print( 7457 Integer.toHexString(System.identityHashCode(filter.activity))); 7458 out.print(' '); 7459 filter.activity.printComponentShortName(out); 7460 out.print(" filter "); 7461 out.println(Integer.toHexString(System.identityHashCode(filter))); 7462 } 7463 7464 @Override 7465 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 7466 return filter.activity; 7467 } 7468 7469 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 7470 PackageParser.Activity activity = (PackageParser.Activity)label; 7471 out.print(prefix); out.print( 7472 Integer.toHexString(System.identityHashCode(activity))); 7473 out.print(' '); 7474 activity.printComponentShortName(out); 7475 if (count > 1) { 7476 out.print(" ("); out.print(count); out.print(" filters)"); 7477 } 7478 out.println(); 7479 } 7480 7481// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7482// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7483// final List<ResolveInfo> retList = Lists.newArrayList(); 7484// while (i.hasNext()) { 7485// final ResolveInfo resolveInfo = i.next(); 7486// if (isEnabledLP(resolveInfo.activityInfo)) { 7487// retList.add(resolveInfo); 7488// } 7489// } 7490// return retList; 7491// } 7492 7493 // Keys are String (activity class name), values are Activity. 7494 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 7495 = new ArrayMap<ComponentName, PackageParser.Activity>(); 7496 private int mFlags; 7497 } 7498 7499 private final class ServiceIntentResolver 7500 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 7501 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7502 boolean defaultOnly, int userId) { 7503 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7504 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7505 } 7506 7507 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7508 int userId) { 7509 if (!sUserManager.exists(userId)) return null; 7510 mFlags = flags; 7511 return super.queryIntent(intent, resolvedType, 7512 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7513 } 7514 7515 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7516 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 7517 if (!sUserManager.exists(userId)) return null; 7518 if (packageServices == null) { 7519 return null; 7520 } 7521 mFlags = flags; 7522 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 7523 final int N = packageServices.size(); 7524 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 7525 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 7526 7527 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 7528 for (int i = 0; i < N; ++i) { 7529 intentFilters = packageServices.get(i).intents; 7530 if (intentFilters != null && intentFilters.size() > 0) { 7531 PackageParser.ServiceIntentInfo[] array = 7532 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 7533 intentFilters.toArray(array); 7534 listCut.add(array); 7535 } 7536 } 7537 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7538 } 7539 7540 public final void addService(PackageParser.Service s) { 7541 mServices.put(s.getComponentName(), s); 7542 if (DEBUG_SHOW_INFO) { 7543 Log.v(TAG, " " 7544 + (s.info.nonLocalizedLabel != null 7545 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7546 Log.v(TAG, " Class=" + s.info.name); 7547 } 7548 final int NI = s.intents.size(); 7549 int j; 7550 for (j=0; j<NI; j++) { 7551 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7552 if (DEBUG_SHOW_INFO) { 7553 Log.v(TAG, " IntentFilter:"); 7554 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7555 } 7556 if (!intent.debugCheck()) { 7557 Log.w(TAG, "==> For Service " + s.info.name); 7558 } 7559 addFilter(intent); 7560 } 7561 } 7562 7563 public final void removeService(PackageParser.Service s) { 7564 mServices.remove(s.getComponentName()); 7565 if (DEBUG_SHOW_INFO) { 7566 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 7567 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 7568 Log.v(TAG, " Class=" + s.info.name); 7569 } 7570 final int NI = s.intents.size(); 7571 int j; 7572 for (j=0; j<NI; j++) { 7573 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 7574 if (DEBUG_SHOW_INFO) { 7575 Log.v(TAG, " IntentFilter:"); 7576 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7577 } 7578 removeFilter(intent); 7579 } 7580 } 7581 7582 @Override 7583 protected boolean allowFilterResult( 7584 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 7585 ServiceInfo filterSi = filter.service.info; 7586 for (int i=dest.size()-1; i>=0; i--) { 7587 ServiceInfo destAi = dest.get(i).serviceInfo; 7588 if (destAi.name == filterSi.name 7589 && destAi.packageName == filterSi.packageName) { 7590 return false; 7591 } 7592 } 7593 return true; 7594 } 7595 7596 @Override 7597 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 7598 return new PackageParser.ServiceIntentInfo[size]; 7599 } 7600 7601 @Override 7602 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 7603 if (!sUserManager.exists(userId)) return true; 7604 PackageParser.Package p = filter.service.owner; 7605 if (p != null) { 7606 PackageSetting ps = (PackageSetting)p.mExtras; 7607 if (ps != null) { 7608 // System apps are never considered stopped for purposes of 7609 // filtering, because there may be no way for the user to 7610 // actually re-launch them. 7611 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7612 && ps.getStopped(userId); 7613 } 7614 } 7615 return false; 7616 } 7617 7618 @Override 7619 protected boolean isPackageForFilter(String packageName, 7620 PackageParser.ServiceIntentInfo info) { 7621 return packageName.equals(info.service.owner.packageName); 7622 } 7623 7624 @Override 7625 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 7626 int match, int userId) { 7627 if (!sUserManager.exists(userId)) return null; 7628 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 7629 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 7630 return null; 7631 } 7632 final PackageParser.Service service = info.service; 7633 if (mSafeMode && (service.info.applicationInfo.flags 7634 &ApplicationInfo.FLAG_SYSTEM) == 0) { 7635 return null; 7636 } 7637 PackageSetting ps = (PackageSetting) service.owner.mExtras; 7638 if (ps == null) { 7639 return null; 7640 } 7641 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 7642 ps.readUserState(userId), userId); 7643 if (si == null) { 7644 return null; 7645 } 7646 final ResolveInfo res = new ResolveInfo(); 7647 res.serviceInfo = si; 7648 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 7649 res.filter = filter; 7650 } 7651 res.priority = info.getPriority(); 7652 res.preferredOrder = service.owner.mPreferredOrder; 7653 //System.out.println("Result: " + res.activityInfo.className + 7654 // " = " + res.priority); 7655 res.match = match; 7656 res.isDefault = info.hasDefault; 7657 res.labelRes = info.labelRes; 7658 res.nonLocalizedLabel = info.nonLocalizedLabel; 7659 res.icon = info.icon; 7660 res.system = isSystemApp(res.serviceInfo.applicationInfo); 7661 return res; 7662 } 7663 7664 @Override 7665 protected void sortResults(List<ResolveInfo> results) { 7666 Collections.sort(results, mResolvePrioritySorter); 7667 } 7668 7669 @Override 7670 protected void dumpFilter(PrintWriter out, String prefix, 7671 PackageParser.ServiceIntentInfo filter) { 7672 out.print(prefix); out.print( 7673 Integer.toHexString(System.identityHashCode(filter.service))); 7674 out.print(' '); 7675 filter.service.printComponentShortName(out); 7676 out.print(" filter "); 7677 out.println(Integer.toHexString(System.identityHashCode(filter))); 7678 } 7679 7680 @Override 7681 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 7682 return filter.service; 7683 } 7684 7685 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 7686 PackageParser.Service service = (PackageParser.Service)label; 7687 out.print(prefix); out.print( 7688 Integer.toHexString(System.identityHashCode(service))); 7689 out.print(' '); 7690 service.printComponentShortName(out); 7691 if (count > 1) { 7692 out.print(" ("); out.print(count); out.print(" filters)"); 7693 } 7694 out.println(); 7695 } 7696 7697// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 7698// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 7699// final List<ResolveInfo> retList = Lists.newArrayList(); 7700// while (i.hasNext()) { 7701// final ResolveInfo resolveInfo = (ResolveInfo) i; 7702// if (isEnabledLP(resolveInfo.serviceInfo)) { 7703// retList.add(resolveInfo); 7704// } 7705// } 7706// return retList; 7707// } 7708 7709 // Keys are String (activity class name), values are Activity. 7710 private final ArrayMap<ComponentName, PackageParser.Service> mServices 7711 = new ArrayMap<ComponentName, PackageParser.Service>(); 7712 private int mFlags; 7713 }; 7714 7715 private final class ProviderIntentResolver 7716 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 7717 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 7718 boolean defaultOnly, int userId) { 7719 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 7720 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 7721 } 7722 7723 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 7724 int userId) { 7725 if (!sUserManager.exists(userId)) 7726 return null; 7727 mFlags = flags; 7728 return super.queryIntent(intent, resolvedType, 7729 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 7730 } 7731 7732 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 7733 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 7734 if (!sUserManager.exists(userId)) 7735 return null; 7736 if (packageProviders == null) { 7737 return null; 7738 } 7739 mFlags = flags; 7740 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 7741 final int N = packageProviders.size(); 7742 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 7743 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 7744 7745 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 7746 for (int i = 0; i < N; ++i) { 7747 intentFilters = packageProviders.get(i).intents; 7748 if (intentFilters != null && intentFilters.size() > 0) { 7749 PackageParser.ProviderIntentInfo[] array = 7750 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 7751 intentFilters.toArray(array); 7752 listCut.add(array); 7753 } 7754 } 7755 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 7756 } 7757 7758 public final void addProvider(PackageParser.Provider p) { 7759 if (mProviders.containsKey(p.getComponentName())) { 7760 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 7761 return; 7762 } 7763 7764 mProviders.put(p.getComponentName(), p); 7765 if (DEBUG_SHOW_INFO) { 7766 Log.v(TAG, " " 7767 + (p.info.nonLocalizedLabel != null 7768 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7769 Log.v(TAG, " Class=" + p.info.name); 7770 } 7771 final int NI = p.intents.size(); 7772 int j; 7773 for (j = 0; j < NI; j++) { 7774 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7775 if (DEBUG_SHOW_INFO) { 7776 Log.v(TAG, " IntentFilter:"); 7777 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7778 } 7779 if (!intent.debugCheck()) { 7780 Log.w(TAG, "==> For Provider " + p.info.name); 7781 } 7782 addFilter(intent); 7783 } 7784 } 7785 7786 public final void removeProvider(PackageParser.Provider p) { 7787 mProviders.remove(p.getComponentName()); 7788 if (DEBUG_SHOW_INFO) { 7789 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 7790 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 7791 Log.v(TAG, " Class=" + p.info.name); 7792 } 7793 final int NI = p.intents.size(); 7794 int j; 7795 for (j = 0; j < NI; j++) { 7796 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 7797 if (DEBUG_SHOW_INFO) { 7798 Log.v(TAG, " IntentFilter:"); 7799 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 7800 } 7801 removeFilter(intent); 7802 } 7803 } 7804 7805 @Override 7806 protected boolean allowFilterResult( 7807 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 7808 ProviderInfo filterPi = filter.provider.info; 7809 for (int i = dest.size() - 1; i >= 0; i--) { 7810 ProviderInfo destPi = dest.get(i).providerInfo; 7811 if (destPi.name == filterPi.name 7812 && destPi.packageName == filterPi.packageName) { 7813 return false; 7814 } 7815 } 7816 return true; 7817 } 7818 7819 @Override 7820 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 7821 return new PackageParser.ProviderIntentInfo[size]; 7822 } 7823 7824 @Override 7825 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 7826 if (!sUserManager.exists(userId)) 7827 return true; 7828 PackageParser.Package p = filter.provider.owner; 7829 if (p != null) { 7830 PackageSetting ps = (PackageSetting) p.mExtras; 7831 if (ps != null) { 7832 // System apps are never considered stopped for purposes of 7833 // filtering, because there may be no way for the user to 7834 // actually re-launch them. 7835 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 7836 && ps.getStopped(userId); 7837 } 7838 } 7839 return false; 7840 } 7841 7842 @Override 7843 protected boolean isPackageForFilter(String packageName, 7844 PackageParser.ProviderIntentInfo info) { 7845 return packageName.equals(info.provider.owner.packageName); 7846 } 7847 7848 @Override 7849 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 7850 int match, int userId) { 7851 if (!sUserManager.exists(userId)) 7852 return null; 7853 final PackageParser.ProviderIntentInfo info = filter; 7854 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 7855 return null; 7856 } 7857 final PackageParser.Provider provider = info.provider; 7858 if (mSafeMode && (provider.info.applicationInfo.flags 7859 & ApplicationInfo.FLAG_SYSTEM) == 0) { 7860 return null; 7861 } 7862 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 7863 if (ps == null) { 7864 return null; 7865 } 7866 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 7867 ps.readUserState(userId), userId); 7868 if (pi == null) { 7869 return null; 7870 } 7871 final ResolveInfo res = new ResolveInfo(); 7872 res.providerInfo = pi; 7873 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 7874 res.filter = filter; 7875 } 7876 res.priority = info.getPriority(); 7877 res.preferredOrder = provider.owner.mPreferredOrder; 7878 res.match = match; 7879 res.isDefault = info.hasDefault; 7880 res.labelRes = info.labelRes; 7881 res.nonLocalizedLabel = info.nonLocalizedLabel; 7882 res.icon = info.icon; 7883 res.system = isSystemApp(res.providerInfo.applicationInfo); 7884 return res; 7885 } 7886 7887 @Override 7888 protected void sortResults(List<ResolveInfo> results) { 7889 Collections.sort(results, mResolvePrioritySorter); 7890 } 7891 7892 @Override 7893 protected void dumpFilter(PrintWriter out, String prefix, 7894 PackageParser.ProviderIntentInfo filter) { 7895 out.print(prefix); 7896 out.print( 7897 Integer.toHexString(System.identityHashCode(filter.provider))); 7898 out.print(' '); 7899 filter.provider.printComponentShortName(out); 7900 out.print(" filter "); 7901 out.println(Integer.toHexString(System.identityHashCode(filter))); 7902 } 7903 7904 @Override 7905 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 7906 return filter.provider; 7907 } 7908 7909 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 7910 PackageParser.Provider provider = (PackageParser.Provider)label; 7911 out.print(prefix); out.print( 7912 Integer.toHexString(System.identityHashCode(provider))); 7913 out.print(' '); 7914 provider.printComponentShortName(out); 7915 if (count > 1) { 7916 out.print(" ("); out.print(count); out.print(" filters)"); 7917 } 7918 out.println(); 7919 } 7920 7921 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 7922 = new ArrayMap<ComponentName, PackageParser.Provider>(); 7923 private int mFlags; 7924 }; 7925 7926 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 7927 new Comparator<ResolveInfo>() { 7928 public int compare(ResolveInfo r1, ResolveInfo r2) { 7929 int v1 = r1.priority; 7930 int v2 = r2.priority; 7931 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 7932 if (v1 != v2) { 7933 return (v1 > v2) ? -1 : 1; 7934 } 7935 v1 = r1.preferredOrder; 7936 v2 = r2.preferredOrder; 7937 if (v1 != v2) { 7938 return (v1 > v2) ? -1 : 1; 7939 } 7940 if (r1.isDefault != r2.isDefault) { 7941 return r1.isDefault ? -1 : 1; 7942 } 7943 v1 = r1.match; 7944 v2 = r2.match; 7945 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 7946 if (v1 != v2) { 7947 return (v1 > v2) ? -1 : 1; 7948 } 7949 if (r1.system != r2.system) { 7950 return r1.system ? -1 : 1; 7951 } 7952 return 0; 7953 } 7954 }; 7955 7956 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 7957 new Comparator<ProviderInfo>() { 7958 public int compare(ProviderInfo p1, ProviderInfo p2) { 7959 final int v1 = p1.initOrder; 7960 final int v2 = p2.initOrder; 7961 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 7962 } 7963 }; 7964 7965 static final void sendPackageBroadcast(String action, String pkg, 7966 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 7967 int[] userIds) { 7968 IActivityManager am = ActivityManagerNative.getDefault(); 7969 if (am != null) { 7970 try { 7971 if (userIds == null) { 7972 userIds = am.getRunningUserIds(); 7973 } 7974 for (int id : userIds) { 7975 final Intent intent = new Intent(action, 7976 pkg != null ? Uri.fromParts("package", pkg, null) : null); 7977 if (extras != null) { 7978 intent.putExtras(extras); 7979 } 7980 if (targetPkg != null) { 7981 intent.setPackage(targetPkg); 7982 } 7983 // Modify the UID when posting to other users 7984 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 7985 if (uid > 0 && UserHandle.getUserId(uid) != id) { 7986 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 7987 intent.putExtra(Intent.EXTRA_UID, uid); 7988 } 7989 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 7990 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 7991 if (DEBUG_BROADCASTS) { 7992 RuntimeException here = new RuntimeException("here"); 7993 here.fillInStackTrace(); 7994 Slog.d(TAG, "Sending to user " + id + ": " 7995 + intent.toShortString(false, true, false, false) 7996 + " " + intent.getExtras(), here); 7997 } 7998 am.broadcastIntent(null, intent, null, finishedReceiver, 7999 0, null, null, null, android.app.AppOpsManager.OP_NONE, 8000 finishedReceiver != null, false, id); 8001 } 8002 } catch (RemoteException ex) { 8003 } 8004 } 8005 } 8006 8007 /** 8008 * Check if the external storage media is available. This is true if there 8009 * is a mounted external storage medium or if the external storage is 8010 * emulated. 8011 */ 8012 private boolean isExternalMediaAvailable() { 8013 return mMediaMounted || Environment.isExternalStorageEmulated(); 8014 } 8015 8016 @Override 8017 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 8018 // writer 8019 synchronized (mPackages) { 8020 if (!isExternalMediaAvailable()) { 8021 // If the external storage is no longer mounted at this point, 8022 // the caller may not have been able to delete all of this 8023 // packages files and can not delete any more. Bail. 8024 return null; 8025 } 8026 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 8027 if (lastPackage != null) { 8028 pkgs.remove(lastPackage); 8029 } 8030 if (pkgs.size() > 0) { 8031 return pkgs.get(0); 8032 } 8033 } 8034 return null; 8035 } 8036 8037 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 8038 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 8039 userId, andCode ? 1 : 0, packageName); 8040 if (mSystemReady) { 8041 msg.sendToTarget(); 8042 } else { 8043 if (mPostSystemReadyMessages == null) { 8044 mPostSystemReadyMessages = new ArrayList<>(); 8045 } 8046 mPostSystemReadyMessages.add(msg); 8047 } 8048 } 8049 8050 void startCleaningPackages() { 8051 // reader 8052 synchronized (mPackages) { 8053 if (!isExternalMediaAvailable()) { 8054 return; 8055 } 8056 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 8057 return; 8058 } 8059 } 8060 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 8061 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 8062 IActivityManager am = ActivityManagerNative.getDefault(); 8063 if (am != null) { 8064 try { 8065 am.startService(null, intent, null, UserHandle.USER_OWNER); 8066 } catch (RemoteException e) { 8067 } 8068 } 8069 } 8070 8071 @Override 8072 public void installPackage(String originPath, IPackageInstallObserver2 observer, 8073 int installFlags, String installerPackageName, VerificationParams verificationParams, 8074 String packageAbiOverride) { 8075 installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams, 8076 packageAbiOverride, UserHandle.getCallingUserId()); 8077 } 8078 8079 @Override 8080 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 8081 int installFlags, String installerPackageName, VerificationParams verificationParams, 8082 String packageAbiOverride, int userId) { 8083 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 8084 8085 final int callingUid = Binder.getCallingUid(); 8086 enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser"); 8087 8088 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8089 try { 8090 if (observer != null) { 8091 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 8092 } 8093 } catch (RemoteException re) { 8094 } 8095 return; 8096 } 8097 8098 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 8099 installFlags |= PackageManager.INSTALL_FROM_ADB; 8100 8101 } else { 8102 // Caller holds INSTALL_PACKAGES permission, so we're less strict 8103 // about installerPackageName. 8104 8105 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 8106 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 8107 } 8108 8109 UserHandle user; 8110 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 8111 user = UserHandle.ALL; 8112 } else { 8113 user = new UserHandle(userId); 8114 } 8115 8116 verificationParams.setInstallerUid(callingUid); 8117 8118 final File originFile = new File(originPath); 8119 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 8120 8121 final Message msg = mHandler.obtainMessage(INIT_COPY); 8122 msg.obj = new InstallParams(origin, observer, installFlags, 8123 installerPackageName, verificationParams, user, packageAbiOverride); 8124 mHandler.sendMessage(msg); 8125 } 8126 8127 void installStage(String packageName, File stagedDir, String stagedCid, 8128 IPackageInstallObserver2 observer, PackageInstaller.SessionParams params, 8129 String installerPackageName, int installerUid, UserHandle user) { 8130 final VerificationParams verifParams = new VerificationParams(null, params.originatingUri, 8131 params.referrerUri, installerUid, null); 8132 8133 final OriginInfo origin; 8134 if (stagedDir != null) { 8135 origin = OriginInfo.fromStagedFile(stagedDir); 8136 } else { 8137 origin = OriginInfo.fromStagedContainer(stagedCid); 8138 } 8139 8140 final Message msg = mHandler.obtainMessage(INIT_COPY); 8141 msg.obj = new InstallParams(origin, observer, params.installFlags, 8142 installerPackageName, verifParams, user, params.abiOverride); 8143 mHandler.sendMessage(msg); 8144 } 8145 8146 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 8147 Bundle extras = new Bundle(1); 8148 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 8149 8150 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 8151 packageName, extras, null, null, new int[] {userId}); 8152 try { 8153 IActivityManager am = ActivityManagerNative.getDefault(); 8154 final boolean isSystem = 8155 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 8156 if (isSystem && am.isUserRunning(userId, false)) { 8157 // The just-installed/enabled app is bundled on the system, so presumed 8158 // to be able to run automatically without needing an explicit launch. 8159 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 8160 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 8161 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 8162 .setPackage(packageName); 8163 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 8164 android.app.AppOpsManager.OP_NONE, false, false, userId); 8165 } 8166 } catch (RemoteException e) { 8167 // shouldn't happen 8168 Slog.w(TAG, "Unable to bootstrap installed package", e); 8169 } 8170 } 8171 8172 @Override 8173 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 8174 int userId) { 8175 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8176 PackageSetting pkgSetting; 8177 final int uid = Binder.getCallingUid(); 8178 enforceCrossUserPermission(uid, userId, true, true, 8179 "setApplicationHiddenSetting for user " + userId); 8180 8181 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 8182 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 8183 return false; 8184 } 8185 8186 long callingId = Binder.clearCallingIdentity(); 8187 try { 8188 boolean sendAdded = false; 8189 boolean sendRemoved = false; 8190 // writer 8191 synchronized (mPackages) { 8192 pkgSetting = mSettings.mPackages.get(packageName); 8193 if (pkgSetting == null) { 8194 return false; 8195 } 8196 if (pkgSetting.getHidden(userId) != hidden) { 8197 pkgSetting.setHidden(hidden, userId); 8198 mSettings.writePackageRestrictionsLPr(userId); 8199 if (hidden) { 8200 sendRemoved = true; 8201 } else { 8202 sendAdded = true; 8203 } 8204 } 8205 } 8206 if (sendAdded) { 8207 sendPackageAddedForUser(packageName, pkgSetting, userId); 8208 return true; 8209 } 8210 if (sendRemoved) { 8211 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 8212 "hiding pkg"); 8213 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 8214 } 8215 } finally { 8216 Binder.restoreCallingIdentity(callingId); 8217 } 8218 return false; 8219 } 8220 8221 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 8222 int userId) { 8223 final PackageRemovedInfo info = new PackageRemovedInfo(); 8224 info.removedPackage = packageName; 8225 info.removedUsers = new int[] {userId}; 8226 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 8227 info.sendBroadcast(false, false, false); 8228 } 8229 8230 /** 8231 * Returns true if application is not found or there was an error. Otherwise it returns 8232 * the hidden state of the package for the given user. 8233 */ 8234 @Override 8235 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 8236 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 8237 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, 8238 false, "getApplicationHidden for user " + userId); 8239 PackageSetting pkgSetting; 8240 long callingId = Binder.clearCallingIdentity(); 8241 try { 8242 // writer 8243 synchronized (mPackages) { 8244 pkgSetting = mSettings.mPackages.get(packageName); 8245 if (pkgSetting == null) { 8246 return true; 8247 } 8248 return pkgSetting.getHidden(userId); 8249 } 8250 } finally { 8251 Binder.restoreCallingIdentity(callingId); 8252 } 8253 } 8254 8255 /** 8256 * @hide 8257 */ 8258 @Override 8259 public int installExistingPackageAsUser(String packageName, int userId) { 8260 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 8261 null); 8262 PackageSetting pkgSetting; 8263 final int uid = Binder.getCallingUid(); 8264 enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user " 8265 + userId); 8266 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 8267 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 8268 } 8269 8270 long callingId = Binder.clearCallingIdentity(); 8271 try { 8272 boolean sendAdded = false; 8273 Bundle extras = new Bundle(1); 8274 8275 // writer 8276 synchronized (mPackages) { 8277 pkgSetting = mSettings.mPackages.get(packageName); 8278 if (pkgSetting == null) { 8279 return PackageManager.INSTALL_FAILED_INVALID_URI; 8280 } 8281 if (!pkgSetting.getInstalled(userId)) { 8282 pkgSetting.setInstalled(true, userId); 8283 pkgSetting.setHidden(false, userId); 8284 mSettings.writePackageRestrictionsLPr(userId); 8285 sendAdded = true; 8286 } 8287 } 8288 8289 if (sendAdded) { 8290 sendPackageAddedForUser(packageName, pkgSetting, userId); 8291 } 8292 } finally { 8293 Binder.restoreCallingIdentity(callingId); 8294 } 8295 8296 return PackageManager.INSTALL_SUCCEEDED; 8297 } 8298 8299 boolean isUserRestricted(int userId, String restrictionKey) { 8300 Bundle restrictions = sUserManager.getUserRestrictions(userId); 8301 if (restrictions.getBoolean(restrictionKey, false)) { 8302 Log.w(TAG, "User is restricted: " + restrictionKey); 8303 return true; 8304 } 8305 return false; 8306 } 8307 8308 @Override 8309 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 8310 mContext.enforceCallingOrSelfPermission( 8311 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8312 "Only package verification agents can verify applications"); 8313 8314 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8315 final PackageVerificationResponse response = new PackageVerificationResponse( 8316 verificationCode, Binder.getCallingUid()); 8317 msg.arg1 = id; 8318 msg.obj = response; 8319 mHandler.sendMessage(msg); 8320 } 8321 8322 @Override 8323 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 8324 long millisecondsToDelay) { 8325 mContext.enforceCallingOrSelfPermission( 8326 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8327 "Only package verification agents can extend verification timeouts"); 8328 8329 final PackageVerificationState state = mPendingVerification.get(id); 8330 final PackageVerificationResponse response = new PackageVerificationResponse( 8331 verificationCodeAtTimeout, Binder.getCallingUid()); 8332 8333 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 8334 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 8335 } 8336 if (millisecondsToDelay < 0) { 8337 millisecondsToDelay = 0; 8338 } 8339 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 8340 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 8341 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 8342 } 8343 8344 if ((state != null) && !state.timeoutExtended()) { 8345 state.extendTimeout(); 8346 8347 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 8348 msg.arg1 = id; 8349 msg.obj = response; 8350 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 8351 } 8352 } 8353 8354 private void broadcastPackageVerified(int verificationId, Uri packageUri, 8355 int verificationCode, UserHandle user) { 8356 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 8357 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 8358 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8359 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8360 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 8361 8362 mContext.sendBroadcastAsUser(intent, user, 8363 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 8364 } 8365 8366 private ComponentName matchComponentForVerifier(String packageName, 8367 List<ResolveInfo> receivers) { 8368 ActivityInfo targetReceiver = null; 8369 8370 final int NR = receivers.size(); 8371 for (int i = 0; i < NR; i++) { 8372 final ResolveInfo info = receivers.get(i); 8373 if (info.activityInfo == null) { 8374 continue; 8375 } 8376 8377 if (packageName.equals(info.activityInfo.packageName)) { 8378 targetReceiver = info.activityInfo; 8379 break; 8380 } 8381 } 8382 8383 if (targetReceiver == null) { 8384 return null; 8385 } 8386 8387 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 8388 } 8389 8390 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 8391 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 8392 if (pkgInfo.verifiers.length == 0) { 8393 return null; 8394 } 8395 8396 final int N = pkgInfo.verifiers.length; 8397 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 8398 for (int i = 0; i < N; i++) { 8399 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 8400 8401 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 8402 receivers); 8403 if (comp == null) { 8404 continue; 8405 } 8406 8407 final int verifierUid = getUidForVerifier(verifierInfo); 8408 if (verifierUid == -1) { 8409 continue; 8410 } 8411 8412 if (DEBUG_VERIFY) { 8413 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 8414 + " with the correct signature"); 8415 } 8416 sufficientVerifiers.add(comp); 8417 verificationState.addSufficientVerifier(verifierUid); 8418 } 8419 8420 return sufficientVerifiers; 8421 } 8422 8423 private int getUidForVerifier(VerifierInfo verifierInfo) { 8424 synchronized (mPackages) { 8425 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 8426 if (pkg == null) { 8427 return -1; 8428 } else if (pkg.mSignatures.length != 1) { 8429 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8430 + " has more than one signature; ignoring"); 8431 return -1; 8432 } 8433 8434 /* 8435 * If the public key of the package's signature does not match 8436 * our expected public key, then this is a different package and 8437 * we should skip. 8438 */ 8439 8440 final byte[] expectedPublicKey; 8441 try { 8442 final Signature verifierSig = pkg.mSignatures[0]; 8443 final PublicKey publicKey = verifierSig.getPublicKey(); 8444 expectedPublicKey = publicKey.getEncoded(); 8445 } catch (CertificateException e) { 8446 return -1; 8447 } 8448 8449 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 8450 8451 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 8452 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 8453 + " does not have the expected public key; ignoring"); 8454 return -1; 8455 } 8456 8457 return pkg.applicationInfo.uid; 8458 } 8459 } 8460 8461 @Override 8462 public void finishPackageInstall(int token) { 8463 enforceSystemOrRoot("Only the system is allowed to finish installs"); 8464 8465 if (DEBUG_INSTALL) { 8466 Slog.v(TAG, "BM finishing package install for " + token); 8467 } 8468 8469 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8470 mHandler.sendMessage(msg); 8471 } 8472 8473 /** 8474 * Get the verification agent timeout. 8475 * 8476 * @return verification timeout in milliseconds 8477 */ 8478 private long getVerificationTimeout() { 8479 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 8480 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 8481 DEFAULT_VERIFICATION_TIMEOUT); 8482 } 8483 8484 /** 8485 * Get the default verification agent response code. 8486 * 8487 * @return default verification response code 8488 */ 8489 private int getDefaultVerificationResponse() { 8490 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8491 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 8492 DEFAULT_VERIFICATION_RESPONSE); 8493 } 8494 8495 /** 8496 * Check whether or not package verification has been enabled. 8497 * 8498 * @return true if verification should be performed 8499 */ 8500 private boolean isVerificationEnabled(int userId, int installFlags) { 8501 if (!DEFAULT_VERIFY_ENABLE) { 8502 return false; 8503 } 8504 8505 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 8506 8507 // Check if installing from ADB 8508 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 8509 // Do not run verification in a test harness environment 8510 if (ActivityManager.isRunningInTestHarness()) { 8511 return false; 8512 } 8513 if (ensureVerifyAppsEnabled) { 8514 return true; 8515 } 8516 // Check if the developer does not want package verification for ADB installs 8517 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8518 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 8519 return false; 8520 } 8521 } 8522 8523 if (ensureVerifyAppsEnabled) { 8524 return true; 8525 } 8526 8527 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8528 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 8529 } 8530 8531 /** 8532 * Get the "allow unknown sources" setting. 8533 * 8534 * @return the current "allow unknown sources" setting 8535 */ 8536 private int getUnknownSourcesSettings() { 8537 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 8538 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 8539 -1); 8540 } 8541 8542 @Override 8543 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 8544 final int uid = Binder.getCallingUid(); 8545 // writer 8546 synchronized (mPackages) { 8547 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 8548 if (targetPackageSetting == null) { 8549 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 8550 } 8551 8552 PackageSetting installerPackageSetting; 8553 if (installerPackageName != null) { 8554 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 8555 if (installerPackageSetting == null) { 8556 throw new IllegalArgumentException("Unknown installer package: " 8557 + installerPackageName); 8558 } 8559 } else { 8560 installerPackageSetting = null; 8561 } 8562 8563 Signature[] callerSignature; 8564 Object obj = mSettings.getUserIdLPr(uid); 8565 if (obj != null) { 8566 if (obj instanceof SharedUserSetting) { 8567 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 8568 } else if (obj instanceof PackageSetting) { 8569 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 8570 } else { 8571 throw new SecurityException("Bad object " + obj + " for uid " + uid); 8572 } 8573 } else { 8574 throw new SecurityException("Unknown calling uid " + uid); 8575 } 8576 8577 // Verify: can't set installerPackageName to a package that is 8578 // not signed with the same cert as the caller. 8579 if (installerPackageSetting != null) { 8580 if (compareSignatures(callerSignature, 8581 installerPackageSetting.signatures.mSignatures) 8582 != PackageManager.SIGNATURE_MATCH) { 8583 throw new SecurityException( 8584 "Caller does not have same cert as new installer package " 8585 + installerPackageName); 8586 } 8587 } 8588 8589 // Verify: if target already has an installer package, it must 8590 // be signed with the same cert as the caller. 8591 if (targetPackageSetting.installerPackageName != null) { 8592 PackageSetting setting = mSettings.mPackages.get( 8593 targetPackageSetting.installerPackageName); 8594 // If the currently set package isn't valid, then it's always 8595 // okay to change it. 8596 if (setting != null) { 8597 if (compareSignatures(callerSignature, 8598 setting.signatures.mSignatures) 8599 != PackageManager.SIGNATURE_MATCH) { 8600 throw new SecurityException( 8601 "Caller does not have same cert as old installer package " 8602 + targetPackageSetting.installerPackageName); 8603 } 8604 } 8605 } 8606 8607 // Okay! 8608 targetPackageSetting.installerPackageName = installerPackageName; 8609 scheduleWriteSettingsLocked(); 8610 } 8611 } 8612 8613 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 8614 // Queue up an async operation since the package installation may take a little while. 8615 mHandler.post(new Runnable() { 8616 public void run() { 8617 mHandler.removeCallbacks(this); 8618 // Result object to be returned 8619 PackageInstalledInfo res = new PackageInstalledInfo(); 8620 res.returnCode = currentStatus; 8621 res.uid = -1; 8622 res.pkg = null; 8623 res.removedInfo = new PackageRemovedInfo(); 8624 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 8625 args.doPreInstall(res.returnCode); 8626 synchronized (mInstallLock) { 8627 installPackageLI(args, res); 8628 } 8629 args.doPostInstall(res.returnCode, res.uid); 8630 } 8631 8632 // A restore should be performed at this point if (a) the install 8633 // succeeded, (b) the operation is not an update, and (c) the new 8634 // package has not opted out of backup participation. 8635 final boolean update = res.removedInfo.removedPackage != null; 8636 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 8637 boolean doRestore = !update 8638 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 8639 8640 // Set up the post-install work request bookkeeping. This will be used 8641 // and cleaned up by the post-install event handling regardless of whether 8642 // there's a restore pass performed. Token values are >= 1. 8643 int token; 8644 if (mNextInstallToken < 0) mNextInstallToken = 1; 8645 token = mNextInstallToken++; 8646 8647 PostInstallData data = new PostInstallData(args, res); 8648 mRunningInstalls.put(token, data); 8649 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 8650 8651 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 8652 // Pass responsibility to the Backup Manager. It will perform a 8653 // restore if appropriate, then pass responsibility back to the 8654 // Package Manager to run the post-install observer callbacks 8655 // and broadcasts. 8656 IBackupManager bm = IBackupManager.Stub.asInterface( 8657 ServiceManager.getService(Context.BACKUP_SERVICE)); 8658 if (bm != null) { 8659 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 8660 + " to BM for possible restore"); 8661 try { 8662 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 8663 } catch (RemoteException e) { 8664 // can't happen; the backup manager is local 8665 } catch (Exception e) { 8666 Slog.e(TAG, "Exception trying to enqueue restore", e); 8667 doRestore = false; 8668 } 8669 } else { 8670 Slog.e(TAG, "Backup Manager not found!"); 8671 doRestore = false; 8672 } 8673 } 8674 8675 if (!doRestore) { 8676 // No restore possible, or the Backup Manager was mysteriously not 8677 // available -- just fire the post-install work request directly. 8678 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 8679 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 8680 mHandler.sendMessage(msg); 8681 } 8682 } 8683 }); 8684 } 8685 8686 private abstract class HandlerParams { 8687 private static final int MAX_RETRIES = 4; 8688 8689 /** 8690 * Number of times startCopy() has been attempted and had a non-fatal 8691 * error. 8692 */ 8693 private int mRetries = 0; 8694 8695 /** User handle for the user requesting the information or installation. */ 8696 private final UserHandle mUser; 8697 8698 HandlerParams(UserHandle user) { 8699 mUser = user; 8700 } 8701 8702 UserHandle getUser() { 8703 return mUser; 8704 } 8705 8706 final boolean startCopy() { 8707 boolean res; 8708 try { 8709 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 8710 8711 if (++mRetries > MAX_RETRIES) { 8712 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 8713 mHandler.sendEmptyMessage(MCS_GIVE_UP); 8714 handleServiceError(); 8715 return false; 8716 } else { 8717 handleStartCopy(); 8718 res = true; 8719 } 8720 } catch (RemoteException e) { 8721 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 8722 mHandler.sendEmptyMessage(MCS_RECONNECT); 8723 res = false; 8724 } 8725 handleReturnCode(); 8726 return res; 8727 } 8728 8729 final void serviceError() { 8730 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 8731 handleServiceError(); 8732 handleReturnCode(); 8733 } 8734 8735 abstract void handleStartCopy() throws RemoteException; 8736 abstract void handleServiceError(); 8737 abstract void handleReturnCode(); 8738 } 8739 8740 class MeasureParams extends HandlerParams { 8741 private final PackageStats mStats; 8742 private boolean mSuccess; 8743 8744 private final IPackageStatsObserver mObserver; 8745 8746 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 8747 super(new UserHandle(stats.userHandle)); 8748 mObserver = observer; 8749 mStats = stats; 8750 } 8751 8752 @Override 8753 public String toString() { 8754 return "MeasureParams{" 8755 + Integer.toHexString(System.identityHashCode(this)) 8756 + " " + mStats.packageName + "}"; 8757 } 8758 8759 @Override 8760 void handleStartCopy() throws RemoteException { 8761 synchronized (mInstallLock) { 8762 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 8763 } 8764 8765 if (mSuccess) { 8766 final boolean mounted; 8767 if (Environment.isExternalStorageEmulated()) { 8768 mounted = true; 8769 } else { 8770 final String status = Environment.getExternalStorageState(); 8771 mounted = (Environment.MEDIA_MOUNTED.equals(status) 8772 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 8773 } 8774 8775 if (mounted) { 8776 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 8777 8778 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 8779 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 8780 8781 mStats.externalDataSize = calculateDirectorySize(mContainerService, 8782 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 8783 8784 // Always subtract cache size, since it's a subdirectory 8785 mStats.externalDataSize -= mStats.externalCacheSize; 8786 8787 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 8788 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 8789 8790 mStats.externalObbSize = calculateDirectorySize(mContainerService, 8791 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 8792 } 8793 } 8794 } 8795 8796 @Override 8797 void handleReturnCode() { 8798 if (mObserver != null) { 8799 try { 8800 mObserver.onGetStatsCompleted(mStats, mSuccess); 8801 } catch (RemoteException e) { 8802 Slog.i(TAG, "Observer no longer exists."); 8803 } 8804 } 8805 } 8806 8807 @Override 8808 void handleServiceError() { 8809 Slog.e(TAG, "Could not measure application " + mStats.packageName 8810 + " external storage"); 8811 } 8812 } 8813 8814 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 8815 throws RemoteException { 8816 long result = 0; 8817 for (File path : paths) { 8818 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 8819 } 8820 return result; 8821 } 8822 8823 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 8824 for (File path : paths) { 8825 try { 8826 mcs.clearDirectory(path.getAbsolutePath()); 8827 } catch (RemoteException e) { 8828 } 8829 } 8830 } 8831 8832 static class OriginInfo { 8833 /** 8834 * Location where install is coming from, before it has been 8835 * copied/renamed into place. This could be a single monolithic APK 8836 * file, or a cluster directory. This location may be untrusted. 8837 */ 8838 final File file; 8839 final String cid; 8840 8841 /** 8842 * Flag indicating that {@link #file} or {@link #cid} has already been 8843 * staged, meaning downstream users don't need to defensively copy the 8844 * contents. 8845 */ 8846 final boolean staged; 8847 8848 /** 8849 * Flag indicating that {@link #file} or {@link #cid} is an already 8850 * installed app that is being moved. 8851 */ 8852 final boolean existing; 8853 8854 final String resolvedPath; 8855 final File resolvedFile; 8856 8857 static OriginInfo fromNothing() { 8858 return new OriginInfo(null, null, false, false); 8859 } 8860 8861 static OriginInfo fromUntrustedFile(File file) { 8862 return new OriginInfo(file, null, false, false); 8863 } 8864 8865 static OriginInfo fromExistingFile(File file) { 8866 return new OriginInfo(file, null, false, true); 8867 } 8868 8869 static OriginInfo fromStagedFile(File file) { 8870 return new OriginInfo(file, null, true, false); 8871 } 8872 8873 static OriginInfo fromStagedContainer(String cid) { 8874 return new OriginInfo(null, cid, true, false); 8875 } 8876 8877 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 8878 this.file = file; 8879 this.cid = cid; 8880 this.staged = staged; 8881 this.existing = existing; 8882 8883 if (cid != null) { 8884 resolvedPath = PackageHelper.getSdDir(cid); 8885 resolvedFile = new File(resolvedPath); 8886 } else if (file != null) { 8887 resolvedPath = file.getAbsolutePath(); 8888 resolvedFile = file; 8889 } else { 8890 resolvedPath = null; 8891 resolvedFile = null; 8892 } 8893 } 8894 } 8895 8896 class InstallParams extends HandlerParams { 8897 final OriginInfo origin; 8898 final IPackageInstallObserver2 observer; 8899 int installFlags; 8900 final String installerPackageName; 8901 final VerificationParams verificationParams; 8902 private InstallArgs mArgs; 8903 private int mRet; 8904 final String packageAbiOverride; 8905 8906 InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 8907 String installerPackageName, VerificationParams verificationParams, UserHandle user, 8908 String packageAbiOverride) { 8909 super(user); 8910 this.origin = origin; 8911 this.observer = observer; 8912 this.installFlags = installFlags; 8913 this.installerPackageName = installerPackageName; 8914 this.verificationParams = verificationParams; 8915 this.packageAbiOverride = packageAbiOverride; 8916 } 8917 8918 @Override 8919 public String toString() { 8920 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 8921 + " file=" + origin.file + " cid=" + origin.cid + "}"; 8922 } 8923 8924 public ManifestDigest getManifestDigest() { 8925 if (verificationParams == null) { 8926 return null; 8927 } 8928 return verificationParams.getManifestDigest(); 8929 } 8930 8931 private int installLocationPolicy(PackageInfoLite pkgLite) { 8932 String packageName = pkgLite.packageName; 8933 int installLocation = pkgLite.installLocation; 8934 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 8935 // reader 8936 synchronized (mPackages) { 8937 PackageParser.Package pkg = mPackages.get(packageName); 8938 if (pkg != null) { 8939 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 8940 // Check for downgrading. 8941 if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 8942 try { 8943 checkDowngrade(pkg, pkgLite); 8944 } catch (PackageManagerException e) { 8945 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 8946 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 8947 } 8948 } 8949 // Check for updated system application. 8950 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8951 if (onSd) { 8952 Slog.w(TAG, "Cannot install update to system app on sdcard"); 8953 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 8954 } 8955 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8956 } else { 8957 if (onSd) { 8958 // Install flag overrides everything. 8959 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8960 } 8961 // If current upgrade specifies particular preference 8962 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 8963 // Application explicitly specified internal. 8964 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8965 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 8966 // App explictly prefers external. Let policy decide 8967 } else { 8968 // Prefer previous location 8969 if (isExternal(pkg)) { 8970 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8971 } 8972 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8973 } 8974 } 8975 } else { 8976 // Invalid install. Return error code 8977 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 8978 } 8979 } 8980 } 8981 // All the special cases have been taken care of. 8982 // Return result based on recommended install location. 8983 if (onSd) { 8984 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8985 } 8986 return pkgLite.recommendedInstallLocation; 8987 } 8988 8989 /* 8990 * Invoke remote method to get package information and install 8991 * location values. Override install location based on default 8992 * policy if needed and then create install arguments based 8993 * on the install location. 8994 */ 8995 public void handleStartCopy() throws RemoteException { 8996 int ret = PackageManager.INSTALL_SUCCEEDED; 8997 8998 // If we're already staged, we've firmly committed to an install location 8999 if (origin.staged) { 9000 if (origin.file != null) { 9001 installFlags |= PackageManager.INSTALL_INTERNAL; 9002 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9003 } else if (origin.cid != null) { 9004 installFlags |= PackageManager.INSTALL_EXTERNAL; 9005 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9006 } else { 9007 throw new IllegalStateException("Invalid stage location"); 9008 } 9009 } 9010 9011 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9012 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 9013 9014 PackageInfoLite pkgLite = null; 9015 9016 if (onInt && onSd) { 9017 // Check if both bits are set. 9018 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 9019 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9020 } else { 9021 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 9022 packageAbiOverride); 9023 9024 /* 9025 * If we have too little free space, try to free cache 9026 * before giving up. 9027 */ 9028 if (!origin.staged && pkgLite.recommendedInstallLocation 9029 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9030 // TODO: focus freeing disk space on the target device 9031 final StorageManager storage = StorageManager.from(mContext); 9032 final long lowThreshold = storage.getStorageLowBytes( 9033 Environment.getDataDirectory()); 9034 9035 final long sizeBytes = mContainerService.calculateInstalledSize( 9036 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 9037 9038 if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) { 9039 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 9040 installFlags, packageAbiOverride); 9041 } 9042 9043 /* 9044 * The cache free must have deleted the file we 9045 * downloaded to install. 9046 * 9047 * TODO: fix the "freeCache" call to not delete 9048 * the file we care about. 9049 */ 9050 if (pkgLite.recommendedInstallLocation 9051 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9052 pkgLite.recommendedInstallLocation 9053 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 9054 } 9055 } 9056 } 9057 9058 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9059 int loc = pkgLite.recommendedInstallLocation; 9060 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 9061 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9062 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 9063 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9064 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 9065 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9066 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 9067 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 9068 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 9069 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 9070 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 9071 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 9072 } else { 9073 // Override with defaults if needed. 9074 loc = installLocationPolicy(pkgLite); 9075 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 9076 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 9077 } else if (!onSd && !onInt) { 9078 // Override install location with flags 9079 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 9080 // Set the flag to install on external media. 9081 installFlags |= PackageManager.INSTALL_EXTERNAL; 9082 installFlags &= ~PackageManager.INSTALL_INTERNAL; 9083 } else { 9084 // Make sure the flag for installing on external 9085 // media is unset 9086 installFlags |= PackageManager.INSTALL_INTERNAL; 9087 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 9088 } 9089 } 9090 } 9091 } 9092 9093 final InstallArgs args = createInstallArgs(this); 9094 mArgs = args; 9095 9096 if (ret == PackageManager.INSTALL_SUCCEEDED) { 9097 /* 9098 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 9099 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 9100 */ 9101 int userIdentifier = getUser().getIdentifier(); 9102 if (userIdentifier == UserHandle.USER_ALL 9103 && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) { 9104 userIdentifier = UserHandle.USER_OWNER; 9105 } 9106 9107 /* 9108 * Determine if we have any installed package verifiers. If we 9109 * do, then we'll defer to them to verify the packages. 9110 */ 9111 final int requiredUid = mRequiredVerifierPackage == null ? -1 9112 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 9113 if (!origin.existing && requiredUid != -1 9114 && isVerificationEnabled(userIdentifier, installFlags)) { 9115 final Intent verification = new Intent( 9116 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 9117 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 9118 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 9119 PACKAGE_MIME_TYPE); 9120 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 9121 9122 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 9123 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 9124 0 /* TODO: Which userId? */); 9125 9126 if (DEBUG_VERIFY) { 9127 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 9128 + verification.toString() + " with " + pkgLite.verifiers.length 9129 + " optional verifiers"); 9130 } 9131 9132 final int verificationId = mPendingVerificationToken++; 9133 9134 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 9135 9136 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 9137 installerPackageName); 9138 9139 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 9140 installFlags); 9141 9142 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 9143 pkgLite.packageName); 9144 9145 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 9146 pkgLite.versionCode); 9147 9148 if (verificationParams != null) { 9149 if (verificationParams.getVerificationURI() != null) { 9150 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 9151 verificationParams.getVerificationURI()); 9152 } 9153 if (verificationParams.getOriginatingURI() != null) { 9154 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 9155 verificationParams.getOriginatingURI()); 9156 } 9157 if (verificationParams.getReferrer() != null) { 9158 verification.putExtra(Intent.EXTRA_REFERRER, 9159 verificationParams.getReferrer()); 9160 } 9161 if (verificationParams.getOriginatingUid() >= 0) { 9162 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 9163 verificationParams.getOriginatingUid()); 9164 } 9165 if (verificationParams.getInstallerUid() >= 0) { 9166 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 9167 verificationParams.getInstallerUid()); 9168 } 9169 } 9170 9171 final PackageVerificationState verificationState = new PackageVerificationState( 9172 requiredUid, args); 9173 9174 mPendingVerification.append(verificationId, verificationState); 9175 9176 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 9177 receivers, verificationState); 9178 9179 /* 9180 * If any sufficient verifiers were listed in the package 9181 * manifest, attempt to ask them. 9182 */ 9183 if (sufficientVerifiers != null) { 9184 final int N = sufficientVerifiers.size(); 9185 if (N == 0) { 9186 Slog.i(TAG, "Additional verifiers required, but none installed."); 9187 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 9188 } else { 9189 for (int i = 0; i < N; i++) { 9190 final ComponentName verifierComponent = sufficientVerifiers.get(i); 9191 9192 final Intent sufficientIntent = new Intent(verification); 9193 sufficientIntent.setComponent(verifierComponent); 9194 9195 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 9196 } 9197 } 9198 } 9199 9200 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 9201 mRequiredVerifierPackage, receivers); 9202 if (ret == PackageManager.INSTALL_SUCCEEDED 9203 && mRequiredVerifierPackage != null) { 9204 /* 9205 * Send the intent to the required verification agent, 9206 * but only start the verification timeout after the 9207 * target BroadcastReceivers have run. 9208 */ 9209 verification.setComponent(requiredVerifierComponent); 9210 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 9211 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9212 new BroadcastReceiver() { 9213 @Override 9214 public void onReceive(Context context, Intent intent) { 9215 final Message msg = mHandler 9216 .obtainMessage(CHECK_PENDING_VERIFICATION); 9217 msg.arg1 = verificationId; 9218 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 9219 } 9220 }, null, 0, null, null); 9221 9222 /* 9223 * We don't want the copy to proceed until verification 9224 * succeeds, so null out this field. 9225 */ 9226 mArgs = null; 9227 } 9228 } else { 9229 /* 9230 * No package verification is enabled, so immediately start 9231 * the remote call to initiate copy using temporary file. 9232 */ 9233 ret = args.copyApk(mContainerService, true); 9234 } 9235 } 9236 9237 mRet = ret; 9238 } 9239 9240 @Override 9241 void handleReturnCode() { 9242 // If mArgs is null, then MCS couldn't be reached. When it 9243 // reconnects, it will try again to install. At that point, this 9244 // will succeed. 9245 if (mArgs != null) { 9246 processPendingInstall(mArgs, mRet); 9247 } 9248 } 9249 9250 @Override 9251 void handleServiceError() { 9252 mArgs = createInstallArgs(this); 9253 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9254 } 9255 9256 public boolean isForwardLocked() { 9257 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9258 } 9259 } 9260 9261 /** 9262 * Used during creation of InstallArgs 9263 * 9264 * @param installFlags package installation flags 9265 * @return true if should be installed on external storage 9266 */ 9267 private static boolean installOnSd(int installFlags) { 9268 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 9269 return false; 9270 } 9271 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 9272 return true; 9273 } 9274 return false; 9275 } 9276 9277 /** 9278 * Used during creation of InstallArgs 9279 * 9280 * @param installFlags package installation flags 9281 * @return true if should be installed as forward locked 9282 */ 9283 private static boolean installForwardLocked(int installFlags) { 9284 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9285 } 9286 9287 private InstallArgs createInstallArgs(InstallParams params) { 9288 if (installOnSd(params.installFlags) || params.isForwardLocked()) { 9289 return new AsecInstallArgs(params); 9290 } else { 9291 return new FileInstallArgs(params); 9292 } 9293 } 9294 9295 /** 9296 * Create args that describe an existing installed package. Typically used 9297 * when cleaning up old installs, or used as a move source. 9298 */ 9299 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 9300 String resourcePath, String nativeLibraryRoot, String[] instructionSets) { 9301 final boolean isInAsec; 9302 if (installOnSd(installFlags)) { 9303 /* Apps on SD card are always in ASEC containers. */ 9304 isInAsec = true; 9305 } else if (installForwardLocked(installFlags) 9306 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 9307 /* 9308 * Forward-locked apps are only in ASEC containers if they're the 9309 * new style 9310 */ 9311 isInAsec = true; 9312 } else { 9313 isInAsec = false; 9314 } 9315 9316 if (isInAsec) { 9317 return new AsecInstallArgs(codePath, instructionSets, 9318 installOnSd(installFlags), installForwardLocked(installFlags)); 9319 } else { 9320 return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot, 9321 instructionSets); 9322 } 9323 } 9324 9325 static abstract class InstallArgs { 9326 /** @see InstallParams#origin */ 9327 final OriginInfo origin; 9328 9329 final IPackageInstallObserver2 observer; 9330 // Always refers to PackageManager flags only 9331 final int installFlags; 9332 final String installerPackageName; 9333 final ManifestDigest manifestDigest; 9334 final UserHandle user; 9335 final String abiOverride; 9336 9337 // The list of instruction sets supported by this app. This is currently 9338 // only used during the rmdex() phase to clean up resources. We can get rid of this 9339 // if we move dex files under the common app path. 9340 /* nullable */ String[] instructionSets; 9341 9342 InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags, 9343 String installerPackageName, ManifestDigest manifestDigest, UserHandle user, 9344 String[] instructionSets, String abiOverride) { 9345 this.origin = origin; 9346 this.installFlags = installFlags; 9347 this.observer = observer; 9348 this.installerPackageName = installerPackageName; 9349 this.manifestDigest = manifestDigest; 9350 this.user = user; 9351 this.instructionSets = instructionSets; 9352 this.abiOverride = abiOverride; 9353 } 9354 9355 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 9356 abstract int doPreInstall(int status); 9357 9358 /** 9359 * Rename package into final resting place. All paths on the given 9360 * scanned package should be updated to reflect the rename. 9361 */ 9362 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 9363 abstract int doPostInstall(int status, int uid); 9364 9365 /** @see PackageSettingBase#codePathString */ 9366 abstract String getCodePath(); 9367 /** @see PackageSettingBase#resourcePathString */ 9368 abstract String getResourcePath(); 9369 abstract String getLegacyNativeLibraryPath(); 9370 9371 // Need installer lock especially for dex file removal. 9372 abstract void cleanUpResourcesLI(); 9373 abstract boolean doPostDeleteLI(boolean delete); 9374 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 9375 9376 /** 9377 * Called before the source arguments are copied. This is used mostly 9378 * for MoveParams when it needs to read the source file to put it in the 9379 * destination. 9380 */ 9381 int doPreCopy() { 9382 return PackageManager.INSTALL_SUCCEEDED; 9383 } 9384 9385 /** 9386 * Called after the source arguments are copied. This is used mostly for 9387 * MoveParams when it needs to read the source file to put it in the 9388 * destination. 9389 * 9390 * @return 9391 */ 9392 int doPostCopy(int uid) { 9393 return PackageManager.INSTALL_SUCCEEDED; 9394 } 9395 9396 protected boolean isFwdLocked() { 9397 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 9398 } 9399 9400 protected boolean isExternal() { 9401 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 9402 } 9403 9404 UserHandle getUser() { 9405 return user; 9406 } 9407 } 9408 9409 /** 9410 * Logic to handle installation of non-ASEC applications, including copying 9411 * and renaming logic. 9412 */ 9413 class FileInstallArgs extends InstallArgs { 9414 private File codeFile; 9415 private File resourceFile; 9416 private File legacyNativeLibraryPath; 9417 9418 // Example topology: 9419 // /data/app/com.example/base.apk 9420 // /data/app/com.example/split_foo.apk 9421 // /data/app/com.example/lib/arm/libfoo.so 9422 // /data/app/com.example/lib/arm64/libfoo.so 9423 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 9424 9425 /** New install */ 9426 FileInstallArgs(InstallParams params) { 9427 super(params.origin, params.observer, params.installFlags, 9428 params.installerPackageName, params.getManifestDigest(), params.getUser(), 9429 null /* instruction sets */, params.packageAbiOverride); 9430 if (isFwdLocked()) { 9431 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 9432 } 9433 } 9434 9435 /** Existing install */ 9436 FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath, 9437 String[] instructionSets) { 9438 super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null); 9439 this.codeFile = (codePath != null) ? new File(codePath) : null; 9440 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 9441 this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ? 9442 new File(legacyNativeLibraryPath) : null; 9443 } 9444 9445 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9446 final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(), 9447 isFwdLocked(), abiOverride); 9448 9449 final StorageManager storage = StorageManager.from(mContext); 9450 return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory())); 9451 } 9452 9453 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9454 if (origin.staged) { 9455 Slog.d(TAG, origin.file + " already staged; skipping copy"); 9456 codeFile = origin.file; 9457 resourceFile = origin.file; 9458 return PackageManager.INSTALL_SUCCEEDED; 9459 } 9460 9461 try { 9462 final File tempDir = mInstallerService.allocateInternalStageDirLegacy(); 9463 codeFile = tempDir; 9464 resourceFile = tempDir; 9465 } catch (IOException e) { 9466 Slog.w(TAG, "Failed to create copy file: " + e); 9467 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9468 } 9469 9470 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 9471 @Override 9472 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 9473 if (!FileUtils.isValidExtFilename(name)) { 9474 throw new IllegalArgumentException("Invalid filename: " + name); 9475 } 9476 try { 9477 final File file = new File(codeFile, name); 9478 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 9479 O_RDWR | O_CREAT, 0644); 9480 Os.chmod(file.getAbsolutePath(), 0644); 9481 return new ParcelFileDescriptor(fd); 9482 } catch (ErrnoException e) { 9483 throw new RemoteException("Failed to open: " + e.getMessage()); 9484 } 9485 } 9486 }; 9487 9488 int ret = PackageManager.INSTALL_SUCCEEDED; 9489 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 9490 if (ret != PackageManager.INSTALL_SUCCEEDED) { 9491 Slog.e(TAG, "Failed to copy package"); 9492 return ret; 9493 } 9494 9495 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 9496 NativeLibraryHelper.Handle handle = null; 9497 try { 9498 handle = NativeLibraryHelper.Handle.create(codeFile); 9499 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 9500 abiOverride); 9501 } catch (IOException e) { 9502 Slog.e(TAG, "Copying native libraries failed", e); 9503 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 9504 } finally { 9505 IoUtils.closeQuietly(handle); 9506 } 9507 9508 return ret; 9509 } 9510 9511 int doPreInstall(int status) { 9512 if (status != PackageManager.INSTALL_SUCCEEDED) { 9513 cleanUp(); 9514 } 9515 return status; 9516 } 9517 9518 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9519 if (status != PackageManager.INSTALL_SUCCEEDED) { 9520 cleanUp(); 9521 return false; 9522 } else { 9523 final File beforeCodeFile = codeFile; 9524 final File afterCodeFile = getNextCodePath(pkg.packageName); 9525 9526 Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 9527 try { 9528 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 9529 } catch (ErrnoException e) { 9530 Slog.d(TAG, "Failed to rename", e); 9531 return false; 9532 } 9533 9534 if (!SELinux.restoreconRecursive(afterCodeFile)) { 9535 Slog.d(TAG, "Failed to restorecon"); 9536 return false; 9537 } 9538 9539 // Reflect the rename internally 9540 codeFile = afterCodeFile; 9541 resourceFile = afterCodeFile; 9542 9543 // Reflect the rename in scanned details 9544 pkg.codePath = afterCodeFile.getAbsolutePath(); 9545 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9546 pkg.baseCodePath); 9547 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9548 pkg.splitCodePaths); 9549 9550 // Reflect the rename in app info 9551 pkg.applicationInfo.setCodePath(pkg.codePath); 9552 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9553 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9554 pkg.applicationInfo.setResourcePath(pkg.codePath); 9555 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9556 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9557 9558 return true; 9559 } 9560 } 9561 9562 int doPostInstall(int status, int uid) { 9563 if (status != PackageManager.INSTALL_SUCCEEDED) { 9564 cleanUp(); 9565 } 9566 return status; 9567 } 9568 9569 @Override 9570 String getCodePath() { 9571 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 9572 } 9573 9574 @Override 9575 String getResourcePath() { 9576 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 9577 } 9578 9579 @Override 9580 String getLegacyNativeLibraryPath() { 9581 return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null; 9582 } 9583 9584 private boolean cleanUp() { 9585 if (codeFile == null || !codeFile.exists()) { 9586 return false; 9587 } 9588 9589 if (codeFile.isDirectory()) { 9590 FileUtils.deleteContents(codeFile); 9591 } 9592 codeFile.delete(); 9593 9594 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 9595 resourceFile.delete(); 9596 } 9597 9598 if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) { 9599 if (!FileUtils.deleteContents(legacyNativeLibraryPath)) { 9600 Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath); 9601 } 9602 legacyNativeLibraryPath.delete(); 9603 } 9604 9605 return true; 9606 } 9607 9608 void cleanUpResourcesLI() { 9609 // Try enumerating all code paths before deleting 9610 List<String> allCodePaths = Collections.EMPTY_LIST; 9611 if (codeFile != null && codeFile.exists()) { 9612 try { 9613 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9614 allCodePaths = pkg.getAllCodePaths(); 9615 } catch (PackageParserException e) { 9616 // Ignored; we tried our best 9617 } 9618 } 9619 9620 cleanUp(); 9621 9622 if (!allCodePaths.isEmpty()) { 9623 if (instructionSets == null) { 9624 throw new IllegalStateException("instructionSet == null"); 9625 } 9626 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9627 for (String codePath : allCodePaths) { 9628 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9629 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9630 if (retCode < 0) { 9631 Slog.w(TAG, "Couldn't remove dex file for package: " 9632 + " at location " + codePath + ", retcode=" + retCode); 9633 // we don't consider this to be a failure of the core package deletion 9634 } 9635 } 9636 } 9637 } 9638 } 9639 9640 boolean doPostDeleteLI(boolean delete) { 9641 // XXX err, shouldn't we respect the delete flag? 9642 cleanUpResourcesLI(); 9643 return true; 9644 } 9645 } 9646 9647 private boolean isAsecExternal(String cid) { 9648 final String asecPath = PackageHelper.getSdFilesystem(cid); 9649 return !asecPath.startsWith(mAsecInternalPath); 9650 } 9651 9652 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 9653 PackageManagerException { 9654 if (copyRet < 0) { 9655 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 9656 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 9657 throw new PackageManagerException(copyRet, message); 9658 } 9659 } 9660 } 9661 9662 /** 9663 * Extract the MountService "container ID" from the full code path of an 9664 * .apk. 9665 */ 9666 static String cidFromCodePath(String fullCodePath) { 9667 int eidx = fullCodePath.lastIndexOf("/"); 9668 String subStr1 = fullCodePath.substring(0, eidx); 9669 int sidx = subStr1.lastIndexOf("/"); 9670 return subStr1.substring(sidx+1, eidx); 9671 } 9672 9673 /** 9674 * Logic to handle installation of ASEC applications, including copying and 9675 * renaming logic. 9676 */ 9677 class AsecInstallArgs extends InstallArgs { 9678 static final String RES_FILE_NAME = "pkg.apk"; 9679 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 9680 9681 String cid; 9682 String packagePath; 9683 String resourcePath; 9684 String legacyNativeLibraryDir; 9685 9686 /** New install */ 9687 AsecInstallArgs(InstallParams params) { 9688 super(params.origin, params.observer, params.installFlags, 9689 params.installerPackageName, params.getManifestDigest(), 9690 params.getUser(), null /* instruction sets */, 9691 params.packageAbiOverride); 9692 } 9693 9694 /** Existing install */ 9695 AsecInstallArgs(String fullCodePath, String[] instructionSets, 9696 boolean isExternal, boolean isForwardLocked) { 9697 super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0) 9698 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9699 instructionSets, null); 9700 // Hackily pretend we're still looking at a full code path 9701 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 9702 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 9703 } 9704 9705 // Extract cid from fullCodePath 9706 int eidx = fullCodePath.lastIndexOf("/"); 9707 String subStr1 = fullCodePath.substring(0, eidx); 9708 int sidx = subStr1.lastIndexOf("/"); 9709 cid = subStr1.substring(sidx+1, eidx); 9710 setMountPath(subStr1); 9711 } 9712 9713 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 9714 super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 9715 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 9716 instructionSets, null); 9717 this.cid = cid; 9718 setMountPath(PackageHelper.getSdDir(cid)); 9719 } 9720 9721 void createCopyFile() { 9722 cid = mInstallerService.allocateExternalStageCidLegacy(); 9723 } 9724 9725 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9726 final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(), 9727 abiOverride); 9728 9729 final File target; 9730 if (isExternal()) { 9731 target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory(); 9732 } else { 9733 target = Environment.getDataDirectory(); 9734 } 9735 9736 final StorageManager storage = StorageManager.from(mContext); 9737 return (sizeBytes <= storage.getStorageBytesUntilLow(target)); 9738 } 9739 9740 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9741 if (origin.staged) { 9742 Slog.d(TAG, origin.cid + " already staged; skipping copy"); 9743 cid = origin.cid; 9744 setMountPath(PackageHelper.getSdDir(cid)); 9745 return PackageManager.INSTALL_SUCCEEDED; 9746 } 9747 9748 if (temp) { 9749 createCopyFile(); 9750 } else { 9751 /* 9752 * Pre-emptively destroy the container since it's destroyed if 9753 * copying fails due to it existing anyway. 9754 */ 9755 PackageHelper.destroySdDir(cid); 9756 } 9757 9758 final String newMountPath = imcs.copyPackageToContainer( 9759 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(), 9760 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 9761 9762 if (newMountPath != null) { 9763 setMountPath(newMountPath); 9764 return PackageManager.INSTALL_SUCCEEDED; 9765 } else { 9766 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9767 } 9768 } 9769 9770 @Override 9771 String getCodePath() { 9772 return packagePath; 9773 } 9774 9775 @Override 9776 String getResourcePath() { 9777 return resourcePath; 9778 } 9779 9780 @Override 9781 String getLegacyNativeLibraryPath() { 9782 return legacyNativeLibraryDir; 9783 } 9784 9785 int doPreInstall(int status) { 9786 if (status != PackageManager.INSTALL_SUCCEEDED) { 9787 // Destroy container 9788 PackageHelper.destroySdDir(cid); 9789 } else { 9790 boolean mounted = PackageHelper.isContainerMounted(cid); 9791 if (!mounted) { 9792 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 9793 Process.SYSTEM_UID); 9794 if (newMountPath != null) { 9795 setMountPath(newMountPath); 9796 } else { 9797 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9798 } 9799 } 9800 } 9801 return status; 9802 } 9803 9804 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 9805 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 9806 String newMountPath = null; 9807 if (PackageHelper.isContainerMounted(cid)) { 9808 // Unmount the container 9809 if (!PackageHelper.unMountSdDir(cid)) { 9810 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9811 return false; 9812 } 9813 } 9814 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9815 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9816 " which might be stale. Will try to clean up."); 9817 // Clean up the stale container and proceed to recreate. 9818 if (!PackageHelper.destroySdDir(newCacheId)) { 9819 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9820 return false; 9821 } 9822 // Successfully cleaned up stale container. Try to rename again. 9823 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9824 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9825 + " inspite of cleaning it up."); 9826 return false; 9827 } 9828 } 9829 if (!PackageHelper.isContainerMounted(newCacheId)) { 9830 Slog.w(TAG, "Mounting container " + newCacheId); 9831 newMountPath = PackageHelper.mountSdDir(newCacheId, 9832 getEncryptKey(), Process.SYSTEM_UID); 9833 } else { 9834 newMountPath = PackageHelper.getSdDir(newCacheId); 9835 } 9836 if (newMountPath == null) { 9837 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9838 return false; 9839 } 9840 Log.i(TAG, "Succesfully renamed " + cid + 9841 " to " + newCacheId + 9842 " at new path: " + newMountPath); 9843 cid = newCacheId; 9844 9845 final File beforeCodeFile = new File(packagePath); 9846 setMountPath(newMountPath); 9847 final File afterCodeFile = new File(packagePath); 9848 9849 // Reflect the rename in scanned details 9850 pkg.codePath = afterCodeFile.getAbsolutePath(); 9851 pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9852 pkg.baseCodePath); 9853 pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile, 9854 pkg.splitCodePaths); 9855 9856 // Reflect the rename in app info 9857 pkg.applicationInfo.setCodePath(pkg.codePath); 9858 pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath); 9859 pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths); 9860 pkg.applicationInfo.setResourcePath(pkg.codePath); 9861 pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath); 9862 pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths); 9863 9864 return true; 9865 } 9866 9867 private void setMountPath(String mountPath) { 9868 final File mountFile = new File(mountPath); 9869 9870 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 9871 if (monolithicFile.exists()) { 9872 packagePath = monolithicFile.getAbsolutePath(); 9873 if (isFwdLocked()) { 9874 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 9875 } else { 9876 resourcePath = packagePath; 9877 } 9878 } else { 9879 packagePath = mountFile.getAbsolutePath(); 9880 resourcePath = packagePath; 9881 } 9882 9883 legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath(); 9884 } 9885 9886 int doPostInstall(int status, int uid) { 9887 if (status != PackageManager.INSTALL_SUCCEEDED) { 9888 cleanUp(); 9889 } else { 9890 final int groupOwner; 9891 final String protectedFile; 9892 if (isFwdLocked()) { 9893 groupOwner = UserHandle.getSharedAppGid(uid); 9894 protectedFile = RES_FILE_NAME; 9895 } else { 9896 groupOwner = -1; 9897 protectedFile = null; 9898 } 9899 9900 if (uid < Process.FIRST_APPLICATION_UID 9901 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9902 Slog.e(TAG, "Failed to finalize " + cid); 9903 PackageHelper.destroySdDir(cid); 9904 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9905 } 9906 9907 boolean mounted = PackageHelper.isContainerMounted(cid); 9908 if (!mounted) { 9909 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9910 } 9911 } 9912 return status; 9913 } 9914 9915 private void cleanUp() { 9916 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9917 9918 // Destroy secure container 9919 PackageHelper.destroySdDir(cid); 9920 } 9921 9922 private List<String> getAllCodePaths() { 9923 final File codeFile = new File(getCodePath()); 9924 if (codeFile != null && codeFile.exists()) { 9925 try { 9926 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 9927 return pkg.getAllCodePaths(); 9928 } catch (PackageParserException e) { 9929 // Ignored; we tried our best 9930 } 9931 } 9932 return Collections.EMPTY_LIST; 9933 } 9934 9935 void cleanUpResourcesLI() { 9936 // Enumerate all code paths before deleting 9937 cleanUpResourcesLI(getAllCodePaths()); 9938 } 9939 9940 private void cleanUpResourcesLI(List<String> allCodePaths) { 9941 cleanUp(); 9942 9943 if (!allCodePaths.isEmpty()) { 9944 if (instructionSets == null) { 9945 throw new IllegalStateException("instructionSet == null"); 9946 } 9947 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 9948 for (String codePath : allCodePaths) { 9949 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 9950 int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet); 9951 if (retCode < 0) { 9952 Slog.w(TAG, "Couldn't remove dex file for package: " 9953 + " at location " + codePath + ", retcode=" + retCode); 9954 // we don't consider this to be a failure of the core package deletion 9955 } 9956 } 9957 } 9958 } 9959 } 9960 9961 boolean matchContainer(String app) { 9962 if (cid.startsWith(app)) { 9963 return true; 9964 } 9965 return false; 9966 } 9967 9968 String getPackageName() { 9969 return getAsecPackageName(cid); 9970 } 9971 9972 boolean doPostDeleteLI(boolean delete) { 9973 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 9974 final List<String> allCodePaths = getAllCodePaths(); 9975 boolean mounted = PackageHelper.isContainerMounted(cid); 9976 if (mounted) { 9977 // Unmount first 9978 if (PackageHelper.unMountSdDir(cid)) { 9979 mounted = false; 9980 } 9981 } 9982 if (!mounted && delete) { 9983 cleanUpResourcesLI(allCodePaths); 9984 } 9985 return !mounted; 9986 } 9987 9988 @Override 9989 int doPreCopy() { 9990 if (isFwdLocked()) { 9991 if (!PackageHelper.fixSdPermissions(cid, 9992 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 9993 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9994 } 9995 } 9996 9997 return PackageManager.INSTALL_SUCCEEDED; 9998 } 9999 10000 @Override 10001 int doPostCopy(int uid) { 10002 if (isFwdLocked()) { 10003 if (uid < Process.FIRST_APPLICATION_UID 10004 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 10005 RES_FILE_NAME)) { 10006 Slog.e(TAG, "Failed to finalize " + cid); 10007 PackageHelper.destroySdDir(cid); 10008 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 10009 } 10010 } 10011 10012 return PackageManager.INSTALL_SUCCEEDED; 10013 } 10014 } 10015 10016 static String getAsecPackageName(String packageCid) { 10017 int idx = packageCid.lastIndexOf("-"); 10018 if (idx == -1) { 10019 return packageCid; 10020 } 10021 return packageCid.substring(0, idx); 10022 } 10023 10024 // Utility method used to create code paths based on package name and available index. 10025 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 10026 String idxStr = ""; 10027 int idx = 1; 10028 // Fall back to default value of idx=1 if prefix is not 10029 // part of oldCodePath 10030 if (oldCodePath != null) { 10031 String subStr = oldCodePath; 10032 // Drop the suffix right away 10033 if (suffix != null && subStr.endsWith(suffix)) { 10034 subStr = subStr.substring(0, subStr.length() - suffix.length()); 10035 } 10036 // If oldCodePath already contains prefix find out the 10037 // ending index to either increment or decrement. 10038 int sidx = subStr.lastIndexOf(prefix); 10039 if (sidx != -1) { 10040 subStr = subStr.substring(sidx + prefix.length()); 10041 if (subStr != null) { 10042 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 10043 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 10044 } 10045 try { 10046 idx = Integer.parseInt(subStr); 10047 if (idx <= 1) { 10048 idx++; 10049 } else { 10050 idx--; 10051 } 10052 } catch(NumberFormatException e) { 10053 } 10054 } 10055 } 10056 } 10057 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 10058 return prefix + idxStr; 10059 } 10060 10061 private File getNextCodePath(String packageName) { 10062 int suffix = 1; 10063 File result; 10064 do { 10065 result = new File(mAppInstallDir, packageName + "-" + suffix); 10066 suffix++; 10067 } while (result.exists()); 10068 return result; 10069 } 10070 10071 // Utility method used to ignore ADD/REMOVE events 10072 // by directory observer. 10073 private static boolean ignoreCodePath(String fullPathStr) { 10074 String apkName = deriveCodePathName(fullPathStr); 10075 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 10076 if (idx != -1 && ((idx+1) < apkName.length())) { 10077 // Make sure the package ends with a numeral 10078 String version = apkName.substring(idx+1); 10079 try { 10080 Integer.parseInt(version); 10081 return true; 10082 } catch (NumberFormatException e) {} 10083 } 10084 return false; 10085 } 10086 10087 // Utility method that returns the relative package path with respect 10088 // to the installation directory. Like say for /data/data/com.test-1.apk 10089 // string com.test-1 is returned. 10090 static String deriveCodePathName(String codePath) { 10091 if (codePath == null) { 10092 return null; 10093 } 10094 final File codeFile = new File(codePath); 10095 final String name = codeFile.getName(); 10096 if (codeFile.isDirectory()) { 10097 return name; 10098 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 10099 final int lastDot = name.lastIndexOf('.'); 10100 return name.substring(0, lastDot); 10101 } else { 10102 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 10103 return null; 10104 } 10105 } 10106 10107 class PackageInstalledInfo { 10108 String name; 10109 int uid; 10110 // The set of users that originally had this package installed. 10111 int[] origUsers; 10112 // The set of users that now have this package installed. 10113 int[] newUsers; 10114 PackageParser.Package pkg; 10115 int returnCode; 10116 String returnMsg; 10117 PackageRemovedInfo removedInfo; 10118 10119 public void setError(int code, String msg) { 10120 returnCode = code; 10121 returnMsg = msg; 10122 Slog.w(TAG, msg); 10123 } 10124 10125 public void setError(String msg, PackageParserException e) { 10126 returnCode = e.error; 10127 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 10128 Slog.w(TAG, msg, e); 10129 } 10130 10131 public void setError(String msg, PackageManagerException e) { 10132 returnCode = e.error; 10133 returnMsg = ExceptionUtils.getCompleteMessage(msg, e); 10134 Slog.w(TAG, msg, e); 10135 } 10136 10137 // In some error cases we want to convey more info back to the observer 10138 String origPackage; 10139 String origPermission; 10140 } 10141 10142 /* 10143 * Install a non-existing package. 10144 */ 10145 private void installNewPackageLI(PackageParser.Package pkg, 10146 int parseFlags, int scanFlags, UserHandle user, 10147 String installerPackageName, PackageInstalledInfo res) { 10148 // Remember this for later, in case we need to rollback this install 10149 String pkgName = pkg.packageName; 10150 10151 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 10152 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 10153 synchronized(mPackages) { 10154 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 10155 // A package with the same name is already installed, though 10156 // it has been renamed to an older name. The package we 10157 // are trying to install should be installed as an update to 10158 // the existing one, but that has not been requested, so bail. 10159 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10160 + " without first uninstalling package running as " 10161 + mSettings.mRenamedPackages.get(pkgName)); 10162 return; 10163 } 10164 if (mPackages.containsKey(pkgName)) { 10165 // Don't allow installation over an existing package with the same name. 10166 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 10167 + " without first uninstalling."); 10168 return; 10169 } 10170 } 10171 10172 try { 10173 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 10174 System.currentTimeMillis(), user); 10175 10176 updateSettingsLI(newPackage, installerPackageName, null, null, res); 10177 // delete the partially installed application. the data directory will have to be 10178 // restored if it was already existing 10179 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10180 // remove package from internal structures. Note that we want deletePackageX to 10181 // delete the package data and cache directories that it created in 10182 // scanPackageLocked, unless those directories existed before we even tried to 10183 // install. 10184 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 10185 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 10186 res.removedInfo, true); 10187 } 10188 10189 } catch (PackageManagerException e) { 10190 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10191 } 10192 } 10193 10194 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 10195 // Upgrade keysets are being used. Determine if new package has a superset of the 10196 // required keys. 10197 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 10198 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10199 for (int i = 0; i < upgradeKeySets.length; i++) { 10200 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 10201 if (newPkg.mSigningKeys.containsAll(upgradeSet)) { 10202 return true; 10203 } 10204 } 10205 return false; 10206 } 10207 10208 private void replacePackageLI(PackageParser.Package pkg, 10209 int parseFlags, int scanFlags, UserHandle user, 10210 String installerPackageName, PackageInstalledInfo res) { 10211 PackageParser.Package oldPackage; 10212 String pkgName = pkg.packageName; 10213 int[] allUsers; 10214 boolean[] perUserInstalled; 10215 10216 // First find the old package info and check signatures 10217 synchronized(mPackages) { 10218 oldPackage = mPackages.get(pkgName); 10219 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 10220 PackageSetting ps = mSettings.mPackages.get(pkgName); 10221 if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 10222 // default to original signature matching 10223 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 10224 != PackageManager.SIGNATURE_MATCH) { 10225 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10226 "New package has a different signature: " + pkgName); 10227 return; 10228 } 10229 } else { 10230 if(!checkUpgradeKeySetLP(ps, pkg)) { 10231 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10232 "New package not signed by keys specified by upgrade-keysets: " 10233 + pkgName); 10234 return; 10235 } 10236 } 10237 10238 // In case of rollback, remember per-user/profile install state 10239 allUsers = sUserManager.getUserIds(); 10240 perUserInstalled = new boolean[allUsers.length]; 10241 for (int i = 0; i < allUsers.length; i++) { 10242 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10243 } 10244 } 10245 10246 boolean sysPkg = (isSystemApp(oldPackage)); 10247 if (sysPkg) { 10248 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10249 user, allUsers, perUserInstalled, installerPackageName, res); 10250 } else { 10251 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags, 10252 user, allUsers, perUserInstalled, installerPackageName, res); 10253 } 10254 } 10255 10256 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 10257 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10258 int[] allUsers, boolean[] perUserInstalled, 10259 String installerPackageName, PackageInstalledInfo res) { 10260 String pkgName = deletedPackage.packageName; 10261 boolean deletedPkg = true; 10262 boolean updatedSettings = false; 10263 10264 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 10265 + deletedPackage); 10266 long origUpdateTime; 10267 if (pkg.mExtras != null) { 10268 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 10269 } else { 10270 origUpdateTime = 0; 10271 } 10272 10273 // First delete the existing package while retaining the data directory 10274 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 10275 res.removedInfo, true)) { 10276 // If the existing package wasn't successfully deleted 10277 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 10278 deletedPkg = false; 10279 } else { 10280 // Successfully deleted the old package; proceed with replace. 10281 10282 // If deleted package lived in a container, give users a chance to 10283 // relinquish resources before killing. 10284 if (isForwardLocked(deletedPackage) || isExternal(deletedPackage)) { 10285 if (DEBUG_INSTALL) { 10286 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 10287 } 10288 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 10289 final ArrayList<String> pkgList = new ArrayList<String>(1); 10290 pkgList.add(deletedPackage.applicationInfo.packageName); 10291 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 10292 } 10293 10294 deleteCodeCacheDirsLI(pkgName); 10295 try { 10296 final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, 10297 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 10298 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10299 updatedSettings = true; 10300 } catch (PackageManagerException e) { 10301 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10302 } 10303 } 10304 10305 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10306 // remove package from internal structures. Note that we want deletePackageX to 10307 // delete the package data and cache directories that it created in 10308 // scanPackageLocked, unless those directories existed before we even tried to 10309 // install. 10310 if(updatedSettings) { 10311 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 10312 deletePackageLI( 10313 pkgName, null, true, allUsers, perUserInstalled, 10314 PackageManager.DELETE_KEEP_DATA, 10315 res.removedInfo, true); 10316 } 10317 // Since we failed to install the new package we need to restore the old 10318 // package that we deleted. 10319 if (deletedPkg) { 10320 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 10321 File restoreFile = new File(deletedPackage.codePath); 10322 // Parse old package 10323 boolean oldOnSd = isExternal(deletedPackage); 10324 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 10325 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) | 10326 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 10327 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 10328 try { 10329 scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null); 10330 } catch (PackageManagerException e) { 10331 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 10332 + e.getMessage()); 10333 return; 10334 } 10335 // Restore of old package succeeded. Update permissions. 10336 // writer 10337 synchronized (mPackages) { 10338 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 10339 UPDATE_PERMISSIONS_ALL); 10340 // can downgrade to reader 10341 mSettings.writeLPr(); 10342 } 10343 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 10344 } 10345 } 10346 } 10347 10348 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 10349 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 10350 int[] allUsers, boolean[] perUserInstalled, 10351 String installerPackageName, PackageInstalledInfo res) { 10352 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 10353 + ", old=" + deletedPackage); 10354 boolean disabledSystem = false; 10355 boolean updatedSettings = false; 10356 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 10357 if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) { 10358 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10359 } 10360 String packageName = deletedPackage.packageName; 10361 if (packageName == null) { 10362 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10363 "Attempt to delete null packageName."); 10364 return; 10365 } 10366 PackageParser.Package oldPkg; 10367 PackageSetting oldPkgSetting; 10368 // reader 10369 synchronized (mPackages) { 10370 oldPkg = mPackages.get(packageName); 10371 oldPkgSetting = mSettings.mPackages.get(packageName); 10372 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 10373 (oldPkgSetting == null)) { 10374 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, 10375 "Couldn't find package:" + packageName + " information"); 10376 return; 10377 } 10378 } 10379 10380 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 10381 10382 res.removedInfo.uid = oldPkg.applicationInfo.uid; 10383 res.removedInfo.removedPackage = packageName; 10384 // Remove existing system package 10385 removePackageLI(oldPkgSetting, true); 10386 // writer 10387 synchronized (mPackages) { 10388 disabledSystem = mSettings.disableSystemPackageLPw(packageName); 10389 if (!disabledSystem && deletedPackage != null) { 10390 // We didn't need to disable the .apk as a current system package, 10391 // which means we are replacing another update that is already 10392 // installed. We need to make sure to delete the older one's .apk. 10393 res.removedInfo.args = createInstallArgsForExisting(0, 10394 deletedPackage.applicationInfo.getCodePath(), 10395 deletedPackage.applicationInfo.getResourcePath(), 10396 deletedPackage.applicationInfo.nativeLibraryRootDir, 10397 getAppDexInstructionSets(deletedPackage.applicationInfo)); 10398 } else { 10399 res.removedInfo.args = null; 10400 } 10401 } 10402 10403 // Successfully disabled the old package. Now proceed with re-installation 10404 deleteCodeCacheDirsLI(packageName); 10405 10406 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10407 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10408 10409 PackageParser.Package newPackage = null; 10410 try { 10411 newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user); 10412 if (newPackage.mExtras != null) { 10413 final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras; 10414 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 10415 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 10416 10417 // is the update attempting to change shared user? that isn't going to work... 10418 if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) { 10419 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 10420 "Forbidding shared user change from " + oldPkgSetting.sharedUser 10421 + " to " + newPkgSetting.sharedUser); 10422 updatedSettings = true; 10423 } 10424 } 10425 10426 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 10427 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 10428 updatedSettings = true; 10429 } 10430 10431 } catch (PackageManagerException e) { 10432 res.setError("Package couldn't be installed in " + pkg.codePath, e); 10433 } 10434 10435 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 10436 // Re installation failed. Restore old information 10437 // Remove new pkg information 10438 if (newPackage != null) { 10439 removeInstalledPackageLI(newPackage, true); 10440 } 10441 // Add back the old system package 10442 try { 10443 scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 10444 } catch (PackageManagerException e) { 10445 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 10446 } 10447 // Restore the old system information in Settings 10448 synchronized (mPackages) { 10449 if (disabledSystem) { 10450 mSettings.enableSystemPackageLPw(packageName); 10451 } 10452 if (updatedSettings) { 10453 mSettings.setInstallerPackageName(packageName, 10454 oldPkgSetting.installerPackageName); 10455 } 10456 mSettings.writeLPr(); 10457 } 10458 } 10459 } 10460 10461 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 10462 int[] allUsers, boolean[] perUserInstalled, 10463 PackageInstalledInfo res) { 10464 String pkgName = newPackage.packageName; 10465 synchronized (mPackages) { 10466 //write settings. the installStatus will be incomplete at this stage. 10467 //note that the new package setting would have already been 10468 //added to mPackages. It hasn't been persisted yet. 10469 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 10470 mSettings.writeLPr(); 10471 } 10472 10473 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 10474 10475 synchronized (mPackages) { 10476 updatePermissionsLPw(newPackage.packageName, newPackage, 10477 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 10478 ? UPDATE_PERMISSIONS_ALL : 0)); 10479 // For system-bundled packages, we assume that installing an upgraded version 10480 // of the package implies that the user actually wants to run that new code, 10481 // so we enable the package. 10482 if (isSystemApp(newPackage)) { 10483 // NB: implicit assumption that system package upgrades apply to all users 10484 if (DEBUG_INSTALL) { 10485 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 10486 } 10487 PackageSetting ps = mSettings.mPackages.get(pkgName); 10488 if (ps != null) { 10489 if (res.origUsers != null) { 10490 for (int userHandle : res.origUsers) { 10491 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 10492 userHandle, installerPackageName); 10493 } 10494 } 10495 // Also convey the prior install/uninstall state 10496 if (allUsers != null && perUserInstalled != null) { 10497 for (int i = 0; i < allUsers.length; i++) { 10498 if (DEBUG_INSTALL) { 10499 Slog.d(TAG, " user " + allUsers[i] 10500 + " => " + perUserInstalled[i]); 10501 } 10502 ps.setInstalled(perUserInstalled[i], allUsers[i]); 10503 } 10504 // these install state changes will be persisted in the 10505 // upcoming call to mSettings.writeLPr(). 10506 } 10507 } 10508 } 10509 res.name = pkgName; 10510 res.uid = newPackage.applicationInfo.uid; 10511 res.pkg = newPackage; 10512 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 10513 mSettings.setInstallerPackageName(pkgName, installerPackageName); 10514 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10515 //to update install status 10516 mSettings.writeLPr(); 10517 } 10518 } 10519 10520 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 10521 final int installFlags = args.installFlags; 10522 String installerPackageName = args.installerPackageName; 10523 File tmpPackageFile = new File(args.getCodePath()); 10524 boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 10525 boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0); 10526 boolean replace = false; 10527 final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE; 10528 // Result object to be returned 10529 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 10530 10531 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 10532 // Retrieve PackageSettings and parse package 10533 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 10534 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 10535 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 10536 PackageParser pp = new PackageParser(); 10537 pp.setSeparateProcesses(mSeparateProcesses); 10538 pp.setDisplayMetrics(mMetrics); 10539 10540 final PackageParser.Package pkg; 10541 try { 10542 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 10543 } catch (PackageParserException e) { 10544 res.setError("Failed parse during installPackageLI", e); 10545 return; 10546 } 10547 10548 // Mark that we have an install time CPU ABI override. 10549 pkg.cpuAbiOverride = args.abiOverride; 10550 10551 String pkgName = res.name = pkg.packageName; 10552 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 10553 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 10554 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 10555 return; 10556 } 10557 } 10558 10559 try { 10560 pp.collectCertificates(pkg, parseFlags); 10561 pp.collectManifestDigest(pkg); 10562 } catch (PackageParserException e) { 10563 res.setError("Failed collect during installPackageLI", e); 10564 return; 10565 } 10566 10567 /* If the installer passed in a manifest digest, compare it now. */ 10568 if (args.manifestDigest != null) { 10569 if (DEBUG_INSTALL) { 10570 final String parsedManifest = pkg.manifestDigest == null ? "null" 10571 : pkg.manifestDigest.toString(); 10572 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 10573 + parsedManifest); 10574 } 10575 10576 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 10577 res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed"); 10578 return; 10579 } 10580 } else if (DEBUG_INSTALL) { 10581 final String parsedManifest = pkg.manifestDigest == null 10582 ? "null" : pkg.manifestDigest.toString(); 10583 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 10584 } 10585 10586 // Get rid of all references to package scan path via parser. 10587 pp = null; 10588 String oldCodePath = null; 10589 boolean systemApp = false; 10590 synchronized (mPackages) { 10591 // Check if installing already existing package 10592 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 10593 String oldName = mSettings.mRenamedPackages.get(pkgName); 10594 if (pkg.mOriginalPackages != null 10595 && pkg.mOriginalPackages.contains(oldName) 10596 && mPackages.containsKey(oldName)) { 10597 // This package is derived from an original package, 10598 // and this device has been updating from that original 10599 // name. We must continue using the original name, so 10600 // rename the new package here. 10601 pkg.setPackageName(oldName); 10602 pkgName = pkg.packageName; 10603 replace = true; 10604 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 10605 + oldName + " pkgName=" + pkgName); 10606 } else if (mPackages.containsKey(pkgName)) { 10607 // This package, under its official name, already exists 10608 // on the device; we should replace it. 10609 replace = true; 10610 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 10611 } 10612 } 10613 10614 PackageSetting ps = mSettings.mPackages.get(pkgName); 10615 if (ps != null) { 10616 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 10617 10618 // Quick sanity check that we're signed correctly if updating; 10619 // we'll check this again later when scanning, but we want to 10620 // bail early here before tripping over redefined permissions. 10621 if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) { 10622 try { 10623 verifySignaturesLP(ps, pkg); 10624 } catch (PackageManagerException e) { 10625 res.setError(e.error, e.getMessage()); 10626 return; 10627 } 10628 } else { 10629 if (!checkUpgradeKeySetLP(ps, pkg)) { 10630 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 10631 + pkg.packageName + " upgrade keys do not match the " 10632 + "previously installed version"); 10633 return; 10634 } 10635 } 10636 10637 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 10638 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 10639 systemApp = (ps.pkg.applicationInfo.flags & 10640 ApplicationInfo.FLAG_SYSTEM) != 0; 10641 } 10642 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10643 } 10644 10645 // Check whether the newly-scanned package wants to define an already-defined perm 10646 int N = pkg.permissions.size(); 10647 for (int i = N-1; i >= 0; i--) { 10648 PackageParser.Permission perm = pkg.permissions.get(i); 10649 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 10650 if (bp != null) { 10651 // If the defining package is signed with our cert, it's okay. This 10652 // also includes the "updating the same package" case, of course. 10653 // "updating same package" could also involve key-rotation. 10654 final boolean sigsOk; 10655 if (!bp.sourcePackage.equals(pkg.packageName) 10656 || !(bp.packageSetting instanceof PackageSetting) 10657 || !bp.packageSetting.keySetData.isUsingUpgradeKeySets() 10658 || ((PackageSetting) bp.packageSetting).sharedUser != null) { 10659 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 10660 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 10661 } else { 10662 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 10663 } 10664 if (!sigsOk) { 10665 // If the owning package is the system itself, we log but allow 10666 // install to proceed; we fail the install on all other permission 10667 // redefinitions. 10668 if (!bp.sourcePackage.equals("android")) { 10669 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 10670 + pkg.packageName + " attempting to redeclare permission " 10671 + perm.info.name + " already owned by " + bp.sourcePackage); 10672 res.origPermission = perm.info.name; 10673 res.origPackage = bp.sourcePackage; 10674 return; 10675 } else { 10676 Slog.w(TAG, "Package " + pkg.packageName 10677 + " attempting to redeclare system permission " 10678 + perm.info.name + "; ignoring new declaration"); 10679 pkg.permissions.remove(i); 10680 } 10681 } 10682 } 10683 } 10684 10685 } 10686 10687 if (systemApp && onSd) { 10688 // Disable updates to system apps on sdcard 10689 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 10690 "Cannot install updates to system apps on sdcard"); 10691 return; 10692 } 10693 10694 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 10695 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 10696 return; 10697 } 10698 10699 if (replace) { 10700 replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 10701 installerPackageName, res); 10702 } else { 10703 installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 10704 args.user, installerPackageName, res); 10705 } 10706 synchronized (mPackages) { 10707 final PackageSetting ps = mSettings.mPackages.get(pkgName); 10708 if (ps != null) { 10709 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 10710 } 10711 } 10712 } 10713 10714 private static boolean isForwardLocked(PackageParser.Package pkg) { 10715 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10716 } 10717 10718 private static boolean isForwardLocked(ApplicationInfo info) { 10719 return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10720 } 10721 10722 private boolean isForwardLocked(PackageSetting ps) { 10723 return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 10724 } 10725 10726 private static boolean isMultiArch(PackageSetting ps) { 10727 return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10728 } 10729 10730 private static boolean isMultiArch(ApplicationInfo info) { 10731 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 10732 } 10733 10734 private static boolean isExternal(PackageParser.Package pkg) { 10735 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10736 } 10737 10738 private static boolean isExternal(PackageSetting ps) { 10739 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10740 } 10741 10742 private static boolean isExternal(ApplicationInfo info) { 10743 return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 10744 } 10745 10746 private static boolean isSystemApp(PackageParser.Package pkg) { 10747 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10748 } 10749 10750 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 10751 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0; 10752 } 10753 10754 private static boolean isSystemApp(ApplicationInfo info) { 10755 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 10756 } 10757 10758 private static boolean isSystemApp(PackageSetting ps) { 10759 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 10760 } 10761 10762 private static boolean isUpdatedSystemApp(PackageSetting ps) { 10763 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10764 } 10765 10766 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 10767 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10768 } 10769 10770 private static boolean isUpdatedSystemApp(ApplicationInfo info) { 10771 return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 10772 } 10773 10774 private int packageFlagsToInstallFlags(PackageSetting ps) { 10775 int installFlags = 0; 10776 if (isExternal(ps)) { 10777 installFlags |= PackageManager.INSTALL_EXTERNAL; 10778 } 10779 if (isForwardLocked(ps)) { 10780 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 10781 } 10782 return installFlags; 10783 } 10784 10785 private void deleteTempPackageFiles() { 10786 final FilenameFilter filter = new FilenameFilter() { 10787 public boolean accept(File dir, String name) { 10788 return name.startsWith("vmdl") && name.endsWith(".tmp"); 10789 } 10790 }; 10791 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 10792 file.delete(); 10793 } 10794 } 10795 10796 @Override 10797 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 10798 int flags) { 10799 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 10800 flags); 10801 } 10802 10803 @Override 10804 public void deletePackage(final String packageName, 10805 final IPackageDeleteObserver2 observer, final int userId, final int flags) { 10806 mContext.enforceCallingOrSelfPermission( 10807 android.Manifest.permission.DELETE_PACKAGES, null); 10808 final int uid = Binder.getCallingUid(); 10809 if (UserHandle.getUserId(uid) != userId) { 10810 mContext.enforceCallingPermission( 10811 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 10812 "deletePackage for user " + userId); 10813 } 10814 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 10815 try { 10816 observer.onPackageDeleted(packageName, 10817 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 10818 } catch (RemoteException re) { 10819 } 10820 return; 10821 } 10822 10823 boolean uninstallBlocked = false; 10824 if ((flags & PackageManager.DELETE_ALL_USERS) != 0) { 10825 int[] users = sUserManager.getUserIds(); 10826 for (int i = 0; i < users.length; ++i) { 10827 if (getBlockUninstallForUser(packageName, users[i])) { 10828 uninstallBlocked = true; 10829 break; 10830 } 10831 } 10832 } else { 10833 uninstallBlocked = getBlockUninstallForUser(packageName, userId); 10834 } 10835 if (uninstallBlocked) { 10836 try { 10837 observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED, 10838 null); 10839 } catch (RemoteException re) { 10840 } 10841 return; 10842 } 10843 10844 if (DEBUG_REMOVE) { 10845 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 10846 } 10847 // Queue up an async operation since the package deletion may take a little while. 10848 mHandler.post(new Runnable() { 10849 public void run() { 10850 mHandler.removeCallbacks(this); 10851 final int returnCode = deletePackageX(packageName, userId, flags); 10852 if (observer != null) { 10853 try { 10854 observer.onPackageDeleted(packageName, returnCode, null); 10855 } catch (RemoteException e) { 10856 Log.i(TAG, "Observer no longer exists."); 10857 } //end catch 10858 } //end if 10859 } //end run 10860 }); 10861 } 10862 10863 private boolean isPackageDeviceAdmin(String packageName, int userId) { 10864 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 10865 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 10866 try { 10867 if (dpm != null) { 10868 if (dpm.isDeviceOwner(packageName)) { 10869 return true; 10870 } 10871 int[] users; 10872 if (userId == UserHandle.USER_ALL) { 10873 users = sUserManager.getUserIds(); 10874 } else { 10875 users = new int[]{userId}; 10876 } 10877 for (int i = 0; i < users.length; ++i) { 10878 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 10879 return true; 10880 } 10881 } 10882 } 10883 } catch (RemoteException e) { 10884 } 10885 return false; 10886 } 10887 10888 /** 10889 * This method is an internal method that could be get invoked either 10890 * to delete an installed package or to clean up a failed installation. 10891 * After deleting an installed package, a broadcast is sent to notify any 10892 * listeners that the package has been installed. For cleaning up a failed 10893 * installation, the broadcast is not necessary since the package's 10894 * installation wouldn't have sent the initial broadcast either 10895 * The key steps in deleting a package are 10896 * deleting the package information in internal structures like mPackages, 10897 * deleting the packages base directories through installd 10898 * updating mSettings to reflect current status 10899 * persisting settings for later use 10900 * sending a broadcast if necessary 10901 */ 10902 private int deletePackageX(String packageName, int userId, int flags) { 10903 final PackageRemovedInfo info = new PackageRemovedInfo(); 10904 final boolean res; 10905 10906 final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0 10907 ? UserHandle.ALL : new UserHandle(userId); 10908 10909 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 10910 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 10911 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 10912 } 10913 10914 boolean removedForAllUsers = false; 10915 boolean systemUpdate = false; 10916 10917 // for the uninstall-updates case and restricted profiles, remember the per- 10918 // userhandle installed state 10919 int[] allUsers; 10920 boolean[] perUserInstalled; 10921 synchronized (mPackages) { 10922 PackageSetting ps = mSettings.mPackages.get(packageName); 10923 allUsers = sUserManager.getUserIds(); 10924 perUserInstalled = new boolean[allUsers.length]; 10925 for (int i = 0; i < allUsers.length; i++) { 10926 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10927 } 10928 } 10929 10930 synchronized (mInstallLock) { 10931 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 10932 res = deletePackageLI(packageName, removeForUser, 10933 true, allUsers, perUserInstalled, 10934 flags | REMOVE_CHATTY, info, true); 10935 systemUpdate = info.isRemovedPackageSystemUpdate; 10936 if (res && !systemUpdate && mPackages.get(packageName) == null) { 10937 removedForAllUsers = true; 10938 } 10939 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 10940 + " removedForAllUsers=" + removedForAllUsers); 10941 } 10942 10943 if (res) { 10944 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 10945 10946 // If the removed package was a system update, the old system package 10947 // was re-enabled; we need to broadcast this information 10948 if (systemUpdate) { 10949 Bundle extras = new Bundle(1); 10950 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 10951 ? info.removedAppId : info.uid); 10952 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10953 10954 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 10955 extras, null, null, null); 10956 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 10957 extras, null, null, null); 10958 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 10959 null, packageName, null, null); 10960 } 10961 } 10962 // Force a gc here. 10963 Runtime.getRuntime().gc(); 10964 // Delete the resources here after sending the broadcast to let 10965 // other processes clean up before deleting resources. 10966 if (info.args != null) { 10967 synchronized (mInstallLock) { 10968 info.args.doPostDeleteLI(true); 10969 } 10970 } 10971 10972 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10973 } 10974 10975 static class PackageRemovedInfo { 10976 String removedPackage; 10977 int uid = -1; 10978 int removedAppId = -1; 10979 int[] removedUsers = null; 10980 boolean isRemovedPackageSystemUpdate = false; 10981 // Clean up resources deleted packages. 10982 InstallArgs args = null; 10983 10984 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 10985 Bundle extras = new Bundle(1); 10986 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 10987 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 10988 if (replacing) { 10989 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10990 } 10991 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 10992 if (removedPackage != null) { 10993 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 10994 extras, null, null, removedUsers); 10995 if (fullRemove && !replacing) { 10996 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 10997 extras, null, null, removedUsers); 10998 } 10999 } 11000 if (removedAppId >= 0) { 11001 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 11002 removedUsers); 11003 } 11004 } 11005 } 11006 11007 /* 11008 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 11009 * flag is not set, the data directory is removed as well. 11010 * make sure this flag is set for partially installed apps. If not its meaningless to 11011 * delete a partially installed application. 11012 */ 11013 private void removePackageDataLI(PackageSetting ps, 11014 int[] allUserHandles, boolean[] perUserInstalled, 11015 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 11016 String packageName = ps.name; 11017 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 11018 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 11019 // Retrieve object to delete permissions for shared user later on 11020 final PackageSetting deletedPs; 11021 // reader 11022 synchronized (mPackages) { 11023 deletedPs = mSettings.mPackages.get(packageName); 11024 if (outInfo != null) { 11025 outInfo.removedPackage = packageName; 11026 outInfo.removedUsers = deletedPs != null 11027 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 11028 : null; 11029 } 11030 } 11031 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 11032 removeDataDirsLI(packageName); 11033 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 11034 } 11035 // writer 11036 synchronized (mPackages) { 11037 if (deletedPs != null) { 11038 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 11039 if (outInfo != null) { 11040 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 11041 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 11042 } 11043 if (deletedPs != null) { 11044 updatePermissionsLPw(deletedPs.name, null, 0); 11045 if (deletedPs.sharedUser != null) { 11046 // remove permissions associated with package 11047 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 11048 } 11049 } 11050 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 11051 } 11052 // make sure to preserve per-user disabled state if this removal was just 11053 // a downgrade of a system app to the factory package 11054 if (allUserHandles != null && perUserInstalled != null) { 11055 if (DEBUG_REMOVE) { 11056 Slog.d(TAG, "Propagating install state across downgrade"); 11057 } 11058 for (int i = 0; i < allUserHandles.length; i++) { 11059 if (DEBUG_REMOVE) { 11060 Slog.d(TAG, " user " + allUserHandles[i] 11061 + " => " + perUserInstalled[i]); 11062 } 11063 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 11064 } 11065 } 11066 } 11067 // can downgrade to reader 11068 if (writeSettings) { 11069 // Save settings now 11070 mSettings.writeLPr(); 11071 } 11072 } 11073 if (outInfo != null) { 11074 // A user ID was deleted here. Go through all users and remove it 11075 // from KeyStore. 11076 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 11077 } 11078 } 11079 11080 static boolean locationIsPrivileged(File path) { 11081 try { 11082 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 11083 .getCanonicalPath(); 11084 return path.getCanonicalPath().startsWith(privilegedAppDir); 11085 } catch (IOException e) { 11086 Slog.e(TAG, "Unable to access code path " + path); 11087 } 11088 return false; 11089 } 11090 11091 /* 11092 * Tries to delete system package. 11093 */ 11094 private boolean deleteSystemPackageLI(PackageSetting newPs, 11095 int[] allUserHandles, boolean[] perUserInstalled, 11096 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 11097 final boolean applyUserRestrictions 11098 = (allUserHandles != null) && (perUserInstalled != null); 11099 PackageSetting disabledPs = null; 11100 // Confirm if the system package has been updated 11101 // An updated system app can be deleted. This will also have to restore 11102 // the system pkg from system partition 11103 // reader 11104 synchronized (mPackages) { 11105 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 11106 } 11107 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 11108 + " disabledPs=" + disabledPs); 11109 if (disabledPs == null) { 11110 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 11111 return false; 11112 } else if (DEBUG_REMOVE) { 11113 Slog.d(TAG, "Deleting system pkg from data partition"); 11114 } 11115 if (DEBUG_REMOVE) { 11116 if (applyUserRestrictions) { 11117 Slog.d(TAG, "Remembering install states:"); 11118 for (int i = 0; i < allUserHandles.length; i++) { 11119 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 11120 } 11121 } 11122 } 11123 // Delete the updated package 11124 outInfo.isRemovedPackageSystemUpdate = true; 11125 if (disabledPs.versionCode < newPs.versionCode) { 11126 // Delete data for downgrades 11127 flags &= ~PackageManager.DELETE_KEEP_DATA; 11128 } else { 11129 // Preserve data by setting flag 11130 flags |= PackageManager.DELETE_KEEP_DATA; 11131 } 11132 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 11133 allUserHandles, perUserInstalled, outInfo, writeSettings); 11134 if (!ret) { 11135 return false; 11136 } 11137 // writer 11138 synchronized (mPackages) { 11139 // Reinstate the old system package 11140 mSettings.enableSystemPackageLPw(newPs.name); 11141 // Remove any native libraries from the upgraded package. 11142 NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString); 11143 } 11144 // Install the system package 11145 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 11146 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 11147 if (locationIsPrivileged(disabledPs.codePath)) { 11148 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 11149 } 11150 11151 final PackageParser.Package newPkg; 11152 try { 11153 newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 11154 } catch (PackageManagerException e) { 11155 Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage()); 11156 return false; 11157 } 11158 11159 // writer 11160 synchronized (mPackages) { 11161 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 11162 updatePermissionsLPw(newPkg.packageName, newPkg, 11163 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 11164 if (applyUserRestrictions) { 11165 if (DEBUG_REMOVE) { 11166 Slog.d(TAG, "Propagating install state across reinstall"); 11167 } 11168 for (int i = 0; i < allUserHandles.length; i++) { 11169 if (DEBUG_REMOVE) { 11170 Slog.d(TAG, " user " + allUserHandles[i] 11171 + " => " + perUserInstalled[i]); 11172 } 11173 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 11174 } 11175 // Regardless of writeSettings we need to ensure that this restriction 11176 // state propagation is persisted 11177 mSettings.writeAllUsersPackageRestrictionsLPr(); 11178 } 11179 // can downgrade to reader here 11180 if (writeSettings) { 11181 mSettings.writeLPr(); 11182 } 11183 } 11184 return true; 11185 } 11186 11187 private boolean deleteInstalledPackageLI(PackageSetting ps, 11188 boolean deleteCodeAndResources, int flags, 11189 int[] allUserHandles, boolean[] perUserInstalled, 11190 PackageRemovedInfo outInfo, boolean writeSettings) { 11191 if (outInfo != null) { 11192 outInfo.uid = ps.appId; 11193 } 11194 11195 // Delete package data from internal structures and also remove data if flag is set 11196 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 11197 11198 // Delete application code and resources 11199 if (deleteCodeAndResources && (outInfo != null)) { 11200 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 11201 ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString, 11202 getAppDexInstructionSets(ps)); 11203 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 11204 } 11205 return true; 11206 } 11207 11208 @Override 11209 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 11210 int userId) { 11211 mContext.enforceCallingOrSelfPermission( 11212 android.Manifest.permission.DELETE_PACKAGES, null); 11213 synchronized (mPackages) { 11214 PackageSetting ps = mSettings.mPackages.get(packageName); 11215 if (ps == null) { 11216 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 11217 return false; 11218 } 11219 if (!ps.getInstalled(userId)) { 11220 // Can't block uninstall for an app that is not installed or enabled. 11221 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 11222 return false; 11223 } 11224 ps.setBlockUninstall(blockUninstall, userId); 11225 mSettings.writePackageRestrictionsLPr(userId); 11226 } 11227 return true; 11228 } 11229 11230 @Override 11231 public boolean getBlockUninstallForUser(String packageName, int userId) { 11232 synchronized (mPackages) { 11233 PackageSetting ps = mSettings.mPackages.get(packageName); 11234 if (ps == null) { 11235 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 11236 return false; 11237 } 11238 return ps.getBlockUninstall(userId); 11239 } 11240 } 11241 11242 /* 11243 * This method handles package deletion in general 11244 */ 11245 private boolean deletePackageLI(String packageName, UserHandle user, 11246 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 11247 int flags, PackageRemovedInfo outInfo, 11248 boolean writeSettings) { 11249 if (packageName == null) { 11250 Slog.w(TAG, "Attempt to delete null packageName."); 11251 return false; 11252 } 11253 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 11254 PackageSetting ps; 11255 boolean dataOnly = false; 11256 int removeUser = -1; 11257 int appId = -1; 11258 synchronized (mPackages) { 11259 ps = mSettings.mPackages.get(packageName); 11260 if (ps == null) { 11261 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11262 return false; 11263 } 11264 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 11265 && user.getIdentifier() != UserHandle.USER_ALL) { 11266 // The caller is asking that the package only be deleted for a single 11267 // user. To do this, we just mark its uninstalled state and delete 11268 // its data. If this is a system app, we only allow this to happen if 11269 // they have set the special DELETE_SYSTEM_APP which requests different 11270 // semantics than normal for uninstalling system apps. 11271 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 11272 ps.setUserState(user.getIdentifier(), 11273 COMPONENT_ENABLED_STATE_DEFAULT, 11274 false, //installed 11275 true, //stopped 11276 true, //notLaunched 11277 false, //hidden 11278 null, null, null, 11279 false // blockUninstall 11280 ); 11281 if (!isSystemApp(ps)) { 11282 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 11283 // Other user still have this package installed, so all 11284 // we need to do is clear this user's data and save that 11285 // it is uninstalled. 11286 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 11287 removeUser = user.getIdentifier(); 11288 appId = ps.appId; 11289 mSettings.writePackageRestrictionsLPr(removeUser); 11290 } else { 11291 // We need to set it back to 'installed' so the uninstall 11292 // broadcasts will be sent correctly. 11293 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 11294 ps.setInstalled(true, user.getIdentifier()); 11295 } 11296 } else { 11297 // This is a system app, so we assume that the 11298 // other users still have this package installed, so all 11299 // we need to do is clear this user's data and save that 11300 // it is uninstalled. 11301 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 11302 removeUser = user.getIdentifier(); 11303 appId = ps.appId; 11304 mSettings.writePackageRestrictionsLPr(removeUser); 11305 } 11306 } 11307 } 11308 11309 if (removeUser >= 0) { 11310 // From above, we determined that we are deleting this only 11311 // for a single user. Continue the work here. 11312 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 11313 if (outInfo != null) { 11314 outInfo.removedPackage = packageName; 11315 outInfo.removedAppId = appId; 11316 outInfo.removedUsers = new int[] {removeUser}; 11317 } 11318 mInstaller.clearUserData(packageName, removeUser); 11319 removeKeystoreDataIfNeeded(removeUser, appId); 11320 schedulePackageCleaning(packageName, removeUser, false); 11321 return true; 11322 } 11323 11324 if (dataOnly) { 11325 // Delete application data first 11326 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 11327 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 11328 return true; 11329 } 11330 11331 boolean ret = false; 11332 if (isSystemApp(ps)) { 11333 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 11334 // When an updated system application is deleted we delete the existing resources as well and 11335 // fall back to existing code in system partition 11336 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 11337 flags, outInfo, writeSettings); 11338 } else { 11339 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 11340 // Kill application pre-emptively especially for apps on sd. 11341 killApplication(packageName, ps.appId, "uninstall pkg"); 11342 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 11343 allUserHandles, perUserInstalled, 11344 outInfo, writeSettings); 11345 } 11346 11347 return ret; 11348 } 11349 11350 private final class ClearStorageConnection implements ServiceConnection { 11351 IMediaContainerService mContainerService; 11352 11353 @Override 11354 public void onServiceConnected(ComponentName name, IBinder service) { 11355 synchronized (this) { 11356 mContainerService = IMediaContainerService.Stub.asInterface(service); 11357 notifyAll(); 11358 } 11359 } 11360 11361 @Override 11362 public void onServiceDisconnected(ComponentName name) { 11363 } 11364 } 11365 11366 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 11367 final boolean mounted; 11368 if (Environment.isExternalStorageEmulated()) { 11369 mounted = true; 11370 } else { 11371 final String status = Environment.getExternalStorageState(); 11372 11373 mounted = status.equals(Environment.MEDIA_MOUNTED) 11374 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 11375 } 11376 11377 if (!mounted) { 11378 return; 11379 } 11380 11381 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 11382 int[] users; 11383 if (userId == UserHandle.USER_ALL) { 11384 users = sUserManager.getUserIds(); 11385 } else { 11386 users = new int[] { userId }; 11387 } 11388 final ClearStorageConnection conn = new ClearStorageConnection(); 11389 if (mContext.bindServiceAsUser( 11390 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 11391 try { 11392 for (int curUser : users) { 11393 long timeout = SystemClock.uptimeMillis() + 5000; 11394 synchronized (conn) { 11395 long now = SystemClock.uptimeMillis(); 11396 while (conn.mContainerService == null && now < timeout) { 11397 try { 11398 conn.wait(timeout - now); 11399 } catch (InterruptedException e) { 11400 } 11401 } 11402 } 11403 if (conn.mContainerService == null) { 11404 return; 11405 } 11406 11407 final UserEnvironment userEnv = new UserEnvironment(curUser); 11408 clearDirectory(conn.mContainerService, 11409 userEnv.buildExternalStorageAppCacheDirs(packageName)); 11410 if (allData) { 11411 clearDirectory(conn.mContainerService, 11412 userEnv.buildExternalStorageAppDataDirs(packageName)); 11413 clearDirectory(conn.mContainerService, 11414 userEnv.buildExternalStorageAppMediaDirs(packageName)); 11415 } 11416 } 11417 } finally { 11418 mContext.unbindService(conn); 11419 } 11420 } 11421 } 11422 11423 @Override 11424 public void clearApplicationUserData(final String packageName, 11425 final IPackageDataObserver observer, final int userId) { 11426 mContext.enforceCallingOrSelfPermission( 11427 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 11428 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data"); 11429 // Queue up an async operation since the package deletion may take a little while. 11430 mHandler.post(new Runnable() { 11431 public void run() { 11432 mHandler.removeCallbacks(this); 11433 final boolean succeeded; 11434 synchronized (mInstallLock) { 11435 succeeded = clearApplicationUserDataLI(packageName, userId); 11436 } 11437 clearExternalStorageDataSync(packageName, userId, true); 11438 if (succeeded) { 11439 // invoke DeviceStorageMonitor's update method to clear any notifications 11440 DeviceStorageMonitorInternal 11441 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 11442 if (dsm != null) { 11443 dsm.checkMemory(); 11444 } 11445 } 11446 if(observer != null) { 11447 try { 11448 observer.onRemoveCompleted(packageName, succeeded); 11449 } catch (RemoteException e) { 11450 Log.i(TAG, "Observer no longer exists."); 11451 } 11452 } //end if observer 11453 } //end run 11454 }); 11455 } 11456 11457 private boolean clearApplicationUserDataLI(String packageName, int userId) { 11458 if (packageName == null) { 11459 Slog.w(TAG, "Attempt to delete null packageName."); 11460 return false; 11461 } 11462 11463 // Try finding details about the requested package 11464 PackageParser.Package pkg; 11465 synchronized (mPackages) { 11466 pkg = mPackages.get(packageName); 11467 if (pkg == null) { 11468 final PackageSetting ps = mSettings.mPackages.get(packageName); 11469 if (ps != null) { 11470 pkg = ps.pkg; 11471 } 11472 } 11473 } 11474 11475 if (pkg == null) { 11476 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 11477 } 11478 11479 // Always delete data directories for package, even if we found no other 11480 // record of app. This helps users recover from UID mismatches without 11481 // resorting to a full data wipe. 11482 int retCode = mInstaller.clearUserData(packageName, userId); 11483 if (retCode < 0) { 11484 Slog.w(TAG, "Couldn't remove cache files for package: " + packageName); 11485 return false; 11486 } 11487 11488 if (pkg == null) { 11489 return false; 11490 } 11491 11492 if (pkg != null && pkg.applicationInfo != null) { 11493 final int appId = pkg.applicationInfo.uid; 11494 removeKeystoreDataIfNeeded(userId, appId); 11495 } 11496 11497 // Create a native library symlink only if we have native libraries 11498 // and if the native libraries are 32 bit libraries. We do not provide 11499 // this symlink for 64 bit libraries. 11500 if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null && 11501 !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) { 11502 final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir; 11503 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) { 11504 Slog.w(TAG, "Failed linking native library dir"); 11505 return false; 11506 } 11507 } 11508 11509 return true; 11510 } 11511 11512 /** 11513 * Remove entries from the keystore daemon. Will only remove it if the 11514 * {@code appId} is valid. 11515 */ 11516 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 11517 if (appId < 0) { 11518 return; 11519 } 11520 11521 final KeyStore keyStore = KeyStore.getInstance(); 11522 if (keyStore != null) { 11523 if (userId == UserHandle.USER_ALL) { 11524 for (final int individual : sUserManager.getUserIds()) { 11525 keyStore.clearUid(UserHandle.getUid(individual, appId)); 11526 } 11527 } else { 11528 keyStore.clearUid(UserHandle.getUid(userId, appId)); 11529 } 11530 } else { 11531 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 11532 } 11533 } 11534 11535 @Override 11536 public void deleteApplicationCacheFiles(final String packageName, 11537 final IPackageDataObserver observer) { 11538 mContext.enforceCallingOrSelfPermission( 11539 android.Manifest.permission.DELETE_CACHE_FILES, null); 11540 // Queue up an async operation since the package deletion may take a little while. 11541 final int userId = UserHandle.getCallingUserId(); 11542 mHandler.post(new Runnable() { 11543 public void run() { 11544 mHandler.removeCallbacks(this); 11545 final boolean succeded; 11546 synchronized (mInstallLock) { 11547 succeded = deleteApplicationCacheFilesLI(packageName, userId); 11548 } 11549 clearExternalStorageDataSync(packageName, userId, false); 11550 if(observer != null) { 11551 try { 11552 observer.onRemoveCompleted(packageName, succeded); 11553 } catch (RemoteException e) { 11554 Log.i(TAG, "Observer no longer exists."); 11555 } 11556 } //end if observer 11557 } //end run 11558 }); 11559 } 11560 11561 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 11562 if (packageName == null) { 11563 Slog.w(TAG, "Attempt to delete null packageName."); 11564 return false; 11565 } 11566 PackageParser.Package p; 11567 synchronized (mPackages) { 11568 p = mPackages.get(packageName); 11569 } 11570 if (p == null) { 11571 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11572 return false; 11573 } 11574 final ApplicationInfo applicationInfo = p.applicationInfo; 11575 if (applicationInfo == null) { 11576 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11577 return false; 11578 } 11579 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 11580 if (retCode < 0) { 11581 Slog.w(TAG, "Couldn't remove cache files for package: " 11582 + packageName + " u" + userId); 11583 return false; 11584 } 11585 return true; 11586 } 11587 11588 @Override 11589 public void getPackageSizeInfo(final String packageName, int userHandle, 11590 final IPackageStatsObserver observer) { 11591 mContext.enforceCallingOrSelfPermission( 11592 android.Manifest.permission.GET_PACKAGE_SIZE, null); 11593 if (packageName == null) { 11594 throw new IllegalArgumentException("Attempt to get size of null packageName"); 11595 } 11596 11597 PackageStats stats = new PackageStats(packageName, userHandle); 11598 11599 /* 11600 * Queue up an async operation since the package measurement may take a 11601 * little while. 11602 */ 11603 Message msg = mHandler.obtainMessage(INIT_COPY); 11604 msg.obj = new MeasureParams(stats, observer); 11605 mHandler.sendMessage(msg); 11606 } 11607 11608 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 11609 PackageStats pStats) { 11610 if (packageName == null) { 11611 Slog.w(TAG, "Attempt to get size of null packageName."); 11612 return false; 11613 } 11614 PackageParser.Package p; 11615 boolean dataOnly = false; 11616 String libDirRoot = null; 11617 String asecPath = null; 11618 PackageSetting ps = null; 11619 synchronized (mPackages) { 11620 p = mPackages.get(packageName); 11621 ps = mSettings.mPackages.get(packageName); 11622 if(p == null) { 11623 dataOnly = true; 11624 if((ps == null) || (ps.pkg == null)) { 11625 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 11626 return false; 11627 } 11628 p = ps.pkg; 11629 } 11630 if (ps != null) { 11631 libDirRoot = ps.legacyNativeLibraryPathString; 11632 } 11633 if (p != null && (isExternal(p) || isForwardLocked(p))) { 11634 String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath()); 11635 if (secureContainerId != null) { 11636 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 11637 } 11638 } 11639 } 11640 String publicSrcDir = null; 11641 if(!dataOnly) { 11642 final ApplicationInfo applicationInfo = p.applicationInfo; 11643 if (applicationInfo == null) { 11644 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 11645 return false; 11646 } 11647 if (isForwardLocked(p)) { 11648 publicSrcDir = applicationInfo.getBaseResourcePath(); 11649 } 11650 } 11651 // TODO: extend to measure size of split APKs 11652 // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree, 11653 // not just the first level. 11654 // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not 11655 // just the primary. 11656 String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps)); 11657 int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot, 11658 publicSrcDir, asecPath, dexCodeInstructionSets, pStats); 11659 if (res < 0) { 11660 return false; 11661 } 11662 11663 // Fix-up for forward-locked applications in ASEC containers. 11664 if (!isExternal(p)) { 11665 pStats.codeSize += pStats.externalCodeSize; 11666 pStats.externalCodeSize = 0L; 11667 } 11668 11669 return true; 11670 } 11671 11672 11673 @Override 11674 public void addPackageToPreferred(String packageName) { 11675 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 11676 } 11677 11678 @Override 11679 public void removePackageFromPreferred(String packageName) { 11680 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 11681 } 11682 11683 @Override 11684 public List<PackageInfo> getPreferredPackages(int flags) { 11685 return new ArrayList<PackageInfo>(); 11686 } 11687 11688 private int getUidTargetSdkVersionLockedLPr(int uid) { 11689 Object obj = mSettings.getUserIdLPr(uid); 11690 if (obj instanceof SharedUserSetting) { 11691 final SharedUserSetting sus = (SharedUserSetting) obj; 11692 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 11693 final Iterator<PackageSetting> it = sus.packages.iterator(); 11694 while (it.hasNext()) { 11695 final PackageSetting ps = it.next(); 11696 if (ps.pkg != null) { 11697 int v = ps.pkg.applicationInfo.targetSdkVersion; 11698 if (v < vers) vers = v; 11699 } 11700 } 11701 return vers; 11702 } else if (obj instanceof PackageSetting) { 11703 final PackageSetting ps = (PackageSetting) obj; 11704 if (ps.pkg != null) { 11705 return ps.pkg.applicationInfo.targetSdkVersion; 11706 } 11707 } 11708 return Build.VERSION_CODES.CUR_DEVELOPMENT; 11709 } 11710 11711 @Override 11712 public void addPreferredActivity(IntentFilter filter, int match, 11713 ComponentName[] set, ComponentName activity, int userId) { 11714 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11715 "Adding preferred"); 11716 } 11717 11718 private void addPreferredActivityInternal(IntentFilter filter, int match, 11719 ComponentName[] set, ComponentName activity, boolean always, int userId, 11720 String opname) { 11721 // writer 11722 int callingUid = Binder.getCallingUid(); 11723 enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity"); 11724 if (filter.countActions() == 0) { 11725 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11726 return; 11727 } 11728 synchronized (mPackages) { 11729 if (mContext.checkCallingOrSelfPermission( 11730 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11731 != PackageManager.PERMISSION_GRANTED) { 11732 if (getUidTargetSdkVersionLockedLPr(callingUid) 11733 < Build.VERSION_CODES.FROYO) { 11734 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 11735 + callingUid); 11736 return; 11737 } 11738 mContext.enforceCallingOrSelfPermission( 11739 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11740 } 11741 11742 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 11743 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 11744 + userId + ":"); 11745 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11746 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 11747 scheduleWritePackageRestrictionsLocked(userId); 11748 } 11749 } 11750 11751 @Override 11752 public void replacePreferredActivity(IntentFilter filter, int match, 11753 ComponentName[] set, ComponentName activity, int userId) { 11754 if (filter.countActions() != 1) { 11755 throw new IllegalArgumentException( 11756 "replacePreferredActivity expects filter to have only 1 action."); 11757 } 11758 if (filter.countDataAuthorities() != 0 11759 || filter.countDataPaths() != 0 11760 || filter.countDataSchemes() > 1 11761 || filter.countDataTypes() != 0) { 11762 throw new IllegalArgumentException( 11763 "replacePreferredActivity expects filter to have no data authorities, " + 11764 "paths, or types; and at most one scheme."); 11765 } 11766 11767 final int callingUid = Binder.getCallingUid(); 11768 enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity"); 11769 synchronized (mPackages) { 11770 if (mContext.checkCallingOrSelfPermission( 11771 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11772 != PackageManager.PERMISSION_GRANTED) { 11773 if (getUidTargetSdkVersionLockedLPr(callingUid) 11774 < Build.VERSION_CODES.FROYO) { 11775 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 11776 + Binder.getCallingUid()); 11777 return; 11778 } 11779 mContext.enforceCallingOrSelfPermission( 11780 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11781 } 11782 11783 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11784 if (pir != null) { 11785 // Get all of the existing entries that exactly match this filter. 11786 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 11787 if (existing != null && existing.size() == 1) { 11788 PreferredActivity cur = existing.get(0); 11789 if (DEBUG_PREFERRED) { 11790 Slog.i(TAG, "Checking replace of preferred:"); 11791 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11792 if (!cur.mPref.mAlways) { 11793 Slog.i(TAG, " -- CUR; not mAlways!"); 11794 } else { 11795 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 11796 Slog.i(TAG, " -- CUR: mSet=" 11797 + Arrays.toString(cur.mPref.mSetComponents)); 11798 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 11799 Slog.i(TAG, " -- NEW: mMatch=" 11800 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 11801 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 11802 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 11803 } 11804 } 11805 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 11806 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 11807 && cur.mPref.sameSet(set)) { 11808 // Setting the preferred activity to what it happens to be already 11809 if (DEBUG_PREFERRED) { 11810 Slog.i(TAG, "Replacing with same preferred activity " 11811 + cur.mPref.mShortComponent + " for user " 11812 + userId + ":"); 11813 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11814 } 11815 return; 11816 } 11817 } 11818 11819 if (existing != null) { 11820 if (DEBUG_PREFERRED) { 11821 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 11822 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11823 } 11824 for (int i = 0; i < existing.size(); i++) { 11825 PreferredActivity pa = existing.get(i); 11826 if (DEBUG_PREFERRED) { 11827 Slog.i(TAG, "Removing existing preferred activity " 11828 + pa.mPref.mComponent + ":"); 11829 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 11830 } 11831 pir.removeFilter(pa); 11832 } 11833 } 11834 } 11835 addPreferredActivityInternal(filter, match, set, activity, true, userId, 11836 "Replacing preferred"); 11837 } 11838 } 11839 11840 @Override 11841 public void clearPackagePreferredActivities(String packageName) { 11842 final int uid = Binder.getCallingUid(); 11843 // writer 11844 synchronized (mPackages) { 11845 PackageParser.Package pkg = mPackages.get(packageName); 11846 if (pkg == null || pkg.applicationInfo.uid != uid) { 11847 if (mContext.checkCallingOrSelfPermission( 11848 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 11849 != PackageManager.PERMISSION_GRANTED) { 11850 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 11851 < Build.VERSION_CODES.FROYO) { 11852 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 11853 + Binder.getCallingUid()); 11854 return; 11855 } 11856 mContext.enforceCallingOrSelfPermission( 11857 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11858 } 11859 } 11860 11861 int user = UserHandle.getCallingUserId(); 11862 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 11863 scheduleWritePackageRestrictionsLocked(user); 11864 } 11865 } 11866 } 11867 11868 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 11869 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 11870 ArrayList<PreferredActivity> removed = null; 11871 boolean changed = false; 11872 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11873 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 11874 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11875 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 11876 continue; 11877 } 11878 Iterator<PreferredActivity> it = pir.filterIterator(); 11879 while (it.hasNext()) { 11880 PreferredActivity pa = it.next(); 11881 // Mark entry for removal only if it matches the package name 11882 // and the entry is of type "always". 11883 if (packageName == null || 11884 (pa.mPref.mComponent.getPackageName().equals(packageName) 11885 && pa.mPref.mAlways)) { 11886 if (removed == null) { 11887 removed = new ArrayList<PreferredActivity>(); 11888 } 11889 removed.add(pa); 11890 } 11891 } 11892 if (removed != null) { 11893 for (int j=0; j<removed.size(); j++) { 11894 PreferredActivity pa = removed.get(j); 11895 pir.removeFilter(pa); 11896 } 11897 changed = true; 11898 } 11899 } 11900 return changed; 11901 } 11902 11903 @Override 11904 public void resetPreferredActivities(int userId) { 11905 /* TODO: Actually use userId. Why is it being passed in? */ 11906 mContext.enforceCallingOrSelfPermission( 11907 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11908 // writer 11909 synchronized (mPackages) { 11910 int user = UserHandle.getCallingUserId(); 11911 clearPackagePreferredActivitiesLPw(null, user); 11912 mSettings.readDefaultPreferredAppsLPw(this, user); 11913 scheduleWritePackageRestrictionsLocked(user); 11914 } 11915 } 11916 11917 @Override 11918 public int getPreferredActivities(List<IntentFilter> outFilters, 11919 List<ComponentName> outActivities, String packageName) { 11920 11921 int num = 0; 11922 final int userId = UserHandle.getCallingUserId(); 11923 // reader 11924 synchronized (mPackages) { 11925 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 11926 if (pir != null) { 11927 final Iterator<PreferredActivity> it = pir.filterIterator(); 11928 while (it.hasNext()) { 11929 final PreferredActivity pa = it.next(); 11930 if (packageName == null 11931 || (pa.mPref.mComponent.getPackageName().equals(packageName) 11932 && pa.mPref.mAlways)) { 11933 if (outFilters != null) { 11934 outFilters.add(new IntentFilter(pa)); 11935 } 11936 if (outActivities != null) { 11937 outActivities.add(pa.mPref.mComponent); 11938 } 11939 } 11940 } 11941 } 11942 } 11943 11944 return num; 11945 } 11946 11947 @Override 11948 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 11949 int userId) { 11950 int callingUid = Binder.getCallingUid(); 11951 if (callingUid != Process.SYSTEM_UID) { 11952 throw new SecurityException( 11953 "addPersistentPreferredActivity can only be run by the system"); 11954 } 11955 if (filter.countActions() == 0) { 11956 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 11957 return; 11958 } 11959 synchronized (mPackages) { 11960 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 11961 " :"); 11962 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 11963 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 11964 new PersistentPreferredActivity(filter, activity)); 11965 scheduleWritePackageRestrictionsLocked(userId); 11966 } 11967 } 11968 11969 @Override 11970 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 11971 int callingUid = Binder.getCallingUid(); 11972 if (callingUid != Process.SYSTEM_UID) { 11973 throw new SecurityException( 11974 "clearPackagePersistentPreferredActivities can only be run by the system"); 11975 } 11976 ArrayList<PersistentPreferredActivity> removed = null; 11977 boolean changed = false; 11978 synchronized (mPackages) { 11979 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 11980 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 11981 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 11982 .valueAt(i); 11983 if (userId != thisUserId) { 11984 continue; 11985 } 11986 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 11987 while (it.hasNext()) { 11988 PersistentPreferredActivity ppa = it.next(); 11989 // Mark entry for removal only if it matches the package name. 11990 if (ppa.mComponent.getPackageName().equals(packageName)) { 11991 if (removed == null) { 11992 removed = new ArrayList<PersistentPreferredActivity>(); 11993 } 11994 removed.add(ppa); 11995 } 11996 } 11997 if (removed != null) { 11998 for (int j=0; j<removed.size(); j++) { 11999 PersistentPreferredActivity ppa = removed.get(j); 12000 ppir.removeFilter(ppa); 12001 } 12002 changed = true; 12003 } 12004 } 12005 12006 if (changed) { 12007 scheduleWritePackageRestrictionsLocked(userId); 12008 } 12009 } 12010 } 12011 12012 @Override 12013 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 12014 int ownerUserId, int sourceUserId, int targetUserId, int flags) { 12015 mContext.enforceCallingOrSelfPermission( 12016 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 12017 int callingUid = Binder.getCallingUid(); 12018 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 12019 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 12020 if (intentFilter.countActions() == 0) { 12021 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 12022 return; 12023 } 12024 synchronized (mPackages) { 12025 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 12026 ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags); 12027 CrossProfileIntentResolver resolver = 12028 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 12029 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 12030 // We have all those whose filter is equal. Now checking if the rest is equal as well. 12031 if (existing != null) { 12032 int size = existing.size(); 12033 for (int i = 0; i < size; i++) { 12034 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 12035 return; 12036 } 12037 } 12038 } 12039 resolver.addFilter(newFilter); 12040 scheduleWritePackageRestrictionsLocked(sourceUserId); 12041 } 12042 } 12043 12044 @Override 12045 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage, 12046 int ownerUserId) { 12047 mContext.enforceCallingOrSelfPermission( 12048 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 12049 int callingUid = Binder.getCallingUid(); 12050 enforceOwnerRights(ownerPackage, ownerUserId, callingUid); 12051 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 12052 int callingUserId = UserHandle.getUserId(callingUid); 12053 synchronized (mPackages) { 12054 CrossProfileIntentResolver resolver = 12055 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 12056 ArraySet<CrossProfileIntentFilter> set = 12057 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 12058 for (CrossProfileIntentFilter filter : set) { 12059 if (filter.getOwnerPackage().equals(ownerPackage) 12060 && filter.getOwnerUserId() == callingUserId) { 12061 resolver.removeFilter(filter); 12062 } 12063 } 12064 scheduleWritePackageRestrictionsLocked(sourceUserId); 12065 } 12066 } 12067 12068 // Enforcing that callingUid is owning pkg on userId 12069 private void enforceOwnerRights(String pkg, int userId, int callingUid) { 12070 // The system owns everything. 12071 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 12072 return; 12073 } 12074 int callingUserId = UserHandle.getUserId(callingUid); 12075 if (callingUserId != userId) { 12076 throw new SecurityException("calling uid " + callingUid 12077 + " pretends to own " + pkg + " on user " + userId + " but belongs to user " 12078 + callingUserId); 12079 } 12080 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 12081 if (pi == null) { 12082 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 12083 + callingUserId); 12084 } 12085 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 12086 throw new SecurityException("Calling uid " + callingUid 12087 + " does not own package " + pkg); 12088 } 12089 } 12090 12091 @Override 12092 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 12093 Intent intent = new Intent(Intent.ACTION_MAIN); 12094 intent.addCategory(Intent.CATEGORY_HOME); 12095 12096 final int callingUserId = UserHandle.getCallingUserId(); 12097 List<ResolveInfo> list = queryIntentActivities(intent, null, 12098 PackageManager.GET_META_DATA, callingUserId); 12099 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 12100 true, false, false, callingUserId); 12101 12102 allHomeCandidates.clear(); 12103 if (list != null) { 12104 for (ResolveInfo ri : list) { 12105 allHomeCandidates.add(ri); 12106 } 12107 } 12108 return (preferred == null || preferred.activityInfo == null) 12109 ? null 12110 : new ComponentName(preferred.activityInfo.packageName, 12111 preferred.activityInfo.name); 12112 } 12113 12114 @Override 12115 public void setApplicationEnabledSetting(String appPackageName, 12116 int newState, int flags, int userId, String callingPackage) { 12117 if (!sUserManager.exists(userId)) return; 12118 if (callingPackage == null) { 12119 callingPackage = Integer.toString(Binder.getCallingUid()); 12120 } 12121 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 12122 } 12123 12124 @Override 12125 public void setComponentEnabledSetting(ComponentName componentName, 12126 int newState, int flags, int userId) { 12127 if (!sUserManager.exists(userId)) return; 12128 setEnabledSetting(componentName.getPackageName(), 12129 componentName.getClassName(), newState, flags, userId, null); 12130 } 12131 12132 private void setEnabledSetting(final String packageName, String className, int newState, 12133 final int flags, int userId, String callingPackage) { 12134 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 12135 || newState == COMPONENT_ENABLED_STATE_ENABLED 12136 || newState == COMPONENT_ENABLED_STATE_DISABLED 12137 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 12138 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 12139 throw new IllegalArgumentException("Invalid new component state: " 12140 + newState); 12141 } 12142 PackageSetting pkgSetting; 12143 final int uid = Binder.getCallingUid(); 12144 final int permission = mContext.checkCallingOrSelfPermission( 12145 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 12146 enforceCrossUserPermission(uid, userId, false, true, "set enabled"); 12147 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 12148 boolean sendNow = false; 12149 boolean isApp = (className == null); 12150 String componentName = isApp ? packageName : className; 12151 int packageUid = -1; 12152 ArrayList<String> components; 12153 12154 // writer 12155 synchronized (mPackages) { 12156 pkgSetting = mSettings.mPackages.get(packageName); 12157 if (pkgSetting == null) { 12158 if (className == null) { 12159 throw new IllegalArgumentException( 12160 "Unknown package: " + packageName); 12161 } 12162 throw new IllegalArgumentException( 12163 "Unknown component: " + packageName 12164 + "/" + className); 12165 } 12166 // Allow root and verify that userId is not being specified by a different user 12167 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 12168 throw new SecurityException( 12169 "Permission Denial: attempt to change component state from pid=" 12170 + Binder.getCallingPid() 12171 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 12172 } 12173 if (className == null) { 12174 // We're dealing with an application/package level state change 12175 if (pkgSetting.getEnabled(userId) == newState) { 12176 // Nothing to do 12177 return; 12178 } 12179 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 12180 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 12181 // Don't care about who enables an app. 12182 callingPackage = null; 12183 } 12184 pkgSetting.setEnabled(newState, userId, callingPackage); 12185 // pkgSetting.pkg.mSetEnabled = newState; 12186 } else { 12187 // We're dealing with a component level state change 12188 // First, verify that this is a valid class name. 12189 PackageParser.Package pkg = pkgSetting.pkg; 12190 if (pkg == null || !pkg.hasComponentClassName(className)) { 12191 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 12192 throw new IllegalArgumentException("Component class " + className 12193 + " does not exist in " + packageName); 12194 } else { 12195 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 12196 + className + " does not exist in " + packageName); 12197 } 12198 } 12199 switch (newState) { 12200 case COMPONENT_ENABLED_STATE_ENABLED: 12201 if (!pkgSetting.enableComponentLPw(className, userId)) { 12202 return; 12203 } 12204 break; 12205 case COMPONENT_ENABLED_STATE_DISABLED: 12206 if (!pkgSetting.disableComponentLPw(className, userId)) { 12207 return; 12208 } 12209 break; 12210 case COMPONENT_ENABLED_STATE_DEFAULT: 12211 if (!pkgSetting.restoreComponentLPw(className, userId)) { 12212 return; 12213 } 12214 break; 12215 default: 12216 Slog.e(TAG, "Invalid new component state: " + newState); 12217 return; 12218 } 12219 } 12220 scheduleWritePackageRestrictionsLocked(userId); 12221 components = mPendingBroadcasts.get(userId, packageName); 12222 final boolean newPackage = components == null; 12223 if (newPackage) { 12224 components = new ArrayList<String>(); 12225 } 12226 if (!components.contains(componentName)) { 12227 components.add(componentName); 12228 } 12229 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 12230 sendNow = true; 12231 // Purge entry from pending broadcast list if another one exists already 12232 // since we are sending one right away. 12233 mPendingBroadcasts.remove(userId, packageName); 12234 } else { 12235 if (newPackage) { 12236 mPendingBroadcasts.put(userId, packageName, components); 12237 } 12238 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 12239 // Schedule a message 12240 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 12241 } 12242 } 12243 } 12244 12245 long callingId = Binder.clearCallingIdentity(); 12246 try { 12247 if (sendNow) { 12248 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 12249 sendPackageChangedBroadcast(packageName, 12250 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 12251 } 12252 } finally { 12253 Binder.restoreCallingIdentity(callingId); 12254 } 12255 } 12256 12257 private void sendPackageChangedBroadcast(String packageName, 12258 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 12259 if (DEBUG_INSTALL) 12260 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 12261 + componentNames); 12262 Bundle extras = new Bundle(4); 12263 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 12264 String nameList[] = new String[componentNames.size()]; 12265 componentNames.toArray(nameList); 12266 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 12267 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 12268 extras.putInt(Intent.EXTRA_UID, packageUid); 12269 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 12270 new int[] {UserHandle.getUserId(packageUid)}); 12271 } 12272 12273 @Override 12274 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 12275 if (!sUserManager.exists(userId)) return; 12276 final int uid = Binder.getCallingUid(); 12277 final int permission = mContext.checkCallingOrSelfPermission( 12278 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 12279 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 12280 enforceCrossUserPermission(uid, userId, true, true, "stop package"); 12281 // writer 12282 synchronized (mPackages) { 12283 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 12284 uid, userId)) { 12285 scheduleWritePackageRestrictionsLocked(userId); 12286 } 12287 } 12288 } 12289 12290 @Override 12291 public String getInstallerPackageName(String packageName) { 12292 // reader 12293 synchronized (mPackages) { 12294 return mSettings.getInstallerPackageNameLPr(packageName); 12295 } 12296 } 12297 12298 @Override 12299 public int getApplicationEnabledSetting(String packageName, int userId) { 12300 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12301 int uid = Binder.getCallingUid(); 12302 enforceCrossUserPermission(uid, userId, false, false, "get enabled"); 12303 // reader 12304 synchronized (mPackages) { 12305 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 12306 } 12307 } 12308 12309 @Override 12310 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 12311 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 12312 int uid = Binder.getCallingUid(); 12313 enforceCrossUserPermission(uid, userId, false, false, "get component enabled"); 12314 // reader 12315 synchronized (mPackages) { 12316 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 12317 } 12318 } 12319 12320 @Override 12321 public void enterSafeMode() { 12322 enforceSystemOrRoot("Only the system can request entering safe mode"); 12323 12324 if (!mSystemReady) { 12325 mSafeMode = true; 12326 } 12327 } 12328 12329 @Override 12330 public void systemReady() { 12331 mSystemReady = true; 12332 12333 // Read the compatibilty setting when the system is ready. 12334 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 12335 mContext.getContentResolver(), 12336 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 12337 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 12338 if (DEBUG_SETTINGS) { 12339 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 12340 } 12341 12342 synchronized (mPackages) { 12343 // Verify that all of the preferred activity components actually 12344 // exist. It is possible for applications to be updated and at 12345 // that point remove a previously declared activity component that 12346 // had been set as a preferred activity. We try to clean this up 12347 // the next time we encounter that preferred activity, but it is 12348 // possible for the user flow to never be able to return to that 12349 // situation so here we do a sanity check to make sure we haven't 12350 // left any junk around. 12351 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 12352 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12353 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12354 removed.clear(); 12355 for (PreferredActivity pa : pir.filterSet()) { 12356 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 12357 removed.add(pa); 12358 } 12359 } 12360 if (removed.size() > 0) { 12361 for (int r=0; r<removed.size(); r++) { 12362 PreferredActivity pa = removed.get(r); 12363 Slog.w(TAG, "Removing dangling preferred activity: " 12364 + pa.mPref.mComponent); 12365 pir.removeFilter(pa); 12366 } 12367 mSettings.writePackageRestrictionsLPr( 12368 mSettings.mPreferredActivities.keyAt(i)); 12369 } 12370 } 12371 } 12372 sUserManager.systemReady(); 12373 12374 // Kick off any messages waiting for system ready 12375 if (mPostSystemReadyMessages != null) { 12376 for (Message msg : mPostSystemReadyMessages) { 12377 msg.sendToTarget(); 12378 } 12379 mPostSystemReadyMessages = null; 12380 } 12381 } 12382 12383 @Override 12384 public boolean isSafeMode() { 12385 return mSafeMode; 12386 } 12387 12388 @Override 12389 public boolean hasSystemUidErrors() { 12390 return mHasSystemUidErrors; 12391 } 12392 12393 static String arrayToString(int[] array) { 12394 StringBuffer buf = new StringBuffer(128); 12395 buf.append('['); 12396 if (array != null) { 12397 for (int i=0; i<array.length; i++) { 12398 if (i > 0) buf.append(", "); 12399 buf.append(array[i]); 12400 } 12401 } 12402 buf.append(']'); 12403 return buf.toString(); 12404 } 12405 12406 static class DumpState { 12407 public static final int DUMP_LIBS = 1 << 0; 12408 public static final int DUMP_FEATURES = 1 << 1; 12409 public static final int DUMP_RESOLVERS = 1 << 2; 12410 public static final int DUMP_PERMISSIONS = 1 << 3; 12411 public static final int DUMP_PACKAGES = 1 << 4; 12412 public static final int DUMP_SHARED_USERS = 1 << 5; 12413 public static final int DUMP_MESSAGES = 1 << 6; 12414 public static final int DUMP_PROVIDERS = 1 << 7; 12415 public static final int DUMP_VERIFIERS = 1 << 8; 12416 public static final int DUMP_PREFERRED = 1 << 9; 12417 public static final int DUMP_PREFERRED_XML = 1 << 10; 12418 public static final int DUMP_KEYSETS = 1 << 11; 12419 public static final int DUMP_VERSION = 1 << 12; 12420 public static final int DUMP_INSTALLS = 1 << 13; 12421 12422 public static final int OPTION_SHOW_FILTERS = 1 << 0; 12423 12424 private int mTypes; 12425 12426 private int mOptions; 12427 12428 private boolean mTitlePrinted; 12429 12430 private SharedUserSetting mSharedUser; 12431 12432 public boolean isDumping(int type) { 12433 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 12434 return true; 12435 } 12436 12437 return (mTypes & type) != 0; 12438 } 12439 12440 public void setDump(int type) { 12441 mTypes |= type; 12442 } 12443 12444 public boolean isOptionEnabled(int option) { 12445 return (mOptions & option) != 0; 12446 } 12447 12448 public void setOptionEnabled(int option) { 12449 mOptions |= option; 12450 } 12451 12452 public boolean onTitlePrinted() { 12453 final boolean printed = mTitlePrinted; 12454 mTitlePrinted = true; 12455 return printed; 12456 } 12457 12458 public boolean getTitlePrinted() { 12459 return mTitlePrinted; 12460 } 12461 12462 public void setTitlePrinted(boolean enabled) { 12463 mTitlePrinted = enabled; 12464 } 12465 12466 public SharedUserSetting getSharedUser() { 12467 return mSharedUser; 12468 } 12469 12470 public void setSharedUser(SharedUserSetting user) { 12471 mSharedUser = user; 12472 } 12473 } 12474 12475 @Override 12476 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 12477 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 12478 != PackageManager.PERMISSION_GRANTED) { 12479 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 12480 + Binder.getCallingPid() 12481 + ", uid=" + Binder.getCallingUid() 12482 + " without permission " 12483 + android.Manifest.permission.DUMP); 12484 return; 12485 } 12486 12487 DumpState dumpState = new DumpState(); 12488 boolean fullPreferred = false; 12489 boolean checkin = false; 12490 12491 String packageName = null; 12492 12493 int opti = 0; 12494 while (opti < args.length) { 12495 String opt = args[opti]; 12496 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 12497 break; 12498 } 12499 opti++; 12500 12501 if ("-a".equals(opt)) { 12502 // Right now we only know how to print all. 12503 } else if ("-h".equals(opt)) { 12504 pw.println("Package manager dump options:"); 12505 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 12506 pw.println(" --checkin: dump for a checkin"); 12507 pw.println(" -f: print details of intent filters"); 12508 pw.println(" -h: print this help"); 12509 pw.println(" cmd may be one of:"); 12510 pw.println(" l[ibraries]: list known shared libraries"); 12511 pw.println(" f[ibraries]: list device features"); 12512 pw.println(" k[eysets]: print known keysets"); 12513 pw.println(" r[esolvers]: dump intent resolvers"); 12514 pw.println(" perm[issions]: dump permissions"); 12515 pw.println(" pref[erred]: print preferred package settings"); 12516 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 12517 pw.println(" prov[iders]: dump content providers"); 12518 pw.println(" p[ackages]: dump installed packages"); 12519 pw.println(" s[hared-users]: dump shared user IDs"); 12520 pw.println(" m[essages]: print collected runtime messages"); 12521 pw.println(" v[erifiers]: print package verifier info"); 12522 pw.println(" version: print database version info"); 12523 pw.println(" write: write current settings now"); 12524 pw.println(" <package.name>: info about given package"); 12525 pw.println(" installs: details about install sessions"); 12526 return; 12527 } else if ("--checkin".equals(opt)) { 12528 checkin = true; 12529 } else if ("-f".equals(opt)) { 12530 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12531 } else { 12532 pw.println("Unknown argument: " + opt + "; use -h for help"); 12533 } 12534 } 12535 12536 // Is the caller requesting to dump a particular piece of data? 12537 if (opti < args.length) { 12538 String cmd = args[opti]; 12539 opti++; 12540 // Is this a package name? 12541 if ("android".equals(cmd) || cmd.contains(".")) { 12542 packageName = cmd; 12543 // When dumping a single package, we always dump all of its 12544 // filter information since the amount of data will be reasonable. 12545 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 12546 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 12547 dumpState.setDump(DumpState.DUMP_LIBS); 12548 } else if ("f".equals(cmd) || "features".equals(cmd)) { 12549 dumpState.setDump(DumpState.DUMP_FEATURES); 12550 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 12551 dumpState.setDump(DumpState.DUMP_RESOLVERS); 12552 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 12553 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 12554 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 12555 dumpState.setDump(DumpState.DUMP_PREFERRED); 12556 } else if ("preferred-xml".equals(cmd)) { 12557 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 12558 if (opti < args.length && "--full".equals(args[opti])) { 12559 fullPreferred = true; 12560 opti++; 12561 } 12562 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 12563 dumpState.setDump(DumpState.DUMP_PACKAGES); 12564 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 12565 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 12566 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 12567 dumpState.setDump(DumpState.DUMP_PROVIDERS); 12568 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 12569 dumpState.setDump(DumpState.DUMP_MESSAGES); 12570 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 12571 dumpState.setDump(DumpState.DUMP_VERIFIERS); 12572 } else if ("version".equals(cmd)) { 12573 dumpState.setDump(DumpState.DUMP_VERSION); 12574 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 12575 dumpState.setDump(DumpState.DUMP_KEYSETS); 12576 } else if ("installs".equals(cmd)) { 12577 dumpState.setDump(DumpState.DUMP_INSTALLS); 12578 } else if ("write".equals(cmd)) { 12579 synchronized (mPackages) { 12580 mSettings.writeLPr(); 12581 pw.println("Settings written."); 12582 return; 12583 } 12584 } 12585 } 12586 12587 if (checkin) { 12588 pw.println("vers,1"); 12589 } 12590 12591 // reader 12592 synchronized (mPackages) { 12593 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 12594 if (!checkin) { 12595 if (dumpState.onTitlePrinted()) 12596 pw.println(); 12597 pw.println("Database versions:"); 12598 pw.print(" SDK Version:"); 12599 pw.print(" internal="); 12600 pw.print(mSettings.mInternalSdkPlatform); 12601 pw.print(" external="); 12602 pw.println(mSettings.mExternalSdkPlatform); 12603 pw.print(" DB Version:"); 12604 pw.print(" internal="); 12605 pw.print(mSettings.mInternalDatabaseVersion); 12606 pw.print(" external="); 12607 pw.println(mSettings.mExternalDatabaseVersion); 12608 } 12609 } 12610 12611 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 12612 if (!checkin) { 12613 if (dumpState.onTitlePrinted()) 12614 pw.println(); 12615 pw.println("Verifiers:"); 12616 pw.print(" Required: "); 12617 pw.print(mRequiredVerifierPackage); 12618 pw.print(" (uid="); 12619 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 12620 pw.println(")"); 12621 } else if (mRequiredVerifierPackage != null) { 12622 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 12623 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 12624 } 12625 } 12626 12627 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 12628 boolean printedHeader = false; 12629 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 12630 while (it.hasNext()) { 12631 String name = it.next(); 12632 SharedLibraryEntry ent = mSharedLibraries.get(name); 12633 if (!checkin) { 12634 if (!printedHeader) { 12635 if (dumpState.onTitlePrinted()) 12636 pw.println(); 12637 pw.println("Libraries:"); 12638 printedHeader = true; 12639 } 12640 pw.print(" "); 12641 } else { 12642 pw.print("lib,"); 12643 } 12644 pw.print(name); 12645 if (!checkin) { 12646 pw.print(" -> "); 12647 } 12648 if (ent.path != null) { 12649 if (!checkin) { 12650 pw.print("(jar) "); 12651 pw.print(ent.path); 12652 } else { 12653 pw.print(",jar,"); 12654 pw.print(ent.path); 12655 } 12656 } else { 12657 if (!checkin) { 12658 pw.print("(apk) "); 12659 pw.print(ent.apk); 12660 } else { 12661 pw.print(",apk,"); 12662 pw.print(ent.apk); 12663 } 12664 } 12665 pw.println(); 12666 } 12667 } 12668 12669 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 12670 if (dumpState.onTitlePrinted()) 12671 pw.println(); 12672 if (!checkin) { 12673 pw.println("Features:"); 12674 } 12675 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 12676 while (it.hasNext()) { 12677 String name = it.next(); 12678 if (!checkin) { 12679 pw.print(" "); 12680 } else { 12681 pw.print("feat,"); 12682 } 12683 pw.println(name); 12684 } 12685 } 12686 12687 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 12688 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 12689 : "Activity Resolver Table:", " ", packageName, 12690 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 12691 dumpState.setTitlePrinted(true); 12692 } 12693 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 12694 : "Receiver Resolver Table:", " ", packageName, 12695 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 12696 dumpState.setTitlePrinted(true); 12697 } 12698 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 12699 : "Service Resolver Table:", " ", packageName, 12700 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 12701 dumpState.setTitlePrinted(true); 12702 } 12703 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 12704 : "Provider Resolver Table:", " ", packageName, 12705 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 12706 dumpState.setTitlePrinted(true); 12707 } 12708 } 12709 12710 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 12711 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 12712 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 12713 int user = mSettings.mPreferredActivities.keyAt(i); 12714 if (pir.dump(pw, 12715 dumpState.getTitlePrinted() 12716 ? "\nPreferred Activities User " + user + ":" 12717 : "Preferred Activities User " + user + ":", " ", 12718 packageName, true, false)) { 12719 dumpState.setTitlePrinted(true); 12720 } 12721 } 12722 } 12723 12724 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 12725 pw.flush(); 12726 FileOutputStream fout = new FileOutputStream(fd); 12727 BufferedOutputStream str = new BufferedOutputStream(fout); 12728 XmlSerializer serializer = new FastXmlSerializer(); 12729 try { 12730 serializer.setOutput(str, "utf-8"); 12731 serializer.startDocument(null, true); 12732 serializer.setFeature( 12733 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 12734 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 12735 serializer.endDocument(); 12736 serializer.flush(); 12737 } catch (IllegalArgumentException e) { 12738 pw.println("Failed writing: " + e); 12739 } catch (IllegalStateException e) { 12740 pw.println("Failed writing: " + e); 12741 } catch (IOException e) { 12742 pw.println("Failed writing: " + e); 12743 } 12744 } 12745 12746 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 12747 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 12748 if (packageName == null) { 12749 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 12750 if (iperm == 0) { 12751 if (dumpState.onTitlePrinted()) 12752 pw.println(); 12753 pw.println("AppOp Permissions:"); 12754 } 12755 pw.print(" AppOp Permission "); 12756 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 12757 pw.println(":"); 12758 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 12759 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 12760 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 12761 } 12762 } 12763 } 12764 } 12765 12766 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 12767 boolean printedSomething = false; 12768 for (PackageParser.Provider p : mProviders.mProviders.values()) { 12769 if (packageName != null && !packageName.equals(p.info.packageName)) { 12770 continue; 12771 } 12772 if (!printedSomething) { 12773 if (dumpState.onTitlePrinted()) 12774 pw.println(); 12775 pw.println("Registered ContentProviders:"); 12776 printedSomething = true; 12777 } 12778 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 12779 pw.print(" "); pw.println(p.toString()); 12780 } 12781 printedSomething = false; 12782 for (Map.Entry<String, PackageParser.Provider> entry : 12783 mProvidersByAuthority.entrySet()) { 12784 PackageParser.Provider p = entry.getValue(); 12785 if (packageName != null && !packageName.equals(p.info.packageName)) { 12786 continue; 12787 } 12788 if (!printedSomething) { 12789 if (dumpState.onTitlePrinted()) 12790 pw.println(); 12791 pw.println("ContentProvider Authorities:"); 12792 printedSomething = true; 12793 } 12794 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 12795 pw.print(" "); pw.println(p.toString()); 12796 if (p.info != null && p.info.applicationInfo != null) { 12797 final String appInfo = p.info.applicationInfo.toString(); 12798 pw.print(" applicationInfo="); pw.println(appInfo); 12799 } 12800 } 12801 } 12802 12803 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 12804 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 12805 } 12806 12807 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 12808 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 12809 } 12810 12811 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 12812 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin); 12813 } 12814 12815 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 12816 // XXX should handle packageName != null by dumping only install data that 12817 // the given package is involved with. 12818 if (dumpState.onTitlePrinted()) pw.println(); 12819 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 12820 } 12821 12822 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 12823 if (dumpState.onTitlePrinted()) pw.println(); 12824 mSettings.dumpReadMessagesLPr(pw, dumpState); 12825 12826 pw.println(); 12827 pw.println("Package warning messages:"); 12828 BufferedReader in = null; 12829 String line = null; 12830 try { 12831 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 12832 while ((line = in.readLine()) != null) { 12833 if (line.contains("ignored: updated version")) continue; 12834 pw.println(line); 12835 } 12836 } catch (IOException ignored) { 12837 } finally { 12838 IoUtils.closeQuietly(in); 12839 } 12840 } 12841 12842 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 12843 BufferedReader in = null; 12844 String line = null; 12845 try { 12846 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 12847 while ((line = in.readLine()) != null) { 12848 if (line.contains("ignored: updated version")) continue; 12849 pw.print("msg,"); 12850 pw.println(line); 12851 } 12852 } catch (IOException ignored) { 12853 } finally { 12854 IoUtils.closeQuietly(in); 12855 } 12856 } 12857 } 12858 } 12859 12860 // ------- apps on sdcard specific code ------- 12861 static final boolean DEBUG_SD_INSTALL = false; 12862 12863 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 12864 12865 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 12866 12867 private boolean mMediaMounted = false; 12868 12869 static String getEncryptKey() { 12870 try { 12871 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 12872 SD_ENCRYPTION_KEYSTORE_NAME); 12873 if (sdEncKey == null) { 12874 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 12875 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 12876 if (sdEncKey == null) { 12877 Slog.e(TAG, "Failed to create encryption keys"); 12878 return null; 12879 } 12880 } 12881 return sdEncKey; 12882 } catch (NoSuchAlgorithmException nsae) { 12883 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 12884 return null; 12885 } catch (IOException ioe) { 12886 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 12887 return null; 12888 } 12889 } 12890 12891 /* 12892 * Update media status on PackageManager. 12893 */ 12894 @Override 12895 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 12896 int callingUid = Binder.getCallingUid(); 12897 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 12898 throw new SecurityException("Media status can only be updated by the system"); 12899 } 12900 // reader; this apparently protects mMediaMounted, but should probably 12901 // be a different lock in that case. 12902 synchronized (mPackages) { 12903 Log.i(TAG, "Updating external media status from " 12904 + (mMediaMounted ? "mounted" : "unmounted") + " to " 12905 + (mediaStatus ? "mounted" : "unmounted")); 12906 if (DEBUG_SD_INSTALL) 12907 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 12908 + ", mMediaMounted=" + mMediaMounted); 12909 if (mediaStatus == mMediaMounted) { 12910 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 12911 : 0, -1); 12912 mHandler.sendMessage(msg); 12913 return; 12914 } 12915 mMediaMounted = mediaStatus; 12916 } 12917 // Queue up an async operation since the package installation may take a 12918 // little while. 12919 mHandler.post(new Runnable() { 12920 public void run() { 12921 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 12922 } 12923 }); 12924 } 12925 12926 /** 12927 * Called by MountService when the initial ASECs to scan are available. 12928 * Should block until all the ASEC containers are finished being scanned. 12929 */ 12930 public void scanAvailableAsecs() { 12931 updateExternalMediaStatusInner(true, false, false); 12932 if (mShouldRestoreconData) { 12933 SELinuxMMAC.setRestoreconDone(); 12934 mShouldRestoreconData = false; 12935 } 12936 } 12937 12938 /* 12939 * Collect information of applications on external media, map them against 12940 * existing containers and update information based on current mount status. 12941 * Please note that we always have to report status if reportStatus has been 12942 * set to true especially when unloading packages. 12943 */ 12944 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 12945 boolean externalStorage) { 12946 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 12947 int[] uidArr = EmptyArray.INT; 12948 12949 final String[] list = PackageHelper.getSecureContainerList(); 12950 if (ArrayUtils.isEmpty(list)) { 12951 Log.i(TAG, "No secure containers found"); 12952 } else { 12953 // Process list of secure containers and categorize them 12954 // as active or stale based on their package internal state. 12955 12956 // reader 12957 synchronized (mPackages) { 12958 for (String cid : list) { 12959 // Leave stages untouched for now; installer service owns them 12960 if (PackageInstallerService.isStageName(cid)) continue; 12961 12962 if (DEBUG_SD_INSTALL) 12963 Log.i(TAG, "Processing container " + cid); 12964 String pkgName = getAsecPackageName(cid); 12965 if (pkgName == null) { 12966 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 12967 continue; 12968 } 12969 if (DEBUG_SD_INSTALL) 12970 Log.i(TAG, "Looking for pkg : " + pkgName); 12971 12972 final PackageSetting ps = mSettings.mPackages.get(pkgName); 12973 if (ps == null) { 12974 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 12975 continue; 12976 } 12977 12978 /* 12979 * Skip packages that are not external if we're unmounting 12980 * external storage. 12981 */ 12982 if (externalStorage && !isMounted && !isExternal(ps)) { 12983 continue; 12984 } 12985 12986 final AsecInstallArgs args = new AsecInstallArgs(cid, 12987 getAppDexInstructionSets(ps), isForwardLocked(ps)); 12988 // The package status is changed only if the code path 12989 // matches between settings and the container id. 12990 if (ps.codePathString != null 12991 && ps.codePathString.startsWith(args.getCodePath())) { 12992 if (DEBUG_SD_INSTALL) { 12993 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 12994 + " at code path: " + ps.codePathString); 12995 } 12996 12997 // We do have a valid package installed on sdcard 12998 processCids.put(args, ps.codePathString); 12999 final int uid = ps.appId; 13000 if (uid != -1) { 13001 uidArr = ArrayUtils.appendInt(uidArr, uid); 13002 } 13003 } else { 13004 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 13005 + ps.codePathString); 13006 } 13007 } 13008 } 13009 13010 Arrays.sort(uidArr); 13011 } 13012 13013 // Process packages with valid entries. 13014 if (isMounted) { 13015 if (DEBUG_SD_INSTALL) 13016 Log.i(TAG, "Loading packages"); 13017 loadMediaPackages(processCids, uidArr); 13018 startCleaningPackages(); 13019 mInstallerService.onSecureContainersAvailable(); 13020 } else { 13021 if (DEBUG_SD_INSTALL) 13022 Log.i(TAG, "Unloading packages"); 13023 unloadMediaPackages(processCids, uidArr, reportStatus); 13024 } 13025 } 13026 13027 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 13028 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 13029 int size = pkgList.size(); 13030 if (size > 0) { 13031 // Send broadcasts here 13032 Bundle extras = new Bundle(); 13033 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 13034 .toArray(new String[size])); 13035 if (uidArr != null) { 13036 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 13037 } 13038 if (replacing) { 13039 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 13040 } 13041 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 13042 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 13043 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 13044 } 13045 } 13046 13047 /* 13048 * Look at potentially valid container ids from processCids If package 13049 * information doesn't match the one on record or package scanning fails, 13050 * the cid is added to list of removeCids. We currently don't delete stale 13051 * containers. 13052 */ 13053 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) { 13054 ArrayList<String> pkgList = new ArrayList<String>(); 13055 Set<AsecInstallArgs> keys = processCids.keySet(); 13056 13057 for (AsecInstallArgs args : keys) { 13058 String codePath = processCids.get(args); 13059 if (DEBUG_SD_INSTALL) 13060 Log.i(TAG, "Loading container : " + args.cid); 13061 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13062 try { 13063 // Make sure there are no container errors first. 13064 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 13065 Slog.e(TAG, "Failed to mount cid : " + args.cid 13066 + " when installing from sdcard"); 13067 continue; 13068 } 13069 // Check code path here. 13070 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 13071 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 13072 + " does not match one in settings " + codePath); 13073 continue; 13074 } 13075 // Parse package 13076 int parseFlags = mDefParseFlags; 13077 if (args.isExternal()) { 13078 parseFlags |= PackageParser.PARSE_ON_SDCARD; 13079 } 13080 if (args.isFwdLocked()) { 13081 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 13082 } 13083 13084 synchronized (mInstallLock) { 13085 PackageParser.Package pkg = null; 13086 try { 13087 pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null); 13088 } catch (PackageManagerException e) { 13089 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 13090 } 13091 // Scan the package 13092 if (pkg != null) { 13093 /* 13094 * TODO why is the lock being held? doPostInstall is 13095 * called in other places without the lock. This needs 13096 * to be straightened out. 13097 */ 13098 // writer 13099 synchronized (mPackages) { 13100 retCode = PackageManager.INSTALL_SUCCEEDED; 13101 pkgList.add(pkg.packageName); 13102 // Post process args 13103 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 13104 pkg.applicationInfo.uid); 13105 } 13106 } else { 13107 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 13108 } 13109 } 13110 13111 } finally { 13112 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 13113 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 13114 } 13115 } 13116 } 13117 // writer 13118 synchronized (mPackages) { 13119 // If the platform SDK has changed since the last time we booted, 13120 // we need to re-grant app permission to catch any new ones that 13121 // appear. This is really a hack, and means that apps can in some 13122 // cases get permissions that the user didn't initially explicitly 13123 // allow... it would be nice to have some better way to handle 13124 // this situation. 13125 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 13126 if (regrantPermissions) 13127 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 13128 + mSdkVersion + "; regranting permissions for external storage"); 13129 mSettings.mExternalSdkPlatform = mSdkVersion; 13130 13131 // Make sure group IDs have been assigned, and any permission 13132 // changes in other apps are accounted for 13133 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 13134 | (regrantPermissions 13135 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 13136 : 0)); 13137 13138 mSettings.updateExternalDatabaseVersion(); 13139 13140 // can downgrade to reader 13141 // Persist settings 13142 mSettings.writeLPr(); 13143 } 13144 // Send a broadcast to let everyone know we are done processing 13145 if (pkgList.size() > 0) { 13146 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 13147 } 13148 } 13149 13150 /* 13151 * Utility method to unload a list of specified containers 13152 */ 13153 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 13154 // Just unmount all valid containers. 13155 for (AsecInstallArgs arg : cidArgs) { 13156 synchronized (mInstallLock) { 13157 arg.doPostDeleteLI(false); 13158 } 13159 } 13160 } 13161 13162 /* 13163 * Unload packages mounted on external media. This involves deleting package 13164 * data from internal structures, sending broadcasts about diabled packages, 13165 * gc'ing to free up references, unmounting all secure containers 13166 * corresponding to packages on external media, and posting a 13167 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 13168 * that we always have to post this message if status has been requested no 13169 * matter what. 13170 */ 13171 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 13172 final boolean reportStatus) { 13173 if (DEBUG_SD_INSTALL) 13174 Log.i(TAG, "unloading media packages"); 13175 ArrayList<String> pkgList = new ArrayList<String>(); 13176 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 13177 final Set<AsecInstallArgs> keys = processCids.keySet(); 13178 for (AsecInstallArgs args : keys) { 13179 String pkgName = args.getPackageName(); 13180 if (DEBUG_SD_INSTALL) 13181 Log.i(TAG, "Trying to unload pkg : " + pkgName); 13182 // Delete package internally 13183 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 13184 synchronized (mInstallLock) { 13185 boolean res = deletePackageLI(pkgName, null, false, null, null, 13186 PackageManager.DELETE_KEEP_DATA, outInfo, false); 13187 if (res) { 13188 pkgList.add(pkgName); 13189 } else { 13190 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 13191 failedList.add(args); 13192 } 13193 } 13194 } 13195 13196 // reader 13197 synchronized (mPackages) { 13198 // We didn't update the settings after removing each package; 13199 // write them now for all packages. 13200 mSettings.writeLPr(); 13201 } 13202 13203 // We have to absolutely send UPDATED_MEDIA_STATUS only 13204 // after confirming that all the receivers processed the ordered 13205 // broadcast when packages get disabled, force a gc to clean things up. 13206 // and unload all the containers. 13207 if (pkgList.size() > 0) { 13208 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 13209 new IIntentReceiver.Stub() { 13210 public void performReceive(Intent intent, int resultCode, String data, 13211 Bundle extras, boolean ordered, boolean sticky, 13212 int sendingUser) throws RemoteException { 13213 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 13214 reportStatus ? 1 : 0, 1, keys); 13215 mHandler.sendMessage(msg); 13216 } 13217 }); 13218 } else { 13219 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 13220 keys); 13221 mHandler.sendMessage(msg); 13222 } 13223 } 13224 13225 /** Binder call */ 13226 @Override 13227 public void movePackage(final String packageName, final IPackageMoveObserver observer, 13228 final int flags) { 13229 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 13230 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 13231 int returnCode = PackageManager.MOVE_SUCCEEDED; 13232 int currInstallFlags = 0; 13233 int newInstallFlags = 0; 13234 13235 File codeFile = null; 13236 String installerPackageName = null; 13237 String packageAbiOverride = null; 13238 13239 // reader 13240 synchronized (mPackages) { 13241 final PackageParser.Package pkg = mPackages.get(packageName); 13242 final PackageSetting ps = mSettings.mPackages.get(packageName); 13243 if (pkg == null || ps == null) { 13244 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 13245 } else { 13246 // Disable moving fwd locked apps and system packages 13247 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 13248 Slog.w(TAG, "Cannot move system application"); 13249 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 13250 } else if (pkg.mOperationPending) { 13251 Slog.w(TAG, "Attempt to move package which has pending operations"); 13252 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 13253 } else { 13254 // Find install location first 13255 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 13256 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 13257 Slog.w(TAG, "Ambigous flags specified for move location."); 13258 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 13259 } else { 13260 newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 13261 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 13262 currInstallFlags = isExternal(pkg) 13263 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL; 13264 13265 if (newInstallFlags == currInstallFlags) { 13266 Slog.w(TAG, "No move required. Trying to move to same location"); 13267 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 13268 } else { 13269 if (isForwardLocked(pkg)) { 13270 currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13271 newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK; 13272 } 13273 } 13274 } 13275 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 13276 pkg.mOperationPending = true; 13277 } 13278 } 13279 13280 codeFile = new File(pkg.codePath); 13281 installerPackageName = ps.installerPackageName; 13282 packageAbiOverride = ps.cpuAbiOverrideString; 13283 } 13284 } 13285 13286 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 13287 try { 13288 observer.packageMoved(packageName, returnCode); 13289 } catch (RemoteException ignored) { 13290 } 13291 return; 13292 } 13293 13294 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 13295 @Override 13296 public void onUserActionRequired(Intent intent) throws RemoteException { 13297 throw new IllegalStateException(); 13298 } 13299 13300 @Override 13301 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 13302 Bundle extras) throws RemoteException { 13303 Slog.d(TAG, "Install result for move: " 13304 + PackageManager.installStatusToString(returnCode, msg)); 13305 13306 // We usually have a new package now after the install, but if 13307 // we failed we need to clear the pending flag on the original 13308 // package object. 13309 synchronized (mPackages) { 13310 final PackageParser.Package pkg = mPackages.get(packageName); 13311 if (pkg != null) { 13312 pkg.mOperationPending = false; 13313 } 13314 } 13315 13316 final int status = PackageManager.installStatusToPublicStatus(returnCode); 13317 switch (status) { 13318 case PackageInstaller.STATUS_SUCCESS: 13319 observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED); 13320 break; 13321 case PackageInstaller.STATUS_FAILURE_STORAGE: 13322 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 13323 break; 13324 default: 13325 observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR); 13326 break; 13327 } 13328 } 13329 }; 13330 13331 // Treat a move like reinstalling an existing app, which ensures that we 13332 // process everythign uniformly, like unpacking native libraries. 13333 newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 13334 13335 final Message msg = mHandler.obtainMessage(INIT_COPY); 13336 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 13337 msg.obj = new InstallParams(origin, installObserver, newInstallFlags, 13338 installerPackageName, null, user, packageAbiOverride); 13339 mHandler.sendMessage(msg); 13340 } 13341 13342 @Override 13343 public boolean setInstallLocation(int loc) { 13344 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 13345 null); 13346 if (getInstallLocation() == loc) { 13347 return true; 13348 } 13349 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 13350 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 13351 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 13352 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 13353 return true; 13354 } 13355 return false; 13356 } 13357 13358 @Override 13359 public int getInstallLocation() { 13360 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13361 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 13362 PackageHelper.APP_INSTALL_AUTO); 13363 } 13364 13365 /** Called by UserManagerService */ 13366 void cleanUpUserLILPw(UserManagerService userManager, int userHandle) { 13367 mDirtyUsers.remove(userHandle); 13368 mSettings.removeUserLPw(userHandle); 13369 mPendingBroadcasts.remove(userHandle); 13370 if (mInstaller != null) { 13371 // Technically, we shouldn't be doing this with the package lock 13372 // held. However, this is very rare, and there is already so much 13373 // other disk I/O going on, that we'll let it slide for now. 13374 mInstaller.removeUserDataDirs(userHandle); 13375 } 13376 mUserNeedsBadging.delete(userHandle); 13377 removeUnusedPackagesLILPw(userManager, userHandle); 13378 } 13379 13380 /** 13381 * We're removing userHandle and would like to remove any downloaded packages 13382 * that are no longer in use by any other user. 13383 * @param userHandle the user being removed 13384 */ 13385 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 13386 final boolean DEBUG_CLEAN_APKS = false; 13387 int [] users = userManager.getUserIdsLPr(); 13388 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 13389 while (psit.hasNext()) { 13390 PackageSetting ps = psit.next(); 13391 if (ps.pkg == null) { 13392 continue; 13393 } 13394 final String packageName = ps.pkg.packageName; 13395 // Skip over if system app 13396 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 13397 continue; 13398 } 13399 if (DEBUG_CLEAN_APKS) { 13400 Slog.i(TAG, "Checking package " + packageName); 13401 } 13402 boolean keep = false; 13403 for (int i = 0; i < users.length; i++) { 13404 if (users[i] != userHandle && ps.getInstalled(users[i])) { 13405 keep = true; 13406 if (DEBUG_CLEAN_APKS) { 13407 Slog.i(TAG, " Keeping package " + packageName + " for user " 13408 + users[i]); 13409 } 13410 break; 13411 } 13412 } 13413 if (!keep) { 13414 if (DEBUG_CLEAN_APKS) { 13415 Slog.i(TAG, " Removing package " + packageName); 13416 } 13417 mHandler.post(new Runnable() { 13418 public void run() { 13419 deletePackageX(packageName, userHandle, 0); 13420 } //end run 13421 }); 13422 } 13423 } 13424 } 13425 13426 /** Called by UserManagerService */ 13427 void createNewUserLILPw(int userHandle, File path) { 13428 if (mInstaller != null) { 13429 mInstaller.createUserConfig(userHandle); 13430 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 13431 } 13432 } 13433 13434 @Override 13435 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 13436 mContext.enforceCallingOrSelfPermission( 13437 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13438 "Only package verification agents can read the verifier device identity"); 13439 13440 synchronized (mPackages) { 13441 return mSettings.getVerifierDeviceIdentityLPw(); 13442 } 13443 } 13444 13445 @Override 13446 public void setPermissionEnforced(String permission, boolean enforced) { 13447 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 13448 if (READ_EXTERNAL_STORAGE.equals(permission)) { 13449 synchronized (mPackages) { 13450 if (mSettings.mReadExternalStorageEnforced == null 13451 || mSettings.mReadExternalStorageEnforced != enforced) { 13452 mSettings.mReadExternalStorageEnforced = enforced; 13453 mSettings.writeLPr(); 13454 } 13455 } 13456 // kill any non-foreground processes so we restart them and 13457 // grant/revoke the GID. 13458 final IActivityManager am = ActivityManagerNative.getDefault(); 13459 if (am != null) { 13460 final long token = Binder.clearCallingIdentity(); 13461 try { 13462 am.killProcessesBelowForeground("setPermissionEnforcement"); 13463 } catch (RemoteException e) { 13464 } finally { 13465 Binder.restoreCallingIdentity(token); 13466 } 13467 } 13468 } else { 13469 throw new IllegalArgumentException("No selective enforcement for " + permission); 13470 } 13471 } 13472 13473 @Override 13474 @Deprecated 13475 public boolean isPermissionEnforced(String permission) { 13476 return true; 13477 } 13478 13479 @Override 13480 public boolean isStorageLow() { 13481 final long token = Binder.clearCallingIdentity(); 13482 try { 13483 final DeviceStorageMonitorInternal 13484 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 13485 if (dsm != null) { 13486 return dsm.isMemoryLow(); 13487 } else { 13488 return false; 13489 } 13490 } finally { 13491 Binder.restoreCallingIdentity(token); 13492 } 13493 } 13494 13495 @Override 13496 public IPackageInstaller getPackageInstaller() { 13497 return mInstallerService; 13498 } 13499 13500 private boolean userNeedsBadging(int userId) { 13501 int index = mUserNeedsBadging.indexOfKey(userId); 13502 if (index < 0) { 13503 final UserInfo userInfo; 13504 final long token = Binder.clearCallingIdentity(); 13505 try { 13506 userInfo = sUserManager.getUserInfo(userId); 13507 } finally { 13508 Binder.restoreCallingIdentity(token); 13509 } 13510 final boolean b; 13511 if (userInfo != null && userInfo.isManagedProfile()) { 13512 b = true; 13513 } else { 13514 b = false; 13515 } 13516 mUserNeedsBadging.put(userId, b); 13517 return b; 13518 } 13519 return mUserNeedsBadging.valueAt(index); 13520 } 13521 13522 @Override 13523 public KeySet getKeySetByAlias(String packageName, String alias) { 13524 if (packageName == null || alias == null) { 13525 return null; 13526 } 13527 synchronized(mPackages) { 13528 final PackageParser.Package pkg = mPackages.get(packageName); 13529 if (pkg == null) { 13530 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13531 throw new IllegalArgumentException("Unknown package: " + packageName); 13532 } 13533 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13534 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 13535 } 13536 } 13537 13538 @Override 13539 public KeySet getSigningKeySet(String packageName) { 13540 if (packageName == null) { 13541 return null; 13542 } 13543 synchronized(mPackages) { 13544 final PackageParser.Package pkg = mPackages.get(packageName); 13545 if (pkg == null) { 13546 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13547 throw new IllegalArgumentException("Unknown package: " + packageName); 13548 } 13549 if (pkg.applicationInfo.uid != Binder.getCallingUid() 13550 && Process.SYSTEM_UID != Binder.getCallingUid()) { 13551 throw new SecurityException("May not access signing KeySet of other apps."); 13552 } 13553 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13554 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 13555 } 13556 } 13557 13558 @Override 13559 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 13560 if (packageName == null || ks == null) { 13561 return false; 13562 } 13563 synchronized(mPackages) { 13564 final PackageParser.Package pkg = mPackages.get(packageName); 13565 if (pkg == null) { 13566 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13567 throw new IllegalArgumentException("Unknown package: " + packageName); 13568 } 13569 IBinder ksh = ks.getToken(); 13570 if (ksh instanceof KeySetHandle) { 13571 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13572 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 13573 } 13574 return false; 13575 } 13576 } 13577 13578 @Override 13579 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 13580 if (packageName == null || ks == null) { 13581 return false; 13582 } 13583 synchronized(mPackages) { 13584 final PackageParser.Package pkg = mPackages.get(packageName); 13585 if (pkg == null) { 13586 Slog.w(TAG, "KeySet requested for unknown package:" + packageName); 13587 throw new IllegalArgumentException("Unknown package: " + packageName); 13588 } 13589 IBinder ksh = ks.getToken(); 13590 if (ksh instanceof KeySetHandle) { 13591 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13592 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 13593 } 13594 return false; 13595 } 13596 } 13597 13598 public void getUsageStatsIfNoPackageUsageInfo() { 13599 if (!mPackageUsage.isHistoricalPackageUsageAvailable()) { 13600 UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 13601 if (usm == null) { 13602 throw new IllegalStateException("UsageStatsManager must be initialized"); 13603 } 13604 long now = System.currentTimeMillis(); 13605 Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now); 13606 for (Map.Entry<String, UsageStats> entry : stats.entrySet()) { 13607 String packageName = entry.getKey(); 13608 PackageParser.Package pkg = mPackages.get(packageName); 13609 if (pkg == null) { 13610 continue; 13611 } 13612 UsageStats usage = entry.getValue(); 13613 pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed(); 13614 mPackageUsage.mIsHistoricalPackageUsageAvailable = true; 13615 } 13616 } 13617 } 13618 13619 /** 13620 * Check and throw if the given before/after packages would be considered a 13621 * downgrade. 13622 */ 13623 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 13624 throws PackageManagerException { 13625 if (after.versionCode < before.mVersionCode) { 13626 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 13627 "Update version code " + after.versionCode + " is older than current " 13628 + before.mVersionCode); 13629 } else if (after.versionCode == before.mVersionCode) { 13630 if (after.baseRevisionCode < before.baseRevisionCode) { 13631 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 13632 "Update base revision code " + after.baseRevisionCode 13633 + " is older than current " + before.baseRevisionCode); 13634 } 13635 13636 if (!ArrayUtils.isEmpty(after.splitNames)) { 13637 for (int i = 0; i < after.splitNames.length; i++) { 13638 final String splitName = after.splitNames[i]; 13639 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 13640 if (j != -1) { 13641 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 13642 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 13643 "Update split " + splitName + " revision code " 13644 + after.splitRevisionCodes[i] + " is older than current " 13645 + before.splitRevisionCodes[j]); 13646 } 13647 } 13648 } 13649 } 13650 } 13651 } 13652} 13653